From 97d176f990d9f4edef6380736f0e78c36cc87ba7 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:09:20 -0800 Subject: [PATCH 1/7] Add style options for code that does not wrap and for display math TranscriptStyle gets three options. All defaults keep the current behavior. - codeWraps: when it is false, a line of code breaks only at a line break in its text. - displayMathAlignment: puts a paragraph that holds only display math at the leading edge, the center or the trailing edge. - displayMathScrolls: when it is true, a display formula that is wider than the column keeps its size instead of a scale-down. BlockLayout records the right edge of its widest line and how far its lines can move left. A streamed block keeps that value for the lines that it does not typeset again. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/BlockLayout.swift | 67 ++++++-- .../Layout/TranscriptStyle.swift | 14 ++ .../TranscriptKitTests/SideScrollTests.swift | 154 ++++++++++++++++++ 3 files changed, 225 insertions(+), 10 deletions(-) create mode 100644 Tests/TranscriptKitTests/SideScrollTests.swift diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index bc0291d..1b2a270 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) } + + /// Lines are not broken at a width: wide enough for any line of text. + 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, @@ -217,7 +255,7 @@ final class BlockLayout: @unchecked Sendable { // 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 = max(CTTypesetterSuggestLineBreak(typesetter, local, Double(wraps ? available - leading : unlimitedWidth)), 1) 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 +266,7 @@ final class BlockLayout: @unchecked Sendable { let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "", attributes: style.attributes(for: block.kind))) add(empty, range: length.. 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 +327,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/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 69af107..2c33e30 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -61,6 +61,20 @@ public struct TranscriptStyle: Equatable, Sendable { /// Where the lines of paragraphs and headings sit in their column. Lists, /// quotes, code and tables stay at the leading edge. public var textAlignment: TranscriptTextAlignment = .leading + /// Whether the lines of code blocks wrap at the width of the text column. + /// On by default. Off, a line of code breaks only where its text has a + /// line break, and a code block with a line that is wider than the column + /// scrolls sideways in `TranscriptTextView`. The block keeps the width of + /// the column. + public var codeWraps = true + /// Where a paragraph that holds only display math puts its formula in the + /// column. Centered by default. A formula that is wider than the column + /// starts at the leading edge. + public var displayMathAlignment: TranscriptTextAlignment = .center + /// Whether a display formula that is wider than the text column scrolls + /// sideways in `TranscriptTextView`. Off by default: the formula is then + /// scaled down to fit. Inline formulas are always scaled down. + public var displayMathScrolls = false struct Insets { var leading: CGFloat = 0 diff --git a/Tests/TranscriptKitTests/SideScrollTests.swift b/Tests/TranscriptKitTests/SideScrollTests.swift new file mode 100644 index 0000000..4292f65 --- /dev/null +++ b/Tests/TranscriptKitTests/SideScrollTests.swift @@ -0,0 +1,154 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +private let longLine = "let values = [" + (1...40).map(String.init).joined(separator: ", ") + "]" +private let code = "func f() {\n " + longLine + "\n return values\n}" + +private func codeDocument(_ text: String = code) -> TranscriptDocument { + TranscriptDocument(blocks: [ + TranscriptBlock(id: "p", text: "Some text before the code."), + TranscriptBlock(id: "c", kind: .code(language: "swift"), text: text), + TranscriptBlock(id: "q", text: "Some text after the code."), + ]) +} + +private func noWrap() -> TranscriptStyle { + var style = TranscriptStyle() + style.codeWraps = false + return style +} + +@Test func codeWrapsByDefaultAndDoesNotScroll() { + let layout = DocumentLayout(document: codeDocument(), width: 300) + let block = layout.entry(at: 1).layout + #expect(block.lines.count > 4) + #expect(block.maximumScrollOffset == 0) + #expect(block.lines.allSatisfy { $0.frame.maxX <= 300 }) +} + +@Test func codeThatDoesNotWrapHasOneLineForEachLineOfText() { + let style = noWrap() + let layout = DocumentLayout(document: codeDocument(), width: 300, style: style) + let block = layout.entry(at: 1).layout + #expect(block.lines.count == 4) + let widest = block.lines.map(\.frame.maxX).max()! + #expect(widest > 300) + #expect(block.contentRight == widest) + #expect(block.maximumScrollOffset == ceil(widest + style.codePadding - 300)) + // The block keeps the width of the column; the text around it still wraps. + #expect(layout.entry(at: 1).frame.width == 300) + #expect(layout.entry(at: 0).layout.maximumScrollOffset == 0) +} + +@Test func codeThatFitsDoesNotScroll() { + let layout = DocumentLayout(document: codeDocument("let a = 1\nlet b = 2"), width: 300, style: noWrap()) + #expect(layout.entry(at: 1).layout.lines.count == 2) + #expect(layout.entry(at: 1).layout.maximumScrollOffset == 0) +} + +@Test func aStreamedCodeBlockThatDoesNotWrapMatchesALayoutFromScratch() { + let style = noWrap() + var previous: DocumentLayout? + let units = Array(code.utf16) + for end in stride(from: 1, through: units.count, by: 3) { + let text = String(utf16CodeUnits: units, count: end) + let document = TranscriptDocument(blocks: [TranscriptBlock(id: "c", kind: .code(language: "swift"), text: text)]) + let streamed = DocumentLayout(document: document, width: 300, style: style, reusing: previous) + let fresh = DocumentLayout(document: document, width: 300, style: style) + let a = streamed.entry(at: 0).layout + let b = fresh.entry(at: 0).layout + #expect(a.lines.map(\.range) == b.lines.map(\.range), "at \(end)") + // Typeset from a different start, a line's width can differ in the last bits. + let same = zip(a.lines, b.lines).allSatisfy { abs($0.frame.minX - $1.frame.minX) < 0.01 && $0.frame.minY == $1.frame.minY + && abs($0.frame.width - $1.frame.width) < 0.01 } + #expect(same, "at \(end)") + #expect(abs(a.maximumScrollOffset - b.maximumScrollOffset) <= 1, "at \(end)") + previous = streamed + } +} + +@Test func aLineLimitKeepsTheScrollWidthOfTheLinesShown() { + var style = noWrap() + style.lineLimit = 3 + let document = TranscriptDocument(blocks: [TranscriptBlock(id: "c", kind: .code(), text: code)]) + let block = DocumentLayout(document: document, width: 300, style: style).entry(at: 0).layout + #expect(block.lines.count == 3) + #expect(block.maximumScrollOffset > 0) + // The last line shown ends in "…" at the edge of the column. + style.lineLimit = 2 + let cut = DocumentLayout(document: document, width: 300, style: style).entry(at: 0).layout + #expect(cut.lines.count == 2) + #expect(cut.maximumScrollOffset == 0) +} + +// MARK: Display math + +/// An opaque formula image, `width` by `height` points. +private func formula(width: Int, height: Int) -> TranscriptMathImage { + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(gray: 0, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + return TranscriptMathImage(image: context.makeImage()!, size: CGSize(width: width, height: height), baseline: 4) +} + +/// The first block of `markdown` laid out at `width` once its formula, `formulaWidth` points wide, is drawn. +private func mathBlock(_ markdown: String, formulaWidth: Int, width: CGFloat = 300, style: TranscriptStyle) async -> BlockLayout { + let store = TranscriptImageStore() + store.setMathRenderer { _, _ in formula(width: formulaWidth, height: 20) } + let document = MarkdownStreamParser.document(from: markdown) + let revision = store.revision + _ = DocumentLayout(document: document, width: width, style: style, reusing: nil, images: store) + for _ in 0..<200 where store.revision == revision { + try? await Task.sleep(for: .milliseconds(10)) + } + return DocumentLayout(document: document, width: width, style: style, reusing: nil, images: store).entry(at: 0).layout +} + +@Test func displayMathCanAlignToTheLeadingEdge() async { + var style = TranscriptStyle() + #expect(abs((await mathBlock("$$x$$", formulaWidth: 60, style: style)).lines[0].frame.midX - 150) <= 1) + style.displayMathAlignment = .leading + #expect((await mathBlock("$$x$$", formulaWidth: 60, style: style)).lines[0].frame.minX == 0) + style.displayMathAlignment = .trailing + #expect((await mathBlock("$$x$$", formulaWidth: 60, style: style)).lines[0].frame.maxX == 300) + // Inline math follows the text, not the display math alignment. + let inline = await mathBlock("Area \\(x\\) here", formulaWidth: 60, style: style) + #expect(inline.lines[0].frame.minX == 0) +} + +@Test func aWideFormulaIsScaledDownUnlessItScrolls() async { + var style = TranscriptStyle() + let scaled = await mathBlock("$$x$$", formulaWidth: 500, style: style) + #expect(scaled.lines[0].frame.width <= 300) + #expect(scaled.maximumScrollOffset == 0) + + style.displayMathScrolls = true + let scrolled = await mathBlock("$$x$$", formulaWidth: 500, style: style) + #expect(scrolled.lines.count == 1) + #expect(scrolled.lines[0].frame.minX == 0) + #expect(scrolled.lines[0].frame.width == 500) + #expect(scrolled.maximumScrollOffset == 200) + // A formula that fits is aligned as before, and does not scroll. + let narrow = await mathBlock("$$x$$", formulaWidth: 60, style: style) + #expect(abs(narrow.lines[0].frame.midX - 150) <= 1) + #expect(narrow.maximumScrollOffset == 0) + // Inline formulas are still scaled down. + let inline = await mathBlock("Area \\(x\\) here", formulaWidth: 500, style: style) + #expect(inline.maximumScrollOffset == 0) + #expect(inline.lines.allSatisfy { $0.frame.maxX <= 300 }) +} + +@Test func aFormulaThatScrollsShowsAllOfItsLatexUntilItIsDrawn() { + var style = TranscriptStyle() + let tex = "$$" + String(repeating: "a + b + c + ", count: 12) + "d$$" + let document = MarkdownStreamParser.document(from: tex) + let truncated = DocumentLayout(document: document, width: 300, style: style).entry(at: 0).layout + #expect(truncated.maximumScrollOffset == 0) + style.displayMathScrolls = true + let whole = DocumentLayout(document: document, width: 300, style: style).entry(at: 0).layout + #expect(whole.maximumScrollOffset > 0) + #expect(whole.lines[0].frame.minX == 0) +} From 422c69b164f310ec4ddc6c573d70be6bab4cdc5c Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:13:58 -0800 Subject: [PATCH 2/7] Draw and hit-test blocks that are scrolled sideways SideScroll keeps an offset for each block that scrolls sideways, by block id. A block that grows keeps its id, so it keeps its offset. Each use cuts the offset to what the block can scroll. DocumentLayout draws the lines of such a block moved left by its offset and clips them to the box of the block. The code background, list markers and quote bars do not move. Caret rects, closest offsets, links and selection rects use the same offset. A caret or a selection rect outside the box moves to the edge of the box. The public methods use no offset, so the text past the edge stays out of reach. The tail and the text that fades in are drawn with the offset that the view gives the layout engine. Each output records that offset, so the view can find a tail that it drew before the latest scroll. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/DocumentLayout.swift | 123 +++++++++--- .../TranscriptKit/Layout/FadeRenderer.swift | 23 ++- .../TranscriptKit/Layout/LayoutEngine.swift | 37 ++-- Sources/TranscriptKit/Layout/SideScroll.swift | 25 +++ .../TranscriptKit/Layout/TailRenderer.swift | 7 +- .../TranscriptKitTests/SideScrollTests.swift | 176 ++++++++++++++++++ 6 files changed, 350 insertions(+), 41 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/SideScroll.swift diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 73f623e..714f913 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -184,6 +184,23 @@ 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 + } + /// 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 [] } @@ -198,15 +215,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 { @@ -215,16 +248,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. @@ -236,6 +279,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.. 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) + drawTagImages(of: lines[index], in: entry) + } } switch layout.marker { @@ -539,23 +616,25 @@ 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)..