diff --git a/Demo/TranscriptDemo/DemoApp.swift b/Demo/TranscriptDemo/DemoApp.swift index 0852147..a1cd484 100644 --- a/Demo/TranscriptDemo/DemoApp.swift +++ b/Demo/TranscriptDemo/DemoApp.swift @@ -18,15 +18,26 @@ struct ContentView: View { @State private var document = TranscriptDocument() @State private var streaming: Task? @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) @@ -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() @@ -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 diff --git a/README.md b/README.md index eacec07..ef82f88 100644 --- a/README.md +++ b/README.md @@ -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; @@ -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 @@ -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 @@ -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) diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index 77da123..ed2f3aa 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -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? + /// 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. @@ -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) @@ -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, height: CGFloat) { + available: CGFloat, blockWidth: CGFloat, wraps: Bool, sizing: ImageSizing, + definitions: [String: String], + reusing previous: BlockLayout?) -> (lines: SharedList, height: CGFloat, right: CGFloat) { let length = block.utf16Count let font = style.font(for: block.kind) let hasDecorations = DecoratedTags.appear(in: block) var lines = SharedList() 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. @@ -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 } } @@ -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, 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, @@ -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 @@ -228,7 +269,18 @@ final class BlockLayout: @unchecked Sendable { let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "", attributes: style.attributes(for: block.kind))) add(empty, range: length.. 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 @@ -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 @@ -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 } } diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index ead2eda..ab19076 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -185,6 +185,43 @@ public final class DocumentLayout: @unchecked Sendable { lastEntryIndex(where: { CGFloat($0.start) }, isAtMost: CGFloat(offset)) } + /// The index of the entry of the block with `id`. `hint` is where it was + /// last, which is checked first. + func entryIndex(ofBlock id: String, hint: Int? = nil) -> Int? { + if let hint, hint >= 0, hint < entryCount, entry(at: hint).layout.block.id == id { return hint } + return (0.. Int? { + guard let index = lastEntryIndex(where: { $0.y }, isAtMost: point.y) else { return nil } + let entry = entry(at: index) + guard entry.layout.maximumScrollOffset > 0, point.y < entry.frame.maxY else { return nil } + let box = entry.layout.scrollBox + return point.x >= box.minX && point.x < box.maxX ? index : nil + } + + /// Whether `a` and `b` scroll alike every block that reaches below `y`, + /// shapes' overhang included: drawn with either, that part looks the same. + func scrollsAlike(_ a: SideScroll, _ b: SideScroll, below y: CGFloat) -> Bool { + guard a != b else { return true } + return scrollsAlike(a, b, from: lastEntryIndex(where: { $0.y }, isAtMost: y - TranscriptPath.maximumOverhang) ?? 0) + } + + /// Whether `a` and `b` scroll alike every block with text at or after `offset`. + func scrollsAlike(_ a: SideScroll, _ b: SideScroll, fromOffset offset: Int) -> Bool { + guard a != b else { return true } + return scrollsAlike(a, b, from: entryIndex(forOffset: offset) ?? 0) + } + + private func scrollsAlike(_ a: SideScroll, _ b: SideScroll, from first: Int) -> Bool { + (first.. [(entry: Entry, line: BlockLayout.Line)] { guard let first = entryIndex(forOffset: offset) else { return [] } @@ -199,15 +236,31 @@ public final class DocumentLayout: @unchecked Sendable { } public func caretRect(at offset: Int) -> CGRect { + caretRect(at: offset, scroll: .none) + } + + /// The caret at `offset` with blocks scrolled sideways by `scroll`. In a + /// block that scrolls, a caret outside the block's box is moved to its edge. + func caretRect(at offset: Int, scroll: SideScroll) -> CGRect { guard let index = entryIndex(forOffset: offset) else { return CGRect(x: 0, y: 0, width: 2, height: style.effectiveBodySize * 1.2) } let entry = entry(at: index) let local = min(max(offset - entry.start, 0), entry.layout.length) - return entry.layout.caretRect(atOffset: local).offsetBy(dx: 0, dy: entry.y) + let rect = entry.layout.caretRect(atOffset: local).offsetBy(dx: 0, dy: entry.y) + guard entry.layout.maximumScrollOffset > 0 else { return rect } + let box = entry.layout.scrollBox + var shifted = rect.offsetBy(dx: -scroll.offset(of: entry.layout), dy: 0) + shifted.origin.x = min(max(shifted.minX, box.minX), box.maxX - shifted.width) + return shifted } public func closestOffset(to point: CGPoint) -> Int { + closestOffset(to: point, scroll: .none) + } + + /// The offset nearest to `point`, with blocks scrolled sideways by `scroll`. + func closestOffset(to point: CGPoint, scroll: SideScroll) -> Int { guard var index = lastEntryIndex(where: { $0.y }, isAtMost: point.y) else { return 0 } // A point in the gap below a block goes to whichever block is nearer. if index + 1 < entryCount { @@ -216,16 +269,26 @@ public final class DocumentLayout: @unchecked Sendable { if point.y >= (current.frame.maxY + next.y) / 2 { index += 1 } } let entry = entry(at: index) - let local = entry.layout.closestOffset(to: CGPoint(x: point.x, y: point.y - entry.y)) + let local = entry.layout.closestOffset(to: CGPoint(x: point.x + scroll.offset(of: entry.layout), y: point.y - entry.y)) return entry.start + local } /// The destination of the link drawn under `point`, if any. public func link(at point: CGPoint) -> String? { + link(at: point, scroll: .none) + } + + /// The destination of the link drawn under `point`, with blocks scrolled + /// sideways by `scroll`. In a block that scrolls, only its box shows links. + func link(at point: CGPoint, scroll: SideScroll) -> String? { guard let index = lastEntryIndex(where: { $0.y }, isAtMost: point.y) else { return nil } let entry = entry(at: index) guard entry.frame.contains(point) else { return nil } - let local = CGPoint(x: point.x, y: point.y - entry.y) + if entry.layout.maximumScrollOffset > 0 { + let box = entry.layout.scrollBox + guard point.x >= box.minX, point.x < box.maxX else { return nil } + } + let local = CGPoint(x: point.x + scroll.offset(of: entry.layout), y: point.y - entry.y) if let link = entry.layout.decorationLink(at: local) { return link } guard let offset = entry.layout.characterOffset(at: local) else { return nil } // A reference link's destination may have been defined further down. @@ -237,6 +300,13 @@ public final class DocumentLayout: @unchecked Sendable { /// One rect per line covered by `range`, across as many blocks as it spans. public func selectionRects(for range: Range) -> [CGRect] { + selectionRects(for: range, scroll: .none) + } + + /// One rect per line covered by `range`, with blocks scrolled sideways by + /// `scroll`. In a block that scrolls, the rects are cut to its box; a rect + /// outside the box becomes an empty one at its edge. + func selectionRects(for range: Range, scroll: SideScroll) -> [CGRect] { guard !range.isEmpty, let first = entryIndex(forOffset: range.lowerBound) else { return [] } var rects: [CGRect] = [] for index in first.. 0 + let dx = scroll.offset(of: entry.layout) + let box = entry.layout.scrollBox for rect in entry.layout.selectionRects(for: lower..] = []) { + func drawLine(_ line: CTLine, at origin: CGPoint, hidden: [Range] = [], visible: ClosedRange? = nil) { drawHighlights(CTLineGetGlyphRuns(line) as! [CTRun], at: origin) - Self.drawGlyphs(of: line, at: origin, hidden: hidden, in: context, text: text, dark: dark, highContrast: highContrast) + Self.drawGlyphs(of: line, at: origin, hidden: hidden, visible: visible, in: context, text: text, dark: dark, + highContrast: highContrast) } func fill(_ rect: CGRect, radius: CGFloat, color: CGColor) { @@ -414,11 +497,11 @@ public final class DocumentLayout: @unchecked Sendable { } /// A line's tag images, clipped like its shapes. - func drawTagImages(of line: BlockLayout.Line, in entry: Entry) { + func drawTagImages(of line: BlockLayout.Line, in entry: Entry, shift: CGFloat) { guard let decorations = line.decorations, !decorations.images.isEmpty else { return } context.saveGState() let side = TranscriptPath.maximumSideOverhang - context.clip(to: CGRect(x: -side, y: entry.y + line.frame.minY - decorations.inkAbove, width: entry.layout.width + 2 * side, + context.clip(to: CGRect(x: shift - side, y: entry.y + line.frame.minY - decorations.inkAbove, width: entry.layout.width + 2 * side, height: line.frame.height + decorations.inkAbove + decorations.inkBelow)) context.translateBy(x: line.frame.minX, y: entry.y + line.baseline) for item in decorations.images { @@ -442,15 +525,16 @@ public final class DocumentLayout: @unchecked Sendable { } /// A line's tag shapes on one layer, clipped to what the line may - /// draw, as invalidation knows it. - func drawShapes(of line: BlockLayout.Line, in entry: Entry, over: Bool) { + /// draw, as invalidation knows it. `shift` is how far the context + /// was moved left for a block that scrolls sideways. + func drawShapes(of line: BlockLayout.Line, in entry: Entry, over: Bool, shift: CGFloat) { guard let decorations = line.decorations else { return } let paths = over ? decorations.over : decorations.behind guard !paths.isEmpty else { return } let owners = over ? decorations.overTags : decorations.behindTags context.saveGState() let side = TranscriptPath.maximumSideOverhang - context.clip(to: CGRect(x: -side, y: entry.y + line.frame.minY - decorations.inkAbove, width: entry.layout.width + 2 * side, + context.clip(to: CGRect(x: shift - side, y: entry.y + line.frame.minY - decorations.inkAbove, width: entry.layout.width + 2 * side, height: line.frame.height + decorations.inkAbove + decorations.inkBelow)) context.translateBy(x: line.frame.minX, y: entry.y + line.baseline) for (index, path) in paths.enumerated() { @@ -535,11 +619,26 @@ public final class DocumentLayout: @unchecked Sendable { visible = first.. 0 + let dx = scroll.offset(of: layout) + func inScrolledBox(_ body: () -> Void) { + guard scrolls else { return body() } + context.saveGState() + context.clip(to: CGRect(x: box.minX, y: frame.minY - overhang, width: box.width, height: frame.height + 2 * overhang)) + context.translateBy(x: -dx, y: 0) + body() + context.restoreGState() + } + // Behind the text: tags' shapes, so that none covers a glyph of // the line above; then the text; then shapes over it. - for index in visible { - drawShapes(of: lines[index], in: entry, over: false) - drawTagImages(of: lines[index], in: entry) + inScrolledBox { + for index in visible { + drawShapes(of: lines[index], in: entry, over: false, shift: dx) + drawTagImages(of: lines[index], in: entry, shift: dx) + } } switch layout.marker { @@ -554,24 +653,31 @@ public final class DocumentLayout: @unchecked Sendable { break } - for index in visible where !lines[index].range.isEmpty { - let line = lines[index] - 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)..