diff --git a/Demo/TranscriptDemo/DemoApp.swift b/Demo/TranscriptDemo/DemoApp.swift index a1cd484..79ef915 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() + } } } } @@ -213,6 +217,74 @@ 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. 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 { + 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)") + if animatesSwap { + withAnimation(.easeInOut(duration: 0.6)) { showsLong.toggle() } + } else { + 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. diff --git a/README.md b/README.md index e4a2c80..5deee28 100644 --- a/README.md +++ b/README.md @@ -267,6 +267,36 @@ 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. 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 +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/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 8795d4c..8beb8d0 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 @@ -94,6 +95,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 @@ -235,6 +238,7 @@ final class LayoutEngine: @unchecked Sendable { lock.withLock { isShutDown = true pending = nil + pendingIsForMain = false mailbox = nil onOutput = nil } @@ -252,8 +256,13 @@ 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, also when a drain is already + /// scheduled. @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 } @@ -265,7 +274,8 @@ final class LayoutEngine: @unchecked Sendable { guard request.sequence > lastSequence else { return nil } lastSequence = request.sequence pending = request - if drainScheduled { return nil } + pendingIsForMain = !schedulesLayout + if drainScheduled || !schedulesLayout { return nil } drainScheduled = true return max(lastDrain + frameInterval - CACurrentMediaTime(), 0) } @@ -282,7 +292,10 @@ final class LayoutEngine: @unchecked Sendable { private func takePending() -> Request? { lock.withLock { () -> Request? in - defer { pending = nil } + defer { + pending = nil + pendingIsForMain = false + } return pending } } @@ -301,7 +314,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 1c9607f..47c86ca 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) @@ -25,6 +26,7 @@ public struct TranscriptText: UIViewRepresentable { private var mathAccessibilityLabel: ((TranscriptMath) -> String)? private var animatesTags = true private var textFadeInDuration: TimeInterval? + private var replacementCrossfadeDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately private var animatesFirstText = false private var isSelectable = true @@ -109,6 +111,25 @@ 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. 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) + /// .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 { @@ -213,6 +234,7 @@ public struct TranscriptText: UIViewRepresentable { view.animatesTags = animatesTags view.animatesTagsInFirstText = animatesFirstText 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 0480dda..8d2dc69 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -9,6 +9,9 @@ private let animationLog = Logger(subsystem: "TranscriptKit", category: "TagAnim private let animationSignposter = OSSignposter(subsystem: "TranscriptKit", category: .pointsOfInterest) /// Where a block that scrolls sideways stops, at the debug level, like `animationLog`. private let sideScrollLog = Logger(subsystem: "TranscriptKit", category: "SideScroll") +/// 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. @@ -19,6 +22,8 @@ private let sideScrollLog = Logger(subsystem: "TranscriptKit", category: "SideSc /// 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 @@ -52,8 +57,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 @@ -61,12 +69,50 @@ 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. 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 + /// 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 + /// 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? { @@ -76,7 +122,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 @@ -283,6 +330,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. @@ -435,7 +490,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()] @@ -749,6 +807,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD stopSideDeceleration() finishAllAnimations() if !WaitingTags.keepWaitingOutsideWindow(tagAnimationTiming) { showWaitingTagsAtRest() } + stopCrossfade() handTailToTiles() releaseTiles() return @@ -1093,6 +1152,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return } let isAppend = output.isAppend && output.base != nil && output.base === installed + 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) @@ -1132,6 +1192,42 @@ 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) + 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 + // 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 + 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 + /// Puts `layout` on screen. /// /// - Parameter changedTop: the layout only added content at the end of @@ -1621,6 +1717,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 @@ -2015,6 +2114,20 @@ private final class SideScrollFrameTarget: NSObject { } } +/// 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 // These never change once made, so their getters are `nonisolated`: the diff --git a/Tests/TranscriptKitTests/ReplacementTests.swift b/Tests/TranscriptKitTests/ReplacementTests.swift new file mode 100644 index 0000000..ad4a715 --- /dev/null +++ b/Tests/TranscriptKitTests/ReplacementTests.swift @@ -0,0 +1,171 @@ +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 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")]) + #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 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))) + 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") + } +}