From 7be513191c0324d265c4505390cd74f8e09b1aad Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:15:10 -0800 Subject: [PATCH 1/8] Choose a path for a replaced document, and let main lay it out DocumentUpdate decides how a view takes a document that the app sets. A document that does not add to the one before goes to the main thread when the app asks for it. An append, and the first text after an empty document, stay on the background path. LayoutEngine.submit takes schedulesLayout. When it is false, the queue does not lay out the request, because the main thread calls relayout at once. This prevents a second layout of the same document. Tests cover the choice, the height of the new layout, and an append after a replacement. An opt-in test times the main-thread call. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/DocumentUpdate.swift | 29 ++++ .../TranscriptKit/Layout/LayoutEngine.swift | 11 +- .../TranscriptKitTests/ReplacementTests.swift | 143 ++++++++++++++++++ 3 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/DocumentUpdate.swift create mode 100644 Tests/TranscriptKitTests/ReplacementTests.swift diff --git a/Sources/TranscriptKit/Layout/DocumentUpdate.swift b/Sources/TranscriptKit/Layout/DocumentUpdate.swift new file mode 100644 index 0000000..7059c76 --- /dev/null +++ b/Sources/TranscriptKit/Layout/DocumentUpdate.swift @@ -0,0 +1,29 @@ +import Foundation + +/// How a view takes a document that the app sets directly. +enum DocumentUpdate: Equatable { + /// Laid out on the layout queue, as each update of a stream is. The + /// view shows the old layout until the new one is ready. + case background + /// Laid out on the main thread at once, so the view's size is the new + /// one before the app measures it. The view crossfades from the old + /// drawing for this many seconds, or shows the new one at once for zero. + case now(crossfade: TimeInterval) + + /// What the view does when the app replaces `old` with `new`. + /// + /// - Parameters: + /// - isLaidOut: the view shows a layout and has a width, so it can + /// lay out the new document now. + /// - crossfade: the view's `replacementCrossfadeDuration`. Nil keeps + /// every document on the background path. + /// - Returns: `.now` only for a document that does not add to `old`. A + /// document that adds to it (longer text in the last block, or more + /// blocks) goes to the background, as a stream's updates do. So does + /// the first text after an empty document. + static func choose(replacing old: TranscriptDocument, with new: TranscriptDocument, isLaidOut: Bool, + crossfade: TimeInterval?) -> DocumentUpdate { + guard isLaidOut, let crossfade, !new.extends(old) else { return .background } + return .now(crossfade: max(crossfade, 0)) + } +} diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 4cf780d..b527103 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -12,7 +12,8 @@ import QuartzCore /// main run loop. /// /// The main thread lays out synchronously only when it cannot wait: the -/// first layout, and a change of width or style. It does so through +/// first layout, a change of width or style, and a replaced document when +/// the view's `replacementCrossfadeDuration` asks for it. It does so through /// `queue.sync`, so the engine's state is only ever touched on its queue. /// /// While text is being appended, the engine also draws the end of the @@ -225,8 +226,12 @@ final class LayoutEngine: @unchecked Sendable { /// Asks for `request` to be laid out. Any thread. Returns false once the /// engine has shut down, so a stream can stop sending to it. + /// + /// - Parameter schedulesLayout: false when the caller calls `relayout` + /// at once, which lays out the request on the main thread. The queue + /// then does not lay it out first. @discardableResult - func submit(_ request: Request) -> Bool { + func submit(_ request: Request, schedulesLayout: Bool = true) -> Bool { var accepted = true let delay: CFTimeInterval? = lock.withLock { guard !isShutDown else { accepted = false; return nil } @@ -238,7 +243,7 @@ final class LayoutEngine: @unchecked Sendable { guard request.sequence > lastSequence else { return nil } lastSequence = request.sequence pending = request - if drainScheduled { return nil } + if drainScheduled || !schedulesLayout { return nil } drainScheduled = true return max(lastDrain + frameInterval - CACurrentMediaTime(), 0) } diff --git a/Tests/TranscriptKitTests/ReplacementTests.swift b/Tests/TranscriptKitTests/ReplacementTests.swift new file mode 100644 index 0000000..09a9d98 --- /dev/null +++ b/Tests/TranscriptKitTests/ReplacementTests.swift @@ -0,0 +1,143 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +private let shortAnswer = """ + ## Summary + + The build runs in **two steps**: the first one compiles the package, and the second one runs the tests on \ + the device. Each step writes its log to the `build` folder. + + - Compile the package. + - Run the tests, then read the log. + + If a step fails, run it again with `--verbose` and read the [guide](https://example.com/guide). + """ + +private let otherAnswer = """ + ## Details + + A short text in a new layout: one heading, one paragraph that wraps onto a few lines at the width of a \ + phone, and a list. + + 1. Open the settings. + 2. Turn on the option. + 3. Close the settings again, and check that the text changed. + + That is all. + """ + +// MARK: Which path a document takes + +@Test func aReplacedDocumentIsLaidOutNow() { + let old = MarkdownStreamParser.document(from: shortAnswer) + let new = MarkdownStreamParser.document(from: otherAnswer) + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: true, crossfade: 0.25) == .now(crossfade: 0.25)) + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: true, crossfade: 0) == .now(crossfade: 0)) + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: true, crossfade: -1) == .now(crossfade: 0)) + // Shorter text is a replacement too. + let shorter = MarkdownStreamParser.document(from: String(shortAnswer.prefix(40))) + #expect(DocumentUpdate.choose(replacing: old, with: shorter, isLaidOut: true, crossfade: 0.25) == .now(crossfade: 0.25)) +} + +@Test func anAppendStaysInTheBackground() { + let old = MarkdownStreamParser.document(from: String(shortAnswer.prefix(120))) + // The same text parsed again, longer: the same block ids, more text. + let longer = MarkdownStreamParser.document(from: shortAnswer) + #expect(longer.extends(old)) + #expect(DocumentUpdate.choose(replacing: old, with: longer, isLaidOut: true, crossfade: 0.25) == .background) + + var appended = TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "Some text")]) + let before = appended + appended.appendToLastBlock(", and more") + appended.append(TranscriptBlock(id: "b", text: "A new block")) + #expect(DocumentUpdate.choose(replacing: before, with: appended, isLaidOut: true, crossfade: 0.25) == .background) +} + +@Test func theOptionAndALayoutAreNeededToLayOutNow() { + let old = MarkdownStreamParser.document(from: shortAnswer) + let new = MarkdownStreamParser.document(from: otherAnswer) + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: true, crossfade: nil) == .background) + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: false, crossfade: 0.25) == .background) + // The first text after an empty document adds to it. + #expect(DocumentUpdate.choose(replacing: TranscriptDocument(), with: new, isLaidOut: true, crossfade: 0.25) == .background) +} + +@Test func aBlockWithTheSameIDAndOtherTextIsAReplacement() { + let old = TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "First answer")]) + let new = TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "Second answer")]) + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: true, crossfade: 0.25) == .now(crossfade: 0.25)) +} + +// MARK: The engine + +/// An engine that shows `document`, as a view with a layout does. +private func engineShowing(_ document: TranscriptDocument, width: CGFloat = 375) -> (LayoutEngine, DocumentLayout) { + let engine = LayoutEngine() + _ = engine.relayout(width: width, style: .init()) + engine.submit(.init(document: document, source: 0, sequence: 1, isFinished: true), schedulesLayout: false) + let shown = engine.relayout(width: width, style: .init())!.layout + return (engine, shown) +} + +@Test func aReplacementIsLaidOutOnceOnTheCallingThread() { + let old = MarkdownStreamParser.document(from: shortAnswer) + let new = MarkdownStreamParser.document(from: otherAnswer + "\n\nOne more paragraph, so the new text is taller.") + let (engine, shown) = engineShowing(old) + engine.submit(.init(document: new, source: 0, sequence: 2, isFinished: true), schedulesLayout: false) + let result = engine.relayout(width: 375, style: .init()) + #expect(result?.layout.document == new) + #expect(result?.isFinished == true) + // The blocks have the ids of the old ones; none of the old lines stay. + let fresh = DocumentLayout(document: new, width: 375) + #expect(result?.layout.height == fresh.height) + #expect(result?.layout.height != shown.height) + #expect(engine.measure(width: 375, style: .init()) == fresh.height) + // The queue does not lay it out again, and nothing older comes after it. + engine.drainNow() + #expect(engine.takeOutput() == nil) + #expect(engine.backgroundLayoutCount == 0) +} + +@Test func anAppendAfterAReplacementBuildsOnIt() { + let (engine, _) = engineShowing(MarkdownStreamParser.document(from: shortAnswer)) + let new = MarkdownStreamParser.document(from: String(otherAnswer.prefix(80))) + engine.submit(.init(document: new, source: 0, sequence: 2, isFinished: true), schedulesLayout: false) + let replaced = engine.relayout(width: 375, style: .init())!.layout + let longer = MarkdownStreamParser.document(from: otherAnswer) + engine.submit(.init(document: longer, source: 0, sequence: 3, isFinished: true)) + // The queue lays it out: `backgroundLayoutCount` waits for it. + #expect(engine.backgroundLayoutCount == 1) + let output = engine.takeOutput() + #expect(output?.layout.document == longer) + #expect(output?.base === replaced) + #expect(output?.isAppend == true) +} + +// Times what the view does on the main thread for a replaced document, for a +// short text: the engine call that the document setter makes. Opt in, in release: +// TRANSCRIPTKIT_TIMING=1 swift test -c release --filter replacementTiming +@Test(.enabled(if: ProcessInfo.processInfo.environment["TRANSCRIPTKIT_TIMING"] != nil)) +func replacementTiming() { + // Each document is new text, so no line of the one before is reused. + let documents = (0..<200).map { index in + MarkdownStreamParser.document(from: (index.isMultiple(of: 2) ? shortAnswer : otherAnswer) + "\n\nAnswer \(index).") + } + print("TIMING replacement text: \(documents[0].utf16Count) UTF-16 units, \(documents[0].count) blocks") + for width: CGFloat in [375, 320] { + let (engine, _) = engineShowing(documents[0], width: width) + var times: [Double] = [] + for (index, document) in documents.enumerated().dropFirst() { + let start = DispatchTime.now().uptimeNanoseconds + engine.submit(.init(document: document, source: 0, sequence: index + 1, isFinished: true), schedulesLayout: false) + _ = engine.relayout(width: width, style: .init()) + times.append(Double(DispatchTime.now().uptimeNanoseconds - start) / 1e3) + } + times.sort() + let median = times[times.count / 2] + let p90 = times[times.count * 9 / 10] + print("TIMING replacement at \(Int(width)) pt: median \(String(format: "%.0f", median)) µs, " + + "90th percentile \(String(format: "%.0f", p90)) µs, best \(String(format: "%.0f", times[0])) µs") + } +} From c90350e7eb707524d9c4b1fe7c2487b8662f3ec1 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:15:10 -0800 Subject: [PATCH 2/8] Replace the document at once, with a crossfade TranscriptTextView gets replacementCrossfadeDuration, and TranscriptText gets crossfadesReplacedText(_:duration:). With a duration, the view lays out a replaced document on the main thread in the document setter. Then sizeThatFits gives the new height in the same SwiftUI update. A fade CATransition on the canvas crossfades from the old drawing to the new one. Appends and streams keep the background path. The default is nil, so the behavior does not change for current apps. A signpost in Points of Interest marks each main-thread replacement. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++ .../TranscriptKit/iOS/TranscriptText.swift | 22 ++++++- .../iOS/TranscriptTextView.swift | 60 ++++++++++++++++++- 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 15e4433..ab1a791 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,24 @@ and Core Animation plays each fade, so the main thread does no work for each fra underline and strikethrough fade in. Backgrounds, images and formulas show at once. A tag that starts its animation ends the fades. The fade is off with Reduce Motion, and with a line limit. +### Replacing the text + +By default, a new document is laid out in the background, also when it replaces the text on screen. Until that +layout is ready, the view shows the old text and reports the old height. An app that swaps one complete text for +another, for example a summary for its details, can lay out the new text at once and crossfade to it: + +```swift +TranscriptText(showsSummary ? summary : details) + .crossfadesReplacedText(duration: 0.25) +``` + +The view then lays out the new document on the main thread in the same SwiftUI update, so SwiftUI gets the new +height at once. The old drawing crossfades to the new one, as a `UITextView` does in a `.transitionCrossDissolve` +transition. A duration of zero shows the new text at once. A document that only adds text to the one before (the +same blocks with more text, or more blocks) still goes to the background, and so do the updates of a stream. The +crossfade has no motion, so it also plays with Reduce Motion. In UIKit, set `replacementCrossfadeDuration` on +`TranscriptTextView`. + ### Images Images in the text show their alt text unless you provide a loader. The library never fetches anything itself, so diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 1a8d959..2d3cfb3 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -9,7 +9,8 @@ import UIKit /// and laid out in the background and go straight to the view, and SwiftUI /// only re-measures the view when its height changes. With /// `init(_ document:)`, every new document goes through a full SwiftUI -/// update (layout still happens in the background). +/// update (layout still happens in the background, unless +/// `crossfadesReplacedText(_:duration:)` lays out a replaced one at once). public struct TranscriptText: UIViewRepresentable { private enum Source { case document(TranscriptDocument) @@ -23,6 +24,7 @@ public struct TranscriptText: UIViewRepresentable { private var mathRenderer: TranscriptMathRenderer? private var animatesTags = true private var textFadeInDuration: TimeInterval? + private var replacementCrossfadeDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately private var isSelectable = true private var playTrigger: AnyHashable? @@ -93,6 +95,23 @@ public struct TranscriptText: UIViewRepresentable { return copy } + /// Lays out a document that replaces the one before at once, so that + /// SwiftUI gets its new height in the same update, and crossfades from + /// the old text to the new one; see + /// `TranscriptTextView.replacementCrossfadeDuration`. A document that + /// only adds text to the one before is laid out in the background, as + /// before. Off by default. + /// + /// ```swift + /// TranscriptText(showsSummary ? summary : details) + /// .crossfadesReplacedText(duration: 0.25) + /// ``` + public func crossfadesReplacedText(_ crossfades: Bool = true, duration: TimeInterval = 0.25) -> TranscriptText { + var copy = self + copy.replacementCrossfadeDuration = crossfades ? duration : nil + return copy + } + /// Whether custom tags with an animation play it when they finish /// arriving; see `TranscriptTextView.animatesTags`. On by default. public func animatesTags(_ animates: Bool) -> TranscriptText { @@ -183,6 +202,7 @@ public struct TranscriptText: UIViewRepresentable { view.style = style view.animatesTags = animatesTags view.textFadeInDuration = textFadeInDuration + view.replacementCrossfadeDuration = replacementCrossfadeDuration view.tagAnimationTiming = animationTiming view.isSelectable = isSelectable view.showsWritingTools = showsWritingTools diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index fdb641f..595ac0a 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -7,6 +7,9 @@ import UIKit private let animationLog = Logger(subsystem: "TranscriptKit", category: "TagAnimations") /// Each tag animation as an interval in Instruments' Points of Interest. private let animationSignposter = OSSignposter(subsystem: "TranscriptKit", category: .pointsOfInterest) +/// Each replaced document that is laid out on the main thread, as an +/// interval in Instruments' Points of Interest. +private let replacementSignposter = OSSignposter(subsystem: "TranscriptKit", category: .pointsOfInterest) /// A read-only text view that draws a whole transcript with Core Text and /// exposes it to the system as one selectable document. @@ -17,6 +20,8 @@ private let animationSignposter = OSSignposter(subsystem: "TranscriptKit", categ /// Layout happens on a background queue. The view keeps showing, and /// answering selection queries from, the last layout it installed until the /// next one is ready, so text positions always match what is on screen. +/// With `replacementCrossfadeDuration`, a replaced document is laid out on +/// the main thread instead. /// /// Text is drawn into tiles on the main thread, except while it is being /// appended: the end of the document is then drawn on the layout queue into @@ -50,8 +55,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD set { let replacesStream = stream != nil guard replacesStream || newValue != directDocument else { return } + let update = DocumentUpdate.choose(replacing: document, with: newValue, isLaidOut: installed != nil && bounds.width > 0, + crossfade: replacementCrossfadeDuration) directDocument = newValue directSequence += 1 + laysOutDirectDocumentNow = update != .background if replacesStream { // Detaching submits `directDocument`, now the new one. Only // one document goes to the engine: an earlier one in between @@ -59,12 +67,39 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD // what the stream's text grew into. stream = nil } else { - engine.submit(.init(document: newValue, source: source, sequence: directSequence, isFinished: true)) + engine.submit(.init(document: newValue, source: source, sequence: directSequence, isFinished: true), + schedulesLayout: !laysOutDirectDocumentNow) + } + laysOutDirectDocumentNow = false + if case .now(let crossfade) = update { + replaceNow(crossfade: crossfade) + } else { + layOutNowIfNothingIsShown() } - layOutNowIfNothingIsShown() } } + /// How long a replaced document takes to crossfade from the old text, + /// or nil to lay it out in the background, as every other update (the + /// default). + /// + /// With a duration, the view lays out a new `document` on the main + /// thread at once when it does not add to the one before (see + /// `TranscriptDocument.extends(_:)`). `sizeThatFits(_:)` and + /// `intrinsicContentSize` then give the new height in the same update. + /// The old drawing crossfades to the new one, as + /// `UIView.transition(with:duration:options:animations:)` does with + /// `.transitionCrossDissolve`. Zero shows the new text at once. + /// + /// Text that only grows, and the updates of a `stream`, keep the + /// background path. A crossfade has no motion, so it also plays with + /// Reduce Motion. + public var replacementCrossfadeDuration: TimeInterval? + + /// The document setter lays out the direct document now, so the engine + /// must not lay it out first. + private var laysOutDirectDocumentNow = false + /// A stream to show. The view then takes each update from the stream /// directly, in the background, without the app or SwiftUI setting `document`. public var stream: TranscriptStream? { @@ -74,7 +109,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD sinkID = nil source += 1 guard let stream else { - engine.submit(.init(document: directDocument, source: source, sequence: directSequence, isFinished: true)) + engine.submit(.init(document: directDocument, source: source, sequence: directSequence, isFinished: true), + schedulesLayout: !laysOutDirectDocumentNow) return } let engine = engine @@ -764,6 +800,24 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD if installed == nil { relayoutNow() } } + /// Lays out a replaced document now (see `replacementCrossfadeDuration`), + /// and crossfades to it from the old drawing. + private func replaceNow(crossfade duration: TimeInterval) { + let shown = installed + let signpost = replacementSignposter.beginInterval("Replace document") + relayoutNow() + replacementSignposter.endInterval("Replace document", signpost) + guard installed !== shown, duration > 0, window != nil, UIView.areAnimationsEnabled else { return } + // The render server fades from the canvas as the last commit showed + // it to the canvas as this commit shows it, with the tiles that the + // new layout draws in this commit. + let transition = CATransition() + transition.type = .fade + transition.duration = duration + transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + canvas.layer.add(transition, forKey: "replacement") + } + /// Puts `layout` on screen. /// /// - Parameter changedTop: the layout only added content at the end of From 0b70cf0e3a9e0d5d6d0a5727cce6d2bd719eee0c Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:15:10 -0800 Subject: [PATCH 3/8] Add a check screen for replaced text to the demo Launch the demo with -replacementCheck to swap a short text and a long text in a card every two seconds. Add -crossfade to turn on the new option. The console shows each swap and each height change of the card, with the time from the swap. Co-Authored-By: Claude Opus 5.5 --- Demo/TranscriptDemo/DemoApp.swift | 67 ++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/Demo/TranscriptDemo/DemoApp.swift b/Demo/TranscriptDemo/DemoApp.swift index 0852147..693fe01 100644 --- a/Demo/TranscriptDemo/DemoApp.swift +++ b/Demo/TranscriptDemo/DemoApp.swift @@ -5,7 +5,11 @@ import TranscriptKit struct DemoApp: App { var body: some Scene { WindowGroup { - ContentView() + if ProcessInfo.processInfo.arguments.contains("-replacementCheck") { + ReplacementCheckView() + } else { + ContentView() + } } } } @@ -178,6 +182,67 @@ enum Sample { """ } +/// Launch with `-replacementCheck` to replace the text of a card every two +/// seconds, with a short text and a long one in turn. Add `-crossfade` to lay +/// out each new text at once and crossfade to it. Each swap logs when it +/// happened, and each change of the card's height logs when SwiftUI saw it. +struct ReplacementCheckView: View { + @State private var showsLong = false + @State private var swap = 0 + @State private var swapTime: CFTimeInterval = 0 + private let crossfades = ProcessInfo.processInfo.arguments.contains("-crossfade") + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + Text(crossfades ? "Crossfade, laid out at once" : "Laid out in the background") + .font(.footnote.monospaced()) + .padding(.bottom, 8) + TranscriptText(MarkdownStreamParser.document(from: showsLong ? Self.long : Self.short)) + .crossfadesReplacedText(crossfades, duration: 0.6) + .padding(12) + .background(Color.yellow.opacity(0.35)) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in + let delay = (CACurrentMediaTime() - swapTime) * 1000 + print("replacement-check swap=\(swap) height=\(height) after=\(String(format: "%.1f", delay)) ms") + } + Rectangle() + .fill(.red) + .frame(height: 8) + } + .padding(16) + } + .task { + while !Task.isCancelled { + try? await Task.sleep(for: .seconds(2)) + swap += 1 + swapTime = CACurrentMediaTime() + print("replacement-check swap=\(swap) long=\(!showsLong)") + showsLong.toggle() + } + } + } + + static let short = """ + ## Summary + + The build has **two steps**. The details come in two seconds. + """ + + static let long = """ + ## Details + + The first step compiles the package. The second step runs the tests on the device, and each step writes its \ + log to the `build` folder. + + 1. Compile the package. + 2. Run the tests. + 3. Read the log, and run a step again with `--verbose` if it fails. + + > A step that fails twice needs a look at the [guide](https://example.com/guide). + """ +} + /// Launch with `-demoSelection` to select a range that starts in the heading /// and ends inside the code block, without touching the screen. Useful for /// screenshots and for checking the selection path from the command line. From 49261bb282721fd624692cbba80d1c9d0a43247b Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:15:54 -0800 Subject: [PATCH 4/8] Play the crossfade without a check of UIKit animations The view adds the fade transition to its layer itself, so it does not depend on UIView.areAnimationsEnabled. The crossfade then also plays in a SwiftUI update that turns off UIKit animations, if one does. An app that wants no crossfade sets a duration of zero. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/iOS/TranscriptTextView.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 595ac0a..9113b96 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -807,10 +807,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let signpost = replacementSignposter.beginInterval("Replace document") relayoutNow() replacementSignposter.endInterval("Replace document", signpost) - guard installed !== shown, duration > 0, window != nil, UIView.areAnimationsEnabled else { return } + guard installed !== shown, duration > 0, window != nil else { return } // The render server fades from the canvas as the last commit showed // it to the canvas as this commit shows it, with the tiles that the - // new layout draws in this commit. + // new layout draws in this commit. It is a layer animation, so + // `UIView.performWithoutAnimation` does not stop it. let transition = CATransition() transition.type = .fade transition.duration = duration From 997cf98d2bd781e1aae635a2a6ff350e21f03405 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:20:16 -0800 Subject: [PATCH 5/8] Let the demo check screen swap the text in an animation Add -animatedSwap to -replacementCheck to swap the text inside withAnimation. The card's height then animates, and a screenshot during the animation shows whether the red bar under the card moves with it. Co-Authored-By: Claude Opus 5.5 --- Demo/TranscriptDemo/DemoApp.swift | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Demo/TranscriptDemo/DemoApp.swift b/Demo/TranscriptDemo/DemoApp.swift index 693fe01..db591cf 100644 --- a/Demo/TranscriptDemo/DemoApp.swift +++ b/Demo/TranscriptDemo/DemoApp.swift @@ -184,13 +184,16 @@ enum Sample { /// Launch with `-replacementCheck` to replace the text of a card every two /// seconds, with a short text and a long one in turn. Add `-crossfade` to lay -/// out each new text at once and crossfade to it. Each swap logs when it -/// happened, and each change of the card's height logs when SwiftUI saw it. +/// out each new text at once and crossfade to it. Add `-animatedSwap` to +/// swap inside `withAnimation`, so that the card's height animates. Each swap +/// logs when it happened, and each change of the card's height logs when +/// SwiftUI saw it. struct ReplacementCheckView: View { @State private var showsLong = false @State private var swap = 0 @State private var swapTime: CFTimeInterval = 0 private let crossfades = ProcessInfo.processInfo.arguments.contains("-crossfade") + private let animatesSwap = ProcessInfo.processInfo.arguments.contains("-animatedSwap") var body: some View { ScrollView { @@ -218,7 +221,11 @@ struct ReplacementCheckView: View { swap += 1 swapTime = CACurrentMediaTime() print("replacement-check swap=\(swap) long=\(!showsLong)") - showsLong.toggle() + if animatesSwap { + withAnimation(.easeInOut(duration: 0.6)) { showsLong.toggle() } + } else { + showsLong.toggle() + } } } } From 3172e8f9fbc655b20a6c822086e054ef2d56799a Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:38:18 -0800 Subject: [PATCH 6/8] Keep a replaced document off the queue, and stop a running crossfade A drain that was already scheduled took a request that the main thread lays out. The main thread then waited for that layout and laid out the same document again. The engine now marks such a request, and a drain leaves it for relayout. A replacement with no crossfade, and a background install that is not an append, now remove a crossfade that still runs. The README and the doc comments now say that a text that starts with the old one, with the same block ids, and the first text after an empty document only add text. They do not crossfade. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 ++++++++ .../TranscriptKit/Layout/LayoutEngine.swift | 14 ++++++++-- .../TranscriptKit/iOS/TranscriptText.swift | 4 ++- .../iOS/TranscriptTextView.swift | 15 ++++++++-- .../TranscriptKitTests/ReplacementTests.swift | 28 +++++++++++++++++++ 5 files changed, 65 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ab1a791..aa3bbd2 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,17 @@ same blocks with more text, or more blocks) still goes to the background, and so crossfade has no motion, so it also plays with Reduce Motion. In UIKit, set `replacementCrossfadeDuration` on `TranscriptTextView`. +Block ids decide what adds to the text. A summary that is the start of its details, parsed with the same id prefix, +gives the details the ids of the summary's blocks, so the switch to the details only adds text: it goes to the +background, with no crossfade. Parse the two texts with different prefixes to crossfade both ways: + +```swift +let summary = MarkdownStreamParser.document(from: summaryText, idPrefix: "summary") +let details = MarkdownStreamParser.document(from: detailsText, idPrefix: "details") +``` + +The first text after an empty document also only adds text, so it goes to the background too. + ### Images Images in the text show their alt text unless you provide a loader. The library never fetches anything itself, so diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index b527103..eafb5de 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -84,6 +84,8 @@ final class LayoutEngine: @unchecked Sendable { // Guarded by `lock`. private let lock = NSLock() private var pending: Request? + /// `pending` waits for `relayout` on the main thread: a drain leaves it. + private var pendingIsForMain = false private var drainScheduled = false /// Layouts are made at most this often: a document that arrives sooner /// waits, and is replaced by any newer one that arrives meanwhile. More @@ -209,6 +211,7 @@ final class LayoutEngine: @unchecked Sendable { lock.withLock { isShutDown = true pending = nil + pendingIsForMain = false mailbox = nil onOutput = nil } @@ -229,7 +232,8 @@ final class LayoutEngine: @unchecked Sendable { /// /// - Parameter schedulesLayout: false when the caller calls `relayout` /// at once, which lays out the request on the main thread. The queue - /// then does not lay it out first. + /// then does not lay it out first, also when a drain is already + /// scheduled. @discardableResult func submit(_ request: Request, schedulesLayout: Bool = true) -> Bool { var accepted = true @@ -243,6 +247,7 @@ final class LayoutEngine: @unchecked Sendable { guard request.sequence > lastSequence else { return nil } lastSequence = request.sequence pending = request + pendingIsForMain = !schedulesLayout if drainScheduled || !schedulesLayout { return nil } drainScheduled = true return max(lastDrain + frameInterval - CACurrentMediaTime(), 0) @@ -259,7 +264,10 @@ final class LayoutEngine: @unchecked Sendable { private func takePending() -> Request? { lock.withLock { () -> Request? in - defer { pending = nil } + defer { + pending = nil + pendingIsForMain = false + } return pending } } @@ -278,7 +286,7 @@ final class LayoutEngine: @unchecked Sendable { private func drain() { let next: Request? = lock.withLock { drainScheduled = false - guard let request = pending else { return nil } + guard let request = pending, !pendingIsForMain else { return nil } pending = nil lastDrain = CACurrentMediaTime() return request diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 2d3cfb3..775d098 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -100,7 +100,9 @@ public struct TranscriptText: UIViewRepresentable { /// the old text to the new one; see /// `TranscriptTextView.replacementCrossfadeDuration`. A document that /// only adds text to the one before is laid out in the background, as - /// before. Off by default. + /// before. That includes a text that starts with the old one, parsed + /// with the same `idPrefix`, and the first text after an empty + /// document. Off by default. /// /// ```swift /// TranscriptText(showsSummary ? summary : details) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 9113b96..dbfeeef 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -92,8 +92,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// `.transitionCrossDissolve`. Zero shows the new text at once. /// /// Text that only grows, and the updates of a `stream`, keep the - /// background path. A crossfade has no motion, so it also plays with - /// Reduce Motion. + /// background path. A new document that starts with the blocks of the + /// old one, with the same ids, only grows the text: for example a + /// summary that is the start of its details, parsed with the same + /// `idPrefix`. It does not crossfade. Parse the two texts with different + /// prefixes to crossfade between them. The first text after an empty + /// document also only grows the text. A crossfade has no motion, so it + /// also plays with Reduce Motion. public var replacementCrossfadeDuration: TimeInterval? /// The document setter lays out the direct document now, so the engine @@ -772,6 +777,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return } let isAppend = output.isAppend && output.base != nil && output.base === installed + if !isAppend { canvas.layer.removeAnimation(forKey: Self.crossfadeKey) } install(output.layout, changedTop: isAppend ? output.changedTop : nil, tail: output.tail, restyled: isAppend ? output.restyled : [], started: output.started, waiting: output.waiting, fade: isAppend ? output.fade : nil, fadingFrom: output.hidden.fadingFrom, isFinished: output.isFinished) @@ -807,6 +813,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let signpost = replacementSignposter.beginInterval("Replace document") relayoutNow() replacementSignposter.endInterval("Replace document", signpost) + canvas.layer.removeAnimation(forKey: Self.crossfadeKey) guard installed !== shown, duration > 0, window != nil else { return } // The render server fades from the canvas as the last commit showed // it to the canvas as this commit shows it, with the tiles that the @@ -816,9 +823,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD transition.type = .fade transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) - canvas.layer.add(transition, forKey: "replacement") + canvas.layer.add(transition, forKey: Self.crossfadeKey) } + private static let crossfadeKey = "replacement" + /// Puts `layout` on screen. /// /// - Parameter changedTop: the layout only added content at the end of diff --git a/Tests/TranscriptKitTests/ReplacementTests.swift b/Tests/TranscriptKitTests/ReplacementTests.swift index 09a9d98..ad4a715 100644 --- a/Tests/TranscriptKitTests/ReplacementTests.swift +++ b/Tests/TranscriptKitTests/ReplacementTests.swift @@ -64,6 +64,16 @@ private let otherAnswer = """ #expect(DocumentUpdate.choose(replacing: TranscriptDocument(), with: new, isLaidOut: true, crossfade: 0.25) == .background) } +@Test func aPrefixWithOtherIDsIsAReplacement() { + let summary = String(shortAnswer.prefix(120)) + // With the same ids, the full text only adds to its start. + #expect(MarkdownStreamParser.document(from: shortAnswer).extends(MarkdownStreamParser.document(from: summary))) + let old = MarkdownStreamParser.document(from: summary, idPrefix: "summary") + let new = MarkdownStreamParser.document(from: shortAnswer, idPrefix: "details") + #expect(DocumentUpdate.choose(replacing: old, with: new, isLaidOut: true, crossfade: 0.25) == .now(crossfade: 0.25)) + #expect(DocumentUpdate.choose(replacing: new, with: old, isLaidOut: true, crossfade: 0.25) == .now(crossfade: 0.25)) +} + @Test func aBlockWithTheSameIDAndOtherTextIsAReplacement() { let old = TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "First answer")]) let new = TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "Second answer")]) @@ -100,6 +110,24 @@ private func engineShowing(_ document: TranscriptDocument, width: CGFloat = 375) #expect(engine.backgroundLayoutCount == 0) } +@Test func aDrainThatIsAlreadyScheduledLeavesAReplacementToTheCallingThread() { + let (engine, _) = engineShowing(MarkdownStreamParser.document(from: shortAnswer)) + let queued = MarkdownStreamParser.document(from: shortAnswer + "\n\nMore text.") + let new = MarkdownStreamParser.document(from: otherAnswer) + // Holds the queue, so the drain that the first request schedules runs + // after the replacement is submitted. + let gate = DispatchSemaphore(value: 0) + engine.queue.async { gate.wait() } + engine.submit(.init(document: queued, source: 0, sequence: 2, isFinished: true)) + engine.submit(.init(document: new, source: 0, sequence: 3, isFinished: true), schedulesLayout: false) + gate.signal() + let result = engine.relayout(width: 375, style: .init()) + #expect(result?.layout.document == new) + engine.drainNow() + #expect(engine.takeOutput() == nil) + #expect(engine.backgroundLayoutCount == 0) +} + @Test func anAppendAfterAReplacementBuildsOnIt() { let (engine, _) = engineShowing(MarkdownStreamParser.document(from: shortAnswer)) let new = MarkdownStreamParser.document(from: String(otherAnswer.prefix(80))) From 8ad2ec0fc3fed20c2b71d801fe7d772089a3c045 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:14:11 -0800 Subject: [PATCH 7/8] Stop a running crossfade with the key that Core Animation uses Core Animation keeps every CATransition under the key kCATransition, whatever key the add call gets. The view added the fade under its own key, so the remove calls did not find it. A zero-duration replacement, a background install that is not an append, and a replacement out of the window then left the old fade on the canvas. The text from before the first replacement showed over the new text until that fade ended. The view now adds and removes the fade with kCATransition. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/iOS/TranscriptTextView.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index dbfeeef..78eafa6 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -826,7 +826,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD canvas.layer.add(transition, forKey: Self.crossfadeKey) } - private static let crossfadeKey = "replacement" + /// Core Animation keeps a `CATransition` under this key, whatever key + /// `add(_:forKey:)` gets. + private static let crossfadeKey = kCATransition /// Puts `layout` on screen. /// From fbde058d03d53a4e9de998b1796f96dd5c568a39 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:17:53 -0800 Subject: [PATCH 8/8] Clip the drawing to the view while a replaced document crossfades The crossfade shows the old drawing until it ends. When the new text is shorter, the view gets its new height at once, but the old text showed below the view, over the content that follows it. When the view grows in an animation, the new text showed below the view too. The canvas is now in a container view. While a crossfade plays, the container clips to the bounds, widened by the space that tags' shapes may draw in. The clip ends with the crossfade, or when the view stops the crossfade or leaves the window. Outside a crossfade, nothing is clipped, as before. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +-- .../iOS/TranscriptTextView.swift | 55 +++++++++++++++++-- 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index aa3bbd2..701235d 100644 --- a/README.md +++ b/README.md @@ -212,10 +212,11 @@ TranscriptText(showsSummary ? summary : details) The view then lays out the new document on the main thread in the same SwiftUI update, so SwiftUI gets the new height at once. The old drawing crossfades to the new one, as a `UITextView` does in a `.transitionCrossDissolve` -transition. A duration of zero shows the new text at once. A document that only adds text to the one before (the -same blocks with more text, or more blocks) still goes to the background, and so do the updates of a stream. The -crossfade has no motion, so it also plays with Reduce Motion. In UIKit, set `replacementCrossfadeDuration` on -`TranscriptTextView`. +transition. While the crossfade plays, the drawing is clipped to the view's bounds and the space that tags' shapes +may draw in, so the old text does not show below a view that got shorter. A duration of zero shows the new text at +once. A document that only adds text to the one before (the same blocks with more text, or more blocks) still goes +to the background, and so do the updates of a stream. The crossfade has no motion, so it also plays with Reduce +Motion. In UIKit, set `replacementCrossfadeDuration` on `TranscriptTextView`. Block ids decide what adds to the text. A summary that is the start of its details, parsed with the same id prefix, gives the details the ids of the summary's blocks, so the switch to the details only adds text: it goes to the diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 78eafa6..b9c5c39 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -89,7 +89,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// `intrinsicContentSize` then give the new height in the same update. /// The old drawing crossfades to the new one, as /// `UIView.transition(with:duration:options:animations:)` does with - /// `.transitionCrossDissolve`. Zero shows the new text at once. + /// `.transitionCrossDissolve`. Zero shows the new text at once. While + /// the crossfade plays, the drawing is clipped to the view's bounds and + /// the space that tags' shapes may draw in (see + /// `TranscriptPath.maximumOverhang`), so the old text does not show + /// below a view that got shorter. A new replacement, a replacement with + /// zero, and a new document from the background that does not add to + /// the text stop a crossfade that plays. /// /// Text that only grows, and the updates of a `stream`, keep the /// background path. A new document that starts with the blocks of the @@ -239,6 +245,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Holds the tiles, and the tail layer above them, below the system's /// selection views. private let canvas = UIView() + /// Holds the canvas, in the coordinates of this view. While a replaced + /// document crossfades, it clips the canvas to the bounds and the space + /// that tags' shapes may draw in, so that the old drawing does not show + /// outside the view's new height. + private let canvasClip = UIView() + /// Counts the crossfades, so that the end of an old one does not stop + /// the clip of a newer one. + private var crossfadeCount = 0 /// Shows the end of the document while text is being appended: a /// surface the layout queue drew (see `TailRenderer`). The tiles draw /// only above its top. @@ -369,7 +383,10 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD isOpaque = false canvas.isUserInteractionEnabled = false canvas.backgroundColor = .clear - addSubview(canvas) + canvasClip.isUserInteractionEnabled = false + canvasClip.backgroundColor = .clear + canvasClip.addSubview(canvas) + addSubview(canvasClip) tailLayer.isHidden = true tailLayer.zPosition = 1 tailLayer.actions = ["contents": NSNull(), "position": NSNull(), "bounds": NSNull(), "hidden": NSNull()] @@ -460,6 +477,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD updateAnimationsEnabled() updateFadeDuration() guard window != nil else { + stopCrossfade() handTailToTiles() releaseTiles() return @@ -777,7 +795,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return } let isAppend = output.isAppend && output.base != nil && output.base === installed - if !isAppend { canvas.layer.removeAnimation(forKey: Self.crossfadeKey) } + if !isAppend { stopCrossfade() } install(output.layout, changedTop: isAppend ? output.changedTop : nil, tail: output.tail, restyled: isAppend ? output.restyled : [], started: output.started, waiting: output.waiting, fade: isAppend ? output.fade : nil, fadingFrom: output.hidden.fadingFrom, isFinished: output.isFinished) @@ -813,7 +831,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let signpost = replacementSignposter.beginInterval("Replace document") relayoutNow() replacementSignposter.endInterval("Replace document", signpost) - canvas.layer.removeAnimation(forKey: Self.crossfadeKey) + stopCrossfade() guard installed !== shown, duration > 0, window != nil else { return } // The render server fades from the canvas as the last commit showed // it to the canvas as this commit shows it, with the tiles that the @@ -823,9 +841,21 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD transition.type = .fade transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + let count = crossfadeCount + transition.delegate = CrossfadeEnd { [weak self] in + guard let self, self.crossfadeCount == count else { return } + self.canvasClip.clipsToBounds = false + } + canvasClip.clipsToBounds = true canvas.layer.add(transition, forKey: Self.crossfadeKey) } + private func stopCrossfade() { + canvas.layer.removeAnimation(forKey: Self.crossfadeKey) + crossfadeCount += 1 + canvasClip.clipsToBounds = false + } + /// Core Animation keeps a `CATransition` under this key, whatever key /// `add(_:forKey:)` gets. private static let crossfadeKey = kCATransition @@ -1235,6 +1265,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public override func layoutSubviews() { super.layoutSubviews() + let clip = bounds.insetBy(dx: -TranscriptPath.maximumSideOverhang, dy: -TranscriptPath.maximumOverhang) + canvasClip.frame = clip + canvasClip.bounds = clip canvas.frame = bounds animationLayer.frame = canvas.bounds fadeLayer.frame = canvas.bounds @@ -1549,6 +1582,20 @@ private final class CanvasView: UIView { } } +/// Runs an action when a crossfade ends or is removed. +@MainActor +private final class CrossfadeEnd: NSObject, CAAnimationDelegate { + private let action: @MainActor () -> Void + + init(_ action: @escaping @MainActor () -> Void) { + self.action = action + } + + nonisolated func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { + MainActor.assumeIsolated { action() } + } +} + // MARK: - Position, range and selection rect types final class TranscriptTextPosition: UITextPosition {