Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 57 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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

Expand Down
45 changes: 42 additions & 3 deletions Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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),
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions Sources/TranscriptKit/Layout/LayoutEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<TagKey>) {
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<TagKey>) {
Expand Down Expand Up @@ -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?
Expand Down
Loading
Loading