diff --git a/README.md b/README.md index 87f545a..a1b318e 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut link, padding, and shapes drawn behind or over the text. Pills and underlines (solid, dashed, dotted, wavy, marker) are built in, and you can draw shapes of your own, and animate a tag's letters and shapes when it finishes arriving. +- **Fade-in.** Optionally, text fades in as it streams in. Core Animation plays the fades. - **SwiftUI and UIKit.** `TranscriptText` for SwiftUI, `TranscriptTextView` for UIKit. ## Requirements @@ -177,6 +178,21 @@ In UIKit, set `tagAnimationTiming` on `TranscriptTextView` and call `playTagAnim waiting when it can no longer play (Reduce Motion turned on, animations turned off, the view leaving its window, a new document) is shown as it ends up. +### Fading in text + +Text that streams in can fade in. Each update's new text fades in on its own, so the fade follows the text as it +arrives. It is off by default. + +```swift +TranscriptText(stream: stream) + .fadesInText(duration: 0.3) +``` + +In UIKit, set `textFadeInDuration` on `TranscriptTextView`. TranscriptKit draws the new text on the layout queue, +and Core Animation plays each fade, so the main thread does no work for each frame of a fade. Glyphs and their +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. + ### 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/Diagnostics.swift b/Sources/TranscriptKit/Diagnostics.swift index ac9bc1d..c114042 100644 --- a/Sources/TranscriptKit/Diagnostics.swift +++ b/Sources/TranscriptKit/Diagnostics.swift @@ -11,6 +11,8 @@ public enum TranscriptDiagnostics { public var tileDraws = 0 /// Tails drawn on the layout queue (see `TailRenderer`). public var tailFrames = 0 + /// Text fading in, drawn on the layout queue (see `FadeRenderer`). + public var fadeFrames = 0 } private static let lock = NSLock() diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 63c5408..2b72e83 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -165,6 +165,19 @@ public final class DocumentLayout: @unchecked Sendable { lastEntryIndex(where: { CGFloat($0.start) }, isAtMost: CGFloat(offset)) } + /// The lines with text at or after `offset`, in order, with their blocks. + func lines(from offset: Int) -> [(entry: Entry, line: BlockLayout.Line)] { + guard let first = entryIndex(forOffset: offset) else { return [] } + var result: [(entry: Entry, line: BlockLayout.Line)] = [] + for index in first.. offset { + result.append((entry, line)) + } + } + return result + } + public func caretRect(at offset: Int) -> CGRect { guard let index = entryIndex(forOffset: offset) else { return CGRect(x: 0, y: 0, width: 2, height: style.effectiveBodySize * 1.2) @@ -361,37 +374,8 @@ public final class DocumentLayout: @unchecked Sendable { // The glyphs for the characters in `hidden` (the line's string // indexes) are left out. func drawLine(_ line: CTLine, at origin: CGPoint, hidden: [Range] = []) { - let runs = CTLineGetGlyphRuns(line) as! [CTRun] - drawHighlights(runs, at: origin) - for run in runs { - let attributes = CTRunGetAttributes(run) as NSDictionary - if attributes[Self.imageKey] != nil { continue } - Self.setGlyphColor(of: attributes, in: context, text: text, dark: dark) - context.textPosition = origin - if hidden.isEmpty { - CTRunDraw(run, context, CFRange(location: 0, length: 0)) - } else { - for range in Self.glyphRanges(of: run, leavingOut: hidden) { CTRunDraw(run, context, range) } - } - let custom = (attributes[Self.foregroundKey] as? TranscriptColor)?.cgColor(dark: dark) - let strike = attributes[Self.strikethroughKey] != nil - let underline = attributes[Self.underlineKey] != nil - guard strike || underline, let font = attributes[kCTFontAttributeName].map({ $0 as! CTFont }) else { continue } - var position = CGPoint.zero - CTRunGetPositions(run, CFRange(location: 0, length: 1), &position) - let runWidth = CGFloat(CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), nil, nil, nil)) - let color = custom ?? attributes[kCTForegroundColorAttributeName].map { $0 as! CGColor } ?? text - let thickness = max(CTFontGetUnderlineThickness(font), 1) - context.setFillColor(color) - if strike { - let y = origin.y - CTFontGetXHeight(font) / 2 - thickness / 2 - context.fill(CGRect(x: origin.x + position.x, y: y, width: runWidth, height: thickness)) - } - if underline { - let y = origin.y - CTFontGetUnderlinePosition(font) - context.fill(CGRect(x: origin.x + position.x, y: y, width: runWidth, height: thickness)) - } - } + drawHighlights(CTLineGetGlyphRuns(line) as! [CTRun], at: origin) + Self.drawGlyphs(of: line, at: origin, hidden: hidden, in: context, text: text, dark: dark) } func fill(_ rect: CGRect, radius: CGFloat, color: CGColor) { @@ -538,7 +522,10 @@ public final class DocumentLayout: @unchecked Sendable { for index in visible where !lines[index].range.isEmpty { let line = lines[index] - let hidden = line.decorations?.hiddenRanges(hiding.playing) ?? [] + var hidden = line.decorations?.hiddenRanges(hiding.playing) ?? [] + if let from = hiding.fadingFrom, entry.start + line.range.upperBound > from { + hidden.append(max(from - entry.start, line.range.lowerBound)..], in context: CGContext, text: CGColor, dark: Bool) { + for run in CTLineGetGlyphRuns(line) as! [CTRun] { + let attributes = CTRunGetAttributes(run) as NSDictionary + if attributes[imageKey] != nil { continue } + let ranges = hidden.isEmpty ? [CFRange(location: 0, length: 0)] : glyphRanges(of: run, leavingOut: hidden) + guard !ranges.isEmpty else { continue } + setGlyphColor(of: attributes, in: context, text: text, dark: dark) + context.textPosition = origin + for range in ranges { CTRunDraw(run, context, range) } + let custom = (attributes[foregroundKey] as? TranscriptColor)?.cgColor(dark: dark) + let strike = attributes[strikethroughKey] != nil + let underline = attributes[underlineKey] != nil + guard strike || underline, let font = attributes[kCTFontAttributeName].map({ $0 as! CTFont }) else { continue } + let color = custom ?? attributes[kCTForegroundColorAttributeName].map { $0 as! CGColor } ?? text + let thickness = max(CTFontGetUnderlineThickness(font), 1) + context.setFillColor(color) + // Ends on whole pixels, so that a line drawn in two parts (some + // of its text fading in) covers the same pixels as one. + func fill(x: CGFloat, y: CGFloat, width: CGFloat) { + var device = context.convertToDeviceSpace(CGRect(x: x, y: y, width: width, height: thickness)) + let minX = device.minX.rounded() + device.size.width = device.maxX.rounded() - minX + device.origin.x = minX + guard device.width > 0 else { return } + context.fill(context.convertToUserSpace(device)) + } + for range in ranges { + var position = CGPoint.zero + CTRunGetPositions(run, CFRange(location: range.location, length: 1), &position) + let width = CGFloat(CTRunGetTypographicBounds(run, range, nil, nil, nil)) + if strike { fill(x: origin.x + position.x, y: origin.y - CTFontGetXHeight(font) / 2 - thickness / 2, width: width) } + if underline { fill(x: origin.x + position.x, y: origin.y - CTFontGetUnderlinePosition(font), width: width) } + } + } + } + /// The runs of `run`'s glyphs whose characters are not in `hidden`. static func glyphRanges(of run: CTRun, leavingOut hidden: [Range]) -> [CFRange] { let count = CTRunGetGlyphCount(run) diff --git a/Sources/TranscriptKit/Layout/FadeRenderer.swift b/Sources/TranscriptKit/Layout/FadeRenderer.swift new file mode 100644 index 0000000..a77c58d --- /dev/null +++ b/Sources/TranscriptKit/Layout/FadeRenderer.swift @@ -0,0 +1,163 @@ +import CoreGraphics +import CoreText +import Foundation + +/// Text that arrived in one update and fades in from then on. +struct Fade: Sendable { + let id: Int + /// Flat offsets. + let range: Range + /// When it started, in `CACurrentMediaTime()`. + let start: CFTimeInterval +} + +/// The text that is fading in, drawn on the layout queue for the view's fade +/// layers: one piece for each fade on each line, with only that fade's +/// glyphs on it. +struct FadeFrame: @unchecked Sendable { + struct Piece: @unchecked Sendable { + let fade: Int + let start: CFTimeInterval + /// Where it goes, in document points, on whole pixels. + let frame: CGRect + /// The same object as in the last frame while the piece is unchanged, + /// so the view gives Core Animation a new image only when it is new. + let image: CGImage + } + + let pieces: [Piece] + let scale: CGFloat +} + +/// Draws the pieces of the text that fades in. A piece is drawn once and +/// kept while its glyphs stay where they are; the text that fades is laid +/// out again with every update, so a word that wraps or a centered line +/// that moves gets its pieces drawn again. +/// +/// Not thread-safe: use it from one queue (the layout engine's). +final class FadeRenderer { + private struct Placement: Equatable { + let range: Range + let frame: CGRect + let origin: CGPoint + let style: Style + } + + /// What the text's look comes from: text whose style changed in place + /// (code colors arrived, a reference became a link) is drawn again. + private struct Style: Equatable { + let spans: [InlineSpan] + let imageRevision: Int? + let definitions: Int + } + + private struct Drawn { + let placement: Placement + let image: CGImage + } + + /// The pieces drawn last, by fade. + private var drawn: [Int: [Drawn]] = [:] + private var colors: TailRenderer.Colors? + private var scale: CGFloat = 0 + + /// How far a line's glyphs may reach beyond its box: accents, descenders, + /// emoji, italic overhangs. + static func margin(of line: BlockLayout.Line) -> (x: CGFloat, y: CGFloat) { + (8, max(line.frame.height, 8)) + } + + /// - Parameter from: where the text left out of the tail and the tiles + /// starts; the oldest fade may start before it. + func render(_ layout: DocumentLayout, from: Int, fades: [Fade], colors: TailRenderer.Colors, scale: CGFloat, + playing: Set) -> FadeFrame? { + if scale != self.scale || self.colors.map({ $0.text != colors.text || $0.dark != colors.dark }) ?? true { + drawn.removeAll() + self.colors = colors + self.scale = scale + } + let live = Set(fades.map(\.id)) + drawn = drawn.filter { live.contains($0.key) } + guard !fades.isEmpty, from < layout.length, scale > 0 else { return nil } + func pixel(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { (value * scale).rounded(rule) / scale } + + let lines = layout.lines(from: from) + let rightToLeft = lines.map { Self.hasRightToLeftText($0.line.ctLine) } + let definitions = layout.document.linkDefinitions.count + var pieces: [FadeFrame.Piece] = [] + for fade in fades { + let previous = drawn[fade.id] ?? [] + var current: [Drawn] = [] + for (index, (entry, line)) in lines.enumerated() { + let lineStart = entry.start + line.range.lowerBound + let lineEnd = entry.start + line.range.upperBound + let lower = max(fade.range.lowerBound, lineStart, from) + let upper = min(fade.range.upperBound, lineEnd) + guard lower < upper else { continue } + let range = lower.. range.lowerBound - entry.start + }, imageRevision: entry.layout.imageRevision, definitions: definitions)) + let image: CGImage + if current.count < previous.count, previous[current.count].placement == placement { + image = previous[current.count].image + } else { + var hidden = line.decorations?.hiddenRanges(playing) ?? [] + let local = (range.lowerBound - entry.start)..<(range.upperBound - entry.start) + if local.lowerBound > line.range.lowerBound { hidden.append(line.range.lowerBound..], + colors: TailRenderer.Colors, scale: CGFloat) -> CGImage? { + let width = Int((frame.width * scale).rounded()) + let height = Int((frame.height * scale).rounded()) + guard width > 0, height > 0, let space = CGColorSpace(name: CGColorSpace.sRGB), + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: space, + bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) + else { return nil } + // Top-left origin, in document points. + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: scale, y: -scale) + context.translateBy(x: -frame.minX, y: -frame.minY) + context.textMatrix = CGAffineTransform(scaleX: 1, y: -1) + DocumentLayout.drawGlyphs(of: line.ctLine, at: origin, + hidden: hidden.map { ($0.lowerBound - line.indexBase)..<($0.upperBound - line.indexBase) }, + in: context, text: colors.text, dark: colors.dark) + return context.makeImage() + } + + private static func hasRightToLeftText(_ line: CTLine) -> Bool { + (CTLineGetGlyphRuns(line) as! [CTRun]).contains { CTRunGetStatus($0).contains(.rightToLeft) } + } +} diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 9071a53..4cf780d 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -58,6 +58,9 @@ final class LayoutEngine: @unchecked Sendable { var waiting: [TagKey] = [] /// How `tail` was drawn: which tags it left out, and how far. var hidden: TagHiding = .none + /// The text that is fading in, from `hidden.fadingFrom` on, which + /// `tail` leaves out. + var fade: FadeFrame? /// The request's `isFinished`. var isFinished = false @@ -69,7 +72,7 @@ final class LayoutEngine: @unchecked Sendable { isAppend: earlier.isAppend && later.isAppend, changedTop: top, restyled: earlier.restyled + later.restyled, tail: later.tail, started: earlier.started + later.started, waiting: earlier.waiting + later.waiting, - hidden: later.hidden, isFinished: later.isFinished) + hidden: later.hidden, fade: later.fade, isFinished: later.isFinished) } } @@ -100,8 +103,17 @@ final class LayoutEngine: @unchecked Sendable { private var animationsEnabled = false /// Whether they start as soon as they close, or wait for the view. private var startsImmediately = true - /// Tags whose animations play, or wait to: the tail is drawn without them. + /// Tags whose animations play, or wait to, and text that fades in: the + /// tail is drawn without them. private var hiding = TagHiding() + /// How long appended text takes to fade in, or nil for no fade. + private var fadeDuration: CFTimeInterval? + /// Appended text from `hiding.fadingFrom` on, oldest first: still fading + /// in, or done but on the line the oldest still fades on. + private var fades: [Fade] = [] + private var lastFadeID = 0 + /// The fades' clock. Tests set their own. + var clock: @Sendable () -> CFTimeInterval = { CACurrentMediaTime() } // Only touched on `queue`. private var latestDocument = TranscriptDocument() @@ -115,6 +127,7 @@ final class LayoutEngine: @unchecked Sendable { /// Layouts made in the background, for tests. private var backgroundLayouts = 0 private var tailRenderer: TailRenderer? + private let fadeRenderer = FadeRenderer() private var tailRendererGeneration = -1 /// Text is being appended, so each output gets a drawn tail. private var tailActive = false @@ -144,6 +157,23 @@ final class LayoutEngine: @unchecked Sendable { } } + /// How long text appended from now on takes to fade in, or nil for no + /// fade. Any thread. + func setFadeDuration(_ duration: CFTimeInterval?) { + lock.withLock { fadeDuration = duration.flatMap { $0 > 0 ? $0 : nil } } + } + + /// Ends every fade, for when the view draws the text at rest. Returns + /// where the fading text started, if any did. Any thread. + func endFades() -> Int? { + lock.withLock { + let from = hiding.fadingFrom + fades.removeAll() + hiding.fadingFrom = nil + return from + } + } + /// The view has started these waiting tags' animations: tails leave /// them out entirely. Any thread. func playAnimations(_ keys: some Sequence) { @@ -290,16 +320,105 @@ final class LayoutEngine: @unchecked Sendable { } } } + let (fading, moved) = updateFades(layout: layout, appendedTo: isAppend ? previous : nil, tagsStarted: !started.isEmpty) + if let moved { restyled.append(insideTail(moved)) } let hidden = lock.withLock { hiding } let tail = drawTail(of: layout, changedTop: changedTop, restyled: restyled, hiding: hidden) + var fade: FadeFrame? + if !fading.isEmpty, let from = hidden.fadingFrom, let style = lock.withLock({ tailStyle }) { + fade = fadeRenderer.render(layout, from: from, fades: fading, colors: style.colors, scale: style.scale, playing: hidden.playing) + TranscriptDiagnostics.count(\.fadeFrames) + } post(Output(layout: layout, source: request.source, base: previous, isAppend: isAppend, changedTop: changedTop, - restyled: restyled, tail: tail, started: started, waiting: waiting, hidden: hidden, + restyled: restyled, tail: tail, started: started, waiting: waiting, hidden: hidden, fade: fade, isFinished: request.isFinished)) } + /// Starts a fade for the text that `layout` appends to `previous`, and + /// moves the frontier to the start of the line that the oldest fade still + /// in progress is on: a line is drawn again once, when all of its text is + /// done, not once for each fade. The fades done before then stay, at + /// full opacity. A tag that starts its animation ends them all, and its + /// update does not fade: the animation draws the tag's letters, which a + /// fade would draw too. + /// + /// - Returns: the fades in flight, and the rows to draw again because + /// text there stopped fading. + private func updateFades(layout: DocumentLayout, appendedTo previous: DocumentLayout?, + tagsStarted: Bool) -> (fades: [Fade], moved: (rect: CGRect, lineTop: CGFloat)?) { + let now = clock() + let (old, new, fading): (Int?, Int?, [Fade]) = lock.withLock { + let old = hiding.fadingFrom + var new: Int? + if let duration = fadeDuration, tailStyle != nil, let previous { + if tagsStarted { + fades.removeAll() + } else if layout.length > previous.length { + lastFadeID += 1 + fades.append(Fade(id: lastFadeID, range: previous.length.. now })?.range.lowerBound { + let lineStart = layout.lines(from: oldest).first.map { $0.entry.start + $0.line.range.lowerBound } ?? oldest + new = old.map { max($0, min(lineStart, oldest)) } ?? oldest + } + } + if let new { + fades.removeAll { $0.range.upperBound <= new } + } else { + fades.removeAll() + } + hiding.fadingFrom = new + return (old, new, fades) + } + guard let old, old != new, old < layout.length else { return (fading, nil) } + // The lines of the text that stopped fading. In a table they are not + // in order of y. + let end = new ?? layout.length + var band: CGRect? + var margin: CGFloat = 0 + for (entry, line) in layout.lines(from: old) where entry.start + line.range.lowerBound < end { + let frame = line.frame.offsetBy(dx: 0, dy: entry.y) + band = band.map { $0.union(frame) } ?? frame + margin = max(margin, FadeRenderer.margin(of: line).y) + } + guard let band else { return (fading, nil) } + return (fading, (CGRect(x: 0, y: band.minY - margin, width: layout.width, height: band.height + 2 * margin), band.minY)) + } + + /// The rows to draw again for text that stopped fading. When its lines + /// are in the tail, the band starts no higher than the tail, so the tail + /// alone draws it, off the main thread; the tiles do not redraw glyphs + /// that reach above their line either when text is appended. + private func insideTail(_ moved: (rect: CGRect, lineTop: CGFloat)) -> CGRect { + guard tailActive, let top = tailRenderer?.top, moved.lineTop >= top, moved.rect.minY < top else { return moved.rect } + return CGRect(x: moved.rect.minX, y: top, width: moved.rect.width, height: moved.rect.maxY - top) + } + + /// Ends the fades whose time is up and draws their rows again, as an + /// update that adds no text, for when updates have stopped. The tail + /// stays in use. Any thread; the result comes like any other. + func settleFinishedFades() { + queue.async { [self] in + guard let layout = base, width > 0, layout.width == width else { return } + let (fading, band) = updateFades(layout: layout, appendedTo: layout, tagsStarted: false) + guard let band else { return } + let moved = insideTail(band) + let hidden = lock.withLock { hiding } + let tail = tailActive ? drawTail(of: layout, changedTop: layout.height, restyled: [moved], hiding: hidden) : nil + var fade: FadeFrame? + if !fading.isEmpty, let from = hidden.fadingFrom, let style = lock.withLock({ tailStyle }) { + fade = fadeRenderer.render(layout, from: from, fades: fading, colors: style.colors, scale: style.scale, playing: hidden.playing) + TranscriptDiagnostics.count(\.fadeFrames) + } + post(Output(layout: layout, source: latestSource, base: layout, isAppend: true, changedTop: layout.height, + restyled: [moved], tail: tail, hidden: hidden, fade: fade, isFinished: latestFinished)) + } + } + /// Draws `layout`'s tail if text is being appended. The first append /// starts the tail; it stays on for every output until settled. private func drawTail(of layout: DocumentLayout, changedTop: CGFloat?, restyled: [CGRect], hiding: TagHiding) -> TailRenderer.Frame? { + let fadingTop = hiding.fadingFrom.flatMap { layout.lines(from: $0).first }.map { $0.entry.y + $0.line.inkTop } guard let style = lock.withLock({ tailStyle }) else { tailActive = false return nil @@ -315,7 +434,7 @@ final class LayoutEngine: @unchecked Sendable { } if changedTop != nil { tailActive = true } guard tailActive, let tailRenderer else { return nil } - guard let frame = tailRenderer.render(layout, changedTop: changedTop, restyled: restyled, hiding: hiding) else { + guard let frame = tailRenderer.render(layout, changedTop: changedTop, restyled: restyled, hiding: hiding, fadingTop: fadingTop) else { // No surface free: the view draws the tail itself until the next append. tailActive = false tailRenderer.reset() @@ -359,13 +478,20 @@ final class LayoutEngine: @unchecked Sendable { /// Lays out the newest document at `width` now and makes it the base for /// what follows. Anything waiting in the mailbox is older and dropped. - func relayout(width: CGFloat, style: TranscriptStyle) -> (layout: DocumentLayout, source: Int, isFinished: Bool)? { + /// + /// - Parameter keepingFades: text that fades in goes on fading if it is + /// where it was, as after the image store changed; the result says + /// where it starts. Otherwise the fades end. + func relayout(width: CGFloat, style: TranscriptStyle, keepingFades: Bool = false) + -> (layout: DocumentLayout, source: Int, isFinished: Bool, fadingFrom: Int?)? { queue.sync { if let request = takePending() { latestDocument = request.document latestSource = request.source latestFinished = request.isFinished } + let previous = base + let sameGeometry = width == self.width && style == self.style self.width = width self.style = style guard width > 0 else { return nil } @@ -378,11 +504,19 @@ final class LayoutEngine: @unchecked Sendable { // every tag at rest after a relayout. tailActive = false tailRenderer?.reset() + var kept: Int? + if keepingFades, sameGeometry, let previous, let from = lock.withLock({ hiding.fadingFrom }), + from <= previous.length, layout.document.extends(previous.document), + layout.caretRect(at: from) == previous.caretRect(at: from), + layout.caretRect(at: previous.length) == previous.caretRect(at: previous.length) { + kept = from + } lock.withLock { mailbox = nil - hiding = TagHiding() + hiding = TagHiding(fadingFrom: kept) + if kept == nil { fades.removeAll() } } - return (layout, latestSource, latestFinished) + return (layout, latestSource, latestFinished, kept) } } diff --git a/Sources/TranscriptKit/Layout/TagDecorations.swift b/Sources/TranscriptKit/Layout/TagDecorations.swift index a51052b..3514f98 100644 --- a/Sources/TranscriptKit/Layout/TagDecorations.swift +++ b/Sources/TranscriptKit/Layout/TagDecorations.swift @@ -94,10 +94,13 @@ struct TagHiding: Equatable, Sendable { var playing: Set = [] /// Waiting to play: shown as text, so their shapes are left out. var waiting: Set = [] + /// Text from this flat offset on is fading in, drawn by the view's fade + /// layers: its glyphs are left out. + var fadingFrom: Int? static let none = TagHiding() - var isEmpty: Bool { playing.isEmpty && waiting.isEmpty } + var isEmpty: Bool { playing.isEmpty && waiting.isEmpty && fadingFrom == nil } func hidesShapes(of key: TagKey) -> Bool { playing.contains(key) || waiting.contains(key) diff --git a/Sources/TranscriptKit/Layout/TailRenderer.swift b/Sources/TranscriptKit/Layout/TailRenderer.swift index a44dc2d..42566d6 100644 --- a/Sources/TranscriptKit/Layout/TailRenderer.swift +++ b/Sources/TranscriptKit/Layout/TailRenderer.swift @@ -109,7 +109,11 @@ final class TailRenderer { /// place; the parts of them inside the tail are drawn again. /// - Parameter hiding: animated tags playing their animation, which the /// view draws itself; see `DocumentLayout.draw`. - func render(_ layout: DocumentLayout, changedTop: CGFloat?, restyled: [CGRect] = [], hiding: TagHiding = .none) -> Frame? { + /// - Parameter fadingTop: the top of the text that fades in. A strip that + /// moves down starts no lower, while it can hold the text, so the tail + /// and not the tiles draws that text when it stops fading. + func render(_ layout: DocumentLayout, changedTop: CGFloat?, restyled: [CGRect] = [], hiding: TagHiding = .none, + fadingTop: CGFloat? = nil) -> Frame? { if layout.width != width || context == nil { guard makeContext(width: layout.width) else { return nil } top = nil @@ -125,7 +129,12 @@ final class TailRenderer { start = changedTop for rect in restyled where rect.maxY > top { start = min(start, max(rect.minY, top)) } } else { - currentTop = Self.lastLineTop(of: layout, scale: scale) + var newTop = Self.lastLineTop(of: layout, scale: scale) + if let fadingTop { + let fits = ((layout.height - Self.height + Self.margin) * scale).rounded(.up) / scale + newTop = min(newTop, max((max(fadingTop, 0) * scale).rounded(.down) / scale, fits)) + } + currentTop = newTop start = currentTop drawnBottom = currentTop + Self.height fullCopyFrom = frame + 1 diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 83ccba0..44ab601 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -22,6 +22,7 @@ public struct TranscriptText: UIViewRepresentable { private var highlighter: TranscriptCodeHighlighter? private var mathRenderer: TranscriptMathRenderer? private var animatesTags = true + private var textFadeInDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately private var isSelectable = true private var playTrigger: AnyHashable? @@ -76,6 +77,13 @@ public struct TranscriptText: UIViewRepresentable { return copy } + /// Fades in text as it streams in; see `TranscriptTextView.textFadeInDuration`. + public func fadesInText(_ fades: Bool = true, duration: TimeInterval = 0.3) -> TranscriptText { + var copy = self + copy.textFadeInDuration = fades ? 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 { @@ -157,6 +165,7 @@ public struct TranscriptText: UIViewRepresentable { } view.style = style view.animatesTags = animatesTags + view.textFadeInDuration = textFadeInDuration view.tagAnimationTiming = animationTiming view.isSelectable = isSelectable if playTrigger != context.coordinator.playTrigger { diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 45c857d..e1ee784 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -95,6 +95,19 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD guard style != oldValue else { return } relayoutNow() updateTailStyle() + updateFadeDuration() + } + } + + /// How long text takes to fade in as it streams in, or nil to show it at + /// once (the default). Each update's new text fades in on its own, so the + /// fade follows the text as it arrives. Core Animation plays the fades; + /// the text is drawn on the layout queue. Off with Reduce Motion and + /// with a line limit. + public var textFadeInDuration: TimeInterval? { + didSet { + guard textFadeInDuration != oldValue else { return } + updateFadeDuration() } } @@ -139,7 +152,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD didSet { engine.images.setLoader(imageLoader) { [weak self] in DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow() } + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } } relayoutNow() @@ -155,7 +168,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD didSet { engine.images.setOnChange { [weak self] in DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow() } + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } } engine.images.setHighlighter(codeHighlighter) @@ -173,7 +186,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD didSet { engine.images.setOnChange { [weak self] in DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow() } + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } } engine.images.setMathRenderer(mathRenderer) @@ -252,6 +265,15 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private let emptyInputView = UIView() /// Holds the layers of tags' animations, above the tail layer. private let animationLayer = CALayer() + /// Holds the text that fades in, above the tail layer. + private let fadeLayer = CALayer() + /// Each fade's layers, one for each line it is on, by fade. + private var fadeLayers: [Int: [CALayer]] = [:] + /// Text from this flat offset on fades in, so the tiles leave it out. + private var fadingFrom: Int? + /// When the newest fade on screen ends. + private var fadesEnd: CFTimeInterval = 0 + private var fadeSettleScheduled = false /// Tags whose animations are playing, which the tiles leave out. private var playing: [TagKey: PlayingTag] = [:] private var playingKeys: Set = [] @@ -265,7 +287,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private var waitingCheckScheduled = false /// The last layout passed over for coming from a replaced source. private var skippedOutput: LayoutEngine.Output? - private var hiding: TagHiding { TagHiding(playing: playingKeys, waiting: waiting) } + private var hiding: TagHiding { TagHiding(playing: playingKeys, waiting: waiting, fadingFrom: fadingFrom) } private struct PlayingTag { let tag: AnimatedTag @@ -307,6 +329,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD tailLayer.zPosition = 1 tailLayer.actions = ["contents": NSNull(), "position": NSNull(), "bounds": NSNull(), "hidden": NSNull()] canvas.layer.addSublayer(tailLayer) + fadeLayer.zPosition = 1.5 + fadeLayer.actions = ["bounds": NSNull(), "position": NSNull(), "sublayers": NSNull()] + canvas.layer.addSublayer(fadeLayer) animationLayer.zPosition = 2 animationLayer.actions = ["bounds": NSNull(), "position": NSNull(), "sublayers": NSNull()] canvas.layer.addSublayer(animationLayer) @@ -328,6 +353,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD // starts again, in them too, with the next append. Animations, // drawn in the old ones, end. view.finishAllAnimations() + view.settleFades() view.updateTailStyle() view.handTailToTiles() view.tiles.values.forEach { $0.setNeedsDisplay() } @@ -369,6 +395,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD scrollObservation = nil updateTailStyle() updateAnimationsEnabled() + updateFadeDuration() guard window != nil else { handTailToTiles() releaseTiles() @@ -645,7 +672,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let isAppend = output.isAppend && output.base != nil && output.base === installed install(output.layout, changedTop: isAppend ? output.changedTop : nil, tail: output.tail, restyled: isAppend ? output.restyled : [], started: output.started, waiting: output.waiting, - isFinished: output.isFinished) + fade: isAppend ? output.fade : nil, fadingFrom: output.hidden.fadingFrom, isFinished: output.isFinished) // A tail drawn while a tag was in another state than it is now (its // animation has started or ended since): the tiles draw that part. if output.tail != nil, output.hidden != hiding { @@ -655,11 +682,16 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Lays out synchronously, for when the view cannot wait for the /// background: no layout on screen yet, or a new width or style. - private func relayoutNow() { - guard bounds.width > 0, let result = engine.relayout(width: bounds.width, style: style) else { return } + /// + /// - Parameter keepingFades: text that fades in goes on fading if the + /// new layout leaves it where it was: an image arrived, or a code + /// block's colors. + private func relayoutNow(keepingFades: Bool = false) { + guard bounds.width > 0, + let result = engine.relayout(width: bounds.width, style: style, keepingFades: keepingFades) else { return } skippedOutput = nil guard result.source == source else { return } - install(result.layout, changedTop: nil, tail: nil, isFinished: result.isFinished) + install(result.layout, changedTop: nil, tail: nil, keptFadingFrom: result.fadingFrom, isFinished: result.isFinished) } private func layOutNowIfNothingIsShown() { @@ -685,13 +717,25 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// - Parameter waiting: animated tags that closed in this update and /// wait for `tagAnimationTiming` to let them play. /// - Parameter isFinished: no more text is coming. + /// - Parameter fade: with `changedTop`, the text fading in, from + /// `fadingFrom` on, which the tail and the tiles leave out. private func install(_ layout: DocumentLayout, changedTop: CGFloat?, tail: TailRenderer.Frame?, restyled: [CGRect] = [], - started: [TagKey] = [], waiting newlyWaiting: [TagKey] = [], isFinished: Bool = false) { + started: [TagKey] = [], waiting newlyWaiting: [TagKey] = [], fade: FadeFrame? = nil, fadingFrom: Int? = nil, + keptFadingFrom: Int? = nil, isFinished: Bool = false) { self.isFinished = isFinished TranscriptDiagnostics.count(\.installs) let old = installed let isAppend = changedTop != nil && old != nil if !isAppend { inputDelegate?.textWillChange(self) } + if isAppend { + self.fadingFrom = fadingFrom + } else if let keptFadingFrom { + // Laid out again with the fading text where it was: its layers stay. + self.fadingFrom = keptFadingFrom + } else { + if self.fadingFrom != nil || !fadeLayers.isEmpty { _ = engine.endFades() } + self.fadingFrom = nil + } installed = layout if let current = selection { let length = layout.length @@ -729,6 +773,12 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD updateCanvas(forceRedraw: true) } + if isAppend { + showFades(fade) + } else if keptFadingFrom == nil { + removeFades() + } + if isAppend { // A playing tag whose glyphs moved (its line wrapped otherwise) // ends where it is. @@ -750,10 +800,123 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + // MARK: Fades + + private func updateFadeDuration() { + let enabled = window != nil && !UIAccessibility.isReduceMotionEnabled && style.lineLimit == nil + engine.setFadeDuration(enabled ? textFadeInDuration : nil) + if !enabled { settleFades() } + } + + /// Puts each fade's pieces in its layers, in the same transaction as the + /// tail and the tiles that leave the text out. A fade's layers keep the + /// animation they started with when their pieces move. + private func showFades(_ frame: FadeFrame?) { + guard let frame, let duration = textFadeInDuration else { + removeFades() + return + } + var pieces: [Int: [FadeFrame.Piece]] = [:] + for piece in frame.pieces { pieces[piece.fade, default: []].append(piece) } + for (id, layers) in fadeLayers where pieces[id] == nil { + layers.forEach { $0.removeFromSuperlayer() } + fadeLayers[id] = nil + } + for (id, fadePieces) in pieces { + var layers = fadeLayers[id] ?? [] + while layers.count > fadePieces.count { layers.removeLast().removeFromSuperlayer() } + for (index, piece) in fadePieces.enumerated() { + let layer: CALayer + if index < layers.count { + layer = layers[index] + } else { + layer = TagAnimationPlayer.StillLayer() + let animation = CABasicAnimation(keyPath: "opacity") + animation.fromValue = 0 + animation.toValue = 1 + animation.beginTime = piece.start + animation.duration = duration + animation.timingFunction = CAMediaTimingFunction(name: .easeOut) + animation.fillMode = .backwards + layer.add(animation, forKey: "fade") + fadeLayer.addSublayer(layer) + layers.append(layer) + } + // A new image costs Core Animation a copy on this thread; an unchanged one, nothing. + if layer.contents.map({ ($0 as AnyObject) !== piece.image }) ?? true { layer.contents = piece.image } + if layer.contentsScale != frame.scale { layer.contentsScale = frame.scale } + if layer.frame != piece.frame { layer.frame = piece.frame } + } + fadeLayers[id] = layers + fadesEnd = max(fadesEnd, (fadePieces.first?.start ?? 0) + duration) + } + if !fadeLayers.isEmpty { scheduleFadeSettling() } + } + + /// Draws the faded text at rest once the newest fade has ended and no + /// newer text has come to fade. The engine draws it into the tail, as + /// an update; if that does not come, the tiles draw it. + private func scheduleFadeSettling() { + guard !fadeSettleScheduled else { return } + fadeSettleScheduled = true + let delay = max(fadesEnd - CACurrentMediaTime(), 0) + 0.05 + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + MainActor.assumeIsolated { + guard let self else { return } + self.fadeSettleScheduled = false + guard !self.fadeLayers.isEmpty else { return } + let late = CACurrentMediaTime() - self.fadesEnd + if late < 0 { + self.scheduleFadeSettling() + } else if late < Self.fadeSettleGrace { + self.engine.settleFinishedFades() + self.fadeSettleScheduled = true + DispatchQueue.main.asyncAfter(deadline: .now() + Self.fadeSettleGrace) { [weak self] in + MainActor.assumeIsolated { + guard let self else { return } + self.fadeSettleScheduled = false + guard !self.fadeLayers.isEmpty else { return } + if CACurrentMediaTime() >= self.fadesEnd + Self.fadeSettleGrace { + self.settleFades() + } else { + self.scheduleFadeSettling() + } + } + } + } else { + self.settleFades() + } + } + } + } + + private static let fadeSettleGrace: CFTimeInterval = 0.25 + + /// Ends every fade: the tiles draw the text again, in the same + /// transaction as the fade layers go. + private func settleFades() { + let from = engine.endFades() ?? fadingFrom + fadingFrom = nil + if let from, let layout = installed { + let top = layout.caretRect(at: min(from, layout.length)).minY - 8 + let band = top...max(top, layout.height + TranscriptPath.maximumOverhang) + // The tail was drawn without the fading text. + if tailTop < band.upperBound { handTailToTiles() } + redrawTiles(in: band) + } + removeFades() + } + + private func removeFades() { + for layers in fadeLayers.values { layers.forEach { $0.removeFromSuperlayer() } } + fadeLayers.removeAll() + } + // MARK: Tag animations @objc private func reduceMotionChanged() { updateAnimationsEnabled() + updateFadeDuration() } private func updateAnimationsEnabled() { @@ -942,6 +1105,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD super.layoutSubviews() canvas.frame = bounds animationLayer.frame = canvas.bounds + fadeLayer.frame = canvas.bounds if bounds.width > 0 { unsizedWidth = 0 } if bounds.width > 0, installed?.width != bounds.width { relayoutNow() diff --git a/Tests/TranscriptKitTests/FadeTests.swift b/Tests/TranscriptKitTests/FadeTests.swift new file mode 100644 index 0000000..2a8b437 --- /dev/null +++ b/Tests/TranscriptKitTests/FadeTests.swift @@ -0,0 +1,367 @@ +import CoreGraphics +import CoreText +import Foundation +import IOSurface +import Testing +@testable import TranscriptKit + +private let colors = TailRenderer.Colors( + text: CGColor(gray: 0, alpha: 1), + codeBackground: CGColor(gray: 0.9, alpha: 1), + accent: CGColor(gray: 0.6, alpha: 1) +) + +private let sample = """ +# Fading in + +Some text with **bold**, *italic*, ~~struck through~~ words, `inline code`, and a [link](https://example.com) that wraps \ +when its line is full of supercalifragilisticexpialidocious words and more. + +- A list item that is long enough to wrap onto a second line of the list +- Another ~~item~~ with a [link](https://example.org) + +```swift +let fading = true +``` + +| A first cell long enough to wrap onto more lines in its column | B | +| --- | --- | +| one | two | + +A last paragraph, centered or not, that ends the sample. +""" + +private final class Clock: @unchecked Sendable { + var now: CFTimeInterval = 1000 +} + +/// Streams `markdown` through a layout engine whose fades last `duration`, +/// moving its clock one frame on per update, and calls `check` with every +/// output. +private func streamFades(_ markdown: String, chunk: Int, style: TranscriptStyle = .init(), duration: CFTimeInterval = 0.1, + check: (LayoutEngine.Output) -> Void) { + let engine = LayoutEngine() + let clock = Clock() + engine.clock = { clock.now } + engine.setTailStyle(colors: colors, scale: 2) + engine.setFadeDuration(duration) + _ = engine.relayout(width: 320, style: style) + var parser = MarkdownStreamParser(idPrefix: "f") + var rest = Substring(markdown) + var sequence = 0 + while !rest.isEmpty { + parser.append(String(rest.prefix(chunk))) + rest = rest.dropFirst(chunk) + sequence += 1 + engine.submit(.init(document: parser.document, source: 1, sequence: sequence)) + engine.drainNow() + if let output = engine.takeOutput() { check(output) } + clock.now += 1.0 / 60 + } +} + +private func bitmap(width: Int, height: Int) -> CGContext { + CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)! +} + +/// Draws the pieces, at full opacity, into a top-left-origin context in +/// document points whose top left is at `origin`. +private func composite(_ fade: FadeFrame?, into context: CGContext, origin: CGPoint, scale: CGFloat) { + guard let fade else { return } + let height = CGFloat(context.height) + for piece in fade.pieces { + // Core Graphics draws images y-up. + let x = (piece.frame.minX - origin.x) * scale + let y = height - (piece.frame.maxY - origin.y) * scale + context.draw(piece.image, in: CGRect(x: x, y: y, width: piece.frame.width * scale, height: piece.frame.height * scale)) + } +} + +private func bytes(of context: CGContext) -> [UInt8] { + Array(UnsafeRawBufferPointer(start: context.data!, count: context.bytesPerRow * context.height)) +} + +/// Bytes that differ by more than 2, and the largest difference. +private func differing(_ a: [UInt8], _ b: [UInt8]) -> (count: Int, largest: Int) { + guard a.count == b.count else { return (max(a.count, b.count), 255) } + let identical = a.withUnsafeBytes { x in b.withUnsafeBytes { y in memcmp(x.baseAddress!, y.baseAddress!, x.count) == 0 } } + if identical { return (0, 0) } + var count = 0 + var largest = 0 + for (x, y) in zip(a, b) { + let difference = abs(Int(x) - Int(y)) + if difference > 2 { count += 1 } + largest = max(largest, difference) + } + return (count, largest) +} + +/// The document from the fading text down: drawn with that text left out, +/// plus the pieces, against drawn in one go. Above it, nothing is left out. +private func documentDifference(_ output: LayoutEngine.Output, scale: CGFloat) -> (count: Int, largest: Int) { + let layout = output.layout + guard let from = output.hidden.fadingFrom else { return (output.fade == nil ? 0 : 1, 0) } + let margin = TailRenderer.sideMargin + let top = max(((layout.caretRect(at: from).minY - 40) * scale).rounded(.down) / scale, 0) + let band = CGRect(x: -margin, y: top, width: layout.width + 2 * margin, height: layout.height + 32 - top) + let width = Int((band.width * scale).rounded()) + let height = Int((band.height * scale).rounded()) + func drawn(hiding: TagHiding) -> CGContext { + let context = bitmap(width: width, height: height) + context.saveGState() + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: scale, y: -scale) + context.translateBy(x: margin, y: -top) + context.clip(to: band) + layout.draw(in: context, dirtyRect: band, text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent, + dark: false, hiding: hiding) + context.restoreGState() + return context + } + let actual = drawn(hiding: output.hidden) + composite(output.fade, into: actual, origin: CGPoint(x: -margin, y: top), scale: scale) + return differing(bytes(of: actual), bytes(of: drawn(hiding: .none))) +} + +/// The tail surface plus the pieces, against the tail drawn in one go. +private func tailDifference(_ output: LayoutEngine.Output, scale: CGFloat) -> (count: Int, largest: Int)? { + guard let tail = output.tail else { return nil } + let layout = output.layout + let margin = TailRenderer.sideMargin + let width = Int(((layout.width + 2 * margin) * scale).rounded()) + let height = Int((TailRenderer.height * scale).rounded()) + let actual = bitmap(width: width, height: height) + tail.surface.lock(options: .readOnly, seed: nil) + for row in 0.. 0, mismatches.count < 3 { + mismatches.append("step \(step), fading from \(output.hidden.fadingFrom.map(String.init) ?? "-"): document \(document), tail \(tail)") + } + checked += 1 + } + #expect(checked > 10) + // Not while a table's header waits for the line below it. + #expect(fading * 2 > step) + #expect(outsideTail == 0) + #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") +} + +@Test func theFrontierMovesALineAtATimeAndItsRowsAreDrawnAgain() { + var froms: [Int?] = [] + var redraws = 0 + var outputs: [LayoutEngine.Output] = [] + // 0.04 s at 60 updates a second: a fade is in progress at the update + // that starts it and the two after. + streamFades(sample, chunk: 4, duration: 0.04) { output in + if let from = froms.last ?? nil, output.hidden.fadingFrom != from { + let end = output.hidden.fadingFrom ?? output.layout.length + // Text that stopped fading is drawn again, if it has lines. + if let line = output.layout.lines(from: from).first, line.entry.start + line.line.range.lowerBound < end { + #expect(output.restyled.contains { $0.minY <= line.entry.y + line.line.frame.minY + 1 }) + redraws += 1 + } + } + froms.append(output.hidden.fadingFrom) + outputs.append(output) + } + for (output, from) in zip(outputs, froms) { + guard let from, let first = output.layout.lines(from: from).first else { continue } + // No piece is above the frontier's line. + #expect(output.fade?.pieces.allSatisfy { $0.frame.maxY > first.entry.y + first.line.frame.minY } != false) + } + // About once per line, not once per update. + #expect(redraws > 5) + #expect(redraws < froms.count / 3) + // The frontier only moves forward while fades go on. + for (a, b) in zip(froms, froms.dropFirst()) { + if let a, let b { #expect(b >= a) } + } +} + +@Test func withoutADurationNothingFades() { + streamFades(sample, chunk: 7, duration: 0) { output in + #expect(output.hidden.fadingFrom == nil) + #expect(output.fade == nil) + } +} + +@Test func aTagThatStartsItsAnimationEndsTheFades() { + let hop = TranscriptTag("hop", TranscriptDecoration(animation: .custom(TestHop()))) + let engine = LayoutEngine() + let clock = Clock() + engine.clock = { clock.now } + engine.setTailStyle(colors: colors, scale: 2) + engine.setFadeDuration(10) + engine.setAnimationsEnabled(true) + _ = engine.relayout(width: 320, style: .init()) + var parser = MarkdownStreamParser(idPrefix: "t", tags: [hop]) + var outputs: [LayoutEngine.Output] = [] + for (index, chunk) in ["Some text and ", "a tag", "", " and more"].enumerated() { + parser.append(chunk) + engine.submit(.init(document: parser.document, source: 1, sequence: index + 1)) + engine.drainNow() + if let output = engine.takeOutput() { outputs.append(output) } + clock.now += 1.0 / 60 + } + #expect(outputs.count == 4) + #expect(outputs[1].hidden.fadingFrom == 0) + // The update in which the tag closes and starts: no fades, and none from it. + #expect(!outputs[2].started.isEmpty) + #expect(outputs[2].hidden.fadingFrom == nil) + #expect(outputs[2].fade == nil) + // Text after it fades again, from where it starts. + #expect(outputs[3].hidden.fadingFrom == outputs[2].layout.length) +} + +private struct TestHop: TranscriptAnimationRecipe { + func animation(for fragments: [TranscriptFragment]) -> TranscriptAnimation { + var animation = TranscriptAnimation() + for (line, fragment) in fragments.enumerated() { + for index in fragment.glyphs.indices { + animation.glyphs.append(.init(fragment: line, glyph: index, offsetY: .spring(peak: -3, start: 0))) + } + } + return animation + } +} + +@Test func aRelayoutEndsTheFades() { + let engine = LayoutEngine() + engine.setTailStyle(colors: colors, scale: 2) + engine.setFadeDuration(10) + _ = engine.relayout(width: 320, style: .init()) + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) + engine.drainNow() + #expect(engine.takeOutput()?.hidden.fadingFrom == 0) + _ = engine.relayout(width: 300, style: .init()) + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text, and more"), source: 1, sequence: 2)) + engine.drainNow() + let output = engine.takeOutput() + // Only the text after the relayout fades. + #expect(output?.hidden.fadingFrom == 9) + #expect(engine.endFades() == 9) + #expect(engine.endFades() == nil) +} + +@Test func whenUpdatesStopTheEngineDrawsTheFadedTextIntoTheTail() { + let engine = LayoutEngine() + let clock = Clock() + engine.clock = { clock.now } + engine.setTailStyle(colors: colors, scale: 2) + engine.setFadeDuration(0.1) + _ = engine.relayout(width: 320, style: .init()) + var parser = MarkdownStreamParser(idPrefix: "s") + for (index, chunk) in ["Some text ", "that keeps ", "coming in."].enumerated() { + parser.append(chunk) + engine.submit(.init(document: parser.document, source: 1, sequence: index + 1)) + engine.drainNow() + _ = engine.takeOutput() + clock.now += 1.0 / 60 + } + clock.now += 1 + engine.settleFinishedFades() + engine.drainNow() + let output = engine.takeOutput() + #expect(output?.hidden.fadingFrom == nil) + #expect(output?.fade == nil) + #expect(output?.isAppend == true) + #expect(output?.restyled.isEmpty == false) + if let output { + #expect(tailDifference(output, scale: 2)?.count == 0) + } + // Nothing more to settle. + engine.settleFinishedFades() + engine.drainNow() + #expect(engine.takeOutput() == nil) +} + +@Test func aRelayoutForTheImageStoreKeepsFadesThatDidNotMove() { + let engine = LayoutEngine() + engine.setTailStyle(colors: colors, scale: 2) + engine.setFadeDuration(10) + _ = engine.relayout(width: 320, style: .init()) + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) + engine.drainNow() + #expect(engine.takeOutput()?.hidden.fadingFrom == 0) + #expect(engine.relayout(width: 320, style: .init(), keepingFades: true)?.fadingFrom == 0) + // At another width the text moves: the fades end. + #expect(engine.relayout(width: 200, style: .init(), keepingFades: true)?.fadingFrom == nil) + #expect(engine.endFades() == nil) +} + +/// While text streams into a paragraph, a fade's piece keeps its image from +/// one update to the next, so the view hands Core Animation only the new +/// text's image: one or two new images an update, however many fades. +@Test func piecesKeepTheirImagesWhileTheirGlyphsStayPut() { + var previous: [ObjectIdentifier] = [] + var newImages: [Int] = [] + var piecesPerUpdate: [Int] = [] + let paragraph = String(repeating: "Words that stream into one long paragraph and wrap now and then. ", count: 6) + streamFades(paragraph, chunk: 3, duration: 0.3) { output in + let images = output.fade?.pieces.map { ObjectIdentifier($0.image) } ?? [] + newImages.append(images.filter { !previous.contains($0) }.count) + piecesPerUpdate.append(images.count) + previous = images + } + let updates = newImages.count + #expect(piecesPerUpdate.dropFirst(20).allSatisfy { $0 >= 10 }) + #expect(newImages.reduce(0, +) * 10 < updates * 15) + #expect(newImages.max() ?? 0 <= 20) +} + + + +/// A piece is drawn again when its text's style changes in place, as when +/// a reference's definition arrives and makes it a link. +@Test func aPieceWhoseStyleChangesIsDrawnAgain() { + let renderer = FadeRenderer() + let before = DocumentLayout(document: MarkdownStreamParser.document(from: "See [the docs][d] here"), width: 320) + let after = DocumentLayout(document: MarkdownStreamParser.document(from: "See [the docs][d] here\n\n[d]: https://example.com"), width: 320) + let fade = Fade(id: 1, range: 0..