From 7e3c90050d6606bc003a74335afd205309bbb055 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:33:03 -0800 Subject: [PATCH 1/3] Set up text selection and scroll checks only when needed A list of cards can show hundreds of short texts. A profile of 200 cards scrolling on an iPhone 12 mini showed that most of a text view's extra main-thread time was not its text. It was setting up `UITextInteraction` and its gesture recognizers, freeing it again, and, for every frame of the scroll, looking up the enclosing scroll view. - A view adds its `UITextInteraction` the first time a touch reaches it, or when the app selects text. Hit testing comes before a touch begins, and the touch's gesture recognizers are gathered after it, so the new ones see that touch. A view that is never touched never sets the interaction up. - A view looks up its scroll view once while it stays where it is, not twice for every frame of a scroll. - A view whose tiles are already released does not look at them again on every frame. Refs #10. Co-Authored-By: Claude Opus 5.5 --- .../iOS/TranscriptTextView.swift | 74 ++++++++++++++----- 1 file changed, 55 insertions(+), 19 deletions(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index e1ee784..43119c1 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -34,14 +34,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// still open. public var isSelectable = true { didSet { - guard isSelectable != oldValue else { return } - if isSelectable { - addInteraction(textInteraction) - } else { - select(nil) + guard isSelectable != oldValue, !isSelectable else { return } + select(nil) + if let textInteraction { removeInteraction(textInteraction) - if isFirstResponder { resignFirstResponder() } + self.textInteraction = nil } + if isFirstResponder { resignFirstResponder() } } } @@ -261,7 +260,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD _ = becomeFirstResponder() selectAll(nil) } - private let textInteraction = UITextInteraction(for: .nonEditable) + /// The system's selection gestures and edit menu. Setting them up costs + /// more than laying out a short text, and most views in a scrolling list + /// are never touched, so they are added when a touch first reaches the + /// view (see `point(inside:with:)`) or the app selects text. + private var textInteraction: UITextInteraction? private let emptyInputView = UIView() /// Holds the layers of tags' animations, above the tail layer. private let animationLayer = CALayer() @@ -342,8 +345,6 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD MainActor.assumeIsolated { self?.installFromEngine() } } } - textInteraction.textInput = self - addInteraction(textInteraction) let linkTap = UITapGestureRecognizer(target: self, action: #selector(handleLinkTap(_:))) linkTap.delegate = self addGestureRecognizer(linkTap) @@ -390,9 +391,17 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD // MARK: Viewport drawing + public override func didMoveToSuperview() { + super.didMoveToSuperview() + cachedScrollView = nil + hasNoScrollView = false + } + public override func didMoveToWindow() { super.didMoveToWindow() scrollObservation = nil + cachedScrollView = nil + hasNoScrollView = false updateTailStyle() updateAnimationsEnabled() updateFadeDuration() @@ -401,9 +410,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD releaseTiles() return } - var ancestor = superview - while let view = ancestor, !(view is UIScrollView) { ancestor = view.superview } - if let scrollView = ancestor as? UIScrollView { + if let scrollView = enclosingScrollView { scrollObservation = scrollView.observe(\.contentOffset) { [weak self] _, _ in MainActor.assumeIsolated { self?.updateCanvas() } } @@ -412,11 +419,25 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD selectAllIfNeeded() } - /// The part of this view currently on screen, or all of it outside a scroll view. - private var visibleRect: CGRect { + private weak var cachedScrollView: UIScrollView? + /// The lookup found no scroll view above this view. + private var hasNoScrollView = false + + /// The nearest scroll view above this view. Looked up once while the + /// view stays where it is: it is needed for every frame of a scroll. + private var enclosingScrollView: UIScrollView? { + if let cachedScrollView { return cachedScrollView } + if hasNoScrollView { return nil } var ancestor = superview while let view = ancestor, !(view is UIScrollView) { ancestor = view.superview } - guard let scrollView = ancestor as? UIScrollView else { return bounds } + cachedScrollView = ancestor as? UIScrollView + hasNoScrollView = cachedScrollView == nil && window != nil + return cachedScrollView + } + + /// The part of this view currently on screen, or all of it outside a scroll view. + private var visibleRect: CGRect { + guard let scrollView = enclosingScrollView else { return bounds } return convert(scrollView.bounds, from: scrollView).intersection(bounds) } @@ -424,9 +445,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// further away, such as a lazy stack's row that scrolled off, frees its tiles. private var isNearVisibleArea: Bool { guard bounds.width > 0, bounds.height > 0 else { return false } - var ancestor = superview - while let view = ancestor, !(view is UIScrollView) { ancestor = view.superview } - guard let scrollView = ancestor as? UIScrollView else { return window != nil } + guard let scrollView = enclosingScrollView else { return window != nil } let area = scrollView.bounds.insetBy(dx: 0, dy: -scrollView.bounds.height / 2) return convert(area, from: scrollView).intersects(bounds) } @@ -444,13 +463,17 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Frees every tile's drawing, for a view with nothing on screen or near it. private func releaseTiles() { - guard !tiles.isEmpty || spareTiles.contains(where: { $0.layer.contents != nil }) else { return } + guard !tilesReleased else { return } + tilesReleased = true tiles.values.forEach { retire($0, freeingDrawing: true) } tiles.removeAll() spareTiles.forEach { $0.layer.contents = nil } trimSpareTiles() } + /// No tile holds a drawing, so releasing them again does nothing. + private var tilesReleased = true + private func trimSpareTiles() { while spareTiles.count > maximumSpareTiles { spareTiles.removeLast().removeFromSuperview() @@ -488,6 +511,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } return } + tilesReleased = false // Keep half a screen of drawn content above and below what is visible. let covered = visible.insetBy(dx: 0, dy: -visible.height / 2).intersection(bounds) let first = Int((covered.minY / tileHeight).rounded(.down)) @@ -1167,9 +1191,20 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// 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 } + // Hit testing comes before the touch begins, and the touch's gesture + // recognizers are gathered after it, so ones added now see it. + if isSelectable { addTextInteractionIfNeeded() } return isSelectable || linkURL(at: point) != nil } + private func addTextInteractionIfNeeded() { + guard isSelectable, textInteraction == nil else { return } + let interaction = UITextInteraction(for: .nonEditable) + interaction.textInput = self + addInteraction(interaction) + textInteraction = interaction + } + /// Read-only: an empty input view keeps the keyboard from appearing. public override var inputView: UIView? { emptyInputView } @@ -1198,6 +1233,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Selects a range of the document's flat UTF-16 offset space, or clears /// the selection when `range` is nil. public func select(_ range: Range?) { + if range != nil { addTextInteractionIfNeeded() } inputDelegate?.selectionWillChange(self) selection = range.map { clamp($0.lowerBound).. Date: Fri, 20 Nov 2026 16:01:56 -0800 Subject: [PATCH 2/3] Draw rows that a lazy stack moves After a push, a tall `TranscriptText` in a `LazyVStack` could show a blank band at its top until the list was scrolled or the text touched. The lazy stack measured the rows above with their real heights and moved the row. The row's own frame and the scroll offset stayed the same, so nothing told the view, and it kept the tiles for where it was before. A watcher now observes each scroll view's content size, which changes when the stack moves rows, once for all the text views in it. When it changes, a view that has some but not all of its tiles updates them on the next turn of the run loop, once the rows are placed. A view whose tiles cover all of it is drawn right wherever it moves. A view without tiles updates when it is scrolled or laid out. The bug was already on `main`. Co-Authored-By: Claude Opus 5.5 --- .../iOS/TranscriptTextView.swift | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 43119c1..c6a09c4 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -307,6 +307,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private var spareTiles: [CanvasView] = [] private let tileHeight: CGFloat = 256 private var scrollObservation: NSKeyValueObservation? + private var canvasCheckScheduled = false public override init(frame: CGRect) { super.init(frame: frame) @@ -414,11 +415,32 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD scrollObservation = scrollView.observe(\.contentOffset) { [weak self] _, _ in MainActor.assumeIsolated { self?.updateCanvas() } } + // A lazy stack moves a row when it measures the rows above it, + // which changes the content size. The row's own frame and the + // scroll offset stay the same, so nothing else tells the view. + ContentSizeWatcher.watcher(for: scrollView).add(self) } updateCanvas() selectAllIfNeeded() } + /// Updates the tiles on the next turn of the run loop, once the stack has + /// placed its rows. One check is pending at a time. Only a view with some + /// of its tiles is checked: one whose tiles cover all of it, as a short + /// text's one tile does, is right wherever it moves, and one with none is + /// far from the screen and updates when it is scrolled or laid out. + fileprivate func updateCanvasSoon() { + guard !canvasCheckScheduled, !tilesReleased, !tiles.isEmpty, !tilesCoverView else { return } + canvasCheckScheduled = true + DispatchQueue.main.async { [weak self] in + MainActor.assumeIsolated { + guard let self else { return } + self.canvasCheckScheduled = false + self.updateCanvas() + } + } + } + private weak var cachedScrollView: UIScrollView? /// The lookup found no scroll view above this view. private var hasNoScrollView = false @@ -474,6 +496,12 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// No tile holds a drawing, so releasing them again does nothing. private var tilesReleased = true + private var tilesCoverView: Bool { + guard !tilesReleased, bounds.height > 0 else { return false } + let count = Int((bounds.height / tileHeight).rounded(.up)) + return tiles.count >= count && (0.. maximumSpareTiles { spareTiles.removeLast().removeFromSuperview() @@ -1455,4 +1483,34 @@ final class TranscriptSelectionRect: UITextSelectionRect { override var containsEnd: Bool { storedContainsEnd } override var isVertical: Bool { false } } + +/// Watches a scroll view's content size for the text views in it, with one +/// observation for all of them: a list can hold many. +@MainActor +private final class ContentSizeWatcher { + private static var key: UInt8 = 0 + private var observation: NSKeyValueObservation? + private let views = NSHashTable.weakObjects() + + /// The scroll view's watcher, which the scroll view keeps. + static func watcher(for scrollView: UIScrollView) -> ContentSizeWatcher { + if let watcher = objc_getAssociatedObject(scrollView, &key) as? ContentSizeWatcher { return watcher } + let watcher = ContentSizeWatcher() + watcher.observation = scrollView.observe(\.contentSize) { [weak watcher] _, _ in + MainActor.assumeIsolated { watcher?.contentSizeChanged() } + } + objc_setAssociatedObject(scrollView, &key, watcher, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return watcher + } + + func add(_ view: TranscriptTextView) { + views.add(view) + } + + private func contentSizeChanged() { + for view in views.allObjects where view.window != nil { + view.updateCanvasSoon() + } + } +} #endif From bbec0c8c18ba05036fb68566f3d8cfe38fc1f14e Mon Sep 17 00:00:00 2001 From: Server Date: Mon, 23 Nov 2026 13:36:03 -0800 Subject: [PATCH 3/3] Fix the selection in lists, draw short texts into smaller tiles, and add a Writing Tools option (#29) * 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 * 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 * 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 * 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 * 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 --------- Co-authored-by: Server Cimen <505984+servercimen@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- README.md | 6 ++ .../TranscriptKit/Layout/DocumentLayout.swift | 19 ++++++ Sources/TranscriptKit/Layout/TileGrid.swift | 26 ++++++++ .../TranscriptKit/iOS/TranscriptText.swift | 10 +++ .../iOS/TranscriptTextView.swift | 56 ++++++++++++++--- Tests/TranscriptKitTests/TileGridTests.swift | 61 +++++++++++++++++++ 6 files changed, 171 insertions(+), 7 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/TileGrid.swift create mode 100644 Tests/TranscriptKitTests/TileGridTests.swift diff --git a/README.md b/README.md index a1b318e..2e3a04e 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 @@ -332,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/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 new file mode 100644 index 0000000..0de4db5 --- /dev/null +++ b/Sources/TranscriptKit/Layout/TileGrid.swift @@ -0,0 +1,26 @@ +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, 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 } + return tile + } +} 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 c6a09c4..fdb641f 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 @@ -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() } @@ -398,6 +400,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 @@ -520,7 +532,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)) } @@ -552,7 +564,9 @@ 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, + glyphBottom: currentLayout.glyphBottom)) if let tile = tiles[index] { if tile.frame != frame { tile.frame = frame @@ -560,7 +574,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)) } @@ -1216,6 +1230,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 } @@ -1236,6 +1268,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(_:)): diff --git a/Tests/TranscriptKitTests/TileGridTests.swift b/Tests/TranscriptKitTests/TileGridTests.swift new file mode 100644 index 0000000..a6ce2ba --- /dev/null +++ b/Tests/TranscriptKitTests/TileGridTests.swift @@ -0,0 +1,61 @@ +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]) +} + +@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) +}