diff --git a/README.md b/README.md index 73d348e..5f0a6ab 100644 --- a/README.md +++ b/README.md @@ -340,8 +340,17 @@ TranscriptText(stream: stream) In UIKit, set `mathRenderer` on `TranscriptTextView`. TranscriptKit uses only the alpha of the image, and draws the formula in the text color, so it follows light and dark appearance. A formula that is wider than the text column is scaled down to fit. A paragraph that holds only display math is centered. While a formula streams in, it shows -nothing until it closes, so the text on screen only grows. Copy gives the LaTeX with its delimiters, and VoiceOver -reads the LaTeX. +nothing until it closes, so the text on screen only grows. Copy gives the LaTeX with its delimiters. + +VoiceOver reads the LaTeX by default. To give VoiceOver other words, for example from a library that turns LaTeX into +speech, set a label. TranscriptKit calls it on the main thread: + +```swift +TranscriptText(stream: stream) + .mathAccessibilityLabel { math in mySpeechText(forLaTeX: math.tex) } +``` + +In UIKit, set `mathAccessibilityLabel` on `TranscriptTextView`. Two style options change display math. `displayMathAlignment` puts the formula at the leading edge, the center (the default) or the trailing edge. With `displayMathScrolls`, a display formula that is wider than the column keeps its @@ -396,13 +405,26 @@ them off with `.showsWritingTools(false)`, or with `showsWritingTools` on `Trans ### VoiceOver VoiceOver reads the text block by block. Headings are in the rotor's list of headings, list items start with their -number or "Checked" or "Unchecked", and each link in a block is an action that opens it. The spoken words "Open %@", -"Checked", "Unchecked" and "Separator" come from your app's `Localizable.strings`, so you can translate them there. +number or "Checked" or "Unchecked", and each link in a block is an action that opens it. A list item also tells its +position in its list and the number of items, such as "Item 2 of 3". A table is a data table with one element for each +cell, so VoiceOver reads it cell by cell, with the row, the column and the column's header. When a table starts a list +item, its first cell reads the item's marker and tells its position. While text streams in, each block keeps its +element, so VoiceOver focus stays on its block. The view tells VoiceOver that the layout changed only when elements +come or go, or when a new layout moves them or changes their size. Text that streams into the last block does not +tell it. + +Assistive technologies, such as VoiceOver, Speak Screen and Voice Control, can ask for the elements and the text from +any thread. TranscriptKit then does the work on the main thread and gives the answer to the thread that asked. + +The spoken words "Open %@", "Checked", "Unchecked", "Separator" and "Item %1$ld of %2$ld" come from your app's +`Localizable.strings`, so you can translate them there. ### Line limit and alignment For short text in cards and list rows, set a line limit and an alignment. When text is left out, the last line shown -ends in "…", and selection and copying cover only what is shown. `TranscriptText` also takes SwiftUI's modifiers: +ends in "…". The selection shows only on the text that is shown. A selection that reaches the end of that text, such as +Select All, also copies the text that is left out, and VoiceOver reads all of the text. `TranscriptText` also takes +SwiftUI's modifiers: ```swift TranscriptText(document) diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift new file mode 100644 index 0000000..1f2b2bc --- /dev/null +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -0,0 +1,465 @@ +import CoreGraphics +import Foundation + +/// What assistive technologies get for one block on screen. It is made from +/// a layout without UIKit, so that it can be tested on macOS. +struct AccessibilityItem: Equatable { + struct Link: Equatable { + let title: String + let url: URL + } + + /// A table's cells, each an element of its own. + struct Table: Equatable { + struct Cell: Equatable { + let row: Int + let column: Int + let frame: CGRect + let label: String + /// For the first cell of a table that starts a list item: the + /// item's position, as for a block. + let value: String? + let links: [Link] + } + + let rowCount: Int + let columnCount: Int + /// Row by row; the first row is the header. + let cells: [Cell] + } + + /// A block's id, and how many blocks before it have the same id. + struct Key: Hashable { + let id: String + let occurrence: Int + } + + /// Unique in the document: an element keeps it from one layout to the + /// next, so VoiceOver focus stays on the block while text streams in. + let key: Key + let frame: CGRect + /// What VoiceOver says: the list marker, then the text. Empty for a + /// table: its first cell has the list marker and the position. + let label: String + /// For the first block of a list item: its position in its list and the + /// number of items in the list, such as "Item 2 of 3". + let value: String? + let isHeading: Bool + /// The links in the text. Each is an action that opens it. + let links: [Link] + let table: Table? +} + +extension DocumentLayout { + /// One item for each block on screen that has text, in reading order. + /// + /// Under a line limit, the last item holds all of its block's text and + /// the text of the blocks that the limit leaves out, as a label that is + /// cut short still reads all of its text. When the last block shown is + /// a table, the text left out gets an item of its own after it. + /// + /// - Parameter math: the words for a formula. + /// - Parameter words: the words of the items made before with the same + /// `math`, which blocks whose layout did not change use again. + func accessibilityItems(math: (TranscriptMath) -> String = \.tex, words: AccessibilityWords? = nil) -> [AccessibilityItem] { + var items: [AccessibilityItem] = [] + let definitions = document.linkDefinitions + words?.begin(definitions: definitions) + defer { words?.end() } + let positions = AccessibilityText.listPositions(in: document, upTo: entryCount) + var uses: [String: Int] = [:] + func key(for block: TranscriptBlock) -> AccessibilityItem.Key { + let use = uses[block.id, default: 0] + uses[block.id] = use + 1 + return AccessibilityItem.Key(id: block.id, occurrence: use) + } + for index in 0.. String, + definitions: [String: String]) -> AccessibilityWords.Words { + let block = layout.block + guard let model = block.kind.table, let grid = layout.table else { + let all = 0.. AccessibilityItem.Table { + var cells: [AccessibilityItem.Table.Cell] = [] + let (rowCount, columnCount) = accessibilityGridSize(model, grid: grid) + for row in 0.. (rows: Int, columns: Int) { + (max(min(model.rows.count, grid.rowY.count - 1), 0), max(min(model.columnCount, grid.columnX.count - 1), 0)) + } + + /// The number of cells that `accessibilityTable` makes. + private static func accessibilityCellCount(_ model: TranscriptTable, grid: BlockLayout.Table) -> Int { + let (rows, columns) = accessibilityGridSize(model, grid: grid) + return model.rows.prefix(rows).reduce(0) { $0 + min($1.count, columns) } + } + + /// Which items the layout has and where they are, found without + /// reading the text of its blocks. + var accessibilityGeometry: AccessibilityGeometry { + var entries: [AccessibilityGeometry.Entry] = [] + entries.reserveCapacity(entryCount) + for index in 0.. 0 { return true } + } else if AccessibilityText.hasItem(entry.layout.block) { + return false + } + } + return true + } +} + +/// The blocks of a layout, with the number of elements and the frame of +/// each, and whether the text that a line limit leaves out has an item. +struct AccessibilityGeometry: Equatable { + struct Entry: Equatable { + let id: String + /// 0 for a block without an item, the number of cells for a table, + /// and 1 for other blocks. + let elements: Int + let frame: CGRect + } + + let entries: [Entry] + /// See `DocumentLayout.hasAccessibilityRemainder`. + let hasRemainder: Bool + + /// Whether the two have the same elements, wherever they are. + func hasSameElements(as other: AccessibilityGeometry) -> Bool { + hasRemainder == other.hasRemainder && entries.count == other.entries.count + && zip(entries, other.entries).allSatisfy { $0.id == $1.id && $0.elements == $1.elements } + } +} + +/// Decides when assistive technologies must hear that the layout changed. +/// +/// A layout that only adds text to the end of the one before needs a +/// layout-changed notification only when elements come or go. Other +/// layouts, such as the ones that a new width or an image start, need it +/// also when an element moved or changed its size. A layout that only gives +/// code other colors has the same geometry, so it needs none. +struct AccessibilityLayoutWatch { + /// The geometry of the layout installed last. + private(set) var geometry: AccessibilityGeometry? + + /// Takes in a layout that was installed, and tells whether it needs a + /// notification. + mutating func install(_ layout: DocumentLayout, isAppend: Bool) -> Bool { + let new = layout.accessibilityGeometry + defer { geometry = new } + guard let old = geometry else { return true } + return isAppend ? !new.hasSameElements(as: old) : new != old + } + + /// Starts from `layout`, whose elements assistive technologies just got. + mutating func start(with layout: DocumentLayout) { + geometry = layout.accessibilityGeometry + } +} + +/// The words of the blocks that items were last made for. A block whose +/// layout is the same object as before keeps its words, so a long +/// transcript is not read again for each layout while text streams in. Use +/// one instance with one `math` only, on one thread at a time. +final class AccessibilityWords { + struct Words { + let text: String + let links: [AccessibilityItem.Link] + /// For a table: each cell's words. + let cells: [Words] + } + + private struct Kept { + let layout: BlockLayout + let words: Words + } + + private var kept: [AccessibilityItem.Key: Kept] = [:] + private var next: [AccessibilityItem.Key: Kept] = [:] + private var definitions: [String: String] = [:] + + /// Starts a new set of items. Other link definitions can change the + /// links of any block, so then no words are used again. + func begin(definitions: [String: String]) { + if definitions != self.definitions { + kept = [:] + self.definitions = definitions + } + next = [:] + } + + func words(for key: AccessibilityItem.Key, layout: BlockLayout) -> Words? { + kept[key].flatMap { $0.layout === layout ? $0.words : nil } + } + + func keep(_ words: Words, for key: AccessibilityItem.Key, layout: BlockLayout) { + next[key] = Kept(layout: layout, words: words) + } + + /// Keeps only the words of the blocks in the last set of items. + func end() { + kept = next + next = [:] + } +} + +/// The words that assistive technologies get for a block. +enum AccessibilityText { + /// The block's text in `range`, with images as their alt text and + /// formulas as `math` gives them, in place of the U+FFFC character each + /// stands for. + static func readable(_ block: TranscriptBlock, in range: Range, math: (TranscriptMath) -> String = \.tex) -> String { + readable(block, in: range, spans: block.spans, math: math) + } + + /// - Parameter spans: the spans of the block that can start in + /// `range`, in the block's order. + static func readable(_ block: TranscriptBlock, in range: Range, spans: some BidirectionalCollection, + math: (TranscriptMath) -> String) -> String { + let text = NSMutableString(string: (block.text as NSString).substring(with: NSRange(location: range.lowerBound, + length: range.count))) + for span in spans.reversed() where range.contains(span.range.lowerBound) && span.range.count == 1 { + guard let replacement = span.image?.alt ?? span.math.map(math) else { continue } + text.replaceCharacters(in: NSRange(location: span.range.lowerBound - range.lowerBound, length: 1), with: replacement) + } + return text as String + } + + /// Whether a block that is not a table gets an item: it has text, or it + /// is a rule. + static func hasItem(_ block: TranscriptBlock) -> Bool { + !readable(block, in: 0.. String { + switch block.marker { + case .task(let checked)?: + let state = checked + ? NSLocalizedString("Checked", comment: "VoiceOver: a task list item that is done") + : NSLocalizedString("Unchecked", comment: "VoiceOver: a task list item that is not done") + return state + ", " + text + case .number(let number)?: + return number + " " + text + case .bullet?, nil: + if case .rule = block.kind { + return NSLocalizedString("Separator", comment: "VoiceOver: a thematic break between blocks") + } + return text + } + } + + /// A list item's position and the number of items in its list. + static func position(_ position: ListPosition) -> String { + let format = NSLocalizedString("Item %1$ld of %2$ld", + comment: "VoiceOver: a list item's position in its list (%1$ld) and the number of items in the list (%2$ld)") + return String(format: format, position.index, position.count) + } + + /// The links that start in `range` of the block's text. + static func links(of block: TranscriptBlock, in range: Range, math: (TranscriptMath) -> String = \.tex, + definitions: [String: String]) -> [AccessibilityItem.Link] { + links(of: block, in: range, spans: block.spans, math: math, definitions: definitions) + } + + /// - Parameter spans: the spans of the block that can start in + /// `range`, in the block's order. + static func links(of block: TranscriptBlock, in range: Range, spans: some BidirectionalCollection, + math: (TranscriptMath) -> String, definitions: [String: String]) -> [AccessibilityItem.Link] { + var links: [AccessibilityItem.Link] = [] + for span in spans where range.contains(span.range.lowerBound) { + guard let target = span.link ?? span.reference.flatMap({ definitions[$0] }), let url = URL(string: target) else { + continue + } + let end = min(span.range.upperBound, block.utf16Count) + links.append(.init(title: readable(block, in: span.range.lowerBound..]) -> [[InlineSpan]] { + var result = Array(repeating: [InlineSpan](), count: ranges.count) + // An empty range before a range with the same start: the range with text comes last. + let order = ranges.indices.sorted { (ranges[$0].lowerBound, ranges[$0].upperBound) < (ranges[$1].lowerBound, ranges[$1].upperBound) } + for span in block.spans { + let start = span.range.lowerBound + var low = 0 + var high = order.count + while low < high { + let middle = (low + high) / 2 + if ranges[order[middle]].lowerBound <= start { low = middle + 1 } else { high = middle } + } + guard low > 0, ranges[order[low - 1]].contains(start) else { continue } + result[order[low - 1]].append(span) + } + return result + } + + struct ListPosition: Equatable { + /// From 1. + let index: Int + let count: Int + } + + /// The position of each list item's first block among the first `end` + /// blocks, by block index. The count takes in every item of the list, + /// also the items after `end`. + /// + /// A list is a run of items at one depth, in the same containers, with + /// the item's content in between. It ends at a block outside those + /// containers, or at an item with another kind of marker: bullets and + /// task boxes go together, and numbers go with numbers that have the + /// same delimiter. + static func listPositions(in document: TranscriptDocument, upTo end: Int) -> [Int: ListPosition] { + struct Run { + /// The index of the list item container of the list's items. + let depth: Int + let containers: ArraySlice + let kind: Character + var items: [Int] = [] + } + var positions: [Int: ListPosition] = [:] + var runs: [Run] = [] + func close(_ run: Run) { + guard run.items.first.map({ $0 < end }) ?? false else { return } + for (position, item) in run.items.enumerated() where item < end { + positions[item] = ListPosition(index: position + 1, count: run.items.count) + } + } + for index in 0.. run.depth && block.containers[...run.depth] == run.containers) { + close(runs.removeLast()) + } + if index >= end, runs.isEmpty { break } + guard let marker = block.marker, let depth = block.containers.lastIndex(of: .listItem) else { continue } + let kind: Character + switch marker { + case .bullet, .task: kind = "-" + case .number(let number): kind = number.last ?? "." + } + if let run = runs.last, run.depth == depth { + if run.kind == kind { + runs[runs.count - 1].items.append(index) + continue + } + close(runs.removeLast()) + } + runs.append(Run(depth: depth, containers: block.containers[...depth], kind: kind, items: [index])) + } + runs.forEach(close) + return positions + } +} + +extension TranscriptBlock.Kind { + var isHeading: Bool { + if case .heading = self { return true } + return false + } +} diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index ab19076..fdd07c1 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -166,6 +166,18 @@ public final class DocumentLayout: @unchecked Sendable { a.containers.count > index && b.containers.count > index && a.containers[...index] == b.containers[...index] } + /// Whether a line limit left some of the document's text out. + var leavesTextOut: Bool { length < document.utf16Count } + + /// The part of the document that a selection of this layout stands for. + /// Under a line limit, a selection that reaches the end of the text + /// shown also covers the text that the limit leaves out, so Select All + /// followed by Copy copies all of the text. + func documentRange(forSelection range: Range) -> Range { + guard !range.isEmpty, range.upperBound >= length, leavesTextOut else { return range } + return range.lowerBound..(_ body: @MainActor () -> Result) -> Result { + if Thread.isMainThread { + return MainActor.assumeIsolated { MainThreadResult(value: body()) }.value + } + return DispatchQueue.main.sync { MainActor.assumeIsolated { MainThreadResult(value: body()) } }.value +} + +/// A result that goes from the main thread to the thread that waits for it. +/// The main thread hands it over and does not keep it. +private struct MainThreadResult: @unchecked Sendable { + let value: Value +} +#endif diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 2432adb..1c9607f 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -22,6 +22,7 @@ public struct TranscriptText: UIViewRepresentable { private var highlighter: TranscriptCodeHighlighter? private var mathRenderer: TranscriptMathRenderer? private var mathCache: TranscriptMathCache = .shared + private var mathAccessibilityLabel: ((TranscriptMath) -> String)? private var animatesTags = true private var textFadeInDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately @@ -92,6 +93,15 @@ public struct TranscriptText: UIViewRepresentable { return copy } + /// The words that VoiceOver says for a formula; see + /// `TranscriptTextView.mathAccessibilityLabel`. Read once, when the view + /// is created. + public func mathAccessibilityLabel(_ label: @escaping (TranscriptMath) -> String) -> TranscriptText { + var copy = self + copy.mathAccessibilityLabel = label + return copy + } + /// Fades in text as it streams in; see `TranscriptTextView.textFadeInDuration`. public func fadesInText(_ fades: Bool = true, duration: TimeInterval = 0.3) -> TranscriptText { var copy = self @@ -184,6 +194,7 @@ public struct TranscriptText: UIViewRepresentable { view.mathCache = mathCache view.mathRenderer = mathRenderer } + if let mathAccessibilityLabel { view.mathAccessibilityLabel = mathAccessibilityLabel } return view } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 430c2da..4f5d2cd 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -2,101 +2,261 @@ import UIKit /// One accessibility element for each block: VoiceOver reads the text block -/// by block, finds headings with the rotor, and opens links as actions. +/// by block, finds headings with the rotor, and opens links as actions. A +/// list item tells its position in its list, and a table is a data table +/// with one element for each cell. extension TranscriptTextView { - /// The elements for `layout`, made again only when the layout changes. + /// The elements for `layout`, brought up to date only when the layout + /// changes. A block keeps its element from one layout to the next, so + /// VoiceOver focus stays where it is while text streams in. func accessibilityElements(for layout: DocumentLayout) -> [UIAccessibilityElement] { - if let cached = accessibilityCache, cached.layout === layout { return cached.elements } + let cache = accessibilityCache ?? AccessibilityCache() + accessibilityCache = cache + if cache.layout === layout { return cache.elements } + var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] - let definitions = layout.document.linkDefinitions - for index in 0.. 0 } + .map(\.layout.block.id)) + for item in layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex, words: cache.words) { let element: UIAccessibilityElement - if entry.layout.maximumScrollOffset > 0 { - let scrolling = SideScrollingElement(accessibilityContainer: self) - let id = block.id - scrolling.onScroll = { [weak self] direction in self?.accessibilityScrollBlock(id, direction) ?? false } - element = scrolling + if let table = item.table { + let tableElement = cache.byKey[item.key] as? TableAccessibilityElement + ?? TableAccessibilityElement(accessibilityContainer: self) + tableElement.update(frame: item.frame, table: table, in: self) + element = tableElement } else { - element = UIAccessibilityElement(accessibilityContainer: self) + let blockElement = cache.byKey[item.key] as? BlockAccessibilityElement + ?? BlockAccessibilityElement(accessibilityContainer: self) + blockElement.update(with: item, scrollsSideways: scrolling.contains(item.key.id), in: self) + element = blockElement } - element.accessibilityLabel = Self.spokenText(text, of: block) - element.accessibilityFrameInContainerSpace = entry.frame - var traits: UIAccessibilityTraits = .staticText - if case .heading = block.kind { traits.insert(.header) } - var actions: [UIAccessibilityCustomAction] = [] - let shown = min(entry.layout.length, block.utf16Count) - let original = block.text as NSString - for span in block.spans where span.range.upperBound <= shown { - guard let target = span.link ?? span.reference.flatMap({ definitions[$0] }), let url = URL(string: target) else { - continue - } - let title = original.substring(with: NSRange(location: span.range.lowerBound, length: span.range.count)) - let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") - actions.append(UIAccessibilityCustomAction(name: String(format: format, title)) { [weak self] _ in - self?.openLink(url) - return true - }) - } - if !actions.isEmpty { traits.insert(.link) } - element.accessibilityTraits = traits - element.accessibilityCustomActions = actions + byKey[item.key] = element elements.append(element) } - accessibilityCache = AccessibilityCache(layout: layout, elements: elements) + if cache.watch.geometry == nil { cache.watch.start(with: layout) } + cache.layout = layout + cache.byKey = byKey + cache.elements = elements return elements } - /// A block's text with images as their alt text and formulas as their - /// LaTeX, in place of the U+FFFC character each stands for. - static func readableText(of block: TranscriptBlock, upTo end: Int) -> String { - let text = NSMutableString(string: (block.text as NSString).substring(to: end)) - for span in block.spans.reversed() where span.range.lowerBound < end && span.range.count == 1 { - guard let replacement = span.image?.alt ?? span.math?.tex else { continue } - text.replaceCharacters(in: NSRange(location: span.range.lowerBound, length: 1), with: replacement) - } - return text as String - } - - /// What VoiceOver says for a block: its list marker, then its text. - static func spokenText(_ text: String, of block: TranscriptBlock) -> String { - switch block.marker { - case .task(let checked)?: - let state = checked - ? NSLocalizedString("Checked", comment: "VoiceOver: a task list item that is done") - : NSLocalizedString("Unchecked", comment: "VoiceOver: a task list item that is not done") - return state + ", " + text - case .number(let number)?: - return number + " " + text - case .bullet?, nil: - if case .rule = block.kind { - return NSLocalizedString("Separator", comment: "VoiceOver: a thematic break between blocks") + /// Makes the elements again on the next request, for example with new + /// words for formulas. + func invalidateAccessibilityElements() { + guard let cache = accessibilityCache, cache.layout != nil else { return } + cache.layout = nil + cache.words = AccessibilityWords() + UIAccessibility.post(notification: .layoutChanged, argument: nil) + } + + /// Tells assistive technologies that elements came or went, or moved, + /// after `layout` was installed (see `AccessibilityLayoutWatch`). + /// Elements keep their identity, so VoiceOver focus stays on its block. + /// Nothing is posted before an assistive technology has asked for the + /// elements. + func postAccessibilityLayoutChangeIfNeeded(for layout: DocumentLayout, isAppend: Bool) { + guard let cache = accessibilityCache, cache.layout != nil else { return } + let isNeeded = cache.watch.install(layout, isAppend: isAppend) + if isNeeded, window != nil { UIAccessibility.post(notification: .layoutChanged, argument: nil) } + } +} + +/// The text and frame of a block or a table cell. Assistive technologies +/// can ask for them from any thread, so they are kept here, and the +/// getters read them on the main thread (see `onMainThread`). A getter +/// first brings the elements up to date, because a client can keep an +/// element while text streams in. +class TextAccessibilityElement: UIAccessibilityElement { + private var label: String? + private var value: String? + private var traits: UIAccessibilityTraits = .staticText + /// The element in the view's coordinates. + private(set) var frameInView: CGRect = .zero + private(set) weak var view: TranscriptTextView? + private var links: [AccessibilityItem.Link]? + private var actions: [UIAccessibilityCustomAction]? + + /// - Parameter frameInContainer: the frame in the container's + /// coordinates, which UIKit can use to scroll the element into view. + func update(label: String, value: String?, isHeading: Bool, frame: CGRect, frameInContainer: CGRect, + links: [AccessibilityItem.Link], in view: TranscriptTextView) { + self.label = label + self.value = value + frameInView = frame + if accessibilityFrameInContainerSpace != frameInContainer { accessibilityFrameInContainerSpace = frameInContainer } + self.view = view + var traits: UIAccessibilityTraits = .staticText + if isHeading { traits.insert(.header) } + if !links.isEmpty { traits.insert(.link) } + self.traits = traits + guard self.links != links else { return } + self.links = links + let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") + actions = links.map { link in + UIAccessibilityCustomAction(name: String(format: format, link.title)) { @Sendable [weak view] _ in + onMainThread { view?.openLink(link.url) } + return true } - return text } } + + nonisolated override var accessibilityLabel: String? { + get { onMainThread { current.label } } + set { onMainThread { label = newValue } } + } + + nonisolated override var accessibilityValue: String? { + get { onMainThread { current.value } } + set { onMainThread { value = newValue } } + } + + nonisolated override var accessibilityTraits: UIAccessibilityTraits { + get { onMainThread { current.traits } } + set { onMainThread { traits = newValue } } + } + + /// From the view: a table cell's container is the table's element, not a view. + nonisolated override var accessibilityFrame: CGRect { + get { onMainThread { current.screenFrame } } + set {} + } + + nonisolated override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { + get { onMainThread { current.actions } } + set { onMainThread { actions = newValue } } + } + + /// This element, once the elements are up to date. + fileprivate var current: TextAccessibilityElement { + view?.updateAccessibilityElements() + return self + } + + private var screenFrame: CGRect { + view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero + } } -/// The element of a block that scrolls sideways: a three-finger swipe -/// moves the block. -final class SideScrollingElement: UIAccessibilityElement { - var onScroll: ((UIAccessibilityScrollDirection) -> Bool)? +/// A block's element. Its block's id keeps it from one layout to the next. +/// When the block scrolls sideways, a three-finger swipe moves the block. +final class BlockAccessibilityElement: TextAccessibilityElement { + /// The id of the block, when the block scrolls sideways. + private var sideScrollingID: String? + + func update(with item: AccessibilityItem, scrollsSideways: Bool, in view: TranscriptTextView) { + update(label: item.label, value: item.value, isHeading: item.isHeading, frame: item.frame, frameInContainer: item.frame, + links: item.links, in: view) + sideScrollingID = scrollsSideways ? item.key.id : nil + } - override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { - onScroll?(direction) ?? false + nonisolated override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { + onMainThread { + _ = current + guard let id = sideScrollingID, let view else { return false } + return view.accessibilityScrollBlock(id, direction) + } } } -final class AccessibilityCache { - let layout: DocumentLayout - let elements: [UIAccessibilityElement] +/// A table's element: a data table that holds one element for each cell, +/// so VoiceOver reads the table cell by cell, with the row and column. +final class TableAccessibilityElement: UIAccessibilityElement, UIAccessibilityContainerDataTable { + private var cells: [CellAccessibilityElement] = [] + private var rowCount = 0 + private var columnCount = 0 + private var frameInView: CGRect = .zero + private weak var view: TranscriptTextView? + + func update(frame: CGRect, table: AccessibilityItem.Table, in view: TranscriptTextView) { + frameInView = frame + if accessibilityFrameInContainerSpace != frame { accessibilityFrameInContainerSpace = frame } + self.view = view + rowCount = table.rowCount + columnCount = table.columnCount + var cells: [CellAccessibilityElement] = [] + for (index, cell) in table.cells.enumerated() { + let element = index < self.cells.count && self.cells[index].row == cell.row && self.cells[index].column == cell.column + ? self.cells[index] : CellAccessibilityElement(accessibilityContainer: self) + element.update(with: cell, inTableAt: frame.origin, in: view) + cells.append(element) + } + self.cells = cells + } + + nonisolated override var isAccessibilityElement: Bool { + get { false } + set {} + } + + nonisolated override var accessibilityContainerType: UIAccessibilityContainerType { + get { .dataTable } + set {} + } + + nonisolated override var accessibilityElements: [Any]? { + get { onMainThread { current.cells } } + set {} + } + + nonisolated override var accessibilityFrame: CGRect { + get { onMainThread { current.screenFrame } } + set {} + } + + nonisolated func accessibilityDataTableCellElement(forRow row: Int, column: Int) -> (any UIAccessibilityContainerDataTableCell)? { + onMainThread { current.cells.first { $0.row == row && $0.column == column } } + } + + nonisolated func accessibilityRowCount() -> Int { onMainThread { current.rowCount } } + + nonisolated func accessibilityColumnCount() -> Int { onMainThread { current.columnCount } } + + nonisolated func accessibilityHeaderElements(forColumn column: Int) -> [any UIAccessibilityContainerDataTableCell]? { + onMainThread { current.cells.first { $0.row == 0 && $0.column == column }.map { [$0] } } + } + + /// This element, once the elements are up to date. + private var current: TableAccessibilityElement { + view?.updateAccessibilityElements() + return self + } + + private var screenFrame: CGRect { + view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero + } +} + +/// A table cell's element. +final class CellAccessibilityElement: TextAccessibilityElement, UIAccessibilityContainerDataTableCell { + private(set) var row = -1 + private(set) var column = -1 - init(layout: DocumentLayout, elements: [UIAccessibilityElement]) { - self.layout = layout - self.elements = elements + func update(with cell: AccessibilityItem.Table.Cell, inTableAt origin: CGPoint, in view: TranscriptTextView) { + row = cell.row + column = cell.column + update(label: cell.label, value: cell.value, isHeading: false, frame: cell.frame, + frameInContainer: cell.frame.offsetBy(dx: -origin.x, dy: -origin.y), links: cell.links, in: view) } + + nonisolated func accessibilityRowRange() -> NSRange { onMainThread { NSRange(location: cell.row, length: 1) } } + + nonisolated func accessibilityColumnRange() -> NSRange { onMainThread { NSRange(location: cell.column, length: 1) } } + + /// This cell, once the elements are up to date. + private var cell: CellAccessibilityElement { + _ = current + return self + } +} + +final class AccessibilityCache { + /// The layout that the elements were last brought up to date for. + var layout: DocumentLayout? + /// The geometry of the layout installed last, from the first request on. + var watch = AccessibilityLayoutWatch() + /// The words of those items, for the current `mathAccessibilityLabel`. + var words = AccessibilityWords() + var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] + var elements: [UIAccessibilityElement] = [] } #endif diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 893fa61..f5efa98 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -254,6 +254,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD await settledWaiters.wait() } + /// The words that VoiceOver says for a formula, for example from a + /// library that turns LaTeX into speech. Called on the main thread. Not + /// set by default: VoiceOver then reads the formula's LaTeX. + public var mathAccessibilityLabel: ((TranscriptMath) -> String)? { + didSet { invalidateAccessibilityElements() } + } + private let engine = LayoutEngine() private lazy var settledWaiters = makeSettledWaiters() @@ -311,10 +318,12 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private var reportedSelection: Range? /// The selected range of the document's flat UTF-16 offset space, or nil - /// when nothing is selected. `document.text(in:)` gives its text. + /// when nothing is selected. `document.text(in:)` gives its text. Under + /// a line limit, a selection that reaches the end of the text shown + /// also covers the text that the limit leaves out. public var selectedRange: Range? { guard let selection, !selection.isEmpty else { return nil } - return selection + return currentLayout.documentRange(forSelection: selection) } /// Called on the main thread after the selection changes, with the new @@ -1154,7 +1163,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD TranscriptDiagnostics.count(\.installs) let old = installed let isAppend = changedTop != nil && old != nil - if !isAppend { inputDelegate?.textWillChange(self) } + if !isAppend { storedInputDelegate?.textWillChange(self) } if isAppend { self.fadingFrom = fadingFrom } else if let keptFadingFrom { @@ -1261,9 +1270,10 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD if layout.length > 0 { hasShownText = true } if !isAppend { - inputDelegate?.textDidChange(self) + storedInputDelegate?.textDidChange(self) refreshSelectionDisplay() } + postAccessibilityLayoutChangeIfNeeded(for: layout, isAppend: isAppend) } // MARK: Fades @@ -1654,23 +1664,35 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD // MARK: Accessibility - /// The elements made for the last layout VoiceOver asked about. + /// The elements, made when an assistive technology first asks for them. var accessibilityCache: AccessibilityCache? + /// Brings the elements up to date with the layout on screen, for an + /// element that an assistive technology kept from an earlier request. + func updateAccessibilityElements() { + guard accessibilityCache != nil else { return } + _ = accessibilityElements(for: currentLayout) + } + /// A container: VoiceOver reads its blocks (see `accessibilityElements(for:)`). - public override var isAccessibilityElement: Bool { + nonisolated public override var isAccessibilityElement: Bool { get { false } set {} } - public override var accessibilityElements: [Any]? { - get { accessibilityElements(for: currentLayout) } + /// Any thread: assistive technologies can ask from another one (see `onMainThread`). + nonisolated public override var accessibilityElements: [Any]? { + get { onMainThread { accessibilityElements(for: currentLayout) } } set {} } // MARK: Responder - public override var canBecomeFirstResponder: Bool { isSelectable } + // The responder and hit test overrides below are `nonisolated` for the + // same reason as the `UITextInput` methods: assistive technologies can + // reach them from another thread (see `onMainThread`). + + nonisolated public override var canBecomeFirstResponder: Bool { onMainThread { isSelectable } } private static let didBecomeFirstResponder = Notification.Name("TranscriptTextViewDidBecomeFirstResponder") @@ -1691,12 +1713,14 @@ 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 || (sidePan != nil && currentLayout.sideScrollingEntryIndex(at: point) != nil) + nonisolated public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + onMainThread { + 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 || (sidePan != nil && currentLayout.sideScrollingEntryIndex(at: point) != nil) + } } private func addTextInteractionIfNeeded() { @@ -1708,58 +1732,67 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } /// Read-only: an empty input view keeps the keyboard from appearing. - public override var inputView: UIView? { emptyInputView } + nonisolated public override var inputView: UIView? { onMainThread { 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(_:)): - return !(selection?.isEmpty ?? true) - case #selector(selectAll(_:)): - return currentLayout.length > 0 && selection != 0.. Bool { + // The sender only goes on to `super`, on the main thread. + nonisolated(unsafe) let sender = sender + return onMainThread { + switch action { + case #selector(copy(_:)): + return !(selection?.isEmpty ?? true) + case #selector(selectAll(_:)): + return currentLayout.length > 0 && selection != 0..?) { if range != nil { addTextInteractionIfNeeded() } - inputDelegate?.selectionWillChange(self) + storedInputDelegate?.selectionWillChange(self) selection = range.map { clamp($0.lowerBound).. Int { (position as? TranscriptTextPosition)?.offset ?? 0 } @@ -1772,131 +1805,161 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD min(max(offset, 0), currentLayout.length) } - public var beginningOfDocument: UITextPosition { TranscriptTextPosition(offset: 0) } - public var endOfDocument: UITextPosition { TranscriptTextPosition(offset: currentLayout.length) } + nonisolated public var beginningOfDocument: UITextPosition { onMainThread { TranscriptTextPosition(offset: 0) } } + nonisolated public var endOfDocument: UITextPosition { onMainThread { TranscriptTextPosition(offset: currentLayout.length) } } - public func textRange(from fromPosition: UITextPosition, to toPosition: UITextPosition) -> UITextRange? { - let a = clamp(offset(of: fromPosition)) - let b = clamp(offset(of: toPosition)) - return TranscriptTextRange(range: min(a, b).. UITextRange? { + onMainThread { + let a = clamp(offset(of: fromPosition)) + let b = clamp(offset(of: toPosition)) + return TranscriptTextRange(range: min(a, b).. UITextPosition? { - let target = self.offset(of: position) + offset - guard target >= 0, target <= currentLayout.length else { return nil } - return TranscriptTextPosition(offset: target) + nonisolated public func position(from position: UITextPosition, offset: Int) -> UITextPosition? { + onMainThread { + let target = self.offset(of: position) + offset + guard target >= 0, target <= currentLayout.length else { return nil } + return TranscriptTextPosition(offset: target) + } } - public func position(from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? { - let start = self.offset(of: position) - switch direction { - case .left: return TranscriptTextPosition(offset: clamp(start - offset)) - case .right: return TranscriptTextPosition(offset: clamp(start + offset)) - case .up, .down: - let caret = currentLayout.caretRect(at: start, scroll: sideScroll) - let step = caret.height * CGFloat(offset) * (direction == .up ? -1 : 1) - let target = currentLayout.closestOffset(to: CGPoint(x: caret.midX, y: caret.midY + step), scroll: sideScroll) - return TranscriptTextPosition(offset: target) - @unknown default: return nil + nonisolated public func position(from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? { + onMainThread { + let start = self.offset(of: position) + switch direction { + case .left: return TranscriptTextPosition(offset: clamp(start - offset)) + case .right: return TranscriptTextPosition(offset: clamp(start + offset)) + case .up, .down: + let caret = currentLayout.caretRect(at: start, scroll: sideScroll) + let step = caret.height * CGFloat(offset) * (direction == .up ? -1 : 1) + let target = currentLayout.closestOffset(to: CGPoint(x: caret.midX, y: caret.midY + step), scroll: sideScroll) + return TranscriptTextPosition(offset: target) + @unknown default: return nil + } } } - public func compare(_ position: UITextPosition, to other: UITextPosition) -> ComparisonResult { - let a = offset(of: position) - let b = offset(of: other) + nonisolated public func compare(_ position: UITextPosition, to other: UITextPosition) -> ComparisonResult { + let a = TranscriptTextPosition.offset(of: position) + let b = TranscriptTextPosition.offset(of: other) return a < b ? .orderedAscending : (a > b ? .orderedDescending : .orderedSame) } - public func offset(from: UITextPosition, to toPosition: UITextPosition) -> Int { - offset(of: toPosition) - offset(of: from) + nonisolated public func offset(from: UITextPosition, to toPosition: UITextPosition) -> Int { + TranscriptTextPosition.offset(of: toPosition) - TranscriptTextPosition.offset(of: from) } - public func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? { - let range = self.range(of: range) - switch direction { - case .left, .up: return TranscriptTextPosition(offset: range.lowerBound) - case .right, .down: return TranscriptTextPosition(offset: range.upperBound) - @unknown default: return nil + nonisolated public func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? { + onMainThread { + let range = self.range(of: range) + switch direction { + case .left, .up: return TranscriptTextPosition(offset: range.lowerBound) + case .right, .down: return TranscriptTextPosition(offset: range.upperBound) + @unknown default: return nil + } } } - public func characterRange(byExtending position: UITextPosition, in direction: UITextLayoutDirection) -> UITextRange? { - let start = offset(of: position) - switch direction { - case .left, .up: return TranscriptTextRange(range: clamp(start - 1).. UITextRange? { + onMainThread { + let start = offset(of: position) + switch direction { + case .left, .up: return TranscriptTextRange(range: clamp(start - 1).. String? { - shownDocument.text(in: self.range(of: range)) + nonisolated public func text(in range: UITextRange) -> String? { + onMainThread { shownDocument.text(in: self.range(of: range)) } } - public var selectedTextRange: UITextRange? { - get { selection.map { TranscriptTextRange(range: $0) } } - set { selection = newValue.map { range(of: $0) } } + nonisolated public var selectedTextRange: UITextRange? { + get { onMainThread { selection.map { TranscriptTextRange(range: $0) } } } + set { onMainThread { selection = newValue.map { range(of: $0) } } } + } + + private weak var storedInputDelegate: UITextInputDelegate? + + nonisolated public var inputDelegate: UITextInputDelegate? { + get { onMainThread { storedInputDelegate } } + set { + // Only the main thread uses the delegate once it is stored. + nonisolated(unsafe) let delegate = newValue + onMainThread { storedInputDelegate = delegate } + } } - public weak var inputDelegate: UITextInputDelegate? - public private(set) lazy var tokenizer: UITextInputTokenizer = UITextInputStringTokenizer(textInput: self) + private lazy var storedTokenizer: UITextInputTokenizer = UITextInputStringTokenizer(textInput: self) + + nonisolated public var tokenizer: UITextInputTokenizer { onMainThread { storedTokenizer } } // MARK: UITextInput — geometry - public func caretRect(for position: UITextPosition) -> CGRect { - currentLayout.caretRect(at: clamp(offset(of: position)), scroll: sideScroll) + nonisolated public func caretRect(for position: UITextPosition) -> CGRect { + onMainThread { currentLayout.caretRect(at: clamp(offset(of: position)), scroll: sideScroll) } } - public func firstRect(for range: UITextRange) -> CGRect { - let range = self.range(of: range) - return currentLayout.selectionRects(for: range, scroll: sideScroll).first - ?? currentLayout.caretRect(at: range.lowerBound, scroll: sideScroll) + nonisolated public func firstRect(for range: UITextRange) -> CGRect { + onMainThread { + let range = self.range(of: range) + return currentLayout.selectionRects(for: range, scroll: sideScroll).first + ?? currentLayout.caretRect(at: range.lowerBound, scroll: sideScroll) + } } - public func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { - let rects = currentLayout.selectionRects(for: self.range(of: range), scroll: sideScroll) - return rects.enumerated().map { index, rect in - TranscriptSelectionRect(rect: rect, containsStart: index == 0, containsEnd: index == rects.count - 1) + nonisolated public func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { + onMainThread { + let rects = currentLayout.selectionRects(for: self.range(of: range), scroll: sideScroll) + return rects.enumerated().map { index, rect in + TranscriptSelectionRect(rect: rect, containsStart: index == 0, containsEnd: index == rects.count - 1) + } } } - public func closestPosition(to point: CGPoint) -> UITextPosition? { - TranscriptTextPosition(offset: currentLayout.closestOffset(to: point, scroll: sideScroll)) + nonisolated public func closestPosition(to point: CGPoint) -> UITextPosition? { + onMainThread { TranscriptTextPosition(offset: currentLayout.closestOffset(to: point, scroll: sideScroll)) } } - public func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { - let range = self.range(of: range) - let offset = currentLayout.closestOffset(to: point, scroll: sideScroll) - return TranscriptTextPosition(offset: min(max(offset, range.lowerBound), range.upperBound)) + nonisolated public func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { + onMainThread { + let range = self.range(of: range) + let offset = currentLayout.closestOffset(to: point, scroll: sideScroll) + return TranscriptTextPosition(offset: min(max(offset, range.lowerBound), range.upperBound)) + } } - public func characterRange(at point: CGPoint) -> UITextRange? { - let offset = currentLayout.closestOffset(to: point, scroll: sideScroll) - guard offset < currentLayout.length else { return nil } - return TranscriptTextRange(range: offset..<(offset + 1)) + nonisolated public func characterRange(at point: CGPoint) -> UITextRange? { + onMainThread { + let offset = currentLayout.closestOffset(to: point, scroll: sideScroll) + guard offset < currentLayout.length else { return nil } + return TranscriptTextRange(range: offset..<(offset + 1)) + } } - public func baseWritingDirection(for position: UITextPosition, in direction: UITextStorageDirection) -> NSWritingDirection { + nonisolated public func baseWritingDirection(for position: UITextPosition, in direction: UITextStorageDirection) -> NSWritingDirection { .leftToRight } - public func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {} + nonisolated public func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {} // MARK: UITextInput — editing (unsupported: the view is read-only) - public var hasText: Bool { currentLayout.length > 0 } - public func insertText(_ text: String) {} - public func deleteBackward() {} - public func replace(_ range: UITextRange, withText text: String) {} - public var markedTextRange: UITextRange? { nil } - public var markedTextStyle: [NSAttributedString.Key: Any]? { + nonisolated public var hasText: Bool { onMainThread { currentLayout.length > 0 } } + nonisolated public func insertText(_ text: String) {} + nonisolated public func deleteBackward() {} + nonisolated public func replace(_ range: UITextRange, withText text: String) {} + nonisolated public var markedTextRange: UITextRange? { nil } + nonisolated public var markedTextStyle: [NSAttributedString.Key: Any]? { get { nil } set {} } - public func setMarkedText(_ markedText: String?, selectedRange: NSRange) {} - public func unmarkText() {} + nonisolated public func setMarkedText(_ markedText: String?, selectedRange: NSRange) {} + nonisolated public func unmarkText() {} } // MARK: - Canvas @@ -1947,32 +2010,43 @@ private final class SideScrollFrameTarget: NSObject { // MARK: - Position, range and selection rect types +// These never change once made, so their getters are `nonisolated`: the +// system can read them on any thread. + final class TranscriptTextPosition: UITextPosition { - let offset: Int + nonisolated let offset: Int init(offset: Int) { self.offset = offset super.init() } + + nonisolated static func offset(of position: UITextPosition) -> Int { + (position as? TranscriptTextPosition)?.offset ?? 0 + } } final class TranscriptTextRange: UITextRange { - let range: Range + nonisolated let range: Range + private nonisolated let startPosition: TranscriptTextPosition + private nonisolated let endPosition: TranscriptTextPosition init(range: Range) { self.range = range + startPosition = TranscriptTextPosition(offset: range.lowerBound) + endPosition = TranscriptTextPosition(offset: range.upperBound) super.init() } - override var start: UITextPosition { TranscriptTextPosition(offset: range.lowerBound) } - override var end: UITextPosition { TranscriptTextPosition(offset: range.upperBound) } - override var isEmpty: Bool { range.isEmpty } + nonisolated override var start: UITextPosition { startPosition } + nonisolated override var end: UITextPosition { endPosition } + nonisolated override var isEmpty: Bool { range.isEmpty } } final class TranscriptSelectionRect: UITextSelectionRect { - private let storedRect: CGRect - private let storedContainsStart: Bool - private let storedContainsEnd: Bool + private nonisolated let storedRect: CGRect + private nonisolated let storedContainsStart: Bool + private nonisolated let storedContainsEnd: Bool init(rect: CGRect, containsStart: Bool, containsEnd: Bool) { storedRect = rect @@ -1981,11 +2055,11 @@ final class TranscriptSelectionRect: UITextSelectionRect { super.init() } - override var rect: CGRect { storedRect } - override var writingDirection: NSWritingDirection { .leftToRight } - override var containsStart: Bool { storedContainsStart } - override var containsEnd: Bool { storedContainsEnd } - override var isVertical: Bool { false } + nonisolated override var rect: CGRect { storedRect } + nonisolated override var writingDirection: NSWritingDirection { .leftToRight } + nonisolated override var containsStart: Bool { storedContainsStart } + nonisolated override var containsEnd: Bool { storedContainsEnd } + nonisolated override var isVertical: Bool { false } } /// Watches a scroll view's content size for the text views in it, with one diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift new file mode 100644 index 0000000..538ce24 --- /dev/null +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -0,0 +1,272 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +private let longParagraph = String(repeating: "Words that wrap onto several lines. ", count: 8) + +private func limited(_ limit: Int?) -> TranscriptStyle { + var style = TranscriptStyle() + style.lineLimit = limit + return style +} + +@Test func aBlockCutByALineLimitIsReadWhole() { + let document = MarkdownStreamParser.document(from: longParagraph) + let cut = DocumentLayout(document: document, width: 200, style: limited(2)) + #expect(cut.leavesTextOut) + let items = cut.accessibilityItems() + #expect(items.count == 1) + #expect(items[0].label == document.block(at: 0).text) + #expect(items[0].frame == cut.entry(at: 0).frame) +} + +@Test func blocksLeftOutByALineLimitAreReadWithTheLastOneShown() { + let document = MarkdownStreamParser.document(from: "First.\n\nSecond with a [link](https://example.com).\n\n- [x] Third") + let cut = DocumentLayout(document: document, width: 300, style: limited(1)) + let items = cut.accessibilityItems() + #expect(items.count == 1) + #expect(items[0].label == "First.\nSecond with a link.\nChecked, Third") + #expect(items[0].links.map(\.url.absoluteString) == ["https://example.com"]) +} + +@Test func textWithinTheLineLimitIsReadAsBefore() { + let document = MarkdownStreamParser.document(from: "# Title\n\nBody.") + let items = DocumentLayout(document: document, width: 300, style: limited(5)).accessibilityItems() + #expect(items.map(\.label) == ["Title", "Body."]) + #expect(items.map(\.isHeading) == [true, false]) +} + +@Test func aSelectionToTheEndOfTheShownTextCoversTheRest() { + let document = MarkdownStreamParser.document(from: "First.\n\n" + longParagraph + "\n\nLast.") + let cut = DocumentLayout(document: document, width: 200, style: limited(2)) + #expect(cut.length < document.utf16Count) + let all = cut.documentRange(forSelection: 0.. [AccessibilityItem] { + DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width).accessibilityItems() +} + +@Test func listItemsTellTheirPositionAndTheItemCount() { + let list = items("- One\n- Two\n more of two\n\n A second paragraph\n- Three") + #expect(list.map(\.label) == ["One", "Two more of two", "A second paragraph", "Three"]) + #expect(list.map(\.value) == ["Item 1 of 3", "Item 2 of 3", nil, "Item 3 of 3"]) +} + +@Test func nestedListsAndSeparateListsCountOnTheirOwn() { + let list = items("1. One\n - Inner a\n - Inner b\n2. Two\n\nText.\n\n- [ ] Task\n- Bullet\n\n3) Other") + #expect(list.map(\.value) == ["Item 1 of 2", "Item 1 of 2", "Item 2 of 2", "Item 2 of 2", nil, "Item 1 of 2", "Item 2 of 2", + "Item 1 of 1"]) +} + +@Test func numbersWithAnotherDelimiterStartANewList() { + let list = items("1. One\n2. Two\n1) Other") + #expect(list.map(\.value) == ["Item 1 of 2", "Item 2 of 2", "Item 1 of 1"]) +} + +@Test func theItemCountTakesInItemsThatALineLimitLeavesOut() { + var style = TranscriptStyle() + style.lineLimit = 1 + let document = MarkdownStreamParser.document(from: "- One\n- Two\n- Three") + let list = DocumentLayout(document: document, width: 300, style: style).accessibilityItems() + #expect(list.map(\.value) == ["Item 1 of 3"]) +} + +@Test func aTableHasOneItemForEachCell() throws { + let list = items("Before.\n\n| Name | Value |\n| --- | ---: |\n| a | [one](https://example.com/1) |\n| b | \\(x^2\\) |") + #expect(list.count == 2) + let table = try #require(list[1].table) + #expect(table.rowCount == 3) + #expect(table.columnCount == 2) + #expect(table.cells.map(\.label) == ["Name", "Value", "a", "one", "b", "x^2"]) + #expect(table.cells.map(\.row) == [0, 0, 1, 1, 2, 2]) + #expect(table.cells.map(\.column) == [0, 1, 0, 1, 0, 1]) + #expect(table.cells[3].links.map(\.url.absoluteString) == ["https://example.com/1"]) + // Cells sit side by side in their rows, inside the table's frame. + #expect(table.cells[0].frame.maxX <= table.cells[1].frame.minX + 0.5) + #expect(table.cells[0].frame.maxY <= table.cells[2].frame.minY + 0.5) + #expect(table.cells.allSatisfy { list[1].frame.insetBy(dx: -0.5, dy: -0.5).contains($0.frame) }) +} + +@Test func aTableThatStreamsInChangesTheShapeWithEachCell() { + var parser = MarkdownStreamParser() + parser.append("| A | B |\n| - | - |\n| 1 |") + let before = DocumentLayout(document: parser.document, width: 300) + parser.append(" 2 |") + let after = DocumentLayout(document: parser.document, width: 300, reusing: before) + #expect(!before.accessibilityGeometry.hasSameElements(as: after.accessibilityGeometry)) + #expect(after.accessibilityItems().first?.table?.cells.count == 4) +} + +@Test func textLeftOutAfterATableGetsAnItemOfItsOwn() { + var style = TranscriptStyle() + style.lineLimit = 3 + let document = MarkdownStreamParser.document(from: "| A | B |\n| - | - |\n| 1 | 2 |\n\nAfter the table.") + let list = DocumentLayout(document: document, width: 300, style: style).accessibilityItems() + #expect(list.count == 2) + #expect(list[0].table != nil) + #expect(list[1].label == "After the table.") +} + +@Test func formulasAreReadWithTheWordsTheAppGives() { + let document = MarkdownStreamParser.document(from: "Area: \\(\\pi r^2\\).") + let layout = DocumentLayout(document: document, width: 300) + #expect(layout.accessibilityItems().map(\.label) == ["Area: \\pi r^2."]) + let spoken = layout.accessibilityItems { $0.tex == "\\pi r^2" ? "pi r squared" : $0.tex } + #expect(spoken.map(\.label) == ["Area: pi r squared."]) +} + +private func isNeeded(from old: DocumentLayout, to new: DocumentLayout, isAppend: Bool) -> Bool { + var watch = AccessibilityLayoutWatch() + watch.start(with: old) + return watch.install(new, isAppend: isAppend) +} + +@Test func aLayoutChangeIsPostedOnlyWhenElementsChange() { + var parser = MarkdownStreamParser() + parser.append("# Title\n\nFirst words") + let before = DocumentLayout(document: parser.document, width: 300) + // The same text laid out again, as after new colors for code: nothing to tell. + #expect(!isNeeded(from: before, to: DocumentLayout(document: parser.document, width: 300), isAppend: false)) + // Another width moves the elements. + #expect(isNeeded(from: before, to: DocumentLayout(document: parser.document, width: 200), isAppend: false)) + parser.append(" and more") + let longer = DocumentLayout(document: parser.document, width: 300, reusing: before) + #expect(!isNeeded(from: before, to: longer, isAppend: true)) + parser.append("\n\nA new paragraph") + let added = DocumentLayout(document: parser.document, width: 300, reusing: longer) + #expect(isNeeded(from: longer, to: added, isAppend: true)) +} + +@Test func textThatStreamsInAfterATableUnderALineLimitChangesTheShape() { + var style = TranscriptStyle() + style.lineLimit = 3 + var parser = MarkdownStreamParser() + parser.append("| A | B |\n| - | - |\n| 1 | 2 |\n\n") + let before = DocumentLayout(document: parser.document, width: 300, style: style) + parser.append("After") + let after = DocumentLayout(document: parser.document, width: 300, style: style) + #expect(before.accessibilityItems().count == 1) + #expect(after.accessibilityItems().count == 2) + #expect(isNeeded(from: before, to: after, isAppend: true)) +} + +@Test func aTableThatStartsAListItemTellsTheMarkerAndThePosition() throws { + let list = items("1. First\n2. | A | B |\n | - | - |\n | 1 | 2 |\n3. Third") + #expect(list.count == 3) + let table = try #require(list[1].table) + #expect(table.cells.map(\.label) == ["2. A", "B", "1", "2"]) + #expect(table.cells.map(\.value) == ["Item 2 of 3", nil, nil, nil]) +} + +@Test func blocksWhoseLayoutDidNotChangeKeepTheirWords() { + var parser = MarkdownStreamParser() + parser.append("Area: \\(\\pi r^2\\).\n\n| A | B |\n| - | - |\n| \\(x\\) | [y](https://example.com) |\n\nFirst words") + let before = DocumentLayout(document: parser.document, width: 300) + parser.append(" and more") + let longer = DocumentLayout(document: parser.document, width: 300, reusing: before) + var calls = 0 + let words = AccessibilityWords() + let math = { (formula: TranscriptMath) -> String in + calls += 1 + return formula.tex + } + let first = before.accessibilityItems(math: math, words: words) + let callsBefore = calls + #expect(callsBefore >= 2) + let second = longer.accessibilityItems(math: math, words: words) + #expect(calls == callsBefore) + #expect(second.map(\.label) == ["Area: \\pi r^2.", "", "First words and more"]) + #expect(second[1] == first[1]) + #expect(second[1].table?.cells.map(\.label) == ["A", "B", "x", "y"]) + #expect(second[1].table?.cells[3].links.map(\.url.absoluteString) == ["https://example.com"]) +} + +@Test func newLinkDefinitionsMakeTheWordsAgain() { + let words = AccessibilityWords() + var parser = MarkdownStreamParser() + parser.append("See [docs][d].\n\nMore") + let before = DocumentLayout(document: parser.document, width: 300) + #expect(before.accessibilityItems(words: words)[0].links.isEmpty) + parser.append(" text\n\n[d]: https://example.com/docs\n") + let after = DocumentLayout(document: parser.document, width: 300, reusing: before) + #expect(after.accessibilityItems(words: words)[0].links.map(\.url.absoluteString) == ["https://example.com/docs"]) +} + +@Test func newColorsAfterTextStreamedInPostNothing() { + var parser = MarkdownStreamParser() + parser.append("Intro.\n\n```swift\nlet a = 1") + var layout = DocumentLayout(document: parser.document, width: 300) + var watch = AccessibilityLayoutWatch() + watch.start(with: layout) + var posts = 0 + for line in ["\nlet b = 2", "\nlet c = 3", "\nlet d = 4"] { + parser.append(line) + layout = DocumentLayout(document: parser.document, width: 300, reusing: layout) + if watch.install(layout, isAppend: true) { posts += 1 } + } + #expect(posts == 0) + // The same text laid out again, as after the code's colors arrive. + if watch.install(DocumentLayout(document: parser.document, width: 300), isAppend: false) { posts += 1 } + #expect(posts == 0) + // A new width moves the elements. + let moved = watch.install(DocumentLayout(document: parser.document, width: 200), isAppend: false) + #expect(moved) +} diff --git a/Tests/TranscriptKitTests/OffMainThreadTests.swift b/Tests/TranscriptKitTests/OffMainThreadTests.swift new file mode 100644 index 0000000..41c21b8 --- /dev/null +++ b/Tests/TranscriptKitTests/OffMainThreadTests.swift @@ -0,0 +1,206 @@ +#if canImport(UIKit) && !os(watchOS) +import Foundation +import Testing +import UIKit +@testable import TranscriptKit + +// Assistive technologies can call accessibility getters and `UITextInput` +// methods from a background thread, through the Objective-C runtime. In +// the Swift 6 language mode, a main actor method called that way stops the +// process. These tests make such calls; the main actor stays free meanwhile. + +private struct Unchecked: @unchecked Sendable { + let value: Value +} + +/// Runs `body` on a background thread and returns its result. +@MainActor +private func offMain(_ body: @escaping @Sendable () -> Result) async -> Result { + let result = await withCheckedContinuation { (continuation: CheckedContinuation, Never>) in + Thread { continuation.resume(returning: Unchecked(value: body())) }.start() + } + return result.value +} + +@MainActor +private func object(_ target: NSObject, _ name: String, _ argument: Any? = nil) async -> AnyObject? { + let target = Unchecked(value: target) + let argument = Unchecked(value: argument) + return await offMain { + target.value.perform(NSSelectorFromString(name), with: argument.value)?.takeUnretainedValue() + } +} + +/// Calls a method that takes one object and returns nothing. +@MainActor +private func call(_ target: NSObject, _ name: String, _ argument: Any?) async { + let call = Unchecked(value: (target, argument)) + await offMain { + typealias Method = @convention(c) (NSObject, Selector, Any?) -> Void + let selector = NSSelectorFromString(name) + let (target, argument) = call.value + unsafeBitCast(target.method(for: selector), to: Method.self)(target, selector, argument) + } +} + +@MainActor +private func integer(_ target: NSObject, _ name: String) async -> Int { + let target = Unchecked(value: target) + return await offMain { + typealias Getter = @convention(c) (NSObject, Selector) -> Int + let selector = NSSelectorFromString(name) + return unsafeBitCast(target.value.method(for: selector), to: Getter.self)(target.value, selector) + } +} + +@MainActor +private func bool(_ target: NSObject, _ name: String) async -> Bool { + let target = Unchecked(value: target) + return await offMain { + typealias Getter = @convention(c) (NSObject, Selector) -> Bool + let selector = NSSelectorFromString(name) + return unsafeBitCast(target.value.method(for: selector), to: Getter.self)(target.value, selector) + } +} + +@MainActor +private func rect(_ target: NSObject, _ name: String, _ argument: NSObject? = nil) async -> CGRect { + let target = Unchecked(value: target) + let argument = Unchecked(value: argument) + return await offMain { + let selector = NSSelectorFromString(name) + if let argument = argument.value { + typealias Method = @convention(c) (NSObject, Selector, NSObject) -> CGRect + return unsafeBitCast(target.value.method(for: selector), to: Method.self)(target.value, selector, argument) + } + typealias Getter = @convention(c) (NSObject, Selector) -> CGRect + return unsafeBitCast(target.value.method(for: selector), to: Getter.self)(target.value, selector) + } +} + +@MainActor +private func viewWithText() -> TranscriptTextView { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 600)) + view.document = MarkdownStreamParser.document(from: """ + # Title + + Some text with a [link](https://example.com). + + - One + - Two + + | A | B | + | - | - | + | 1 | 2 | + """) + view.layoutIfNeeded() + return view +} + +@MainActor +@Test func accessibilityGettersWorkOffTheMainThread() async throws { + let view = viewWithText() + #expect(await !bool(view, "isAccessibilityElement")) + let elements = try #require(await object(view, "accessibilityElements") as? [NSObject]) + #expect(elements.count == 5) + #expect(await object(elements[0], "accessibilityLabel") as? String == "Title") + #expect(await integer(elements[0], "accessibilityTraits") & Int(UIAccessibilityTraits.header.rawValue) != 0) + #expect(await object(elements[3], "accessibilityValue") as? String == "Item 2 of 2") + let actions = await object(elements[1], "accessibilityCustomActions") as? [UIAccessibilityCustomAction] + #expect(actions?.count == 1) + _ = await rect(elements[0], "accessibilityFrame") + + let table = elements[4] + #expect(await !bool(table, "isAccessibilityElement")) + #expect(await integer(table, "accessibilityContainerType") == UIAccessibilityContainerType.dataTable.rawValue) + #expect(await integer(table, "accessibilityRowCount") == 2) + #expect(await integer(table, "accessibilityColumnCount") == 2) + let cells = try #require(await object(table, "accessibilityElements") as? [NSObject]) + #expect(cells.count == 4) + #expect(await object(cells[3], "accessibilityLabel") as? String == "2") + _ = await rect(cells[3], "accessibilityFrame") + let header = await object(table, "accessibilityHeaderElementsForColumn:", NSNumber(value: 1)) + _ = header + let rowRange = await offMain { [cell = Unchecked(value: cells[3])] in + typealias Getter = @convention(c) (NSObject, Selector) -> NSRange + let selector = NSSelectorFromString("accessibilityRowRange") + return unsafeBitCast(cell.value.method(for: selector), to: Getter.self)(cell.value, selector) + } + #expect(rowRange == NSRange(location: 1, length: 1)) +} + +@MainActor +@Test func textInputWorksOffTheMainThread() async throws { + let view = viewWithText() + let start = try #require(await object(view, "beginningOfDocument") as? UITextPosition) + let end = try #require(await object(view, "endOfDocument") as? TranscriptTextPosition) + #expect(end.offset > 0) + let all = view.textRange(from: start, to: end)! + #expect((await object(view, "textInRange:", all) as? String)?.hasPrefix("Title") == true) + #expect(await rect(view, "caretRectForPosition:", start).height > 0) + #expect(await rect(view, "firstRectForRange:", all).height > 0) + let rects = try #require(await object(view, "selectionRectsForRange:", all) as? [UITextSelectionRect]) + #expect(!rects.isEmpty) + #expect(await rect(rects[0], "rect").height > 0) + #expect((await object(all, "start") as? TranscriptTextPosition)?.offset == 0) + #expect(await bool(view, "hasText")) + #expect(await object(view, "selectedTextRange") == nil) + _ = await object(view, "setSelectedTextRange:", all) + #expect(view.selectedRange == (all as? TranscriptTextRange)?.range) + let tokenizer = try #require(await object(view, "tokenizer") as? UITextInputTokenizer) + let word = await offMain { [tokenizer = Unchecked(value: tokenizer as! NSObject), start = Unchecked(value: start)] in + typealias Enclose = @convention(c) (NSObject, Selector, UITextPosition, Int, Int) -> UITextRange? + let selector = NSSelectorFromString("rangeEnclosingPosition:withGranularity:inDirection:") + return unsafeBitCast(tokenizer.value.method(for: selector), to: Enclose.self)( + tokenizer.value, selector, start.value, UITextGranularity.word.rawValue, UITextStorageDirection.forward.rawValue) + } + #expect((word as? TranscriptTextRange)?.range == 0..<5) +} +@MainActor +@Test func settersActionsAndHitTestsWorkOffTheMainThread() async throws { + let view = viewWithText() + var opened: [URL] = [] + view.openLink = { opened.append($0) } + let elements = try #require(await object(view, "accessibilityElements") as? [NSObject]) + let action = try #require((await object(elements[1], "accessibilityCustomActions") as? [UIAccessibilityCustomAction])?.first) + let handler = try #require(action.actionHandler) + let handled = await offMain { [handler = Unchecked(value: handler), action = Unchecked(value: action)] in + handler.value(action.value) + } + #expect(handled) + #expect(opened.map(\.absoluteString) == ["https://example.com"]) + + let delegate = Delegate() + await call(view, "setInputDelegate:", delegate) + #expect(await object(view, "inputDelegate") === delegate) + await call(view, "setInputDelegate:", nil) + if #available(iOS 18.0, macCatalyst 18.0, *) { + _ = await offMain { [view = Unchecked(value: view)] in view.value.writingToolsBehavior = .none } + let behavior = await offMain { [view = Unchecked(value: view)] in view.value.writingToolsBehavior } + #expect(behavior == .none) + #expect(!view.showsWritingTools) + } + + #expect(await bool(view, "canBecomeFirstResponder")) + #expect(await object(view, "inputView") != nil) + let inside = await offMain { [view = Unchecked(value: view)] in view.value.point(inside: CGPoint(x: 10, y: 10), with: nil) } + #expect(inside) + await call(view, "selectAll:", nil) + #expect(view.selectedRange?.lowerBound == 0) + let copy = await offMain { [view = Unchecked(value: view)] in + view.value.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil) + } + #expect(copy) +} + +private final class Delegate: NSObject, UITextInputDelegate { + func selectionWillChange(_ textInput: (any UITextInput)?) {} + func selectionDidChange(_ textInput: (any UITextInput)?) {} + func textWillChange(_ textInput: (any UITextInput)?) {} + func textDidChange(_ textInput: (any UITextInput)?) {} + #if !targetEnvironment(macCatalyst) + @available(iOS 18.4, *) + func conversationContext(_ context: UIConversationContext?, didChange textInput: (any UITextInput)?) {} + #endif +} +#endif diff --git a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift new file mode 100644 index 0000000..f4a4ccb --- /dev/null +++ b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift @@ -0,0 +1,131 @@ +#if canImport(UIKit) && !os(watchOS) +import Foundation +import Testing +import UIKit +@testable import TranscriptKit + +/// Lets the main actor run until `condition` holds, for at most two seconds. +@MainActor +private func wait(until condition: () -> Bool) async { + let deadline = Date(timeIntervalSinceNow: 2) + while !condition(), Date() < deadline { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +@MainActor +private func elements(of view: TranscriptTextView) -> [UIAccessibilityElement] { + (view.accessibilityElements as? [UIAccessibilityElement]) ?? [] +} + +@MainActor +@Test func elementsStayTheSameObjectsWhileTextStreams() async { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + let parser = { (markdown: String) in MarkdownStreamParser.document(from: markdown, idPrefix: "t") } + view.document = parser("# Title\n\nFirst words") + view.layoutIfNeeded() + let before = elements(of: view) + #expect(before.map(\.accessibilityLabel) == ["Title", "First words"]) + + view.document = parser("# Title\n\nFirst words and more") + await wait { elements(of: view).last?.accessibilityLabel == "First words and more" } + let longer = elements(of: view) + #expect(longer.count == 2) + #expect(zip(before, longer).allSatisfy { $0 === $1 }) + + view.document = parser("# Title\n\nFirst words and more\n\nNew block") + await wait { elements(of: view).count == 3 } + let added = elements(of: view) + #expect(added.count == 3) + #expect(added[0] === before[0] && added[1] === before[1]) + + view.frame.size.width = 200 + view.layoutIfNeeded() + let narrower = elements(of: view) + #expect(zip(added, narrower).allSatisfy { $0 === $1 }) + #expect((narrower[1] as? TextAccessibilityElement)?.frameInView.width == 200) +} + +@MainActor +@Test func anElementThatAClientHoldsShowsTheNewText() async { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + let parser = { (markdown: String) in MarkdownStreamParser.document(from: markdown, idPrefix: "t") } + view.document = parser("# Title\n\nFirst words") + view.layoutIfNeeded() + let held = elements(of: view)[1] + let length = (view.endOfDocument as? TranscriptTextPosition)?.offset ?? 0 + view.document = parser("# Title\n\nFirst words and more") + // Waits for the new layout without asking the view for its elements. + await wait { ((view.endOfDocument as? TranscriptTextPosition)?.offset ?? 0) > length } + #expect(held.accessibilityLabel == "First words and more") +} + +@MainActor +@Test func aTableIsADataTableOfCells() throws { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + view.document = MarkdownStreamParser.document(from: "- One\n- Two\n\n| A | B |\n| - | - |\n| 1 | 2 |") + view.layoutIfNeeded() + let all = elements(of: view) + #expect(all.count == 3) + #expect(all[1].accessibilityValue == "Item 2 of 2") + let table = try #require(all[2] as? UIAccessibilityContainerDataTable & UIAccessibilityElement) + #expect(table.accessibilityContainerType == .dataTable) + #expect(table.accessibilityRowCount() == 2) + #expect(table.accessibilityColumnCount() == 2) + let cell = try #require(table.accessibilityDataTableCellElement(forRow: 1, column: 1) as? UIAccessibilityElement) + #expect(cell.accessibilityLabel == "2") + #expect(cell.accessibilityContainer as AnyObject === table) + #expect((table.accessibilityElements ?? []).count == 4) + let header = table.accessibilityHeaderElements?(forColumn: 1)?.first as? UIAccessibilityElement + #expect(header?.accessibilityLabel == "B") +} + +@MainActor +@Test func formulasUseTheLabelTheAppSets() { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + view.document = MarkdownStreamParser.document(from: "Area: \\(\\pi r^2\\).") + view.layoutIfNeeded() + #expect(elements(of: view).first?.accessibilityLabel == "Area: \\pi r^2.") + view.mathAccessibilityLabel = { _ in "pi r squared" } + #expect(elements(of: view).first?.accessibilityLabel == "Area: pi r squared.") +} +@MainActor +@Test func selectAllUnderALineLimitCopiesAllOfTheText() async { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 200, height: 400)) + var parser = MarkdownStreamParser() + parser.append(String(repeating: "Words that wrap onto several lines. ", count: 6) + "\n\n## Later heading\n\nLast") + view.document = parser.document + var style = view.style + style.lineLimit = 2 + view.style = style + view.layoutIfNeeded() + var reported: [Range?] = [] + view.onSelectionChange = { reported.append($0) } + view.selectAll(nil) + let shown = (view.endOfDocument as? TranscriptTextPosition)?.offset ?? 0 + #expect(shown < parser.document.utf16Count) + #expect(view.selectedRange == 0..