Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions Sources/TranscriptKit/Layout/TileGrid.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
10 changes: 10 additions & 0 deletions Sources/TranscriptKit/iOS/TranscriptText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public struct TranscriptText: UIViewRepresentable {
private var playTrigger: AnyHashable?
private var selectionChange: ((Range<Int>?) -> 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`).
Expand Down Expand Up @@ -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?
}
Expand Down Expand Up @@ -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()
Expand Down
56 changes: 49 additions & 7 deletions Sources/TranscriptKit/iOS/TranscriptTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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() }
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
}
Expand Down Expand Up @@ -552,15 +564,17 @@ 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
tile.setNeedsDisplay()
} 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))
}
Expand Down Expand Up @@ -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 }
Expand All @@ -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(_:)):
Expand Down
61 changes: 61 additions & 0 deletions Tests/TranscriptKitTests/TileGridTests.swift
Original file line number Diff line number Diff line change
@@ -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..<count {
#expect(TileGrid.tileHeight(at: index, viewHeight: viewHeight) == TileGrid.height)
}
}
}

@Test func aShortTextsTileCoversItAndTheShapesBelowIt() {
for height in stride(from: CGFloat(1), through: 300, by: 0.5) {
let tile = TileGrid.tileHeight(at: 0, viewHeight: height)
let needed = height + TranscriptPath.maximumOverhang
#expect(tile >= 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)
}
Loading