diff --git a/README.md b/README.md index ef82f88..73d348e 100644 --- a/README.md +++ b/README.md @@ -127,9 +127,14 @@ let tags = [ let stream = TranscriptStream(tags: tags) ``` +A pill that breaks across two lines is open where it breaks. To keep a tag on one line, set `keepsTogether: true` +in its decoration: a tag that does not fit at the end of a line then goes to the next line as a whole. A tag wider +than a line, or with a line break in it, still breaks. + A tag can also show a small image before its text, such as an icon in a pill. The image takes room after the tag's -padding, so the tag's shapes surround it, and it is centred on the text's cap height. A tint fills the shape of a -template image, such as a symbol: +padding, so the tag's shapes surround it, and it is centred on the text's cap height. A tag with an animation shows +its image once the animation has played; with `showsDuringAnimation: true`, the image shows from the start, while +the tag waits and while it plays. A tint fills the shape of a template image, such as a symbol: ```swift TranscriptTag("chip") { attributes in @@ -147,10 +152,21 @@ TranscriptTag("chip") { attributes in ``` Tags the app doesn't define show as written. For a shape of your own, implement `TranscriptShapeRecipe`. It returns -paths for each line the tag's text is on and may draw a little outside the text, up to 12 points to the sides, -past the view's edges. The chat sample has two such shapes, `Zigzag` and `SoftUnderline`, in +paths for each line the tag's text is on and may draw a little outside the text, up to 12 points to the sides +and 6 points above and below the line, past the view's edges. The chat sample has two such shapes, `Zigzag` and `SoftUnderline`, in [`SampleTags.swift`](Examples/ChatSample/ChatSample/SampleTags.swift). +An app can also build a tagged document without the parser. Make an `InlineSpan.CustomTag` from a tag definition, +or from a name and a decoration. Then make the span with `InlineSpan(range:tagged:)`, which also gives it the +decoration's traits and link: + +```swift +let mention = InlineSpan.CustomTag(tags[0], attributes: ["id": "42"]) +let document = TranscriptDocument(blocks: [ + TranscriptBlock(text: "Ask @ana now.", spans: [InlineSpan(range: 4..<8, tagged: mention)]), +]) +``` + ### Animated tags A tag can also play an animation when its closing tag arrives in streamed text. Implement @@ -178,7 +194,8 @@ TranscriptTag("hop", TranscriptDecoration(animation: .custom(Hop()))) Until its closing tag arrives, an animated tag shows its text without its shapes. The view then draws the tag's glyphs and the animation's paths on Core Animation layers above the text, and draws the tag as usual again when the animation ends, so the last frame should match that: glyphs back in place, paths fully shown. Only tags that -close while text streams in are animated, not earlier messages. Turn animations off with `animatesTags` on the view +close while text streams in are animated, not earlier messages (see below to animate text that is complete when it +is shown). Turn animations off with `animatesTags` on the view or `.animatesTags(false)` on `TranscriptText`; with Reduce Motion on, nothing is animated. The chat sample's `Boing` sweeps a highlighter band in under the text while each letter jumps as the band reaches it. @@ -197,8 +214,41 @@ TranscriptText(stream: stream) ``` In UIKit, set `tagAnimationTiming` on `TranscriptTextView` and call `playTagAnimations()`. A tag that is still -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. +waiting when it can no longer play (Reduce Motion turned on, animations turned off, a new document) is shown as it +ends up. A view that leaves its window does the same, unless the timing has `.whenVisible` or `.whenRequested`: its +tags then go on waiting until the view is back in a window. With `.whenVisible`, a view that is hidden or has an +alpha of 0, or is inside such a view, is not visible. The view looks again a short time later, at most one second +apart, so a tag can start up to one second after its view shows. When the view lays out the same text again, for +example at a new width or when an image arrives, waiting tags go on waiting and playing tags go on playing. A +playing tag whose glyphs move plays again from the start. + +Text that is complete when it is shown, such as a document set directly or a page of many short texts, can animate +its tags too. With `animatesTagsInFirstText`, each tag in the first text that the view shows plays its animation +one time, as if it had just closed. The timing applies, so with `.whenVisible`, each tag plays when it comes on +screen: + +```swift +TranscriptText(document) + .animatesTagsInFirstText() + .tagAnimationTiming(.whenVisible) +``` + +A view that is made again, as a lazy stack does with a row that scrolls back into view, plays them again. + +Tags that wait often start at the same moment, for example when the stream finishes. To stagger them, also +implement `animation(for:in:)` in the recipe. The group gives the tag's place among the tags that start together, +in text order, and how many they are: + +```swift +func animation(for fragments: [TranscriptFragment], in group: TranscriptAnimationGroup) -> TranscriptAnimation { + var staggered = animation(for: fragments) + let delay = Double(group.index) * 0.15 + for index in staggered.glyphs.indices { + staggered.glyphs[index].offsetY = staggered.glyphs[index].offsetY?.delayed(by: delay) + } + return staggered +} +``` ### Fading in text diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index ed2f3aa..04506e2 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -204,6 +204,20 @@ final class BlockLayout: @unchecked Sendable { line.range.allSatisfy { text.character(at: $0) == 0x0A } } while keep > 0, holdsOnlyLineBreaks(previous.lines[keep]) { keep -= 1 } + // The padding after a tag that runs to the end of the text, + // as an open one does, is on the last character, so the word + // written last may have gone down a line for it alone. Once + // more text comes, the padding moves on, and the line above + // may take that word back. + let previousLength = previous.block.utf16Count + let endsInPadding = previous.block.spans.contains { span in + span.range.upperBound == previousLength && (span.customTag?.decoration.padding ?? 0) > 0 + } + if keep > 0, endsInPadding { keep -= 1 } + // A tag that keeps together may have gone down a line, and + // may no longer fit on a line of its own: the line above it + // is laid out again. + while keep > 0, DecoratedTags.keptTagStarts(at: previous.lines[keep].range.lowerBound, in: block) { keep -= 1 } } if keep > 0 { lines = previous.lines.prefix(keep) @@ -255,10 +269,16 @@ final class BlockLayout: @unchecked Sendable { let local = start - restart // A padded tag that starts the line has no character before it // on the line to carry its padding, so the line moves over. - let leading = min(decorated?.startPadding[start] ?? 0, available / 2) - let count = wraps + func room(at offset: Int) -> CGFloat { min(decorated?.startPadding[offset] ?? 0, available / 2) } + let leading = room(at: start) + var count = wraps ? max(CTTypesetterSuggestLineBreak(typesetter, local, Double(available - leading)), 1) : Self.lengthToLineBreak(in: string, from: local) + if wraps, let decorated, start + count < length { + count = decorated.lineEnd(from: start, to: start + count) { range in + Self.width(of: range.lowerBound - restart, count: range.count, in: typesetter) <= available - room(at: range.lowerBound) + } - start + } let ctLine = CTTypesetterCreateLine(typesetter, CFRange(location: local, length: count)) add(ctLine, range: start..<(start + count), indexBase: restart, leading: leading, text: attributed) start += count @@ -283,6 +303,13 @@ final class BlockLayout: @unchecked Sendable { return end - start } + /// How wide `count` characters from `start` are on one line, without + /// the space at their end. + private static func width(of start: Int, count: Int, in typesetter: CTTypesetter) -> CGFloat { + let line = CTTypesetterCreateLine(typesetter, CFRange(location: start, length: count)) + return CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(line)) + } + /// Line metrics made `height` tall, with the text centred, when the app /// set a line height. A line is never less tall than its text needs. private static func fitted(_ metrics: (width: CGFloat, height: CGFloat, ascent: CGFloat), @@ -461,6 +488,12 @@ final class BlockLayout: @unchecked Sendable { } start += count } + if let decorated { + let base = cell.range.lowerBound + longestWord = max(longestWord, decorated.widestKeptTag(in: cell.range) { range in + Self.width(of: range.lowerBound - base, count: range.count, in: cell.typesetter) + }) + } natural.append(ceil(widest) + padding * 2) minimum.append(ceil(longestWord) + padding * 2) } @@ -557,7 +590,13 @@ final class BlockLayout: @unchecked Sendable { } var start = 0 while start < cell.text.length { - let count = max(CTTypesetterSuggestLineBreak(cell.typesetter, start, Double(textWidth)), 1) + var count = max(CTTypesetterSuggestLineBreak(cell.typesetter, start, Double(textWidth)), 1) + if let decorated, start + count < cell.text.length { + let base = cell.range.lowerBound + count = decorated.lineEnd(from: base + start, to: base + start + count) { range in + Self.width(of: range.lowerBound - base, count: range.count, in: cell.typesetter) <= textWidth + } - base - start + } let ctLine = CTTypesetterCreateLine(cell.typesetter, CFRange(location: start, length: count)) add(ctLine, range: (cell.range.lowerBound + start)..<(cell.range.lowerBound + start + count)) start += count diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 78ac866..8795d4c 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -194,6 +194,13 @@ final class LayoutEngine: @unchecked Sendable { } } + /// The view holds these closed tags back until their timing lets them + /// play, as tags that close in an update wait: tails leave their shapes + /// out. Any thread. + func holdAnimations(_ keys: some Sequence) { + lock.withLock { hiding.waiting.formUnion(keys) } + } + /// The view has started these waiting tags' animations: tails leave /// them out entirely. Any thread. func playAnimations(_ keys: some Sequence) { @@ -531,8 +538,9 @@ final class LayoutEngine: @unchecked Sendable { base = layout measured = nil // The view draws everything itself after this; the tail starts - // again with the next append. Animations stop: the view shows - // every tag at rest after a relayout. + // again with the next append. The view tells the engine again + // which tags still wait or play (`holdAnimations`, + // `playAnimations`). tailActive = false tailRenderer?.reset() var kept: Int? diff --git a/Sources/TranscriptKit/Layout/TagAnimations.swift b/Sources/TranscriptKit/Layout/TagAnimations.swift index 569db63..84f4fba 100644 --- a/Sources/TranscriptKit/Layout/TagAnimations.swift +++ b/Sources/TranscriptKit/Layout/TagAnimations.swift @@ -62,12 +62,52 @@ extension DocumentLayout { return found } + /// Every animated tag in this layout that has closed, as its lines hold + /// them: those a line limit cuts off are left out. + func closedAnimatedTags() -> Set { + var keys: Set = [] + for index in 0..) -> [(tag: AnimatedTag, group: TranscriptAnimationGroup)] { + // One look from the end finds every block, as tags of a first text + // can be in all of them. + var unfound = Set(keys.map(\.block)) + var indices: [String: Int] = [:] + var index = entryCount - 1 + while index >= 0, !unfound.isEmpty { + let id = entry(at: index).layout.block.id + if unfound.remove(id) != nil { indices[id] = index } + index -= 1 + } + var found: [(tag: AnimatedTag, block: Int)] = [] + for key in keys { + guard let index = indices[key.block], let tag = animatedTag(key, inEntry: index) else { continue } + found.append((tag, index)) + } + found.sort { ($0.block, $0.tag.key.start, $0.tag.key.name) < ($1.block, $1.tag.key.start, $1.tag.key.name) } + return found.enumerated().map { ($1.tag, TranscriptAnimationGroup(index: $0, count: found.count)) } + } + /// The tag `key` names, if it is in this layout and has closed. func animatedTag(_ key: TagKey) -> AnimatedTag? { // Animated tags are almost always in the last blocks. var index = entryCount - 1 while index >= 0, entry(at: index).layout.block.id != key.block { index -= 1 } guard index >= 0 else { return nil } + return animatedTag(key, inEntry: index) + } + + private func animatedTag(_ key: TagKey, inEntry index: Int) -> AnimatedTag? { let entry = entry(at: index) var parts: [(fragment: AnimatedFragment, origin: CGPoint)] = [] var animation: TranscriptDecoration.Animation? @@ -86,3 +126,167 @@ extension DocumentLayout { return AnimatedTag(key: key, animation: animation, parts: parts, band: top...bottom) } } + +/// The animated tags of a view that have closed and wait for the view's +/// `TranscriptAnimationTiming` to let them play, and which of them may play. +struct WaitingTags: Sendable { + private(set) var keys: Set = [] + /// Waiting tags the app has asked to play (`playTagAnimations()`). + private(set) var requested: Set = [] + /// The rows each waiting tag takes up in the layout on screen, kept from + /// one look to the next: a scroll looks at every waiting tag. + private var bands: [TagKey: ClosedRange] = [:] + + /// Where the view is and what it shows, for `takeReady`. + struct Viewer { + var isInWindow: Bool + /// The view or one of its ancestors is hidden or fully transparent. + var isHidden: Bool + /// The part of the view on screen, in its coordinates. + var visibleRect: CGRect + /// No more text is coming. + var isFinished: Bool + } + + var isEmpty: Bool { keys.isEmpty } + + mutating func add(_ keys: some Sequence) { + self.keys.formUnion(keys) + } + + /// Lets every tag waiting now play once the rest of the timing allows. + mutating func request() { + requested.formUnion(keys) + } + + /// Lets the waiting tags of `keys` play once the rest of the timing + /// allows, as if the app had asked. + mutating func request(_ keys: Set) { + requested.formUnion(keys.intersection(self.keys)) + } + + /// Keeps only the tags in `kept`, for a layout that holds only those. + mutating func keep(_ kept: Set) { + keys.formIntersection(kept) + requested.formIntersection(keys) + bands = bands.filter { keys.contains($0.key) } + } + + /// Forgets where the tags are, for a new layout on screen. + mutating func forgetBands() { + bands.removeAll() + } + + /// Empties the list, and returns the tags that waited. + mutating func removeAll() -> Set { + defer { + keys.removeAll() + requested.removeAll() + bands.removeAll() + } + return keys + } + + /// Takes the waiting tags that `timing` lets play now out of the list. + /// A view that is not in a window plays none: nothing would show them. + /// + /// - Parameter band: the rows of the document a tag takes up, or nil + /// if the view's layout does not hold it. It is asked once for each + /// tag until `forgetBands()`. + mutating func takeReady(timing: TranscriptAnimationTiming, viewer: Viewer, + band: (TagKey) -> ClosedRange?) -> [TagKey] { + guard !keys.isEmpty, viewer.isInWindow else { return [] } + if timing.contains(.afterStreamFinishes), !viewer.isFinished { return [] } + if timing.contains(.whenVisible), viewer.isHidden { return [] } + var ready: [TagKey] = [] + for key in keys { + if timing.contains(.whenRequested), !requested.contains(key) { continue } + if timing.contains(.whenVisible) { + if bands[key] == nil { bands[key] = band(key) } + guard let band = bands[key], Self.isOnScreen(band, in: viewer.visibleRect) else { continue } + } + ready.append(key) + } + for key in ready { + keys.remove(key) + requested.remove(key) + bands[key] = nil + } + return ready + } + + /// The animations of a view that go on, or wait to play, when the view + /// shows a new layout. + struct Carried: Equatable { + /// Playing tags that go on playing. + var playing: Set = [] + /// Tags that wait to play: waiting tags that go on waiting, tags + /// held back to play for the first time, and `replayed`. + var waiting: Set = [] + /// Playing tags that the layout moved: they play again from the + /// start, with no need to ask again for `.whenRequested`. + var replayed: Set = [] + } + + /// What goes on when a view shows a new layout. + /// + /// - Parameters: + /// - isAppend: the layout adds text at the end of the one on screen. + /// The view keeps its waiting tags and starts or holds `started`, the + /// tags that closed in it. + /// - keepsText: the layout is not an append, but the view laid out the + /// same text again, as when an image arrives or the width changes. + /// Other layouts that are not appends draw every tag at rest. + /// - firstText: the layout is the first with text that the view shows, + /// and its closed tags play one time (`animatesTagsInFirstText`). + /// - closed: the layout's closed animated tags. + /// - waiting: the tags that wait now. + /// - playing: the tags that play now. + /// - isPlacedAsBefore: whether the layout draws a playing tag's glyphs + /// where they were. + static func carried(isAppend: Bool, keepsText: Bool, firstText: Bool, closed: Set, waiting: Set, + started: Set, playing: Set, isPlacedAsBefore: (TagKey) -> Bool) -> Carried { + var carried = Carried() + if isAppend { + if firstText { carried.waiting = closed.subtracting(started).subtracting(playing).subtracting(waiting) } + return carried + } + if keepsText { + for key in playing where closed.contains(key) { + if isPlacedAsBefore(key) { carried.playing.insert(key) } else { carried.replayed.insert(key) } + } + carried.waiting = waiting.intersection(closed).union(carried.replayed) + } + if firstText { carried.waiting.formUnion(closed.subtracting(carried.playing)) } + return carried + } + + /// Whether the tags wait only for a hidden view to show: nothing tells + /// the view when an ancestor shows again, so it looks again later. + func waitForHiddenView(timing: TranscriptAnimationTiming, viewer: Viewer) -> Bool { + !keys.isEmpty && timing.contains(.whenVisible) && viewer.isInWindow && viewer.isHidden + } + + /// Whether waiting tags keep waiting while the view is out of its + /// window: they wait to be seen, or for the app, and neither has + /// happened yet. + static func keepWaitingOutsideWindow(_ timing: TranscriptAnimationTiming) -> Bool { + !timing.isDisjoint(with: [.whenVisible, .whenRequested]) + } + + /// Whether a tag's rows count as on screen: all of them, or for a tag + /// taller than what is visible, some of them. + static func isOnScreen(_ band: ClosedRange, in visible: CGRect) -> Bool { + guard !visible.isNull, visible.height > 0 else { return false } + if band.upperBound - band.lowerBound > visible.height { + return band.upperBound > visible.minY && band.lowerBound < visible.maxY + } + return band.lowerBound >= visible.minY && band.upperBound <= visible.maxY + } + + /// Whether a view is hidden: it or one of its ancestors, from the view + /// up, is hidden or has an alpha of 0 (below 0.01, as hit testing has it). + static func isHidden(_ chain: some Sequence<(isHidden: Bool, alpha: CGFloat)>) -> Bool { + chain.contains { $0.isHidden || $0.alpha < 0.01 } + } +} diff --git a/Sources/TranscriptKit/Layout/TagDecorations.swift b/Sources/TranscriptKit/Layout/TagDecorations.swift index 3514f98..917e8d5 100644 --- a/Sources/TranscriptKit/Layout/TagDecorations.swift +++ b/Sources/TranscriptKit/Layout/TagDecorations.swift @@ -14,6 +14,10 @@ struct DecoratedTags { /// Its place among the block's spans, where outer tags come first. let order: Int + /// It keeps together and has no line break in its text, so it can + /// stay on one line. + let keepsTogether: Bool + var padding: CGFloat { tag.decoration.padding } /// The space before the text: the padding, and the image after it. var leadingRoom: CGFloat { padding + (tag.decoration.image?.room ?? 0) } @@ -49,7 +53,9 @@ struct DecoratedTags { guard let custom = span.customTag, custom.shapesText else { continue } var textEnd = span.range.upperBound while textEnd > span.range.lowerBound, text.character(at: textEnd - 1) == 0x0A { textEnd -= 1 } - let tag = Tag(range: span.range, textEnd: textEnd, tag: custom, order: order) + let keepsTogether = custom.decoration.keepsTogether + && !(span.range.lowerBound.. 0 else { continue } let before = span.range.lowerBound - 1 @@ -62,6 +68,44 @@ struct DecoratedTags { self.startPadding = startPadding } + /// Where a line that starts at block offset `start` and would end at + /// `end` ends instead, so that it does not cut a tag that keeps together + /// and fits on a line of its own: just before the first such tag that + /// starts on the line after `start` and goes on past `end`, so that it + /// starts the next line. A line that starts with such a tag holds all + /// of it, even when text without a space follows it. + /// + /// - Parameter fits: whether the text in a range fits on a line that + /// starts at the range's start. + func lineEnd(from start: Int, to end: Int, fits: (Range) -> Bool) -> Int { + for tag in tags where tag.keepsTogether + && tag.range.lowerBound >= start && tag.range.lowerBound < end && tag.textEnd > end { + guard fits(tag.range.lowerBound.. start ? tag.range.lowerBound : tag.textEnd + } + return end + } + + /// The widest text of a tag that keeps together and has no line break, + /// in `range`, as `width` measures it: such a tag is not cut where it + /// fits, so it counts as one word. + func widestKeptTag(in range: Range, width: (Range) -> CGFloat) -> CGFloat { + var widest: CGFloat = 0 + for tag in tags where tag.keepsTogether && range.lowerBound <= tag.range.lowerBound && tag.textEnd <= range.upperBound + && tag.textEnd > tag.range.lowerBound { + widest = max(widest, width(tag.range.lowerBound.. Bool { + block.spans.contains { $0.range.lowerBound == offset && $0.customTag?.decoration.keepsTogether == true } + } + /// Whether `inner` is `outer` or inside it. private func isWithin(_ inner: Tag, _ outer: Tag) -> Bool { outer.range.lowerBound <= inner.range.lowerBound && inner.range.upperBound <= outer.range.upperBound @@ -255,12 +299,13 @@ final class LineDecorations: @unchecked Sendable { if let link = tag.tag.decoration.link, tag.leadingRoom > 0 { links.append((rect, link)) } - if let image = tag.tag.decoration.image, isStart, showsShapes { + if let image = tag.tag.decoration.image, isStart, showsShapes || image.showsDuringAnimation { // Just before the text, centred on its cap height. let capHeight = CTFontGetCapHeight(font) let imageRect = CGRect(x: minX - image.gap - image.size.width, y: -capHeight / 2 - image.size.height / 2, width: image.size.width, height: image.size.height) - images.append((imageRect, image, key)) + // One that shows during the animation is never left out. + images.append((imageRect, image, image.showsDuringAnimation ? nil : key)) inkTop = min(inkTop, imageRect.minY) inkBottom = max(inkBottom, imageRect.maxY) } diff --git a/Sources/TranscriptKit/Layout/TailRenderer.swift b/Sources/TranscriptKit/Layout/TailRenderer.swift index 27552a6..40e71e3 100644 --- a/Sources/TranscriptKit/Layout/TailRenderer.swift +++ b/Sources/TranscriptKit/Layout/TailRenderer.swift @@ -140,7 +140,7 @@ final class TailRenderer { 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)) + newTop = min(newTop, max((max(fadingTop, -TranscriptPath.maximumOverhang) * scale).rounded(.down) / scale, fits)) } currentTop = newTop start = currentTop @@ -264,7 +264,8 @@ final class TailRenderer { // A table grows by its last row, grid and all. lineTop = entry.y + table.rowY[table.rowY.count - 2] - BlockLayout.Table.changeMargin } - return (max(0, lineTop) * scale).rounded(.down) / scale + // Shapes may reach above the first line, as far as the first tile does. + return (max(-TranscriptPath.maximumOverhang, lineTop) * scale).rounded(.down) / scale } /// The pixels the tail currently holds, for tests. diff --git a/Sources/TranscriptKit/Layout/TileGrid.swift b/Sources/TranscriptKit/Layout/TileGrid.swift index 0de4db5..24186d6 100644 --- a/Sources/TranscriptKit/Layout/TileGrid.swift +++ b/Sources/TranscriptKit/Layout/TileGrid.swift @@ -8,9 +8,21 @@ enum TileGrid { /// The height of the smallest tile. static let minimumHeight: CGFloat = 32 - /// The height of tile `index` in a view `viewHeight` points high, whose - /// glyphs draw down to `glyphBottom`. A view shorter than one tile has one - /// tile that covers only the view, the shapes that reach below its last + /// Where tile `index` starts and how high it is, in the view. The first + /// tile also covers `TranscriptPath.maximumOverhang` above the view, so + /// that shapes that reach above the first line, such as a pill on the + /// first line of a view without padding, are not cut. Its bottom is the + /// same as without that room. + static func tileFrame(at index: Int, viewHeight: CGFloat, glyphBottom: CGFloat = 0) -> (top: CGFloat, height: CGFloat) { + let top = index == 0 ? -TranscriptPath.maximumOverhang : CGFloat(index) * height + let bottom = CGFloat(index) * height + tileHeight(at: index, viewHeight: viewHeight, glyphBottom: glyphBottom) + return (top, bottom - top) + } + + /// The height of tile `index` below its top edge in the grid (0 for the + /// first tile) in a view `viewHeight` points high, whose glyphs draw + /// down to `glyphBottom`. A view shorter than one tile has one tile + /// that covers only the view, the shapes that reach below its last /// line and the glyphs, rounded up to 32, 64, 128 or 256 points. So a /// one-line text keeps a small drawing, and text that grows resizes its /// tile at most three times. In a taller view, every tile is 256 points diff --git a/Sources/TranscriptKit/Markdown/InlineParser.swift b/Sources/TranscriptKit/Markdown/InlineParser.swift index 3902cce..fd12de2 100644 --- a/Sources/TranscriptKit/Markdown/InlineParser.swift +++ b/Sources/TranscriptKit/Markdown/InlineParser.swift @@ -791,7 +791,7 @@ enum InlineParser { state.position = breakEndsLine ? end + 1 : end case .customTag(let definition, let attributes, let end): let decoration = definition.decoration(for: attributes) - let custom = InlineSpan.CustomTag(name: definition.name, attributes: attributes, decoration: decoration) + let custom = InlineSpan.CustomTag(name: definition.name, attributes: attributes, decoration: decoration, isOpen: false) let piece = state.appendSealedPiece(EmptyCollection()) state.tags.append(Tag(name: definition.name, traits: decoration.traits, piece: piece, custom: custom)) state.position = end diff --git a/Sources/TranscriptKit/Model/TranscriptAnimation.swift b/Sources/TranscriptKit/Model/TranscriptAnimation.swift index 24d3e0d..17cf8c9 100644 --- a/Sources/TranscriptKit/Model/TranscriptAnimation.swift +++ b/Sources/TranscriptKit/Model/TranscriptAnimation.swift @@ -34,12 +34,17 @@ import Foundation /// /// - Only tags that close while the view shows the text being appended are /// animated. Text that is already complete when it is shown, such as -/// earlier messages, is drawn as it ends up. +/// earlier messages, is drawn as it ends up, unless +/// `TranscriptTextView.animatesTagsInFirstText` is on. /// - With Reduce Motion on, or `TranscriptTextView.animatesTags` off, /// nothing is animated. /// - A recipe is a value: two that are equal must make the same animation. /// - `animation(for:)` runs on the main thread when the animation starts. /// Keep it quick: a few curves per glyph is fine. +/// - Several tags can start at the same moment, for example when the +/// stream finishes or when they come on screen. To stagger them, +/// implement `animation(for:in:)` too, and delay each tag by its +/// `TranscriptAnimationGroup.index`. /// - Glyphs and paths are drawn above the view's text, not cut off at its /// edges, so they may move further than shapes may reach /// (`TranscriptPath.maximumOverhang`); keep them near the text, or they @@ -48,6 +53,44 @@ public protocol TranscriptAnimationRecipe: Hashable, Sendable { /// The animation for one tag, from its fragments: one per line its text /// is on, in order, each with its glyphs (`TranscriptFragment.glyphs`). func animation(for fragments: [TranscriptFragment]) -> TranscriptAnimation + + /// The animation for one tag of `group`, the tags whose animations start + /// at the same moment in the same view. By default, `animation(for:)`. + func animation(for fragments: [TranscriptFragment], in group: TranscriptAnimationGroup) -> TranscriptAnimation +} + +extension TranscriptAnimationRecipe { + public func animation(for fragments: [TranscriptFragment], in group: TranscriptAnimationGroup) -> TranscriptAnimation { + animation(for: fragments) + } +} + +/// The tags whose animations start at the same moment in one view, and the +/// place of one of them, for a `TranscriptAnimationRecipe` that staggers them. +/// +/// ```swift +/// func animation(for fragments: [TranscriptFragment], in group: TranscriptAnimationGroup) -> TranscriptAnimation { +/// var staggered = animation(for: fragments) +/// let delay = Double(group.index) * 0.15 +/// for index in staggered.glyphs.indices { +/// staggered.glyphs[index].offsetY = staggered.glyphs[index].offsetY?.delayed(by: delay) +/// } +/// return staggered +/// } +/// ``` +public struct TranscriptAnimationGroup: Sendable, Hashable { + /// The tag's place among them, in text order, from 0. + public var index: Int + /// How many tags start together, 1 or more. + public var count: Int + + public init(index: Int, count: Int) { + self.index = max(index, 0) + self.count = max(count, self.index + 1) + } + + /// A tag that starts alone. + public static let single = TranscriptAnimationGroup(index: 0, count: 1) } /// What a `TranscriptAnimationRecipe` plays: how each glyph moves and which @@ -266,8 +309,16 @@ public struct TranscriptCurve: Sendable, Equatable { /// ``` /// /// A tag that is still waiting when animations can no longer play (Reduce -/// Motion turned on, `animatesTags` turned off, the view leaving its window, -/// or a new document) is shown as it ends up, shapes and all. +/// Motion turned on, `animatesTags` turned off, or a new document) is shown +/// as it ends up, shapes and all. A view that leaves its window does the +/// same, unless the timing has `.whenVisible` or `.whenRequested`: its tags +/// then go on waiting, and tags that close meanwhile wait too. A view out of +/// its window plays no animation. +/// +/// When the view lays out the same text again (a new width or style, or an +/// image, code colors or a formula that arrived), waiting tags go on +/// waiting and playing tags go on playing. A playing tag whose glyphs move +/// plays again from the start. public struct TranscriptAnimationTiming: OptionSet, Hashable, Sendable { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } @@ -275,7 +326,11 @@ public struct TranscriptAnimationTiming: OptionSet, Hashable, Sendable { /// As soon as the tag's closing tag arrives. public static let immediately: TranscriptAnimationTiming = [] /// Not before the tag's text is on screen: a tag that closes while it is - /// scrolled out of view plays when it is scrolled into view. + /// scrolled out of view plays when it is scrolled into view. A view that + /// is hidden, or has an alpha of 0, is not on screen, nor is one inside + /// such a view. No call tells the view when an ancestor shows again, so + /// the view looks again after 0.25 s, then less often, up to one second + /// apart, until it shows. public static let whenVisible = TranscriptAnimationTiming(rawValue: 1 << 0) /// Not before the stream has finished (`TranscriptStream.finish()`), or /// the view shows a document that was set directly rather than streamed. @@ -323,8 +378,8 @@ extension TranscriptDecoration { AnyHashable(recipe).hash(into: &hasher) } - func animation(for fragments: [TranscriptFragment]) -> TranscriptAnimation { - recipe.animation(for: fragments) + func animation(for fragments: [TranscriptFragment], in group: TranscriptAnimationGroup = .single) -> TranscriptAnimation { + recipe.animation(for: fragments, in: group) } } } diff --git a/Sources/TranscriptKit/Model/TranscriptDocument.swift b/Sources/TranscriptKit/Model/TranscriptDocument.swift index 459e858..c4d9d2b 100644 --- a/Sources/TranscriptKit/Model/TranscriptDocument.swift +++ b/Sources/TranscriptKit/Model/TranscriptDocument.swift @@ -44,7 +44,9 @@ public struct InlineSpan: Equatable, Sendable { } /// For text inside a custom tag (see `TranscriptTag`): the tag and its - /// decoration. Its traits and link are also in `traits` and `link`. + /// decoration. In a parsed span, and in one made with + /// `InlineSpan(range:tagged:)`, its traits and link are also in `traits` + /// and `link`. Setting it does not change them. public var customTag: CustomTag? { get { extras?.customTag } set { extras = Extras.make(image: image, reference: reference, customTag: newValue, math: math) } @@ -58,6 +60,13 @@ public struct InlineSpan: Equatable, Sendable { self.extras = Extras.make(image: image, reference: reference, customTag: customTag, math: math) } + /// A span for text inside a custom tag, as the parser makes it: with + /// the tag's decoration, its traits, and its link. For a document that + /// the app builds without the parser. + public init(range: Range, tagged tag: CustomTag) { + self.init(range: range, traits: tag.decoration.traits, link: tag.decoration.link, customTag: tag) + } + init(range: Range, traits: Traits, link: String?, extras: Extras?) { self.range = range self.traits = traits diff --git a/Sources/TranscriptKit/Model/TranscriptTag.swift b/Sources/TranscriptKit/Model/TranscriptTag.swift index 589b61f..1020d55 100644 --- a/Sources/TranscriptKit/Model/TranscriptTag.swift +++ b/Sources/TranscriptKit/Model/TranscriptTag.swift @@ -105,10 +105,15 @@ public struct TranscriptDecoration: Equatable, Sendable { /// A small image before the text, such as an icon in a pill. It sits in /// the space where the tag starts, after `padding`, so shapes surround it. public var image: TranscriptTagImage? + /// Whether the tag's text stays on one line, as a pill should: a tag + /// that does not fit at the end of a line goes to the next line as a + /// whole. A tag wider than a line, or with a line break in it, still + /// breaks. Off by default. + public var keepsTogether: Bool public init(traits: InlineSpan.Traits = [], foreground: TranscriptColor? = nil, background: TranscriptColor? = nil, link: String? = nil, padding: CGFloat = 0, shapes: [Shape] = [], animation: Animation? = nil, - image: TranscriptTagImage? = nil) { + image: TranscriptTagImage? = nil, keepsTogether: Bool = false) { self.traits = traits self.foreground = foreground self.background = background @@ -117,15 +122,17 @@ public struct TranscriptDecoration: Equatable, Sendable { self.shapes = shapes self.animation = animation self.image = image + self.keepsTogether = keepsTogether } /// Whether layout has to do anything for it beyond styling the text. - var shapesText: Bool { padding > 0 || !shapes.isEmpty || animation != nil || image != nil } + var shapesText: Bool { padding > 0 || !shapes.isEmpty || animation != nil || image != nil || keepsTogether } } /// A small image before a custom tag's text; see `TranscriptDecoration.image`. /// It is centred on the text's cap height. A tag with an animation shows its -/// image when it shows its shapes: once the animation has played. +/// image when it shows its shapes, once the animation has played, unless +/// `showsDuringAnimation` is set. public struct TranscriptTagImage: Equatable, @unchecked Sendable { public var image: CGImage /// How large it is drawn, in points. @@ -135,12 +142,18 @@ public struct TranscriptTagImage: Equatable, @unchecked Sendable { /// A color to fill the image's shape with, for a template image such as /// a symbol, or nil to draw the image's own colors. public var tint: TranscriptColor? + /// For a tag with an animation: whether the image shows from the start, + /// while the tag is open, while it waits for its animation and while the + /// animation plays. The animation does not move it. Off by default: the + /// image shows with the tag's shapes. + public var showsDuringAnimation: Bool - public init(_ image: CGImage, size: CGSize, gap: CGFloat = 4, tint: TranscriptColor? = nil) { + public init(_ image: CGImage, size: CGSize, gap: CGFloat = 4, tint: TranscriptColor? = nil, showsDuringAnimation: Bool = false) { self.image = image self.size = size self.gap = max(gap, 0) self.tint = tint + self.showsDuringAnimation = showsDuringAnimation } /// The space the image takes before the text. @@ -148,6 +161,7 @@ public struct TranscriptTagImage: Equatable, @unchecked Sendable { public static func == (a: TranscriptTagImage, b: TranscriptTagImage) -> Bool { a.image === b.image && a.size == b.size && a.gap == b.gap && a.tint == b.tint + && a.showsDuringAnimation == b.showsDuringAnimation } } @@ -248,7 +262,22 @@ extension InlineSpan { let shapesText: Bool let isAnimated: Bool - init(name: String, attributes: [String: String], decoration: TranscriptDecoration, isOpen: Bool = false) { + /// A tag for a span that the app makes itself, for example in a + /// document built with `TranscriptDocument(blocks:)`. Make the span + /// with `InlineSpan(range:tagged:)`, so that it also gets the + /// decoration's traits and link. + /// + /// - Parameter name: lowercased, as the parser does. + public convenience init(name: String, attributes: [String: String] = [:], decoration: TranscriptDecoration) { + self.init(name: name.lowercased(), attributes: attributes, decoration: decoration, isOpen: false) + } + + /// The tag `tag` defines, with the decoration it gives `attributes`. + public convenience init(_ tag: TranscriptTag, attributes: [String: String] = [:]) { + self.init(name: tag.name, attributes: attributes, decoration: tag.decoration(for: attributes), isOpen: false) + } + + init(name: String, attributes: [String: String], decoration: TranscriptDecoration, isOpen: Bool) { self.name = name self.attributes = attributes self.decoration = decoration diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 653b324..2432adb 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -25,6 +25,7 @@ public struct TranscriptText: UIViewRepresentable { private var animatesTags = true private var textFadeInDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately + private var animatesFirstText = false private var isSelectable = true private var playTrigger: AnyHashable? private var selectionChange: ((Range?) -> Void)? @@ -106,6 +107,15 @@ public struct TranscriptText: UIViewRepresentable { return copy } + /// Whether the tags with an animation that the first text already holds + /// play it, each one time; see `TranscriptTextView.animatesTagsInFirstText`. + /// Off by default. + public func animatesTagsInFirstText(_ animates: Bool = true) -> TranscriptText { + var copy = self + copy.animatesFirstText = animates + return copy + } + /// When tags' animations play once their closing tag has arrived; see /// `TranscriptAnimationTiming`. Right away by default. public func tagAnimationTiming(_ timing: TranscriptAnimationTiming) -> TranscriptText { @@ -190,6 +200,7 @@ public struct TranscriptText: UIViewRepresentable { } view.style = style view.animatesTags = animatesTags + view.animatesTagsInFirstText = animatesFirstText view.textFadeInDuration = textFadeInDuration view.tagAnimationTiming = animationTiming view.isSelectable = isSelectable diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 8f6bd4f..893fa61 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -149,11 +149,23 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + /// Whether the tags with an animation that the view's first text already + /// holds play it, each one time, as if they had just closed. Off by + /// default: text that is complete when it is shown, such as an earlier + /// message or a document set directly, shows its tags as they end up. + /// + /// The first text is the first layout with text that the view shows. + /// `tagAnimationTiming` applies: with `.whenVisible`, each tag plays when + /// it comes on screen. Tags that close later animate as usual. A view + /// that is made again, as a lazy stack does with a row that scrolls back + /// into view, plays them again. Set it before the view shows text. + public var animatesTagsInFirstText = false + /// Lets every tag waiting to animate now play, as soon as the rest of /// `tagAnimationTiming` allows. Tags that close later wait for the next /// call. Does nothing unless the timing includes `.whenRequested`. public func playTagAnimations() { - requested.formUnion(waiting) + waiting.request() startWaitingTagsSoon() } @@ -348,15 +360,19 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private var playingKeys: Set = [] /// Tags that have closed and wait for `tagAnimationTiming` to let them /// play; the tiles draw them without their shapes. - private var waiting: Set = [] - /// Waiting tags the app has asked to play (`playTagAnimations()`). - private var requested: Set = [] + private var waiting = WaitingTags() /// No more text is coming to the document on screen. private var isFinished = false private var waitingCheckScheduled = false + private var visibilityCheckScheduled = false + private var visibilityCheckDelay = TranscriptTextView.firstVisibilityCheck + private static let firstVisibilityCheck: TimeInterval = 0.25 + private static let lastVisibilityCheck: TimeInterval = 1 + /// A layout with text has been on screen. + private var hasShownText = 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, fadingFrom: fadingFrom) } + private var hiding: TagHiding { TagHiding(playing: playingKeys, waiting: waiting.keys, fadingFrom: fadingFrom) } private struct PlayingTag { let tag: AnimatedTag @@ -722,6 +738,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD updateFadeDuration() guard window != nil else { stopSideDeceleration() + finishAllAnimations() + if !WaitingTags.keepWaitingOutsideWindow(tagAnimationTiming) { showWaitingTagsAtRest() } handTailToTiles() releaseTiles() return @@ -737,6 +755,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } updateCanvas() selectAllIfNeeded() + startWaitingTagsSoon() } /// Updates the tiles on the next turn of the run loop, once the stack has @@ -832,8 +851,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Marks the parts of existing tiles between those y's for drawing. Tiles /// made later draw everything anyway. private func redrawTiles(in range: ClosedRange) { - for (index, tile) in tiles { - let minY = CGFloat(index) * tileHeight + for tile in tiles.values { + let minY = tile.frame.minY let top = max(range.lowerBound - minY - 2, 0) let bottom = min(range.upperBound - minY + 2, tile.bounds.height) if top < bottom { @@ -844,7 +863,10 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private func updateCanvas(forceRedraw: Bool = false, changed: ClosedRange? = nil) { // Tags waiting to be on screen may be now. - if !waiting.isEmpty, tagAnimationTiming.contains(.whenVisible) { startWaitingTagsSoon() } + if !waiting.isEmpty, tagAnimationTiming.contains(.whenVisible) { + visibilityCheckDelay = Self.firstVisibilityCheck + startWaitingTagsSoon() + } let visible = visibleRect guard !visible.isNull, visible.height > 0, bounds.width > 0 else { if !isNearVisibleArea { @@ -867,9 +889,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD for index in first...last { // Wider than the view: tags' shapes may draw past the text column. let side = TranscriptPath.maximumSideOverhang - let frame = CGRect(x: -side, y: CGFloat(index) * tileHeight, width: bounds.width + 2 * side, - height: TileGrid.tileHeight(at: index, viewHeight: bounds.height, - glyphBottom: currentLayout.glyphBottom)) + let rows = TileGrid.tileFrame(at: index, viewHeight: bounds.height, glyphBottom: currentLayout.glyphBottom) + let frame = CGRect(x: -side, y: rows.top, width: bounds.width + 2 * side, height: rows.height) if let tile = tiles[index] { if tile.frame != frame { tile.frame = frame @@ -1094,7 +1115,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let result = engine.relayout(width: bounds.width, style: layoutStyle, keepingFades: keepingFades) else { return } skippedOutput = nil guard result.source == source else { return } - install(result.layout, changedTop: nil, tail: nil, keptFadingFrom: result.fadingFrom, isFinished: result.isFinished) + install(result.layout, changedTop: nil, tail: nil, keptFadingFrom: result.fadingFrom, isFinished: result.isFinished, + keepsAnimations: true) } private func layOutNowIfNothingIsShown() { @@ -1122,9 +1144,12 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// - 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. + /// - Parameter keepsAnimations: the view laid out its text again (a new + /// width or style, an image or code colors that arrived). Tags that + /// wait or play go on if the text is the one they are in. private func install(_ layout: DocumentLayout, changedTop: CGFloat?, tail: TailRenderer.Frame?, restyled: [CGRect] = [], started: [TagKey] = [], waiting newlyWaiting: [TagKey] = [], fade: FadeFrame? = nil, fadingFrom: Int? = nil, - keptFadingFrom: Int? = nil, isFinished: Bool = false) { + keptFadingFrom: Int? = nil, isFinished: Bool = false, keepsAnimations: Bool = false) { self.isFinished = isFinished TranscriptDiagnostics.count(\.installs) let old = installed @@ -1195,20 +1220,45 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD removeFades() } + waiting.forgetBands() + let firstText = animatesFirstText && layout.length > 0 + let keepsText = keepsAnimations && !isAppend && old.map { layout.document.extends($0.document) } == true + let closed = firstText || (keepsText && !(waiting.isEmpty && playing.isEmpty)) ? layout.closedAnimatedTags() : [] if isAppend { // A playing tag whose glyphs moved (its line wrapped otherwise) // ends where it is. for (key, play) in playing where layout.animatedTag(key).map({ !$0.isPlaced(like: play.tag) }) ?? true { finishAnimation(key) } - for key in started { startAnimation(key, in: layout) } - waiting.formUnion(newlyWaiting) + startAnimations(started, in: layout) + waiting.add(newlyWaiting) + let held = WaitingTags.carried(isAppend: true, keepsText: false, firstText: firstText, closed: closed, + waiting: waiting.keys, started: Set(started + newlyWaiting), playing: playingKeys) { _ in true } + if !held.waiting.isEmpty { + engine.holdAnimations(held.waiting) + waiting.add(held.waiting) + } startWaitingTagsSoon() } else { - // Everything was drawn again, at rest. - removeAllAnimations() + // Everything was drawn again, at rest, apart from the tags that + // go on (see `WaitingTags.carried`). + let carried = WaitingTags.carried(isAppend: false, keepsText: keepsText, firstText: firstText, closed: closed, + waiting: waiting.keys, started: [], playing: playingKeys) { key in + guard let play = playing[key], let tag = layout.animatedTag(key) else { return false } + return tag.isPlaced(like: play.tag) + } + removeAllAnimations(keepingWaiting: carried.waiting, keepingPlaying: carried.playing, in: layout) engine.settleAnimations(started + newlyWaiting) + if !carried.waiting.isEmpty || !carried.playing.isEmpty { + // A relayout starts the engine's list again. + engine.holdAnimations(carried.waiting.union(carried.playing)) + engine.playAnimations(carried.playing) + waiting.add(carried.waiting) + waiting.request(carried.replayed) + startWaitingTagsSoon() + } } + if layout.length > 0 { hasShownText = true } if !isAppend { inputDelegate?.textDidChange(self) @@ -1335,13 +1385,23 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD updateFadeDuration() } + /// Whether tags can animate at all: on, and Reduce Motion off. + private var animationsCanPlay: Bool { animatesTags && !UIAccessibility.isReduceMotionEnabled } + + /// Whether the first text's closed tags wait to play. + private var animatesFirstText: Bool { animatesTagsInFirstText && !hasShownText && animationsCanPlay } + + /// Tells the engine whether tags that close start or wait. Outside a + /// window, only tags that wait to be seen or for the app wait; others + /// are drawn as they end up. Leaving the window is handled in + /// `didMoveToWindow`. private func updateAnimationsEnabled() { - let enabled = animatesTags && window != nil && !UIAccessibility.isReduceMotionEnabled if animatesTags, window != nil, UIAccessibility.isReduceMotionEnabled { animationLog.debug("Tags are not animated: Reduce Motion is on") } + let enabled = animationsCanPlay && (window != nil || WaitingTags.keepWaitingOutsideWindow(tagAnimationTiming)) engine.setAnimationsEnabled(enabled, immediately: tagAnimationTiming == .immediately) - if !enabled { + if !animationsCanPlay { finishAllAnimations() showWaitingTagsAtRest() } @@ -1368,42 +1428,50 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private func startWaitingTags() { guard !waiting.isEmpty, let layout = installed else { return } let timing = tagAnimationTiming - if timing.contains(.afterStreamFinishes), !isFinished { return } - let visible = timing.contains(.whenVisible) ? visibleRect : .null - var ready: [TagKey] = [] - for key in waiting { - if timing.contains(.whenRequested), !requested.contains(key) { continue } - if timing.contains(.whenVisible) { - guard window != nil, let tag = layout.animatedTag(key), Self.isOnScreen(tag.band, in: visible) else { continue } - } - ready.append(key) + let looks = timing.contains(.whenVisible) && window != nil + let viewer = WaitingTags.Viewer(isInWindow: window != nil, isHidden: looks && isHiddenInWindow, + visibleRect: looks ? visibleRect : .null, isFinished: isFinished) + let ready = waiting.takeReady(timing: timing, viewer: viewer) { layout.animatedTag($0)?.band } + if waiting.waitForHiddenView(timing: timing, viewer: viewer) { + checkVisibilityLater() + } else { + visibilityCheckDelay = Self.firstVisibilityCheck } guard !ready.isEmpty else { return } - for key in ready.sorted(by: { ($0.block, $0.start) < ($1.block, $1.start) }) { - waiting.remove(key) - requested.remove(key) - engine.playAnimations([key]) - startAnimation(key, in: layout, wasWaiting: true) - } - } - - /// Whether a tag's rows count as on screen: all of them, or for a tag - /// taller than what is visible, some of them. - private static func isOnScreen(_ band: ClosedRange, in visible: CGRect) -> Bool { - guard !visible.isNull, visible.height > 0 else { return false } - if band.upperBound - band.lowerBound > visible.height { - return band.upperBound > visible.minY && band.lowerBound < visible.maxY + engine.playAnimations(ready) + startAnimations(ready, in: layout, wereWaiting: true) + } + + /// Whether this view or an ancestor is hidden or has an alpha of 0. The + /// layers are read, so that a layer above the view that no view owns + /// counts too. + private var isHiddenInWindow: Bool { + WaitingTags.isHidden(sequence(first: layer, next: \.superlayer).lazy.map { ($0.isHidden, CGFloat($0.opacity)) }) + } + + /// Looks again in a moment whether tags that wait for a hidden view can + /// play: no call tells the view when an ancestor shows again. Each look + /// while the view stays hidden comes later than the one before, up to + /// one second apart. + private func checkVisibilityLater() { + guard !visibilityCheckScheduled else { return } + visibilityCheckScheduled = true + let delay = visibilityCheckDelay + visibilityCheckDelay = min(delay * 2, Self.lastVisibilityCheck) + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + MainActor.assumeIsolated { + guard let self else { return } + self.visibilityCheckScheduled = false + self.startWaitingTags() + } } - return band.lowerBound >= visible.minY && band.upperBound <= visible.maxY } /// Draws every waiting tag as it ends up, shapes and all, for when it /// can no longer play. private func showWaitingTagsAtRest() { guard !waiting.isEmpty else { return } - let keys = waiting - waiting.removeAll() - requested.removeAll() + let keys = waiting.removeAll() engine.settleAnimations(keys) for key in keys { guard let tag = installed?.animatedTag(key) else { continue } @@ -1414,16 +1482,26 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } - /// Plays `key`'s animation over the text, which from now on leaves it out. + /// Plays the animations of `keys`, which start together, over the text, + /// which from now on leaves them out. /// - /// - Parameter wasWaiting: it waited for its timing, and the tail, drawn - /// when it was waiting, still shows its glyphs. - private func startAnimation(_ key: TagKey, in layout: DocumentLayout, wasWaiting: Bool = false) { - if playing[key] != nil { finishAnimation(key) } - guard let tag = layout.animatedTag(key) else { - engine.settleAnimations([key]) - return + /// - Parameter wereWaiting: they waited for their timing, and the tail, + /// drawn when they were waiting, still shows their glyphs. + private func startAnimations(_ keys: [TagKey], in layout: DocumentLayout, wereWaiting: Bool = false) { + guard !keys.isEmpty else { return } + let batch = layout.tagsStartingTogether(keys) + if batch.count < keys.count { + let found = Set(batch.map(\.tag.key)) + engine.settleAnimations(keys.filter { !found.contains($0) }) } + for (tag, group) in batch { + startAnimation(tag, in: group, wasWaiting: wereWaiting, layout: layout) + } + } + + private func startAnimation(_ tag: AnimatedTag, in group: TranscriptAnimationGroup, wasWaiting: Bool, layout: DocumentLayout) { + let key = tag.key + if playing[key] != nil { finishAnimation(key) } // Its layers could not follow the block's offset: the tag shows at rest. if sidePan != nil, let index = layout.entryIndex(ofBlock: key.block), layout.entry(at: index).layout.maximumScrollOffset > 0 { engine.settleAnimations([key]) @@ -1432,7 +1510,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return } if wasWaiting, tailTop < band(of: tag).upperBound { handTailToTiles() } - let animation = tag.animation.animation(for: tag.fragments) + let animation = tag.animation.animation(for: tag.fragments, in: group) let colors = resolvedColors() let scale = traitCollection.displayScale let sprites = TagAnimationPlayer.sprites(for: tag, animation: animation, @@ -1482,19 +1560,25 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } /// Drops every animation without redrawing, for when everything is - /// being drawn again anyway. - private func removeAllAnimations() { - engine.settleAnimations(waiting) - waiting.removeAll() - requested.removeAll() + /// being drawn again anyway, apart from the waiting tags in `keptWaiting` + /// and the playing tags in `keptPlaying`, which `layout` places where + /// they were. + private func removeAllAnimations(keepingWaiting keptWaiting: Set, keepingPlaying keptPlaying: Set, + in layout: DocumentLayout) { + engine.settleAnimations(waiting.keys.subtracting(keptWaiting)) + waiting.keep(keptWaiting) guard !playing.isEmpty else { return } engine.settleAnimations(playingKeys) - for play in playing.values { + for (key, play) in playing { + if keptPlaying.contains(key), let tag = layout.animatedTag(key) { + playing[key] = PlayingTag(tag: tag, layer: play.layer, start: play.start, signpost: play.signpost) + continue + } play.layer.removeFromSuperlayer() animationSignposter.endInterval("Tag animation", play.signpost) + playing[key] = nil + playingKeys.remove(key) } - playing.removeAll() - playingKeys.removeAll() } /// The rows a tag's drawing can change, its shapes' reach included. diff --git a/Tests/TranscriptKitTests/CustomTagTests.swift b/Tests/TranscriptKitTests/CustomTagTests.swift index 4398533..bea9907 100644 --- a/Tests/TranscriptKitTests/CustomTagTests.swift +++ b/Tests/TranscriptKitTests/CustomTagTests.swift @@ -122,6 +122,27 @@ private func tagged(_ result: InlineParser.Result) -> [String] { #expect(inline("a b@ana now."#, idPrefix: "a", tags: tags) + let mention = try #require(tags.first { $0.name == "mention" }) + let made = TranscriptDocument(blocks: [ + TranscriptBlock(id: "a-0", text: "Ask @ana now.", + spans: [InlineSpan(range: 4..<8, tagged: InlineSpan.CustomTag(mention, attributes: ["id": "42"]))]), + ]) + #expect(made.blocks[0].spans == parsed.blocks[0].spans) + #expect(made.blocks[0].spans[0].traits == .bold) + #expect(made.blocks[0].spans[0].link == "app://people/42") + + let named = InlineSpan.CustomTag(name: "Mention", attributes: ["id": "42"], decoration: mention.decoration(for: ["id": "42"])) + #expect(named == made.blocks[0].spans[0].customTag) + // The plain initializer keeps the span's own traits and link. + let plain = InlineSpan(range: 0..<1, link: "app://other", customTag: named) + #expect(plain.link == "app://other" && plain.traits.isEmpty && plain.customTag == named) + #expect(InlineSpan(range: 0..<1, customTag: named).link == nil) +} + // MARK: Streaming private let streamedSamples = [ diff --git a/Tests/TranscriptKitTests/DecorationShapeTests.swift b/Tests/TranscriptKitTests/DecorationShapeTests.swift index 478206d..9d64727 100644 --- a/Tests/TranscriptKitTests/DecorationShapeTests.swift +++ b/Tests/TranscriptKitTests/DecorationShapeTests.swift @@ -20,6 +20,8 @@ private let shapeTags: [TranscriptTag] = [ TranscriptTag("marker", TranscriptDecoration(shapes: [.underline(.marker, color: yellow)])), TranscriptTag("wave", TranscriptDecoration(shapes: [.underline(.wavy, color: border)])), TranscriptTag("probe", TranscriptDecoration(padding: 3, shapes: [.custom(FragmentProbe())])), + TranscriptTag("whole", TranscriptDecoration(padding: 6, shapes: [.pill(fill: indigo.opacity(0.2))], keepsTogether: true)), + TranscriptTag("word", TranscriptDecoration(traits: .bold, keepsTogether: true)), ] /// Fills each fragment's box with a color that says which ends it has. @@ -146,6 +148,17 @@ private let streamedShapes = [ "An open pill with a line break
after it, and more
text, a pill in a marker here.\n", "Two breaks in an open pill

then more
, and a marker

too
.\n", "| Who | Note |\n| --- | --- |\n| @a | yes, and a long cell that wraps |\n\n- item one\n- two\n", + // Goes down a line whole, then grows wider than a line and breaks. + "Some words before it and a pill that keeps together until it grows wider than one whole line after.\n\n" + + "Then two words at the end of a line and one
with a break
too.\n", + "| A | B |\n| --- | --- |\n| x | some text then a kept pill in a narrow cell |\n", + // The same without padding. + "Some words before it and a bold run that keeps together until it grows wider than one whole line after.\n", + // The padding after an open pill sends its last word down a line, + // and the line above takes it back when the next word starts. + "Some words before it and a pill that keeps together until it grows wider than one whole line after.\n", + // Text without a space after the tag. + "Some words to fill a line, then a long pillgluedOnAfterItWithoutASpace and more words.\n", ] /// Every line's geometry and shapes, to compare two layouts. @@ -364,3 +377,91 @@ private struct VisibleArea: TranscriptShapeRecipe { #expect(abs(area.minY - (line.frame.minY - line.baseline - TranscriptPath.maximumOverhang)) < 0.01) } } + +// MARK: Keeping together + +/// The lines that hold text of the tag that starts at `offset` in block 0. +private func linesHolding(_ layout: DocumentLayout, tagAt offset: Int) -> [Range] { + let block = layout.entry(at: 0).layout + let tag = block.block.spans.first { $0.range.lowerBound == offset && $0.customTag != nil }! + return block.lines.map(\.range).filter { $0.overlaps(tag.range) } +} + +@Test func aTagThatKeepsTogetherGoesToTheNextLineWhole() { + // At 230 points, "a long pill" does not fit after the words before it. + let text = "Some words to fill a line, then a long pill after it." + let start = 32 + var moved = 0 + for width: CGFloat in [200, 230, 260, 300] { + let broken = layout(text.replacingOccurrences(of: "TAG", with: "pill"), width: width) + let kept = layout(text.replacingOccurrences(of: "TAG", with: "whole"), width: width) + let keptLines = linesHolding(kept, tagAt: start) + #expect(keptLines.count == 1, "\(width): \(keptLines)") + if linesHolding(broken, tagAt: start).count > 1 { + moved += 1 + // It starts the next line, with its padding before it. + #expect(keptLines[0].lowerBound == start) + let line = kept.entry(at: 0).layout.lines.first { $0.range == keptLines[0] }! + #expect(line.frame.minX >= 6 - 0.01) + } + } + #expect(moved > 0) +} + +@Test func aTagWiderThanALineStillBreaks() { + let text = "Words then a pill much too long to fit on any one line of this narrow view." + let kept = layout(text, width: 160) + let broken = layout(text.replacingOccurrences(of: "whole", with: "pill"), width: 160) + #expect(signature(kept).count == signature(broken).count) + #expect(kept.entry(at: 0).layout.lines.map(\.range) == broken.entry(at: 0).layout.lines.map(\.range)) + // A line break in it breaks it too. + let withBreak = layout("Some words to fill a line, then one
two
after it.", width: 230) + #expect(linesHolding(withBreak, tagAt: 32).count == 2) +} + +@Test func aTagThatKeepsTogetherStaysWholeInATableCell() throws { + let markdown = "| A | B |\n| --- | --- |\n| x | some text then a kept pill in a narrow cell |\n" + func lineCount(_ name: String, width: CGFloat) throws -> Int { + let block = layout(markdown.replacingOccurrences(of: "TAG", with: name), width: width).entry(at: 0).layout + let span = try #require(block.block.spans.first { $0.customTag?.name == name }) + return block.lines.filter { $0.range.overlaps(span.range) }.count + } + var split = 0 + for width: CGFloat in [160, 200, 240] { + #expect(try lineCount("whole", width: width) == 1, "\(width)") + if try lineCount("pill", width: width) > 1 { split += 1 } + } + // Without the option, the pill breaks at one of these widths at least. + #expect(split > 0) +} + +/// Text that follows a tag without a space does not make a tag that fits +/// look wider than a line. +@Test func aTagThatKeepsTogetherStaysWholeBeforeTextWithoutASpace() { + let text = "Some words to fill a line, then a long pillgluedOnAfterIt here." + var moved = 0 + for width: CGFloat in [170, 200, 230, 260, 300] { + let kept = layout(text, width: width) + let keptLines = linesHolding(kept, tagAt: 32) + #expect(keptLines.count == 1, "\(width): \(keptLines)") + if keptLines.first?.lowerBound == 32 { moved += 1 } + } + #expect(moved > 0) + // A line that starts with the tag holds all of it. + let alone = layout("a long pillgluedOnAfterItAndLongerThanTheLine", width: 120) + #expect(linesHolding(alone, tagAt: 0).count == 1) +} + +/// A column is at least as wide as a tag in it that keeps together, as it +/// is at least as wide as its longest word. +@Test func aTableColumnMakesRoomForATagThatKeepsTogether() throws { + let long = "a cell with many more words than fit in this table" + let markdown = "| A | B |\n| --- | --- |\n| a kept pill | \(long) |\n| x | \(long) |\n" + func lineCount(_ name: String) throws -> Int { + let block = layout(markdown.replacingOccurrences(of: "TAG", with: name), width: 220).entry(at: 0).layout + let span = try #require(block.block.spans.first { $0.customTag?.name == name }) + return block.lines.filter { $0.range.overlaps(span.range) }.count + } + #expect(try lineCount("whole") == 1) + #expect(try lineCount("pill") > 1) +} diff --git a/Tests/TranscriptKitTests/TagAnimationTests.swift b/Tests/TranscriptKitTests/TagAnimationTests.swift index f884ae1..8a9589d 100644 --- a/Tests/TranscriptKitTests/TagAnimationTests.swift +++ b/Tests/TranscriptKitTests/TagAnimationTests.swift @@ -359,6 +359,49 @@ func textAfterATagKeepsItsAnimationGoing(next: String) throws { #expect(before.isPlaced(like: after)) } +// MARK: Tags that start together + +/// Delays each tag by its place among the tags that start with it. +private struct Stagger: TranscriptAnimationRecipe { + func animation(for fragments: [TranscriptFragment]) -> TranscriptAnimation { + animation(for: fragments, in: .single) + } + + func animation(for fragments: [TranscriptFragment], in group: TranscriptAnimationGroup) -> TranscriptAnimation { + var animation = TranscriptAnimation() + let start = Double(group.index) * 0.1 + for (line, fragment) in fragments.enumerated() { + for index in fragment.glyphs.indices { + animation.glyphs.append(.init(fragment: line, glyph: index, offsetY: .ramp(from: -2, to: 0, start: start, duration: 0.2))) + } + } + return animation + } +} + +@Test func tagsThatStartTogetherAreNumberedInTextOrder() throws { + let staggered = [TranscriptTag("lift", TranscriptDecoration(animation: .custom(Stagger())))] + // Twelve paragraphs: block ids "s-2" and "s-10" sort the other way as text. + let paragraphs = (0..<12).map { $0 == 2 || $0 == 10 ? "Para \($0) here" : "Para \($0)" } + let layout = DocumentLayout(document: MarkdownStreamParser.document(from: paragraphs.joined(separator: "\n\n"), idPrefix: "s", + tags: staggered), width: 300) + let late = TagKey(block: "s-10", start: 5, name: "lift") + let early = TagKey(block: "s-2", start: 5, name: "lift") + let missing = TagKey(block: "s-3", start: 0, name: "lift") + let batch = layout.tagsStartingTogether([late, missing, early]) + #expect(batch.map(\.tag.key) == [early, late]) + #expect(batch.map(\.group) == [TranscriptAnimationGroup(index: 0, count: 2), TranscriptAnimationGroup(index: 1, count: 2)]) + let starts = batch.map { item in + item.tag.animation.animation(for: item.tag.fragments, in: item.group).glyphs.compactMap { $0.offsetY?.startTime }.min() + } + #expect(starts == [0, 0.1]) + + // A recipe that ignores the group plays the same for every tag. + let hop = try #require(DocumentLayout(document: document(sample), width: 260).animatedTag(TagKey(block: "a-0", start: 21, name: "hop"))) + #expect(hop.animation.animation(for: hop.fragments, in: TranscriptAnimationGroup(index: 3, count: 4)).duration + == hop.animation.animation(for: hop.fragments).duration) +} + // MARK: Timing @Test func aStreamSaysWhenItHasFinished() throws { @@ -495,3 +538,195 @@ private enum TailRendererProbe { #expect(abs(layer.frame.minY - sprite.frame.minY) < 0.001 && abs(layer.frame.height - sprite.frame.height) < 0.001) } } + +// MARK: Which waiting tags play + +private let shown = WaitingTags.Viewer(isInWindow: true, isHidden: false, visibleRect: CGRect(x: 0, y: 0, width: 300, height: 400), + isFinished: true) + +private func waitingList(_ keys: [TagKey]) -> WaitingTags { + var list = WaitingTags() + list.add(keys) + return list +} + +private let first = TagKey(block: "w-0", start: 0, name: "hop") +private let second = TagKey(block: "w-1", start: 4, name: "hop") + +@Test func waitingTagsPlayWhenTheirTimingAllows() { + let bands = [first: CGFloat(10)...30, second: CGFloat(500)...520] + var list = waitingList([first, second]) + #expect(Set(list.takeReady(timing: .immediately, viewer: shown) { bands[$0] }) == [first, second]) + #expect(list.isEmpty) + + list = waitingList([first, second]) + #expect(list.takeReady(timing: .whenVisible, viewer: shown) { bands[$0] } == [first]) + #expect(list.keys == [second]) + + list = waitingList([first, second]) + var streaming = shown + streaming.isFinished = false + #expect(list.takeReady(timing: .afterStreamFinishes, viewer: streaming) { bands[$0] }.isEmpty) + + // Requested: only the tags waiting when the app asked. + list = waitingList([first]) + list.request() + list.add([second]) + #expect(list.takeReady(timing: .whenRequested, viewer: shown) { bands[$0] } == [first]) + #expect(list.keys == [second] && list.requested.isEmpty) +} + +/// Out of its window, a view plays nothing, and tags that wait to be seen +/// or for the app keep waiting until it comes back. +@Test func waitingTagsWaitForTheViewToBeInAWindow() { + var away = shown + away.isInWindow = false + let band: (TagKey) -> ClosedRange? = { _ in 10...30 } + for timing: TranscriptAnimationTiming in [.immediately, .whenVisible, .whenRequested, .afterStreamFinishes] { + var list = waitingList([first]) + list.request() + #expect(list.takeReady(timing: timing, viewer: away, band: band).isEmpty) + #expect(list.keys == [first]) + // Back in the window, they play. + #expect(list.takeReady(timing: timing, viewer: shown, band: band) == [first]) + } + #expect(WaitingTags.keepWaitingOutsideWindow(.whenVisible)) + #expect(WaitingTags.keepWaitingOutsideWindow(.whenRequested)) + #expect(WaitingTags.keepWaitingOutsideWindow([.whenVisible, .afterStreamFinishes])) + #expect(!WaitingTags.keepWaitingOutsideWindow(.immediately)) + #expect(!WaitingTags.keepWaitingOutsideWindow(.afterStreamFinishes)) +} + +@Test func aHiddenViewIsNotVisible() { + var hidden = shown + hidden.isHidden = true + let band: (TagKey) -> ClosedRange? = { _ in 10...30 } + var list = waitingList([first]) + #expect(list.takeReady(timing: .whenVisible, viewer: hidden, band: band).isEmpty) + #expect(list.waitForHiddenView(timing: .whenVisible, viewer: hidden)) + #expect(!list.waitForHiddenView(timing: .whenVisible, viewer: shown)) + #expect(!list.waitForHiddenView(timing: .whenRequested, viewer: hidden)) + // Other timings do not look. + #expect(list.takeReady(timing: .afterStreamFinishes, viewer: hidden, band: band) == [first]) + + #expect(!WaitingTags.isHidden([(isHidden: false, alpha: 1), (isHidden: false, alpha: 0.5)])) + #expect(WaitingTags.isHidden([(isHidden: false, alpha: 1), (isHidden: true, alpha: 1)])) + #expect(WaitingTags.isHidden([(isHidden: false, alpha: 1), (isHidden: false, alpha: 0)])) + #expect(WaitingTags.isHidden([(isHidden: false, alpha: 0.001)])) +} + +@Test func keptWaitingTagsAreTheOnesStillLaidOut() { + var list = waitingList([first, second]) + list.request() + list.keep([second]) + #expect(list.keys == [second] && list.requested == [second]) + #expect(list.removeAll() == [second]) + #expect(list.isEmpty && list.requested.isEmpty) +} + +// MARK: Text that is complete when it is shown + +/// A document built directly, with its tags closed: the view can hold each +/// of them back to play, and the engine draws the tail without their shapes +/// until the view starts them. +@Test func closedTagsOfAFirstLayoutCanWaitToPlay() throws { + let hop = try #require(tags.first { $0.name == "hop" }) + let text = "Done: login timeouts. Next: billing." + let blocks = [ + TranscriptBlock(id: "d-0", text: text, spans: [ + InlineSpan(range: 6..<20, tagged: InlineSpan.CustomTag(hop)), + InlineSpan(range: 28..<35, tagged: InlineSpan.CustomTag(hop)), + ]), + ] + let document = TranscriptDocument(blocks: blocks) + let layout = DocumentLayout(document: document, width: 300) + let keys: Set = [TagKey(block: "d-0", start: 6, name: "hop"), TagKey(block: "d-0", start: 28, name: "hop")] + #expect(layout.closedAnimatedTags() == keys) + // Settled blocks are not newly closed: the engine does not start their tags on its own. + #expect(layout.newlyClosedAnimatedTags(since: DocumentLayout(document: document, width: 300)).isEmpty) + #expect(layout.tagsStartingTogether(keys).map(\.group.index) == [0, 1]) + + let engine = LayoutEngine() + engine.setTailStyle(colors: colors, scale: 2) + engine.setAnimationsEnabled(true, immediately: false) + engine.submit(.init(document: document, source: 1, sequence: 1, isFinished: true)) + let laidOut = try #require(engine.relayout(width: 300, style: TranscriptStyle())) + engine.holdAnimations(laidOut.layout.closedAnimatedTags()) + var more = document + more.append(TranscriptBlock(id: "d-1", text: "More.")) + engine.submit(.init(document: more, source: 1, sequence: 2, isFinished: true)) + engine.drainNow() + #expect(try #require(engine.takeOutput()).hidden == TagHiding(waiting: keys)) + engine.playAnimations(keys) + var last = more + last.append(TranscriptBlock(id: "d-2", text: "Last.")) + engine.submit(.init(document: last, source: 1, sequence: 3, isFinished: true)) + engine.drainNow() + #expect(try #require(engine.takeOutput()).hidden == TagHiding(playing: keys)) +} + +/// A view asks where each waiting tag is only once for each layout: a +/// scroll looks at every waiting tag. +@Test func waitingTagsRememberWhereTheyAre() { + var asked: [TagKey] = [] + var list = waitingList([first, second]) + let offScreen = WaitingTags.Viewer(isInWindow: true, isHidden: false, visibleRect: CGRect(x: 0, y: 1000, width: 300, height: 400), + isFinished: true) + for _ in 0..<3 { + #expect(list.takeReady(timing: .whenVisible, viewer: offScreen) { asked.append($0); return 10...30 }.isEmpty) + } + #expect(asked.count == 2) + list.forgetBands() + _ = list.takeReady(timing: .whenVisible, viewer: offScreen) { asked.append($0); return 10...30 } + #expect(asked.count == 4) + #expect(Set(list.takeReady(timing: .whenVisible, viewer: shown) { asked.append($0); return 10...30 }) == [first, second]) + #expect(asked.count == 4) +} + +@Test func someWaitingTagsCanBeRequested() { + var list = waitingList([first]) + list.request([first, second]) + #expect(list.requested == [first]) +} + +// MARK: What goes on when a view shows a new layout + +private let third = TagKey(block: "w-2", start: 0, name: "hop") + +@Test func aRelayoutOfTheSameTextKeepsTagsThatWaitOrPlay() { + let closed: Set = [first, second, third] + let carried = WaitingTags.carried(isAppend: false, keepsText: true, firstText: false, closed: closed, + waiting: [first], started: [], playing: [second, third]) { $0 == second } + // The second still plays where it was; the third moved, so it plays again. + #expect(carried == WaitingTags.Carried(playing: [second], waiting: [first, third], replayed: [third])) + + // Tags the layout no longer holds go. + let fewer = WaitingTags.carried(isAppend: false, keepsText: true, firstText: false, closed: [second], + waiting: [first], started: [], playing: [second, third]) { _ in true } + #expect(fewer == WaitingTags.Carried(playing: [second])) +} + +@Test func aNewDocumentShowsEveryTagAtRest() { + let carried = WaitingTags.carried(isAppend: false, keepsText: false, firstText: false, closed: [first, second], + waiting: [first], started: [], playing: [second]) { _ in true } + #expect(carried == WaitingTags.Carried()) +} + +@Test func theFirstTextHoldsItsClosedTagsBack() { + // Laid out directly, every closed tag waits to play. + let direct = WaitingTags.carried(isAppend: false, keepsText: false, firstText: true, closed: [first, second], + waiting: [], started: [], playing: []) { _ in true } + #expect(direct == WaitingTags.Carried(waiting: [first, second])) + // Appended to an empty layout: the tags that the engine did not start or hold. + let appended = WaitingTags.carried(isAppend: true, keepsText: false, firstText: true, closed: [first, second, third], + waiting: [], started: [first], playing: [first]) { _ in true } + #expect(appended == WaitingTags.Carried(waiting: [second, third])) + // With animations off in the engine, as out of a window, it started none. + let unstarted = WaitingTags.carried(isAppend: true, keepsText: false, firstText: true, closed: [first, second], + waiting: [], started: [], playing: []) { _ in true } + #expect(unstarted == WaitingTags.Carried(waiting: [first, second])) + // Later appends hold nothing back. + let later = WaitingTags.carried(isAppend: true, keepsText: false, firstText: false, closed: [first, second], + waiting: [], started: [], playing: []) { _ in true } + #expect(later == WaitingTags.Carried()) +} diff --git a/Tests/TranscriptKitTests/TagImageTests.swift b/Tests/TranscriptKitTests/TagImageTests.swift index 6e80218..bf00fcf 100644 --- a/Tests/TranscriptKitTests/TagImageTests.swift +++ b/Tests/TranscriptKitTests/TagImageTests.swift @@ -96,3 +96,65 @@ private func glyphX(_ layout: DocumentLayout, at offset: Int) -> CGFloat { #expect(image.tint == blue) #expect(image != TranscriptTagImage(image.image, size: image.size)) } + +private struct Nudge: TranscriptAnimationRecipe { + func animation(for fragments: [TranscriptFragment]) -> TranscriptAnimation { + TranscriptAnimation(glyphs: [.init(fragment: 0, glyph: 0, offsetY: .ramp(from: -2, to: 0, duration: 0.2))]) + } +} + +/// The red at the image's centre, drawn with `hiding`. +private func imageIsDrawn(_ laidOut: DocumentLayout, hiding: TagHiding) throws -> Bool { + let line = laidOut.entry(at: 0).layout.lines[0] + let start = try #require(expectedImageRect(laidOut)) + let scale: CGFloat = 2 + let width = Int((laidOut.width * scale).rounded()) + let height = Int((laidOut.height * scale).rounded()) + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(gray: 1, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: scale, y: -scale) + laidOut.draw(in: context, dirtyRect: CGRect(x: 0, y: 0, width: laidOut.width, height: laidOut.height), + text: CGColor(gray: 0, alpha: 1), codeBackground: CGColor(gray: 0.9, alpha: 1), + accent: CGColor(gray: 0.6, alpha: 1), dark: false, highContrast: false, hiding: hiding) + let bytes = UnsafeRawBufferPointer(start: context.data!, count: width * height * 4) + let x = Int(((line.frame.minX + start.midX) * scale).rounded()) + let y = Int(((laidOut.entry(at: 0).y + line.baseline + start.midY) * scale).rounded()) + let index = (y * width + x) * 4 + return bytes[index] > 200 && bytes[index + 1] < 60 && bytes[index + 2] < 60 +} + +/// Where the image of a tag that starts at offset 4 goes: 14 points wide, +/// 4 points before the text, on the cap height. +private func expectedImageRect(_ laidOut: DocumentLayout) -> CGRect? { + let line = laidOut.entry(at: 0).layout.lines[0] + let textStart = glyphStart(line, at: 4) + guard textStart.isFinite else { return nil } + let capHeight = CTFontGetCapHeight(TranscriptStyle().font(for: .paragraph)) + return CGRect(x: textStart - 4 - 14, y: -capHeight / 2 - 7, width: 14, height: 14) +} + +@Test(arguments: [false, true]) +func anAnimatedTagCanShowItsImageBeforeItsAnimationEnds(showsDuringAnimation: Bool) throws { + let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), gap: 4, + showsDuringAnimation: showsDuringAnimation) + let tag = TranscriptTag("chip", TranscriptDecoration(padding: 2, animation: .custom(Nudge()), image: image)) + var parser = MarkdownStreamParser(idPrefix: "a", tags: [tag]) + parser.append("See Friday") + let open = DocumentLayout(document: parser.document, width: 300) + #expect(try imageIsDrawn(open, hiding: .none) == showsDuringAnimation) + + parser.append(" soon") + let closed = DocumentLayout(document: parser.document, width: 300, reusing: open) + let key = TagKey(block: "a-0", start: 4, name: "chip") + #expect(closed.animatedTag(key) != nil) + #expect(try imageIsDrawn(closed, hiding: TagHiding(waiting: [key])) == showsDuringAnimation) + #expect(try imageIsDrawn(closed, hiding: TagHiding(playing: [key])) == showsDuringAnimation) + // Once the animation has played, it shows either way. + #expect(try imageIsDrawn(closed, hiding: .none)) + // The text stays where it was. + #expect(abs(glyphStart(open.entry(at: 0).layout.lines[0], at: 4) - glyphStart(closed.entry(at: 0).layout.lines[0], at: 4)) < 0.01) +} diff --git a/Tests/TranscriptKitTests/TileGridTests.swift b/Tests/TranscriptKitTests/TileGridTests.swift index a6ce2ba..62f1b11 100644 --- a/Tests/TranscriptKitTests/TileGridTests.swift +++ b/Tests/TranscriptKitTests/TileGridTests.swift @@ -59,3 +59,50 @@ import Testing #expect(layout.height >= TileGrid.height) #expect(layout.glyphBottom == layout.height) } + +@Test func theFirstTileStartsAboveTheView() { + let overhang = TranscriptPath.maximumOverhang + for viewHeight: CGFloat in [1, 20, 26, 27, 100, 250, 300, 600] { + let first = TileGrid.tileFrame(at: 0, viewHeight: viewHeight) + #expect(first.top == -overhang) + // Its bottom stays where it was, under the view and the shapes below it. + #expect(first.top + first.height == TileGrid.tileHeight(at: 0, viewHeight: viewHeight)) + } + let second = TileGrid.tileFrame(at: 1, viewHeight: 600) + #expect(second.top == TileGrid.height && second.height == TileGrid.height) + // Glyphs that draw below the text are still covered. + let marked = TileGrid.tileFrame(at: 0, viewHeight: 21, glyphBottom: 35) + #expect(marked.top + marked.height >= 35) +} + +/// A pill with room above the text, on the first line of a view without +/// padding, reaches above the view: the first tile and the tail draw it. +@Test func aPillAboveTheFirstLineIsDrawn() throws { + let red = TranscriptColor(red: 1, green: 0, blue: 0) + let tag = TranscriptTag("pill", TranscriptDecoration(padding: 4, shapes: [.pill(fill: red, verticalPadding: 4)])) + let document = MarkdownStreamParser.document(from: "Pill on the first line", idPrefix: "p", tags: [tag]) + let layout = DocumentLayout(document: document, width: 300) + let line = layout.entry(at: 0).layout.lines[0] + #expect(layout.entry(at: 0).y + line.inkTop < -2) + #expect(TailRenderer.lastLineTop(of: layout, scale: 2) < -2) + #expect(TailRenderer.lastLineTop(of: layout, scale: 2) >= -TranscriptPath.maximumOverhang) + + // Drawn into the first tile's rows, the pill shows above y = 0. + let scale: CGFloat = 2 + let tile = TileGrid.tileFrame(at: 0, viewHeight: layout.height) + let width = Int((layout.width * scale).rounded()) + let height = Int((tile.height * scale).rounded()) + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: scale, y: -scale) + context.translateBy(x: 0, y: -tile.top) + let rows = CGRect(x: 0, y: tile.top, width: layout.width, height: tile.height) + layout.draw(in: context, dirtyRect: rows, text: CGColor(gray: 0, alpha: 1), codeBackground: CGColor(gray: 0.9, alpha: 1), + accent: CGColor(gray: 0.6, alpha: 1)) + let bytes = UnsafeRawBufferPointer(start: context.data!, count: width * height * 4) + // One point above the view, in the middle of the pill. + let x = Int(((line.frame.minX + 12) * scale).rounded()) + let y = Int(((-1 - tile.top) * scale).rounded()) + #expect(bytes[(y * width + x) * 4] > 200) +}