Skip to content
Merged
41 changes: 38 additions & 3 deletions Demo/TranscriptDemo/DemoApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,26 @@ struct ContentView: View {
@State private var document = TranscriptDocument()
@State private var streaming: Task<Void, Never>?
@State private var tappedLink: URL?
/// With `-sideScroll`, code does not wrap and wide display math scrolls
/// sideways from the leading edge.
private let style: TranscriptStyle = {
var style = TranscriptStyle()
if ProcessInfo.processInfo.arguments.contains("-sideScroll") {
style.codeWraps = false
style.displayMathScrolls = true
style.displayMathAlignment = .leading
}
return style
}()

var body: some View {
NavigationStack {
ScrollView {
Group {
if usesDocumentPath {
TranscriptText(document)
TranscriptText(document, style: style)
} else {
TranscriptText(stream: transcript)
TranscriptText(stream: transcript, style: style)
}
}
.padding(16)
Expand Down Expand Up @@ -86,7 +97,8 @@ struct ContentView: View {
private func stream() async {
// `-slowStream` stretches the response over about 15 seconds, for testing gestures.
let pause = ProcessInfo.processInfo.arguments.contains("-slowStream") ? 90 : 20
var pending = Substring(Sample.streamedMarkdown)
let wide = ProcessInfo.processInfo.arguments.contains("-wideSample")
var pending = Substring(Sample.streamedMarkdown + (wide ? Sample.wide : ""))
// The document path uses its own parser, so no `TranscriptStream` (and
// no display link) is involved at all.
var parser = MarkdownStreamParser()
Expand Down Expand Up @@ -121,9 +133,32 @@ enum Sample {
}
return TranscriptStream(markdown: sections.joined())
}
if ProcessInfo.processInfo.arguments.contains("-wideSample") {
return TranscriptStream(markdown: intro + wide)
}
return TranscriptStream(markdown: intro)
}

/// A code block with a long line and a wide formula, for `-sideScroll`.
/// With `-wideSample`, the intro ends with them, and so does the streamed answer.
static let wide = #"""
## Wide blocks

```swift
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] // END
let total = primes.reduce(0, +)
print(total)
```

$$
\sum_{k=1}^{n} k^2 = \frac{n(n+1)(2n+1)}{6} = 1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + \cdots + n^2 \quad \text{END}
$$

A paragraph after the wide blocks still wraps at the width of the screen, as it did before.


"""#

static let intro = """
# One selection, many blocks

Expand Down
37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut
- **Markdown:**
- headings, paragraphs, emphasis, strikethrough and inline code;
- nested lists, task lists and quotes;
- fenced and indented code blocks, colored by a highlighter your app provides, and tables;
- fenced and indented code blocks, colored by a highlighter your app provides, which wrap or scroll sideways, 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;
Expand Down Expand Up @@ -243,6 +244,25 @@ 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, and Increase Contrast values when it has them.

### Code that does not wrap

By default, a line of code wraps at the width of the text column. Set `codeWraps` to false to keep each line of code
on one line. A code block with a line that is wider than the column then scrolls sideways in the view:

```swift
var style = TranscriptStyle()
style.codeWraps = false
TranscriptText(stream: stream, style: style)
```

The block keeps the width of the column, and only its text moves. A sideways drag that starts in the block scrolls
the block. A drag up or down still scrolls the scroll view around the text. After the drag, the block slows down as a
scroll view does. A touch on the block stops it, and does not open a link. Selection, links, copy and the selection
handles follow the scrolled text. With VoiceOver, a three-finger swipe to the left or right scrolls the block. A block
that grows while it streams keeps its offset. It also keeps its offset when the text after it changes, while the block
stays a block of the same kind. A new document starts with all blocks at their leading edge. While a block that text
streams into moves sideways, the new text shows at once, without a fade.

### Math

LaTeX between `\(` and `\)` is inline math. A line that starts with `\[` or `$$` starts display math, which ends at
Expand Down Expand Up @@ -273,6 +293,18 @@ scaled down to fit. A paragraph that holds only display math is centered. While
nothing until it closes, so the text on screen only grows. Copy gives the LaTeX with its delimiters, and VoiceOver
reads the LaTeX.

Two style options change display math. `displayMathAlignment` puts the formula at the leading edge, the center (the
default) or the trailing edge. With `displayMathScrolls`, a display formula that is wider than the column keeps its
size and scrolls sideways, as code that does not wrap does. When the formula shows its LaTeX, because there is no
renderer or the renderer returns nil, the LaTeX is then shown whole instead of cut with "…". Inline formulas are always
scaled down to fit.

```swift
var style = TranscriptStyle()
style.displayMathAlignment = .leading
style.displayMathScrolls = true
```

Until the renderer draws a formula, the formula is empty space of about its size. The LaTeX of a formula can change
from one update to the next, for example when your app closes an open formula in each new snapshot of the text. Then
the formula keeps its last image until the new one is drawn. Each formula has at most one drawing in progress, and
Expand All @@ -298,7 +330,8 @@ a cache after your renderer changes how it draws: the views that use the cache t
### 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
list row. A tap that is not on a link then goes to that view, and links still open:
list row. A tap that is not on a link then goes to that view, and links still open. A block that scrolls sideways
still takes the touches in it:

```swift
TranscriptText(document)
Expand Down
81 changes: 71 additions & 10 deletions Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,33 @@ final class BlockLayout: @unchecked Sendable {
/// For a block with reference links: those whose label was defined when
/// it was laid out, and so styled as links.
let definedReferences: Set<String>?
/// The right edge of the widest line.
let contentRight: CGFloat
/// How far the block's lines can move left: how much wider they are than
/// the block's box, its trailing padding included. Zero for a block that
/// does not scroll sideways, or whose lines fit.
let maximumScrollOffset: CGFloat

/// The box that the lines of a block that scrolls sideways show in.
var scrollBox: CGRect { CGRect(x: contentLeading, y: 0, width: max(width - contentLeading, 0), height: height) }

/// The widest an image or a formula grows in a block that scrolls sideways.
static let unlimitedWidth: CGFloat = 100_000

/// Whether `block` is a paragraph that holds only display math.
static func isDisplayMath(_ block: TranscriptBlock) -> Bool {
block.spans.count == 1 && block.spans[0].math?.isDisplay == true
&& block.text.trimmingCharacters(in: .whitespacesAndNewlines) == "\u{FFFC}"
}

/// Whether the style lets `block` scroll sideways instead of wrapping or scaling down.
static func scrollsSideways(_ block: TranscriptBlock, style: TranscriptStyle) -> Bool {
switch block.kind {
case .code: return !style.codeWraps
case .paragraph: return style.displayMathScrolls && isDisplayMath(block)
case .heading, .rule, .table: return false
}
}

/// The labels of `block`'s reference links that `definitions` defines,
/// or nil if it has none.
Expand Down Expand Up @@ -130,14 +157,19 @@ final class BlockLayout: @unchecked Sendable {
lines = laidOut.lines
self.height = laidOut.height
self.table = laidOut.table
self.contentRight = laidOut.table.frame.maxX
self.maximumScrollOffset = 0
} else {
let sizing = ImageSizing(store: images, maximumWidth: available)
let scrolls = Self.scrollsSideways(block, style: style)
let sizing = ImageSizing(store: images, maximumWidth: scrolls ? Self.unlimitedWidth : available)
let laidOut = Self.layOutText(block, style: style, insets: insets, available: available, blockWidth: width,
sizing: sizing, definitions: definitions,
wraps: !scrolls, sizing: sizing, definitions: definitions,
reusing: previous.flatMap { $0.width == width && $0.imageRevision == revision ? $0 : nil })
lines = laidOut.lines
self.height = laidOut.height
self.table = nil
self.contentRight = laidOut.right
self.maximumScrollOffset = scrolls ? max(ceil(laidOut.right + insets.trailing - width), 0) : 0
}
self.lines = lines
self.marker = Self.makeMarker(for: block, style: style, firstLine: lines.first)
Expand All @@ -146,15 +178,18 @@ final class BlockLayout: @unchecked Sendable {

// MARK: Text

/// - Parameter wraps: whether lines break at `available`, or only at line breaks.
private static func layOutText(_ block: TranscriptBlock, style: TranscriptStyle, insets: TranscriptStyle.Insets,
available: CGFloat, blockWidth: CGFloat, sizing: ImageSizing, definitions: [String: String],
reusing previous: BlockLayout?) -> (lines: SharedList<Line>, height: CGFloat) {
available: CGFloat, blockWidth: CGFloat, wraps: Bool, sizing: ImageSizing,
definitions: [String: String],
reusing previous: BlockLayout?) -> (lines: SharedList<Line>, height: CGFloat, right: CGFloat) {
let length = block.utf16Count
let font = style.font(for: block.kind)
let hasDecorations = DecoratedTags.appear(in: block)
var lines = SharedList<Line>()
var y = insets.vertical
var restart = 0
var right: CGFloat = 0
if let previous, previous.style == style, previous.block.isStyledPrefix(of: block), previous.lines.count > 1 {
// Line breaks are chosen greedily, so appended text can only
// change the last line and what follows it.
Expand All @@ -174,6 +209,9 @@ final class BlockLayout: @unchecked Sendable {
lines = previous.lines.prefix(keep)
restart = previous.lines[keep].range.lowerBound
y = previous.lines[keep].frame.minY
// The lines typeset again hold at least the text they held, so
// the widest of the earlier lines is no wider than this.
right = previous.contentRight
}
}

Expand All @@ -182,13 +220,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}"
let isDisplayMath = Self.isDisplayMath(block)
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 + (isDisplayMath
? max(((available - leading - metrics.width) / 2).rounded(.down), 0)
? offset(for: style.displayMathAlignment, width: metrics.width, room: available - leading)
: alignmentOffset(block, style: style, width: metrics.width, room: available - leading))
right = max(right, x + metrics.width)
var decorations: LineDecorations?
if let decorated, let text {
decorations = LineDecorations.make(line: ctLine, range: range, indexBase: indexBase, visibleWidth: metrics.width,
Expand All @@ -211,13 +249,16 @@ final class BlockLayout: @unchecked Sendable {
let attributed = style.attributedString(for: block, from: restart, images: sizing, definitions: definitions,
kerns: decorated?.kerns ?? [:])
let typesetter = CTTypesetterCreateWithAttributedString(attributed)
let string = attributed.string as NSString
var start = restart
while start < length {
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 = max(CTTypesetterSuggestLineBreak(typesetter, local, Double(available - leading)), 1)
let count = wraps
? max(CTTypesetterSuggestLineBreak(typesetter, local, Double(available - leading)), 1)
: Self.lengthToLineBreak(in: string, from: local)
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 @@ -228,7 +269,18 @@ final class BlockLayout: @unchecked Sendable {
let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "", attributes: style.attributes(for: block.kind)))
add(empty, range: length..<length, indexBase: length)
}
return (lines, y - gap + insets.vertical)
return (lines, y - gap + insets.vertical, right)
}

/// The length of the line of `string` that starts at `start`: up to and
/// including its line break, or to the end.
static func lengthToLineBreak(in string: NSString, from start: Int) -> Int {
let rest = NSRange(location: start, length: string.length - start)
let found = string.rangeOfCharacter(from: .newlines, options: [], range: rest)
guard found.location != NSNotFound else { return max(rest.length, 1) }
var end = found.location + found.length
if string.character(at: found.location) == 0x0D, end < string.length, string.character(at: end) == 0x0A { end += 1 }
return end - start
}

/// Line metrics made `height` tall, with the text centred, when the app
Expand All @@ -243,8 +295,14 @@ final class BlockLayout: @unchecked Sendable {
/// alignment. Only paragraphs and headings outside lists and quotes move.
static func alignmentOffset(_ block: TranscriptBlock, style: TranscriptStyle, width: CGFloat, room: CGFloat) -> CGFloat {
guard isAligned(block, style: style) else { return 0 }
return offset(for: style.textAlignment, width: width, room: room)
}

/// How far a line `width` wide moves right in `room` for `alignment`.
/// A line wider than `room` stays at the leading edge.
static func offset(for alignment: TranscriptTextAlignment, width: CGFloat, room: CGFloat) -> CGFloat {
let slack = max(room - width, 0)
switch style.textAlignment {
switch alignment {
case .leading: return 0
case .center: return (slack / 2).rounded(.down)
case .trailing: return slack
Expand Down Expand Up @@ -283,6 +341,9 @@ final class BlockLayout: @unchecked Sendable {
lines = kept
let bottom = kept.last.map { $0.frame.maxY } ?? 0
height = bottom + insets.vertical
contentRight = kept.reduce(0) { max($0, $1.frame.maxX) }
maximumScrollOffset = original.table == nil && Self.scrollsSideways(block, style: style)
? max(ceil(contentRight + insets.trailing - width), 0) : 0
length = kept.last?.range.upperBound ?? 0
attachments = original.attachments.filter { $0.rect.minY < bottom }
}
Expand Down
Loading
Loading