From f87a47cc8f2eff94187727ca096ee87113f24e88 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:28:53 -0800 Subject: [PATCH 1/5] Clear the selection when the view leaves its window A text view in a lazy stack, or in a tab that is not selected, can leave its window while some of its text is selected. A selectable `UITextView` can then raise "UIPreviewTarget requires that the container view is in a window" when its edit menu or drag preview refers to it. Apps avoid this by clearing the selection of such a view when it leaves its window. `TranscriptTextView` now does the same. When it leaves its window, it clears its selection and resigns first responder. The crash was not reproduced with `TranscriptTextView`. This change guards against the same failure. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/iOS/TranscriptTextView.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index c6a09c4..87630f0 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -398,6 +398,16 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD hasNoScrollView = false } + public override func willMove(toWindow newWindow: UIWindow?) { + super.willMove(toWindow: newWindow) + // A selectable `UITextView` can raise "UIPreviewTarget requires that + // the container view is in a window" when its edit menu or drag + // preview outlives its window. A cleared selection has neither. + guard newWindow == nil else { return } + if selection != nil { select(nil) } + if isFirstResponder { resignFirstResponder() } + } + public override func didMoveToWindow() { super.didMoveToWindow() scrollObservation = nil From 5ca748143972b63528b8ea5064e63cbf7ca7668c Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:06:43 -0800 Subject: [PATCH 2/5] Draw a short text into a smaller tile Each view drew its text into tiles 256 points high, whatever its height. A one-line title kept a whole tile, which at 3x on a phone is about 3 MB, ten times what its text needs. A list of cards with three short texts each used more memory than SwiftUI `Text` for this reason. A view shorter than one tile now has one tile that covers only the view and the shapes that reach below its last line. Its height is 32, 64, 128 or 256 points, so text that grows resizes it at most three times. In a taller view, every tile stays 256 points high, so a long answer that streams in does not resize each new tile as it grows. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/TileGrid.swift | 25 ++++++++++++ .../iOS/TranscriptTextView.swift | 15 ++++---- Tests/TranscriptKitTests/TileGridTests.swift | 38 +++++++++++++++++++ 3 files changed, 71 insertions(+), 7 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/TileGrid.swift create mode 100644 Tests/TranscriptKitTests/TileGridTests.swift diff --git a/Sources/TranscriptKit/Layout/TileGrid.swift b/Sources/TranscriptKit/Layout/TileGrid.swift new file mode 100644 index 0000000..5957da4 --- /dev/null +++ b/Sources/TranscriptKit/Layout/TileGrid.swift @@ -0,0 +1,25 @@ +import CoreGraphics + +/// How `TranscriptTextView` cuts its text into the tiles that it draws. +enum TileGrid { + /// The height of a tile in a view that is taller than one tile. + static let height: CGFloat = 256 + + /// The height of the smallest tile. + static let minimumHeight: CGFloat = 32 + + /// The height of tile `index` in a view `viewHeight` points high. A view + /// shorter than one tile has one tile that covers only the view and the + /// shapes that reach below its last line, rounded up to 32, 64, 128 or + /// 256 points. So a one-line text keeps a small drawing, and text that + /// grows resizes its tile at most three times. In a taller view, every + /// tile is 256 points high, so a long answer that streams in does not + /// resize each new tile as it grows. + static func tileHeight(at index: Int, viewHeight: CGFloat) -> CGFloat { + let needed = viewHeight + TranscriptPath.maximumOverhang + guard index == 0, needed < height else { return height } + var tile = height + while tile > minimumHeight, tile / 2 >= needed { tile /= 2 } + return tile + } +} diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 87630f0..a599234 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -300,12 +300,12 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let signpost: OSSignpostIntervalState } - /// The drawn text, in fixed-height tiles that exist only near the visible - /// area. Memory stays flat however long the document is, and an update - /// redraws only the tiles it touches. + /// The drawn text, in tiles that exist only near the visible area (see + /// `TileGrid`). Memory stays flat however long the document is, and an + /// update redraws only the tiles it touches. private var tiles: [Int: CanvasView] = [:] private var spareTiles: [CanvasView] = [] - private let tileHeight: CGFloat = 256 + private let tileHeight = TileGrid.height private var scrollObservation: NSKeyValueObservation? private var canvasCheckScheduled = false @@ -530,7 +530,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD for (index, tile) in tiles { let minY = CGFloat(index) * tileHeight let top = max(range.lowerBound - minY - 2, 0) - let bottom = min(range.upperBound - minY + 2, tileHeight) + let bottom = min(range.upperBound - minY + 2, tile.bounds.height) if top < bottom { tile.setNeedsDisplay(CGRect(x: 0, y: top, width: tile.bounds.width, height: bottom - top)) } @@ -562,7 +562,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD for index in first...last { // Wider than the view: tags' shapes may draw past the text column. let side = TranscriptPath.maximumSideOverhang - let frame = CGRect(x: -side, y: CGFloat(index) * tileHeight, width: bounds.width + 2 * side, height: tileHeight) + let frame = CGRect(x: -side, y: CGFloat(index) * tileHeight, width: bounds.width + 2 * side, + height: TileGrid.tileHeight(at: index, viewHeight: bounds.height)) if let tile = tiles[index] { if tile.frame != frame { tile.frame = frame @@ -570,7 +571,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } else if forceRedraw { if let changed { let top = max(changed.lowerBound - frame.minY - 2, 0) - let bottom = min(changed.upperBound - frame.minY + 2, tileHeight) + let bottom = min(changed.upperBound - frame.minY + 2, frame.height) if top < bottom { tile.setNeedsDisplay(CGRect(x: 0, y: top, width: frame.width, height: bottom - top)) } diff --git a/Tests/TranscriptKitTests/TileGridTests.swift b/Tests/TranscriptKitTests/TileGridTests.swift new file mode 100644 index 0000000..9e1ddcd --- /dev/null +++ b/Tests/TranscriptKitTests/TileGridTests.swift @@ -0,0 +1,38 @@ +import CoreGraphics +import Testing +@testable import TranscriptKit + +@Test func aShortTextGetsASmallTile() { + #expect(TileGrid.tileHeight(at: 0, viewHeight: 20) == 32) + #expect(TileGrid.tileHeight(at: 0, viewHeight: 26) == 32) + #expect(TileGrid.tileHeight(at: 0, viewHeight: 27) == 64) + #expect(TileGrid.tileHeight(at: 0, viewHeight: 100) == 128) + #expect(TileGrid.tileHeight(at: 0, viewHeight: 200) == 256) +} + +@Test func aTallerTextKeepsFullTiles() { + for viewHeight: CGFloat in [251, 300, 600, 1000] { + let count = Int((viewHeight / TileGrid.height).rounded(.up)) + for index in 0..= min(needed, TileGrid.height)) + #expect(tile == TileGrid.minimumHeight || tile == TileGrid.height || tile / 2 < needed) + } +} + +@Test func growingTextResizesItsTileAtMostThreeTimes() { + var heights: [CGFloat] = [] + for height in stride(from: CGFloat(1), through: 2 * TileGrid.height, by: 1) { + let tile = TileGrid.tileHeight(at: 0, viewHeight: height) + if heights.last != tile { heights.append(tile) } + } + #expect(heights == [32, 64, 128, 256]) +} From dc92289e642e72e844761975a38971c80af38d94 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:06:43 -0800 Subject: [PATCH 3/5] Add an option to hide Writing Tools in the edit menu On devices that have Writing Tools, the edit menu can offer them for the selected text. A `UITextView` that shows text which is not the user's often turns them off. `TranscriptTextView.showsWritingTools` and `TranscriptText.showsWritingTools(_:)` turn them off. They are on by default, as in a `UITextView`. On iOS 18 and later, the view reports the choice through `writingToolsBehavior`. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +++ Sources/TranscriptKit/iOS/TranscriptText.swift | 10 ++++++++++ Sources/TranscriptKit/iOS/TranscriptTextView.swift | 10 ++++++++++ 3 files changed, 23 insertions(+) diff --git a/README.md b/README.md index a1b318e..dd7ed97 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,9 @@ TranscriptText(document) In UIKit, set `isSelectable` on `TranscriptTextView`. +On devices that have Writing Tools, the edit menu can offer them for the selected text, as in a `UITextView`. Turn +them off with `.showsWritingTools(false)`, or with `showsWritingTools` on `TranscriptTextView`. + ### VoiceOver VoiceOver reads the text block by block. Headings are in the rotor's list of headings, list items start with their diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 44ab601..7defa3b 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -28,6 +28,7 @@ public struct TranscriptText: UIViewRepresentable { private var playTrigger: AnyHashable? private var selectionChange: ((Range?) -> Void)? private var selectsAll = false + private var showsWritingTools = true /// Changed when the view's height changes before SwiftUI has placed it, /// so that SwiftUI measures the view again (see /// `TranscriptTextView.onHeightChangeWhileUnsized`). @@ -133,6 +134,14 @@ public struct TranscriptText: UIViewRepresentable { return copy } + /// Whether the edit menu offers Writing Tools; see + /// `TranscriptTextView.showsWritingTools`. On by default. + public func showsWritingTools(_ shows: Bool) -> TranscriptText { + var copy = self + copy.showsWritingTools = shows + return copy + } + public final class Coordinator { var playTrigger: AnyHashable? } @@ -168,6 +177,7 @@ public struct TranscriptText: UIViewRepresentable { view.textFadeInDuration = textFadeInDuration view.tagAnimationTiming = animationTiming view.isSelectable = isSelectable + view.showsWritingTools = showsWritingTools if playTrigger != context.coordinator.playTrigger { context.coordinator.playTrigger = playTrigger view.playTagAnimations() diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index a599234..1870f86 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1247,6 +1247,16 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Read-only: an empty input view keeps the keyboard from appearing. public override var inputView: UIView? { emptyInputView } + /// Whether the edit menu offers Writing Tools for the selected text, on + /// devices that have them. On by default, as in a `UITextView`. + public var showsWritingTools = true + + @available(iOS 18.0, *) + public var writingToolsBehavior: UIWritingToolsBehavior { + get { showsWritingTools ? .default : .none } + set { showsWritingTools = newValue != .none } + } + public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { switch action { case #selector(copy(_:)): From d388fc81eab66f2155dbf4a740fb40c753fcf7d0 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:44:30 -0800 Subject: [PATCH 4/5] End the selection when another view takes first responder When the person selected text in a second `TranscriptTextView`, the first view kept its selection, its highlight and its handles. So two views showed a selection at the same time. Now a view that becomes first responder posts a notification, and the other views in the same window end their selection. The view does not end its selection in `resignFirstResponder()`: Share and Translate in the edit menu make the view resign. A sheet that closes on a nil selection then closed together with the system sheet. Checked on an iPhone: a second selection ends the first one, and Share and Translate keep the selection. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +++ .../iOS/TranscriptTextView.swift | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/README.md b/README.md index dd7ed97..2e3a04e 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,9 @@ TranscriptText(document) } ``` +One view in a window has a selection at a time. When the person selects text in another view, the first view's +selection ends, and its range is nil. The selection stays when the person opens Share or Translate from the edit menu. + In UIKit, use `onSelectionChange`, `selectedRange` and `selectsAllWhenShown` on `TranscriptTextView`. ## In this repository diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 1870f86..b7e7810 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -341,6 +341,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD canvas.layer.addSublayer(animationLayer) NotificationCenter.default.addObserver(self, selector: #selector(reduceMotionChanged), name: UIAccessibility.reduceMotionStatusDidChangeNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(otherViewBecameFirstResponder(_:)), + name: Self.didBecomeFirstResponder, object: nil) engine.setOutputHandler { [weak self] in DispatchQueue.main.async { MainActor.assumeIsolated { self?.installFromEngine() } @@ -1227,6 +1229,24 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public override var canBecomeFirstResponder: Bool { isSelectable } + private static let didBecomeFirstResponder = Notification.Name("TranscriptTextViewDidBecomeFirstResponder") + + /// Ends the selection of the other views in the window. This is not done + /// in `resignFirstResponder()`: Share and Translate in the edit menu make + /// the view resign, and the selection must stay for them. + @discardableResult + public override func becomeFirstResponder() -> Bool { + let became = super.becomeFirstResponder() + if became { NotificationCenter.default.post(name: Self.didBecomeFirstResponder, object: self) } + return became + } + + @objc private func otherViewBecameFirstResponder(_ notification: Notification) { + guard let other = notification.object as? TranscriptTextView, other !== self, + other.window === window, selection != nil else { return } + select(nil) + } + /// Without selection, only links take touches. public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard super.point(inside: point, with: event) else { return false } From 53ee50e99585f557bf8b259a8448e5636dc779ac Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:13:19 -0800 Subject: [PATCH 5/5] Size a short text's tile to cover its glyphs A view shorter than one tile got a tile that covered its height and the shapes of its tags. Some glyphs draw further down: marks stacked under a letter, and some letters at large sizes. The tile cut them off. On main, the 256-point tile showed them. Now a layout shorter than one tile measures the lowest point of its glyphs, and the tile covers it. A taller layout does not measure. On an iPhone 12 mini, an `a` with eight dots under it shows all of them. In a list of 200 cards, the memory peak stays at 21 MB, and the main-thread CPU stays within the spread between runs. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/DocumentLayout.swift | 19 +++++++++++++++ Sources/TranscriptKit/Layout/TileGrid.swift | 19 +++++++-------- .../iOS/TranscriptTextView.swift | 3 ++- Tests/TranscriptKitTests/TileGridTests.swift | 23 +++++++++++++++++++ 4 files changed, 54 insertions(+), 10 deletions(-) diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 2b72e83..73f623e 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -27,6 +27,11 @@ public final class DocumentLayout: @unchecked Sendable { public let length: Int /// How many block layouts were carried over from the previous layout. public let reusedBlockCount: Int + /// The lowest point that the glyphs of the text draw. It can be below + /// `height`: marks stacked under a letter draw past the line's descent. + /// It is measured only for a layout shorter than one tile (see + /// `TileGrid`). For a taller layout, it is `height`. + let glyphBottom: CGFloat /// One entry per settled block of `document`. Their positions never /// change, so successive layouts share this list and only append to it. @@ -132,6 +137,20 @@ public final class DocumentLayout: @unchecked Sendable { self.height = y self.length = max(start - 1, 0) self.reusedBlockCount = reused + self.glyphBottom = y < TileGrid.height ? Self.glyphBottom(of: Array(settled) + open) : y + } + + private static func glyphBottom(of entries: [Entry]) -> CGFloat { + var bottom: CGFloat = 0 + for entry in entries { + for line in entry.layout.lines { + let glyphs = CTLineGetBoundsWithOptions(line.ctLine, .useGlyphPathBounds) + guard !glyphs.isNull, !glyphs.isEmpty else { continue } + // Core Text measures up from the baseline. + bottom = max(bottom, entry.y + line.baseline - glyphs.minY) + } + } + return bottom } /// The next item of a list sits closer to the list content above it than diff --git a/Sources/TranscriptKit/Layout/TileGrid.swift b/Sources/TranscriptKit/Layout/TileGrid.swift index 5957da4..0de4db5 100644 --- a/Sources/TranscriptKit/Layout/TileGrid.swift +++ b/Sources/TranscriptKit/Layout/TileGrid.swift @@ -8,15 +8,16 @@ enum TileGrid { /// The height of the smallest tile. static let minimumHeight: CGFloat = 32 - /// The height of tile `index` in a view `viewHeight` points high. A view - /// shorter than one tile has one tile that covers only the view and the - /// shapes that reach below its last line, rounded up to 32, 64, 128 or - /// 256 points. So a one-line text keeps a small drawing, and text that - /// grows resizes its tile at most three times. In a taller view, every - /// tile is 256 points high, so a long answer that streams in does not - /// resize each new tile as it grows. - static func tileHeight(at index: Int, viewHeight: CGFloat) -> CGFloat { - let needed = viewHeight + TranscriptPath.maximumOverhang + /// The height of tile `index` in a view `viewHeight` points high, whose + /// glyphs draw down to `glyphBottom`. A view shorter than one tile has one + /// tile that covers only the view, the shapes that reach below its last + /// line and the glyphs, rounded up to 32, 64, 128 or 256 points. So a + /// one-line text keeps a small drawing, and text that grows resizes its + /// tile at most three times. In a taller view, every tile is 256 points + /// high, so a long answer that streams in does not resize each new tile + /// as it grows. + static func tileHeight(at index: Int, viewHeight: CGFloat, glyphBottom: CGFloat = 0) -> CGFloat { + let needed = max(viewHeight + TranscriptPath.maximumOverhang, glyphBottom) guard index == 0, needed < height else { return height } var tile = height while tile > minimumHeight, tile / 2 >= needed { tile /= 2 } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index b7e7810..fdb641f 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -565,7 +565,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD // Wider than the view: tags' shapes may draw past the text column. let side = TranscriptPath.maximumSideOverhang let frame = CGRect(x: -side, y: CGFloat(index) * tileHeight, width: bounds.width + 2 * side, - height: TileGrid.tileHeight(at: index, viewHeight: bounds.height)) + height: TileGrid.tileHeight(at: index, viewHeight: bounds.height, + glyphBottom: currentLayout.glyphBottom)) if let tile = tiles[index] { if tile.frame != frame { tile.frame = frame diff --git a/Tests/TranscriptKitTests/TileGridTests.swift b/Tests/TranscriptKitTests/TileGridTests.swift index 9e1ddcd..a6ce2ba 100644 --- a/Tests/TranscriptKitTests/TileGridTests.swift +++ b/Tests/TranscriptKitTests/TileGridTests.swift @@ -36,3 +36,26 @@ import Testing } #expect(heights == [32, 64, 128, 256]) } + +@Test func aShortTextsTileCoversGlyphsThatDrawBelowIt() { + #expect(TileGrid.tileHeight(at: 0, viewHeight: 21, glyphBottom: 20) == 32) + #expect(TileGrid.tileHeight(at: 0, viewHeight: 21, glyphBottom: 35) == 64) + #expect(TileGrid.tileHeight(at: 0, viewHeight: 21, glyphBottom: 300) == TileGrid.height) +} + +@Test func stackedMarksDrawBelowTheLayout() { + let marks = String(repeating: "\u{323}", count: 5) + let stacked = DocumentLayout(document: TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "a\(marks) b")]), width: 300) + #expect(stacked.glyphBottom > stacked.height + TranscriptPath.maximumOverhang) + + let plain = DocumentLayout(document: TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: "Descenders: gjpqy")]), width: 300) + #expect(plain.glyphBottom > 0) + #expect(plain.glyphBottom <= plain.height) +} + +@Test func aTallLayoutDoesNotMeasureItsGlyphs() { + let text = String(repeating: "A paragraph that fills more than one tile. ", count: 60) + let layout = DocumentLayout(document: TranscriptDocument(blocks: [TranscriptBlock(id: "a", text: text)]), width: 300) + #expect(layout.height >= TileGrid.height) + #expect(layout.glyphBottom == layout.height) +}