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
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut
- fenced and indented code blocks, colored by a highlighter your app provides, and tables;
- links, bare URLs and email addresses, and reference links;
- images, drawn by a loader your app provides;
- LaTeX math, drawn by a renderer your app provides;
- HTML entities and a few HTML tags.
- **Custom tags.** Define tags such as `<mention id="ana">@Ana</mention>` and how they look: font traits, colours, a
link, padding, and shapes drawn behind or over the text. Pills and underlines (solid, dashed, dotted, wavy,
Expand Down Expand Up @@ -205,6 +206,34 @@ TranscriptText(stream: stream)
In UIKit, set `codeHighlighter` on `TranscriptTextView`. Colors are `TranscriptColor`s, so give them a light and a dark
value when the theme has both.

### Math

LaTeX between `\(` and `\)` is inline math. A line that starts with `\[` or `$$` starts display math, which ends at
`\]` or `$$`. Display math is a block of its own and can span lines: TranscriptKit keeps its lines as written, even a
line that starts with `-` or `#`. If a blank line comes before the closer, it is not a formula, and its lines show as
text. `$$ … $$` inside a line is display math too. A `\[` inside a line is a Markdown escape, so `\[1\]` shows `[1]`.
A single `$` is text, so prices stay as written. TranscriptKit does not read Markdown inside a formula.

Without a renderer, a formula shows its LaTeX in the code font. A renderer gets the formula and the font size of the
text around it. It returns an image, the image's size in points, and its baseline: the distance from the bottom edge
up to the baseline. TranscriptKit calls it off the main thread, once for each formula and font size.

```swift
TranscriptText(stream: stream)
.mathRenderer { math, fontSize in
guard let drawn = await myMathRenderer.draw(math.tex, display: math.isDisplay, fontSize: fontSize) else {
return nil
}
return TranscriptMathImage(image: drawn.cgImage, size: drawn.size, baseline: drawn.descent)
}
```

In UIKit, set `mathRenderer` on `TranscriptTextView`. TranscriptKit uses only the alpha of the image, and draws the
formula in the text color, so it follows light and dark appearance. A formula that is wider than the text column is
scaled down to fit. A paragraph that holds only display math is centered. While a formula streams in, it shows
nothing until it closes, so the text on screen only grows. Copy gives the LaTeX with its delimiters, and VoiceOver
reads the LaTeX.

### Selection

The text is selectable by default. Turn selection off for text inside a view that reacts to taps, such as a card or a
Expand Down
8 changes: 6 additions & 2 deletions Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ final class BlockLayout: @unchecked Sendable {

let insets = style.insets(for: block)
let available = max(width - insets.leading - insets.trailing, 1)
let hasImages = block.spans.contains { $0.image != nil }
let hasImages = block.spans.contains { $0.image != nil || $0.math != nil }
// Laid out again when the store's pictures or code colors change.
let usesStore = hasImages || (block.kind.isCode && images?.hasHighlighter == true)
let revision = usesStore ? (images?.revision ?? 0) : nil
Expand Down Expand Up @@ -182,9 +182,13 @@ final class BlockLayout: @unchecked Sendable {

let fixedHeight = style.lineHeight(for: block.kind)
let gap = fixedHeight == nil ? style.lineSpacing : 0
let isDisplayMath = block.spans.count == 1 && block.spans[0].math?.isDisplay == true
&& block.text.trimmingCharacters(in: .whitespacesAndNewlines) == "\u{FFFC}"
func add(_ ctLine: CTLine, range: Range<Int>, indexBase: Int, leading: CGFloat = 0, text: NSAttributedString? = nil) {
let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight)
let x = insets.leading + leading + alignmentOffset(block, style: style, width: metrics.width, room: available - leading)
let x = insets.leading + leading + (isDisplayMath
? max(((available - leading - metrics.width) / 2).rounded(.down), 0)
: alignmentOffset(block, style: style, width: metrics.width, room: available - leading))
var decorations: LineDecorations?
if let decorated, let text {
decorations = LineDecorations.make(line: ctLine, range: range, indexBase: indexBase, visibleWidth: metrics.width,
Expand Down
9 changes: 8 additions & 1 deletion Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,14 @@ public final class DocumentLayout: @unchecked Sendable {
context.translateBy(x: rect.minX, y: rect.maxY)
context.scaleBy(x: 1, y: -1)
context.interpolationQuality = .high
context.draw(picture, in: CGRect(origin: .zero, size: rect.size))
let box = CGRect(origin: .zero, size: rect.size)
if attachment.isMask {
context.clip(to: box, mask: picture)
context.setFillColor(text)
context.fill(box)
} else {
context.draw(picture, in: box)
}
return
}
// No picture: a chip with the alt text.
Expand Down
55 changes: 55 additions & 0 deletions Sources/TranscriptKit/Layout/ImageStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,61 @@ final class TranscriptImageStore: @unchecked Sendable {
handler?()
}

// MARK: Formulas

private struct FormulaKey: Hashable {
let math: TranscriptMath
/// The font size, to half a point.
let size: Int
}

private var mathRenderer: TranscriptMathRenderer?
private var mathGeneration = 0
private var formulas: [FormulaKey: TranscriptMathImage] = [:]
private var formulasRequested: Set<FormulaKey> = []

var hasMathRenderer: Bool { lock.withLock { mathRenderer != nil } }

/// Sets the math renderer. Formulas drawn by an earlier one are dropped,
/// and the revision goes up so that they are laid out again.
func setMathRenderer(_ renderer: TranscriptMathRenderer?) {
lock.withLock {
mathRenderer = renderer
mathGeneration += 1
_revision += 1
formulas = [:]
formulasRequested = []
}
}

/// The drawn formula if it has arrived. Starts drawing it if not.
func formula(for math: TranscriptMath, fontSize: CGFloat) -> TranscriptMathImage? {
let key = FormulaKey(math: math, size: Int((fontSize * 2).rounded()))
let (formula, render, generation): (TranscriptMathImage?, TranscriptMathRenderer?, Int) = lock.withLock {
if let formula = formulas[key] { return (formula, nil, mathGeneration) }
guard let mathRenderer, !formulasRequested.contains(key) else { return (nil, nil, mathGeneration) }
formulasRequested.insert(key)
return (nil, mathRenderer, mathGeneration)
}
if let render {
Task.detached { [weak self] in
let drawn = await render(math, CGFloat(key.size) / 2)?.withAlphaAsMask()
self?.finishFormula(key, drawn, generation: generation)
}
}
return formula
}

private func finishFormula(_ key: FormulaKey, _ formula: TranscriptMathImage?, generation: Int) {
let handler: (@Sendable () -> Void)? = lock.withLock {
guard generation == mathGeneration, let formula else { return nil }
formulas[key] = formula
_revision += 1
return onChange
}
handler?()
}

/// The picture for `image` if it has arrived. Starts loading it if not.
func picture(for image: TranscriptImage) -> CGImage? {
let (picture, load, generation): (CGImage?, Loader?, Int) = lock.withLock {
Expand Down
46 changes: 44 additions & 2 deletions Sources/TranscriptKit/Layout/TranscriptStyle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -257,13 +257,15 @@ public struct TranscriptStyle: Equatable, Sendable {
var traits = extraTraits
var isLink = false
var image: TranscriptImage?
var math: TranscriptMath?
// Spans are sorted with outer ones first, so an inner tag's colors win.
var foreground: TranscriptColor?
var background: TranscriptColor?
for span in spans where span.range.lowerBound <= lower && span.range.upperBound >= upper {
traits.formUnion(span.traits)
if span.link != nil || span.reference.map({ definitions[$0] != nil }) == true { isLink = true }
if let spanImage = span.image { image = spanImage }
if let spanMath = span.math { math = spanMath }
if let decoration = span.customTag?.decoration {
if let color = decoration.foreground { foreground = color }
if let color = decoration.background { background = color }
Expand All @@ -283,9 +285,10 @@ public struct TranscriptStyle: Equatable, Sendable {
result.addAttribute(Self.foregroundKey, value: linkColor, range: range)
}
if let background { result.addAttribute(Self.backgroundKey, value: background, range: range) }
if let image, range.length == 1 {
if image != nil || math != nil, range.length == 1 {
let font = result.attribute(Self.fontKey, at: lower, effectiveRange: nil).map { $0 as! CTFont } ?? self.font(for: block.kind)
let attachment = ImageAttachment(image: image, sizing: images, font: font, style: self)
let attachment = math.map { ImageAttachment(math: $0, sizing: images, font: font, style: self) }
?? ImageAttachment(image: image!, sizing: images, font: font, style: self)
result.addAttribute(Self.imageKey, value: attachment, range: range)
result.addAttribute(Self.runDelegateKey, value: attachment.makeRunDelegate(), range: range)
}
Expand Down Expand Up @@ -316,9 +319,48 @@ final class ImageAttachment: @unchecked Sendable {
let size: CGSize
/// Above the baseline; the rest of `size.height` is below it.
let ascent: CGFloat
/// For a formula: it, and its picture is a mask drawn in the text color.
let math: TranscriptMath?
var isMask: Bool { math != nil && picture != nil }

/// A formula, drawn by the store's math renderer, or its LaTeX as written
/// until it is (or if it is not).
init(math: TranscriptMath, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) {
self.image = TranscriptImage(source: "", alt: math.tex)
self.math = math
let maximumWidth = max(sizing?.maximumWidth ?? 320, 20)
if let formula = sizing?.store?.formula(for: math, fontSize: CTFontGetSize(font)) {
let natural = CGSize(width: max(formula.size.width, 1), height: max(formula.size.height, 1))
let scale = min(1, maximumWidth / natural.width)
self.picture = formula.image
self.label = nil
self.size = CGSize(width: ceil(natural.width * scale), height: ceil(natural.height * scale))
self.ascent = size.height - formula.baseline * scale
} else {
let size = CTFontGetSize(font) * 0.85
let code = style.codeFont?.makeFont(size: size) ?? CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil)!
let attributes: [NSAttributedString.Key: Any] = [
TranscriptStyle.fontKey: code,
NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true,
]
var line = CTLineCreateWithAttributedString(NSAttributedString(string: math.source, attributes: attributes))
let padding: CGFloat = 6
let available = maximumWidth - padding * 2
if CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) > available {
let ellipsis = CTLineCreateWithAttributedString(NSAttributedString(string: "…", attributes: attributes))
line = CTLineCreateTruncatedLine(line, Double(available), .end, ellipsis) ?? line
}
self.picture = nil
self.label = line
let width = ceil(CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))) + padding * 2
self.size = CGSize(width: min(width, maximumWidth), height: ceil(CTFontGetAscent(font) + CTFontGetDescent(font)) + 4)
self.ascent = ceil(CTFontGetAscent(font)) + 2
}
}

init(image: TranscriptImage, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) {
self.image = image
self.math = nil
let maximumWidth = max(sizing?.maximumWidth ?? 320, 20)
if let picture = sizing?.store?.picture(for: image) {
let natural = CGSize(width: max(CGFloat(picture.width), 1), height: max(CGFloat(picture.height), 1))
Expand Down
Loading