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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut
link, padding, and shapes drawn behind or over the text. Pills and underlines (solid, dashed, dotted, wavy,
marker) are built in, and you can draw shapes of your own, and animate a tag's letters and shapes when it
finishes arriving.
- **Fade-in.** Optionally, text fades in as it streams in. Core Animation plays the fades.
- **SwiftUI and UIKit.** `TranscriptText` for SwiftUI, `TranscriptTextView` for UIKit.

## Requirements
Expand Down Expand Up @@ -177,6 +178,21 @@ In UIKit, set `tagAnimationTiming` on `TranscriptTextView` and call `playTagAnim
waiting when it can no longer play (Reduce Motion turned on, animations turned off, the view leaving its window, a
new document) is shown as it ends up.

### Fading in text

Text that streams in can fade in. Each update's new text fades in on its own, so the fade follows the text as it
arrives. It is off by default.

```swift
TranscriptText(stream: stream)
.fadesInText(duration: 0.3)
```

In UIKit, set `textFadeInDuration` on `TranscriptTextView`. TranscriptKit draws the new text on the layout queue,
and Core Animation plays each fade, so the main thread does no work for each frame of a fade. Glyphs and their
underline and strikethrough fade in. Backgrounds, images and formulas show at once. A tag that starts its animation
ends the fades. The fade is off with Reduce Motion, and with a line limit.

### Images

Images in the text show their alt text unless you provide a loader. The library never fetches anything itself, so
Expand Down
2 changes: 2 additions & 0 deletions Sources/TranscriptKit/Diagnostics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ public enum TranscriptDiagnostics {
public var tileDraws = 0
/// Tails drawn on the layout queue (see `TailRenderer`).
public var tailFrames = 0
/// Text fading in, drawn on the layout queue (see `FadeRenderer`).
public var fadeFrames = 0
}

private static let lock = NSLock()
Expand Down
90 changes: 58 additions & 32 deletions Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,19 @@ public final class DocumentLayout: @unchecked Sendable {
lastEntryIndex(where: { CGFloat($0.start) }, isAtMost: CGFloat(offset))
}

/// The lines with text at or after `offset`, in order, with their blocks.
func lines(from offset: Int) -> [(entry: Entry, line: BlockLayout.Line)] {
guard let first = entryIndex(forOffset: offset) else { return [] }
var result: [(entry: Entry, line: BlockLayout.Line)] = []
for index in first..<entryCount {
let entry = entry(at: index)
for line in entry.layout.lines where !line.range.isEmpty && entry.start + line.range.upperBound > offset {
result.append((entry, line))
}
}
return result
}

public func caretRect(at offset: Int) -> CGRect {
guard let index = entryIndex(forOffset: offset) else {
return CGRect(x: 0, y: 0, width: 2, height: style.effectiveBodySize * 1.2)
Expand Down Expand Up @@ -361,37 +374,8 @@ public final class DocumentLayout: @unchecked Sendable {
// The glyphs for the characters in `hidden` (the line's string
// indexes) are left out.
func drawLine(_ line: CTLine, at origin: CGPoint, hidden: [Range<Int>] = []) {
let runs = CTLineGetGlyphRuns(line) as! [CTRun]
drawHighlights(runs, at: origin)
for run in runs {
let attributes = CTRunGetAttributes(run) as NSDictionary
if attributes[Self.imageKey] != nil { continue }
Self.setGlyphColor(of: attributes, in: context, text: text, dark: dark)
context.textPosition = origin
if hidden.isEmpty {
CTRunDraw(run, context, CFRange(location: 0, length: 0))
} else {
for range in Self.glyphRanges(of: run, leavingOut: hidden) { CTRunDraw(run, context, range) }
}
let custom = (attributes[Self.foregroundKey] as? TranscriptColor)?.cgColor(dark: dark)
let strike = attributes[Self.strikethroughKey] != nil
let underline = attributes[Self.underlineKey] != nil
guard strike || underline, let font = attributes[kCTFontAttributeName].map({ $0 as! CTFont }) else { continue }
var position = CGPoint.zero
CTRunGetPositions(run, CFRange(location: 0, length: 1), &position)
let runWidth = CGFloat(CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), nil, nil, nil))
let color = custom ?? attributes[kCTForegroundColorAttributeName].map { $0 as! CGColor } ?? text
let thickness = max(CTFontGetUnderlineThickness(font), 1)
context.setFillColor(color)
if strike {
let y = origin.y - CTFontGetXHeight(font) / 2 - thickness / 2
context.fill(CGRect(x: origin.x + position.x, y: y, width: runWidth, height: thickness))
}
if underline {
let y = origin.y - CTFontGetUnderlinePosition(font)
context.fill(CGRect(x: origin.x + position.x, y: y, width: runWidth, height: thickness))
}
}
drawHighlights(CTLineGetGlyphRuns(line) as! [CTRun], at: origin)
Self.drawGlyphs(of: line, at: origin, hidden: hidden, in: context, text: text, dark: dark)
}

func fill(_ rect: CGRect, radius: CGFloat, color: CGColor) {
Expand Down Expand Up @@ -538,7 +522,10 @@ public final class DocumentLayout: @unchecked Sendable {

for index in visible where !lines[index].range.isEmpty {
let line = lines[index]
let hidden = line.decorations?.hiddenRanges(hiding.playing) ?? []
var hidden = line.decorations?.hiddenRanges(hiding.playing) ?? []
if let from = hiding.fadingFrom, entry.start + line.range.upperBound > from {
hidden.append(max(from - entry.start, line.range.lowerBound)..<line.range.upperBound)
}
drawLine(line.ctLine, at: CGPoint(x: line.frame.minX, y: entry.y + line.baseline),
hidden: hidden.map { ($0.lowerBound - line.indexBase)..<($0.upperBound - line.indexBase) })
}
Expand All @@ -560,6 +547,45 @@ public final class DocumentLayout: @unchecked Sendable {
context.setFillColor(custom ?? text)
}

/// Draws a line's glyphs, and their strikethrough and underline, leaving
/// out the characters in `hidden` (line string indexes). Images are left
/// to the caller. The context's text matrix must flip glyphs upright.
static func drawGlyphs(of line: CTLine, at origin: CGPoint, hidden: [Range<Int>], in context: CGContext, text: CGColor, dark: Bool) {
for run in CTLineGetGlyphRuns(line) as! [CTRun] {
let attributes = CTRunGetAttributes(run) as NSDictionary
if attributes[imageKey] != nil { continue }
let ranges = hidden.isEmpty ? [CFRange(location: 0, length: 0)] : glyphRanges(of: run, leavingOut: hidden)
guard !ranges.isEmpty else { continue }
setGlyphColor(of: attributes, in: context, text: text, dark: dark)
context.textPosition = origin
for range in ranges { CTRunDraw(run, context, range) }
let custom = (attributes[foregroundKey] as? TranscriptColor)?.cgColor(dark: dark)
let strike = attributes[strikethroughKey] != nil
let underline = attributes[underlineKey] != nil
guard strike || underline, let font = attributes[kCTFontAttributeName].map({ $0 as! CTFont }) else { continue }
let color = custom ?? attributes[kCTForegroundColorAttributeName].map { $0 as! CGColor } ?? text
let thickness = max(CTFontGetUnderlineThickness(font), 1)
context.setFillColor(color)
// Ends on whole pixels, so that a line drawn in two parts (some
// of its text fading in) covers the same pixels as one.
func fill(x: CGFloat, y: CGFloat, width: CGFloat) {
var device = context.convertToDeviceSpace(CGRect(x: x, y: y, width: width, height: thickness))
let minX = device.minX.rounded()
device.size.width = device.maxX.rounded() - minX
device.origin.x = minX
guard device.width > 0 else { return }
context.fill(context.convertToUserSpace(device))
}
for range in ranges {
var position = CGPoint.zero
CTRunGetPositions(run, CFRange(location: range.location, length: 1), &position)
let width = CGFloat(CTRunGetTypographicBounds(run, range, nil, nil, nil))
if strike { fill(x: origin.x + position.x, y: origin.y - CTFontGetXHeight(font) / 2 - thickness / 2, width: width) }
if underline { fill(x: origin.x + position.x, y: origin.y - CTFontGetUnderlinePosition(font), width: width) }
}
}
}

/// The runs of `run`'s glyphs whose characters are not in `hidden`.
static func glyphRanges(of run: CTRun, leavingOut hidden: [Range<Int>]) -> [CFRange] {
let count = CTRunGetGlyphCount(run)
Expand Down
163 changes: 163 additions & 0 deletions Sources/TranscriptKit/Layout/FadeRenderer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import CoreGraphics
import CoreText
import Foundation

/// Text that arrived in one update and fades in from then on.
struct Fade: Sendable {
let id: Int
/// Flat offsets.
let range: Range<Int>
/// When it started, in `CACurrentMediaTime()`.
let start: CFTimeInterval
}

/// The text that is fading in, drawn on the layout queue for the view's fade
/// layers: one piece for each fade on each line, with only that fade's
/// glyphs on it.
struct FadeFrame: @unchecked Sendable {
struct Piece: @unchecked Sendable {
let fade: Int
let start: CFTimeInterval
/// Where it goes, in document points, on whole pixels.
let frame: CGRect
/// The same object as in the last frame while the piece is unchanged,
/// so the view gives Core Animation a new image only when it is new.
let image: CGImage
}

let pieces: [Piece]
let scale: CGFloat
}

/// Draws the pieces of the text that fades in. A piece is drawn once and
/// kept while its glyphs stay where they are; the text that fades is laid
/// out again with every update, so a word that wraps or a centered line
/// that moves gets its pieces drawn again.
///
/// Not thread-safe: use it from one queue (the layout engine's).
final class FadeRenderer {
private struct Placement: Equatable {
let range: Range<Int>
let frame: CGRect
let origin: CGPoint
let style: Style
}

/// What the text's look comes from: text whose style changed in place
/// (code colors arrived, a reference became a link) is drawn again.
private struct Style: Equatable {
let spans: [InlineSpan]
let imageRevision: Int?
let definitions: Int
}

private struct Drawn {
let placement: Placement
let image: CGImage
}

/// The pieces drawn last, by fade.
private var drawn: [Int: [Drawn]] = [:]
private var colors: TailRenderer.Colors?
private var scale: CGFloat = 0

/// How far a line's glyphs may reach beyond its box: accents, descenders,
/// emoji, italic overhangs.
static func margin(of line: BlockLayout.Line) -> (x: CGFloat, y: CGFloat) {
(8, max(line.frame.height, 8))
}

/// - Parameter from: where the text left out of the tail and the tiles
/// starts; the oldest fade may start before it.
func render(_ layout: DocumentLayout, from: Int, fades: [Fade], colors: TailRenderer.Colors, scale: CGFloat,
playing: Set<TagKey>) -> FadeFrame? {
if scale != self.scale || self.colors.map({ $0.text != colors.text || $0.dark != colors.dark }) ?? true {
drawn.removeAll()
self.colors = colors
self.scale = scale
}
let live = Set(fades.map(\.id))
drawn = drawn.filter { live.contains($0.key) }
guard !fades.isEmpty, from < layout.length, scale > 0 else { return nil }
func pixel(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { (value * scale).rounded(rule) / scale }

let lines = layout.lines(from: from)
let rightToLeft = lines.map { Self.hasRightToLeftText($0.line.ctLine) }
let definitions = layout.document.linkDefinitions.count
var pieces: [FadeFrame.Piece] = []
for fade in fades {
let previous = drawn[fade.id] ?? []
var current: [Drawn] = []
for (index, (entry, line)) in lines.enumerated() {
let lineStart = entry.start + line.range.lowerBound
let lineEnd = entry.start + line.range.upperBound
let lower = max(fade.range.lowerBound, lineStart, from)
let upper = min(fade.range.upperBound, lineEnd)
guard lower < upper else { continue }
let range = lower..<upper
let margin = Self.margin(of: line)
let origin = CGPoint(x: line.frame.minX, y: entry.y + line.baseline)
var minX = line.frame.minX
var maxX = line.frame.maxX
if !rightToLeft[index] {
let carets = [range.lowerBound, range.upperBound].map {
origin.x + CTLineGetOffsetForStringIndex(line.ctLine, $0 - entry.start - line.indexBase, nil)
}
minX = carets.min()!
maxX = carets.max()!
}
let frame = CGRect(x: pixel(minX - margin.x, .down), y: pixel(entry.y + line.frame.minY - margin.y, .down),
width: 0, height: 0)
let placement = Placement(
range: range,
frame: CGRect(x: frame.minX, y: frame.minY, width: pixel(maxX + margin.x, .up) - frame.minX,
height: pixel(entry.y + line.frame.maxY + margin.y, .up) - frame.minY),
origin: origin,
style: Style(spans: entry.layout.block.spans.filter {
$0.range.lowerBound < range.upperBound - entry.start && $0.range.upperBound > range.lowerBound - entry.start
}, imageRevision: entry.layout.imageRevision, definitions: definitions))
let image: CGImage
if current.count < previous.count, previous[current.count].placement == placement {
image = previous[current.count].image
} else {
var hidden = line.decorations?.hiddenRanges(playing) ?? []
let local = (range.lowerBound - entry.start)..<(range.upperBound - entry.start)
if local.lowerBound > line.range.lowerBound { hidden.append(line.range.lowerBound..<local.lowerBound) }
if local.upperBound < line.range.upperBound { hidden.append(local.upperBound..<line.range.upperBound) }
guard let drawnImage = Self.draw(line, at: origin, in: placement.frame, hiding: hidden, colors: colors, scale: scale)
else { continue }
image = drawnImage
}
current.append(Drawn(placement: placement, image: image))
pieces.append(.init(fade: fade.id, start: fade.start, frame: placement.frame, image: image))
}
drawn[fade.id] = current
}
return FadeFrame(pieces: pieces, scale: scale)
}

/// `line`'s glyphs, leaving out `hidden` (block offsets), in a bitmap of `frame`.
private static func draw(_ line: BlockLayout.Line, at origin: CGPoint, in frame: CGRect, hiding hidden: [Range<Int>],
colors: TailRenderer.Colors, scale: CGFloat) -> CGImage? {
let width = Int((frame.width * scale).rounded())
let height = Int((frame.height * scale).rounded())
guard width > 0, height > 0, let space = CGColorSpace(name: CGColorSpace.sRGB),
let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
else { return nil }
// Top-left origin, in document points.
context.translateBy(x: 0, y: CGFloat(height))
context.scaleBy(x: scale, y: -scale)
context.translateBy(x: -frame.minX, y: -frame.minY)
context.textMatrix = CGAffineTransform(scaleX: 1, y: -1)
DocumentLayout.drawGlyphs(of: line.ctLine, at: origin,
hidden: hidden.map { ($0.lowerBound - line.indexBase)..<($0.upperBound - line.indexBase) },
in: context, text: colors.text, dark: colors.dark)
return context.makeImage()
}

private static func hasRightToLeftText(_ line: CTLine) -> Bool {
(CTLineGetGlyphRuns(line) as! [CTRun]).contains { CTRunGetStatus($0).contains(.rightToLeft) }
}
}
Loading
Loading