From 70d64fa3281f87354a8adf29bbb930e6903a637f Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:15:21 -0800 Subject: [PATCH 01/14] Read and copy all of the text under a line limit Under a line limit, VoiceOver now reads the whole text of the block that the limit cuts. The last element also reads the blocks that the limit leaves out, as a label that is cut short does. A selection that reaches the end of the text shown now also covers the text that the limit leaves out. Select All followed by Copy copies all of the text. The selection highlight still covers only the text shown. selectedRange and selectedText give the same range that Copy uses. The accessibility text now comes from a model without UIKit, so that the tests on macOS cover it. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- .../Layout/AccessibilityContent.swift | 107 ++++++++++++++++++ .../TranscriptKit/Layout/DocumentLayout.swift | 12 ++ .../Layout/TranscriptStyle.swift | 6 +- .../TranscriptTextView+Accessibility.swift | 59 ++-------- .../iOS/TranscriptTextView.swift | 15 +-- .../AccessibilityTests.swift | 64 +++++++++++ 7 files changed, 207 insertions(+), 60 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/AccessibilityContent.swift create mode 100644 Tests/TranscriptKitTests/AccessibilityTests.swift diff --git a/README.md b/README.md index 15e4433..62bcfd4 100644 --- a/README.md +++ b/README.md @@ -280,7 +280,9 @@ number or "Checked" or "Unchecked", and each link in a block is an action that o ### 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..08b93d5 --- /dev/null +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -0,0 +1,107 @@ +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 + } + + let frame: CGRect + /// What VoiceOver says: the list marker, then the text. + let label: String + let isHeading: Bool + /// The links in the text. Each is an action that opens it. + let links: [Link] +} + +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. + func accessibilityItems() -> [AccessibilityItem] { + var items: [AccessibilityItem] = [] + let definitions = document.linkDefinitions + for index in 0..) -> String { + let text = NSMutableString(string: (block.text as NSString).substring(with: NSRange(location: range.lowerBound, + length: range.count))) + for span in block.spans.reversed() where range.contains(span.range.lowerBound) && span.range.count == 1 { + guard let replacement = span.image?.alt ?? span.math?.tex else { continue } + text.replaceCharacters(in: NSRange(location: span.range.lowerBound - range.lowerBound, length: 1), with: replacement) + } + return text as String + } + + /// What VoiceOver says for a block: its list marker, then its text. + static func spoken(_ 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") + } + return text + } + } + + /// The links that start in `range` of the block's text. + static func links(of block: TranscriptBlock, in range: Range, definitions: [String: String]) -> [AccessibilityItem.Link] { + var links: [AccessibilityItem.Link] = [] + for span in block.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.. 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.. [UIAccessibilityElement] { if let cached = accessibilityCache, cached.layout === layout { return cached.elements } var elements: [UIAccessibilityElement] = [] - let definitions = layout.document.linkDefinitions - for index in 0.. 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") - } - return text - } - } } final class AccessibilityCache { diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index fdb641f..a6b3741 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -233,10 +233,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 @@ -1292,8 +1294,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } public override func copy(_ sender: Any?) { - guard let selection, !selection.isEmpty else { return } - UIPasteboard.general.string = shownDocument.copyText(in: selection) + guard let range = selectedRange else { return } + UIPasteboard.general.string = shownDocument.copyText(in: range) } public override func selectAll(_ sender: Any?) { @@ -1310,10 +1312,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD refreshSelectionDisplay() } - /// The currently selected text, if any. + /// The currently selected text, if any: the text of `selectedRange`. public var selectedText: String? { - guard let selection, !selection.isEmpty else { return nil } - return shownDocument.text(in: selection) + selectedRange.map { shownDocument.text(in: $0) } } // MARK: UITextInput — positions and ranges diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift new file mode 100644 index 0000000..ab4b684 --- /dev/null +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -0,0 +1,64 @@ +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.. Date: Mon, 23 Nov 2026 17:18:32 -0800 Subject: [PATCH 02/14] Keep one accessibility element per block while text streams Each block now keeps its accessibility element from one layout to the next, by its block id. A new layout updates the label, frame, traits and link actions of the element in place. VoiceOver focus thus stays on its block while text streams in. The view posts a layout-changed notification only after an assistive technology asked for the elements, and only when elements come or go, or when the layout is not an append. Text that streams into the last block posts nothing. Co-Authored-By: Claude Opus 5.5 --- .../Layout/AccessibilityContent.swift | 27 ++++++- .../TranscriptTextView+Accessibility.swift | 79 +++++++++++++------ .../iOS/TranscriptTextView.swift | 3 +- .../AccessibilityTests.swift | 36 +++++++++ .../TextViewAccessibilityTests.swift | 48 +++++++++++ 5 files changed, 166 insertions(+), 27 deletions(-) create mode 100644 Tests/TranscriptKitTests/TextViewAccessibilityTests.swift diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index 08b93d5..89a73b8 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -9,6 +9,10 @@ struct AccessibilityItem: Equatable { let url: URL } + /// The block's id, made 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: String let frame: CGRect /// What VoiceOver says: the list marker, then the text. let label: String @@ -26,13 +30,17 @@ extension DocumentLayout { func accessibilityItems() -> [AccessibilityItem] { var items: [AccessibilityItem] = [] let definitions = document.linkDefinitions + var uses: [String: Int] = [:] for index in 0.. 0 else { return AccessibilityShape(entries: 0, lastHasNoItem: false) } + let block = entry(at: entryCount - 1).layout.block + return AccessibilityShape(entries: entryCount, lastHasNoItem: block.text.isEmpty && block.kind != .rule) + } +} + +struct AccessibilityShape: Equatable { + let entries: Int + /// The last block has no text yet, so it has no item. + let lastHasNoItem: Bool } /// The words that assistive technologies get for a block. diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 71fcb72..334076e 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -4,40 +4,71 @@ 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. 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: [String: BlockAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] for item in layout.accessibilityItems() { - let element = UIAccessibilityElement(accessibilityContainer: self) - element.accessibilityLabel = item.label - element.accessibilityFrameInContainerSpace = item.frame - var traits: UIAccessibilityTraits = .staticText - if item.isHeading { traits.insert(.header) } - let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") - let actions = item.links.map { link in - UIAccessibilityCustomAction(name: String(format: format, link.title)) { [weak self] _ in - self?.openLink(link.url) - return true - } - } - if !actions.isEmpty { traits.insert(.link) } - element.accessibilityTraits = traits - element.accessibilityCustomActions = actions + let element = cache.byKey[item.key] ?? BlockAccessibilityElement(accessibilityContainer: self) + element.update(with: item) { [weak self] url in self?.openLink(url) } + byKey[item.key] = element elements.append(element) } - accessibilityCache = AccessibilityCache(layout: layout, elements: elements) + cache.layout = layout + cache.shape = layout.accessibilityShape + cache.byKey = byKey + cache.elements = elements return elements } + + /// Tells assistive technologies that elements came or went, or moved, + /// after `layout` was installed. Elements keep their identity, so VoiceOver + /// focus stays on its block. Nothing is posted before an assistive + /// technology has asked for the elements, or when an update only adds + /// text to the last block. + func postAccessibilityLayoutChangeIfNeeded(for layout: DocumentLayout, isAppend: Bool) { + guard let cache = accessibilityCache, cache.layout != nil, window != nil else { return } + let shape = layout.accessibilityShape + guard !isAppend || shape != cache.shape else { return } + cache.shape = shape + UIAccessibility.post(notification: .layoutChanged, argument: nil) + } } -final class AccessibilityCache { - let layout: DocumentLayout - let elements: [UIAccessibilityElement] +/// A block's element. Its block's id keeps it from one layout to the next. +final class BlockAccessibilityElement: UIAccessibilityElement { + private var links: [AccessibilityItem.Link]? - init(layout: DocumentLayout, elements: [UIAccessibilityElement]) { - self.layout = layout - self.elements = elements + func update(with item: AccessibilityItem, openLink: @escaping (URL) -> Void) { + if accessibilityLabel != item.label { accessibilityLabel = item.label } + if accessibilityFrameInContainerSpace != item.frame { accessibilityFrameInContainerSpace = item.frame } + var traits: UIAccessibilityTraits = .staticText + if item.isHeading { traits.insert(.header) } + if !item.links.isEmpty { traits.insert(.link) } + if accessibilityTraits != traits { accessibilityTraits = traits } + guard links != item.links else { return } + links = item.links + let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") + accessibilityCustomActions = item.links.map { link in + UIAccessibilityCustomAction(name: String(format: format, link.title)) { _ in + openLink(link.url) + return true + } + } } } + +final class AccessibilityCache { + /// The layout that the elements were last brought up to date for. + var layout: DocumentLayout? + /// The shape of the layout that assistive technologies last heard about. + var shape: AccessibilityShape? + var byKey: [String: BlockAccessibilityElement] = [:] + var elements: [UIAccessibilityElement] = [] +} #endif diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index a6b3741..4613412 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -866,6 +866,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD inputDelegate?.textDidChange(self) refreshSelectionDisplay() } + postAccessibilityLayoutChangeIfNeeded(for: layout, isAppend: isAppend) } // MARK: Fades @@ -1214,7 +1215,7 @@ 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? /// A container: VoiceOver reads its blocks (see `accessibilityElements(for:)`). diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index ab4b684..d326109 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -62,3 +62,39 @@ private func limited(_ limit: Int?) -> TranscriptStyle { let block = MarkdownStreamParser.document(from: "See ![a cat](cat.png) and \\(x^2\\).").block(at: 0) #expect(AccessibilityText.readable(block, in: 0.. 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].accessibilityFrameInContainerSpace.width == 200) +} +#endif From 07a2ca8184696bb3b912a7a35341de545f8c95af Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:22:18 -0800 Subject: [PATCH 03/14] Tell list positions, read tables by cell, and let the app name formulas The first block of a list item now gives its position in its list and the number of items as its accessibility value, such as "Item 2 of 3". A list ends at a block outside its containers, or at an item with another kind of marker. The count includes items that a line limit leaves out. A table is now a data table container with one element for each cell. VoiceOver reads the row, the column and the column header. A link in a cell is an action of that cell. The new mathAccessibilityLabel closure on TranscriptTextView, and the mathAccessibilityLabel modifier on TranscriptText, give the words for a formula. Without them, VoiceOver reads the LaTeX, as before. The new string "Item %1$ld of %2$ld" comes from the app's Localizable.strings, as the other spoken strings do. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 ++- .../Layout/AccessibilityContent.swift | 178 +++++++++++++++--- .../TranscriptKit/iOS/TranscriptText.swift | 11 ++ .../TranscriptTextView+Accessibility.swift | 146 ++++++++++++-- .../iOS/TranscriptTextView.swift | 7 + .../AccessibilityTests.swift | 73 +++++++ .../TextViewAccessibilityTests.swift | 30 +++ 7 files changed, 421 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 62bcfd4..e3a3731 100644 --- a/README.md +++ b/README.md @@ -253,8 +253,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`. ### Selection @@ -274,8 +283,13 @@ 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. While text streams in, each +block keeps its element, so VoiceOver focus stays on its block. + +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 diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index 89a73b8..7d536cd 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -9,16 +9,36 @@ struct AccessibilityItem: Equatable { 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 + let links: [Link] + } + + let rowCount: Int + let columnCount: Int + /// Row by row; the first row is the header. + let cells: [Cell] + } + /// The block's id, made 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: String let frame: CGRect - /// What VoiceOver says: the list marker, then the text. + /// What VoiceOver says: the list marker, then the text. Empty for a table. 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 { @@ -26,46 +46,90 @@ extension DocumentLayout { /// /// 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. - func accessibilityItems() -> [AccessibilityItem] { + /// 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. + func accessibilityItems(math: (TranscriptMath) -> String = \.tex) -> [AccessibilityItem] { var items: [AccessibilityItem] = [] let definitions = document.linkDefinitions + let positions = AccessibilityText.listPositions(in: document, upTo: entryCount) var uses: [String: Int] = [:] + func key(for block: TranscriptBlock) -> String { + let use = uses[block.id, default: 0] + uses[block.id] = use + 1 + return use == 0 ? block.id : "\(block.id)#\(use)" + } for index in 0.. String, + definitions: [String: String]) -> AccessibilityItem.Table { + var cells: [AccessibilityItem.Table.Cell] = [] + let rowCount = min(model.rows.count, grid.rowY.count - 1) + let columnCount = min(model.columnCount, grid.columnX.count - 1) + for row in 0.. 0 else { return AccessibilityShape(entries: 0, lastHasNoItem: false) } + guard entryCount > 0 else { return AccessibilityShape(entries: 0, lastHasNoItem: false, lastTableCells: 0) } let block = entry(at: entryCount - 1).layout.block - return AccessibilityShape(entries: entryCount, lastHasNoItem: block.text.isEmpty && block.kind != .rule) + return AccessibilityShape(entries: entryCount, lastHasNoItem: block.text.isEmpty && block.kind != .rule, + lastTableCells: block.kind.table?.rows.reduce(0) { $0 + $1.count } ?? 0) } } @@ -73,18 +137,21 @@ struct AccessibilityShape: Equatable { let entries: Int /// The last block has no text yet, so it has no item. let lastHasNoItem: Bool + /// The number of cells in the last block, if it is a table: a row that + /// streams in adds elements. + let lastTableCells: Int } /// 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 their LaTeX, in place of the U+FFFC character each + /// formulas as `math` gives them, in place of the U+FFFC character each /// stands for. - static func readable(_ block: TranscriptBlock, in range: Range) -> String { + static func readable(_ block: TranscriptBlock, in range: Range, math: (TranscriptMath) -> String = \.tex) -> String { let text = NSMutableString(string: (block.text as NSString).substring(with: NSRange(location: range.lowerBound, length: range.count))) for span in block.spans.reversed() where range.contains(span.range.lowerBound) && span.range.count == 1 { - guard let replacement = span.image?.alt ?? span.math?.tex else { continue } + 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 @@ -108,18 +175,83 @@ enum AccessibilityText { } } + /// 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, definitions: [String: String]) -> [AccessibilityItem.Link] { + static func links(of block: TranscriptBlock, in range: Range, math: (TranscriptMath) -> String = \.tex, + definitions: [String: String]) -> [AccessibilityItem.Link] { var links: [AccessibilityItem.Link] = [] for span in block.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.. [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 { diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 1a8d959..37dc4d8 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -21,6 +21,7 @@ public struct TranscriptText: UIViewRepresentable { private var loader: (@Sendable (TranscriptImage) async -> CGImage?)? private var highlighter: TranscriptCodeHighlighter? private var mathRenderer: TranscriptMathRenderer? + private var mathAccessibilityLabel: ((TranscriptMath) -> String)? private var animatesTags = true private var textFadeInDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately @@ -86,6 +87,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 @@ -166,6 +176,7 @@ public struct TranscriptText: UIViewRepresentable { if let loader { view.imageLoader = loader } if let highlighter { view.codeHighlighter = highlighter } if let mathRenderer { 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 334076e..214e2bb 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -2,7 +2,9 @@ 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`, brought up to date only when the layout /// changes. A block keeps its element from one layout to the next, so @@ -11,11 +13,22 @@ extension TranscriptTextView { let cache = accessibilityCache ?? AccessibilityCache() accessibilityCache = cache if cache.layout === layout { return cache.elements } - var byKey: [String: BlockAccessibilityElement] = [:] + var byKey: [String: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] - for item in layout.accessibilityItems() { - let element = cache.byKey[item.key] ?? BlockAccessibilityElement(accessibilityContainer: self) - element.update(with: item) { [weak self] url in self?.openLink(url) } + let openLink: (URL) -> Void = { [weak self] url in self?.openLink(url) } + for item in layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex) { + let element: UIAccessibilityElement + 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, openLink: openLink) + element = tableElement + } else { + let blockElement = cache.byKey[item.key] as? BlockAccessibilityElement + ?? BlockAccessibilityElement(accessibilityContainer: self) + blockElement.update(with: item, openLink: openLink) + element = blockElement + } byKey[item.key] = element elements.append(element) } @@ -26,11 +39,19 @@ extension TranscriptTextView { return elements } + /// 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 + UIAccessibility.post(notification: .layoutChanged, argument: nil) + } + /// Tells assistive technologies that elements came or went, or moved, - /// after `layout` was installed. Elements keep their identity, so VoiceOver - /// focus stays on its block. Nothing is posted before an assistive - /// technology has asked for the elements, or when an update only adds - /// text to the last block. + /// after `layout` was installed. Elements keep their identity, so + /// VoiceOver focus stays on its block. Nothing is posted before an + /// assistive technology has asked for the elements, or when an update + /// only adds text to the last block. func postAccessibilityLayoutChangeIfNeeded(for layout: DocumentLayout, isAppend: Bool) { guard let cache = accessibilityCache, cache.layout != nil, window != nil else { return } let shape = layout.accessibilityShape @@ -40,27 +61,114 @@ extension TranscriptTextView { } } +private func traits(heading: Bool, links: Bool) -> UIAccessibilityTraits { + var traits: UIAccessibilityTraits = .staticText + if heading { traits.insert(.header) } + if links { traits.insert(.link) } + return traits +} + +@MainActor +private func actions(for links: [AccessibilityItem.Link], openLink: @escaping (URL) -> Void) -> [UIAccessibilityCustomAction] { + let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") + return links.map { link in + UIAccessibilityCustomAction(name: String(format: format, link.title)) { _ in + openLink(link.url) + return true + } + } +} + /// A block's element. Its block's id keeps it from one layout to the next. final class BlockAccessibilityElement: UIAccessibilityElement { private var links: [AccessibilityItem.Link]? func update(with item: AccessibilityItem, openLink: @escaping (URL) -> Void) { if accessibilityLabel != item.label { accessibilityLabel = item.label } + if accessibilityValue != item.value { accessibilityValue = item.value } if accessibilityFrameInContainerSpace != item.frame { accessibilityFrameInContainerSpace = item.frame } - var traits: UIAccessibilityTraits = .staticText - if item.isHeading { traits.insert(.header) } - if !item.links.isEmpty { traits.insert(.link) } + let traits = traits(heading: item.isHeading, links: !item.links.isEmpty) if accessibilityTraits != traits { accessibilityTraits = traits } guard links != item.links else { return } links = item.links - let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") - accessibilityCustomActions = item.links.map { link in - UIAccessibilityCustomAction(name: String(format: format, link.title)) { _ in - openLink(link.url) - return true - } + accessibilityCustomActions = actions(for: item.links, openLink: openLink) + } +} + +/// 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 + + override init(accessibilityContainer container: Any) { + super.init(accessibilityContainer: container) + isAccessibilityElement = false + accessibilityContainerType = .dataTable + } + + func update(frame: CGRect, table: AccessibilityItem.Table, in view: TranscriptTextView, openLink: @escaping (URL) -> Void) { + if accessibilityFrameInContainerSpace != frame { accessibilityFrameInContainerSpace = frame } + 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, in: view, openLink: openLink) + cells.append(element) } + if cells.count != self.cells.count || zip(cells, self.cells).contains(where: { $0 !== $1 }) { + self.cells = cells + accessibilityElements = cells + } + } + + func accessibilityDataTableCellElement(forRow row: Int, column: Int) -> (any UIAccessibilityContainerDataTableCell)? { + cells.first { $0.row == row && $0.column == column } } + + func accessibilityRowCount() -> Int { rowCount } + + func accessibilityColumnCount() -> Int { columnCount } + + func accessibilityHeaderElements(forColumn column: Int) -> [any UIAccessibilityContainerDataTableCell]? { + cells.first { $0.row == 0 && $0.column == column }.map { [$0] } + } +} + +/// A table cell's element. +final class CellAccessibilityElement: UIAccessibilityElement, UIAccessibilityContainerDataTableCell { + private(set) var row = -1 + private(set) var column = -1 + /// The cell in the view's coordinates. + private var frameInView: CGRect = .zero + private weak var view: UIView? + private var links: [AccessibilityItem.Link]? + + func update(with cell: AccessibilityItem.Table.Cell, in view: UIView, openLink: @escaping (URL) -> Void) { + row = cell.row + column = cell.column + frameInView = cell.frame + self.view = view + if accessibilityLabel != cell.label { accessibilityLabel = cell.label } + let traits = traits(heading: false, links: !cell.links.isEmpty) + if accessibilityTraits != traits { accessibilityTraits = traits } + guard links != cell.links else { return } + links = cell.links + accessibilityCustomActions = actions(for: cell.links, openLink: openLink) + } + + /// From the view, because the container is the table's element and not a view. + override var accessibilityFrame: CGRect { + get { view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero } + set {} + } + + func accessibilityRowRange() -> NSRange { NSRange(location: row, length: 1) } + + func accessibilityColumnRange() -> NSRange { NSRange(location: column, length: 1) } } final class AccessibilityCache { @@ -68,7 +176,7 @@ final class AccessibilityCache { var layout: DocumentLayout? /// The shape of the layout that assistive technologies last heard about. var shape: AccessibilityShape? - var byKey: [String: BlockAccessibilityElement] = [:] + var byKey: [String: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] } #endif diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 4613412..6667bba 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -193,6 +193,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + /// 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() /// Holds the tiles, and the tail layer above them, below the system's diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index d326109..7397833 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -98,3 +98,76 @@ private func limited(_ limit: Int?) -> TranscriptStyle { #expect(filled.accessibilityItems().count == 2) #expect(empty.accessibilityShape != filled.accessibilityShape) } + +private func items(_ markdown: String, width: CGFloat = 300) -> [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.accessibilityShape != after.accessibilityShape) + #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."]) +} diff --git a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift index 0eefaa4..2ca81d5 100644 --- a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift +++ b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift @@ -45,4 +45,34 @@ private func elements(of view: TranscriptTextView) -> [UIAccessibilityElement] { #expect(zip(added, narrower).allSatisfy { $0 === $1 }) #expect(narrower[1].accessibilityFrameInContainerSpace.width == 200) } + +@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.") +} #endif From f61c3dedeab5462ecda5bfaeded308c2d3d2c954 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:29:51 -0800 Subject: [PATCH 04/14] Answer assistive technologies on any thread In the Swift 6 language mode, a main actor method that Objective-C calls from another thread stops the process. VoiceOver, Speak Screen, Voice Control and the text rotor can call accessibility getters and UITextInput methods from another thread. A test that called isAccessibilityElement on the view from a background thread stopped in _checkExpectedExecutor. These methods are now nonisolated: - The view's isAccessibilityElement and accessibilityElements. - Every UITextInput method and property of the view, its tokenizer, its input delegate and writingToolsBehavior. - The getters of the text position, text range and selection rect types. They read values that never change. - The label, value, traits, frame and custom actions of the block and cell elements, which now keep these values in Swift properties. - The data table methods of the table element and the row and column ranges of the cell elements. - The link actions. A method that needs the view's state does its work on the main thread with onMainThread: at once on the main thread, and otherwise with DispatchQueue.main.sync from the thread that called. The main thread never waits for another thread. The new tests call each of these methods from a background thread through the Objective-C runtime. They run in the Mac Catalyst variant, because swift test on macOS does not build the UIKit code. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + Sources/TranscriptKit/iOS/MainThread.swift | 25 ++ .../TranscriptTextView+Accessibility.swift | 168 +++++++----- .../iOS/TranscriptTextView.swift | 240 +++++++++++------- .../OffMainThreadTests.swift | 144 +++++++++++ .../TextViewAccessibilityTests.swift | 2 +- 6 files changed, 415 insertions(+), 167 deletions(-) create mode 100644 Sources/TranscriptKit/iOS/MainThread.swift create mode 100644 Tests/TranscriptKitTests/OffMainThreadTests.swift diff --git a/README.md b/README.md index e3a3731..b6a0348 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,9 @@ position in its list and the number of items, such as "Item 2 of 3". A table is cell, so VoiceOver reads it cell by cell, with the row, the column and the column's header. While text streams in, each block keeps its element, so VoiceOver focus stays on its block. +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. diff --git a/Sources/TranscriptKit/iOS/MainThread.swift b/Sources/TranscriptKit/iOS/MainThread.swift new file mode 100644 index 0000000..d94a428 --- /dev/null +++ b/Sources/TranscriptKit/iOS/MainThread.swift @@ -0,0 +1,25 @@ +#if canImport(UIKit) && !os(watchOS) +import Foundation + +/// Runs `body` on the main thread and returns its result: at once on the +/// main thread, and otherwise after the main thread has run it. +/// +/// Assistive technologies, such as VoiceOver, Speak Screen, Voice Control +/// and the text rotor, can call accessibility getters and `UITextInput` +/// methods from other threads. In the Swift 6 language mode, a main actor +/// method that Objective-C calls from another thread stops the app, so +/// those methods are `nonisolated` and do their work here. Only the calling +/// thread waits: the main thread never waits for another thread here. +nonisolated func onMainThread(_ 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/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 214e2bb..738646a 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -15,18 +15,17 @@ extension TranscriptTextView { if cache.layout === layout { return cache.elements } var byKey: [String: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] - let openLink: (URL) -> Void = { [weak self] url in self?.openLink(url) } for item in layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex) { let element: UIAccessibilityElement 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, openLink: openLink) + tableElement.update(frame: item.frame, table: table, in: self) element = tableElement } else { let blockElement = cache.byKey[item.key] as? BlockAccessibilityElement ?? BlockAccessibilityElement(accessibilityContainer: self) - blockElement.update(with: item, openLink: openLink) + blockElement.update(with: item, in: self) element = blockElement } byKey[item.key] = element @@ -61,37 +60,71 @@ extension TranscriptTextView { } } -private func traits(heading: Bool, links: Bool) -> UIAccessibilityTraits { - var traits: UIAccessibilityTraits = .staticText - if heading { traits.insert(.header) } - if links { traits.insert(.link) } - return traits -} +/// 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`). +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 weak var view: TranscriptTextView? + private var links: [AccessibilityItem.Link]? + private var actions: [UIAccessibilityCustomAction]? -@MainActor -private func actions(for links: [AccessibilityItem.Link], openLink: @escaping (URL) -> Void) -> [UIAccessibilityCustomAction] { - let format = NSLocalizedString("Open %@", comment: "VoiceOver action that opens a link; %@ is the link's text") - return links.map { link in - UIAccessibilityCustomAction(name: String(format: format, link.title)) { _ in - openLink(link.url) - return true + func update(label: String, value: String?, isHeading: Bool, frame: CGRect, links: [AccessibilityItem.Link], + in view: TranscriptTextView) { + self.label = label + self.value = value + frameInView = frame + 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 + } } } + + nonisolated override var accessibilityLabel: String? { + get { onMainThread { label } } + set { onMainThread { label = newValue } } + } + + nonisolated override var accessibilityValue: String? { + get { onMainThread { value } } + set { onMainThread { value = newValue } } + } + + nonisolated override var accessibilityTraits: UIAccessibilityTraits { + get { onMainThread { 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 { view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero } } + set {} + } + + nonisolated override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { + get { onMainThread { actions } } + set { onMainThread { actions = newValue } } + } } /// A block's element. Its block's id keeps it from one layout to the next. -final class BlockAccessibilityElement: UIAccessibilityElement { - private var links: [AccessibilityItem.Link]? - - func update(with item: AccessibilityItem, openLink: @escaping (URL) -> Void) { - if accessibilityLabel != item.label { accessibilityLabel = item.label } - if accessibilityValue != item.value { accessibilityValue = item.value } - if accessibilityFrameInContainerSpace != item.frame { accessibilityFrameInContainerSpace = item.frame } - let traits = traits(heading: item.isHeading, links: !item.links.isEmpty) - if accessibilityTraits != traits { accessibilityTraits = traits } - guard links != item.links else { return } - links = item.links - accessibilityCustomActions = actions(for: item.links, openLink: openLink) +final class BlockAccessibilityElement: TextAccessibilityElement { + func update(with item: AccessibilityItem, in view: TranscriptTextView) { + update(label: item.label, value: item.value, isHeading: item.isHeading, frame: item.frame, links: item.links, in: view) } } @@ -101,74 +134,71 @@ final class TableAccessibilityElement: UIAccessibilityElement, UIAccessibilityCo private var cells: [CellAccessibilityElement] = [] private var rowCount = 0 private var columnCount = 0 + private var frameInView: CGRect = .zero + private weak var view: TranscriptTextView? - override init(accessibilityContainer container: Any) { - super.init(accessibilityContainer: container) - isAccessibilityElement = false - accessibilityContainerType = .dataTable - } - - func update(frame: CGRect, table: AccessibilityItem.Table, in view: TranscriptTextView, openLink: @escaping (URL) -> Void) { - if accessibilityFrameInContainerSpace != frame { accessibilityFrameInContainerSpace = frame } + func update(frame: CGRect, table: AccessibilityItem.Table, in view: TranscriptTextView) { + frameInView = 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, in: view, openLink: openLink) + element.update(with: cell, in: view) cells.append(element) } - if cells.count != self.cells.count || zip(cells, self.cells).contains(where: { $0 !== $1 }) { - self.cells = cells - accessibilityElements = cells - } + 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 { cells } } + set {} } - func accessibilityDataTableCellElement(forRow row: Int, column: Int) -> (any UIAccessibilityContainerDataTableCell)? { - cells.first { $0.row == row && $0.column == column } + nonisolated override var accessibilityFrame: CGRect { + get { onMainThread { view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero } } + set {} } - func accessibilityRowCount() -> Int { rowCount } + nonisolated func accessibilityDataTableCellElement(forRow row: Int, column: Int) -> (any UIAccessibilityContainerDataTableCell)? { + onMainThread { cells.first { $0.row == row && $0.column == column } } + } - func accessibilityColumnCount() -> Int { columnCount } + nonisolated func accessibilityRowCount() -> Int { onMainThread { rowCount } } - func accessibilityHeaderElements(forColumn column: Int) -> [any UIAccessibilityContainerDataTableCell]? { - cells.first { $0.row == 0 && $0.column == column }.map { [$0] } + nonisolated func accessibilityColumnCount() -> Int { onMainThread { columnCount } } + + nonisolated func accessibilityHeaderElements(forColumn column: Int) -> [any UIAccessibilityContainerDataTableCell]? { + onMainThread { cells.first { $0.row == 0 && $0.column == column }.map { [$0] } } } } /// A table cell's element. -final class CellAccessibilityElement: UIAccessibilityElement, UIAccessibilityContainerDataTableCell { +final class CellAccessibilityElement: TextAccessibilityElement, UIAccessibilityContainerDataTableCell { private(set) var row = -1 private(set) var column = -1 - /// The cell in the view's coordinates. - private var frameInView: CGRect = .zero - private weak var view: UIView? - private var links: [AccessibilityItem.Link]? - func update(with cell: AccessibilityItem.Table.Cell, in view: UIView, openLink: @escaping (URL) -> Void) { + func update(with cell: AccessibilityItem.Table.Cell, in view: TranscriptTextView) { row = cell.row column = cell.column - frameInView = cell.frame - self.view = view - if accessibilityLabel != cell.label { accessibilityLabel = cell.label } - let traits = traits(heading: false, links: !cell.links.isEmpty) - if accessibilityTraits != traits { accessibilityTraits = traits } - guard links != cell.links else { return } - links = cell.links - accessibilityCustomActions = actions(for: cell.links, openLink: openLink) - } - - /// From the view, because the container is the table's element and not a view. - override var accessibilityFrame: CGRect { - get { view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero } - set {} + update(label: cell.label, value: nil, isHeading: false, frame: cell.frame, links: cell.links, in: view) } - func accessibilityRowRange() -> NSRange { NSRange(location: row, length: 1) } + nonisolated func accessibilityRowRange() -> NSRange { onMainThread { NSRange(location: row, length: 1) } } - func accessibilityColumnRange() -> NSRange { NSRange(location: column, length: 1) } + nonisolated func accessibilityColumnRange() -> NSRange { onMainThread { NSRange(location: column, length: 1) } } } final class AccessibilityCache { diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 6667bba..9242ae3 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -801,7 +801,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 { @@ -870,7 +870,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } if !isAppend { - inputDelegate?.textDidChange(self) + storedInputDelegate?.textDidChange(self) refreshSelectionDisplay() } postAccessibilityLayoutChangeIfNeeded(for: layout, isAppend: isAppend) @@ -1226,13 +1226,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD var accessibilityCache: AccessibilityCache? /// 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 {} } @@ -1283,9 +1284,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public var showsWritingTools = true @available(iOS 18.0, *) - public var writingToolsBehavior: UIWritingToolsBehavior { - get { showsWritingTools ? .default : .none } - set { showsWritingTools = newValue != .none } + nonisolated public var writingToolsBehavior: UIWritingToolsBehavior { + get { onMainThread { showsWritingTools ? .default : .none } } + set { onMainThread { showsWritingTools = newValue != .none } } } public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { @@ -1314,9 +1315,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// the selection when `range` is nil. public func select(_ range: Range?) { if range != nil { addTextInteractionIfNeeded() } - inputDelegate?.selectionWillChange(self) + storedInputDelegate?.selectionWillChange(self) selection = range.map { clamp($0.lowerBound).. Int { (position as? TranscriptTextPosition)?.offset ?? 0 } @@ -1339,130 +1344,160 @@ 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) - let step = caret.height * CGFloat(offset) * (direction == .up ? -1 : 1) - let target = currentLayout.closestOffset(to: CGPoint(x: caret.midX, y: caret.midY + step)) - 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) + let step = caret.height * CGFloat(offset) * (direction == .up ? -1 : 1) + let target = currentLayout.closestOffset(to: CGPoint(x: caret.midX, y: caret.midY + step)) + 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))) + nonisolated public func caretRect(for position: UITextPosition) -> CGRect { + onMainThread { currentLayout.caretRect(at: clamp(offset(of: position))) } } - public func firstRect(for range: UITextRange) -> CGRect { - let range = self.range(of: range) - return currentLayout.selectionRects(for: range).first ?? currentLayout.caretRect(at: range.lowerBound) + nonisolated public func firstRect(for range: UITextRange) -> CGRect { + onMainThread { + let range = self.range(of: range) + return currentLayout.selectionRects(for: range).first ?? currentLayout.caretRect(at: range.lowerBound) + } } - public func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { - let rects = currentLayout.selectionRects(for: self.range(of: range)) - 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)) + 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)) + nonisolated public func closestPosition(to point: CGPoint) -> UITextPosition? { + onMainThread { TranscriptTextPosition(offset: currentLayout.closestOffset(to: point)) } } - public func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { - let range = self.range(of: range) - let offset = currentLayout.closestOffset(to: point) - 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) + return TranscriptTextPosition(offset: min(max(offset, range.lowerBound), range.upperBound)) + } } - public func characterRange(at point: CGPoint) -> UITextRange? { - let offset = currentLayout.closestOffset(to: point) - 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) + 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 @@ -1494,32 +1529,43 @@ private final class CanvasView: UIView { // 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 @@ -1528,11 +1574,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/OffMainThreadTests.swift b/Tests/TranscriptKitTests/OffMainThreadTests.swift new file mode 100644 index 0000000..7ca2f69 --- /dev/null +++ b/Tests/TranscriptKitTests/OffMainThreadTests.swift @@ -0,0 +1,144 @@ +#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() + } +} + +@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), start = Unchecked(value: start)] in + tokenizer.value.rangeEnclosingPosition(start.value, with: .word, inDirection: .storage(.forward)) + } + #expect((word as? TranscriptTextRange)?.range == 0..<5) +} +#endif diff --git a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift index 2ca81d5..c2ef297 100644 --- a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift +++ b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift @@ -43,7 +43,7 @@ private func elements(of view: TranscriptTextView) -> [UIAccessibilityElement] { view.layoutIfNeeded() let narrower = elements(of: view) #expect(zip(added, narrower).allSatisfy { $0 === $1 }) - #expect(narrower[1].accessibilityFrameInContainerSpace.width == 200) + #expect((narrower[1] as? TextAccessibilityElement)?.frameInView.width == 200) } @MainActor From 94fa75bc42481842aa949d7318d0d423af7fcb74 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:35:08 -0800 Subject: [PATCH 05/14] Set the container frame of accessibility elements again The elements now give their screen frame from a nonisolated getter. UIKit can also use the frame in container coordinates, for example to scroll an element into view. The update on the main thread now sets that frame too: the block's frame in the view, and a cell's frame in its table. Co-Authored-By: Claude Opus 5.5 --- .../iOS/TranscriptTextView+Accessibility.swift | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 738646a..60c4a99 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -73,11 +73,14 @@ class TextAccessibilityElement: UIAccessibilityElement { private var links: [AccessibilityItem.Link]? private var actions: [UIAccessibilityCustomAction]? - func update(label: String, value: String?, isHeading: Bool, frame: CGRect, links: [AccessibilityItem.Link], - in view: TranscriptTextView) { + /// - 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) } @@ -124,7 +127,8 @@ class TextAccessibilityElement: UIAccessibilityElement { /// A block's element. Its block's id keeps it from one layout to the next. final class BlockAccessibilityElement: TextAccessibilityElement { func update(with item: AccessibilityItem, in view: TranscriptTextView) { - update(label: item.label, value: item.value, isHeading: item.isHeading, frame: item.frame, links: item.links, in: view) + update(label: item.label, value: item.value, isHeading: item.isHeading, frame: item.frame, frameInContainer: item.frame, + links: item.links, in: view) } } @@ -139,6 +143,7 @@ final class TableAccessibilityElement: UIAccessibilityElement, UIAccessibilityCo 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 @@ -146,7 +151,7 @@ final class TableAccessibilityElement: UIAccessibilityElement, UIAccessibilityCo 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, in: view) + element.update(with: cell, inTableAt: frame.origin, in: view) cells.append(element) } self.cells = cells @@ -190,10 +195,11 @@ final class CellAccessibilityElement: TextAccessibilityElement, UIAccessibilityC private(set) var row = -1 private(set) var column = -1 - func update(with cell: AccessibilityItem.Table.Cell, in view: TranscriptTextView) { + func update(with cell: AccessibilityItem.Table.Cell, inTableAt origin: CGPoint, in view: TranscriptTextView) { row = cell.row column = cell.column - update(label: cell.label, value: nil, isHeading: false, frame: cell.frame, links: cell.links, in: view) + update(label: cell.label, value: nil, 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: row, length: 1) } } From b479db34160b0af579895929d06e6791b303a4e8 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:46:09 -0800 Subject: [PATCH 06/14] Update a kept accessibility element before it answers An assistive technology can keep an element, such as the element that has VoiceOver focus, and read it again later. An update that only adds text to the last block posts no notification, so the client does not ask the view for its elements again. The element then gave its old text. Each getter of a block, cell or table element now first brings the elements up to date with the layout on screen. When the elements already match that layout, this costs nothing more. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptTextView+Accessibility.swift | 46 ++++++++++++++----- .../iOS/TranscriptTextView.swift | 7 +++ .../TextViewAccessibilityTests.swift | 14 ++++++ 3 files changed, 55 insertions(+), 12 deletions(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 60c4a99..8bb8b8e 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -62,7 +62,9 @@ extension TranscriptTextView { /// 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`). +/// 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? @@ -98,30 +100,40 @@ class TextAccessibilityElement: UIAccessibilityElement { } nonisolated override var accessibilityLabel: String? { - get { onMainThread { label } } + get { onMainThread { current.label } } set { onMainThread { label = newValue } } } nonisolated override var accessibilityValue: String? { - get { onMainThread { value } } + get { onMainThread { current.value } } set { onMainThread { value = newValue } } } nonisolated override var accessibilityTraits: UIAccessibilityTraits { - get { onMainThread { traits } } + 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 { view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero } } + get { onMainThread { current.screenFrame } } set {} } nonisolated override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { - get { onMainThread { actions } } + get { onMainThread { current.actions } } set { onMainThread { actions = newValue } } } + + /// This element, once the elements are up to date. + private var current: TextAccessibilityElement { + view?.updateAccessibilityElements() + return self + } + + private var screenFrame: CGRect { + view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero + } } /// A block's element. Its block's id keeps it from one layout to the next. @@ -168,25 +180,35 @@ final class TableAccessibilityElement: UIAccessibilityElement, UIAccessibilityCo } nonisolated override var accessibilityElements: [Any]? { - get { onMainThread { cells } } + get { onMainThread { current.cells } } set {} } nonisolated override var accessibilityFrame: CGRect { - get { onMainThread { view.map { UIAccessibility.convertToScreenCoordinates(frameInView, in: $0) } ?? .zero } } + get { onMainThread { current.screenFrame } } set {} } nonisolated func accessibilityDataTableCellElement(forRow row: Int, column: Int) -> (any UIAccessibilityContainerDataTableCell)? { - onMainThread { cells.first { $0.row == row && $0.column == column } } + onMainThread { current.cells.first { $0.row == row && $0.column == column } } } - nonisolated func accessibilityRowCount() -> Int { onMainThread { rowCount } } + nonisolated func accessibilityRowCount() -> Int { onMainThread { current.rowCount } } - nonisolated func accessibilityColumnCount() -> Int { onMainThread { columnCount } } + nonisolated func accessibilityColumnCount() -> Int { onMainThread { current.columnCount } } nonisolated func accessibilityHeaderElements(forColumn column: Int) -> [any UIAccessibilityContainerDataTableCell]? { - onMainThread { cells.first { $0.row == 0 && $0.column == column }.map { [$0] } } + 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 } } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 9242ae3..ad464a9 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1225,6 +1225,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// 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:)`). nonisolated public override var isAccessibilityElement: Bool { get { false } diff --git a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift index c2ef297..9b3f72b 100644 --- a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift +++ b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift @@ -46,6 +46,20 @@ private func elements(of view: TranscriptTextView) -> [UIAccessibilityElement] { #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)) From 3d79314cf0a2915652c9c2891ed9dc8ed3f2301a Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:05:59 -0800 Subject: [PATCH 07/14] Post a layout change only when the elements change A layout that is not an append, such as a layout after new colors for code, posted a layout-changed notification every time. Now such a layout posts only when its items differ from the items that the elements were last made with. An append posts only when its shape changes. The shape now also tells whether the text that a line limit leaves out has an item of its own. Before, a paragraph that streamed in after a table under a line limit added an element and posted nothing. Co-Authored-By: Claude Opus 5.5 --- .../Layout/AccessibilityContent.swift | 74 +++++++++++++++++-- .../TranscriptTextView+Accessibility.swift | 24 ++++-- .../AccessibilityTests.swift | 36 +++++++++ 3 files changed, 119 insertions(+), 15 deletions(-) diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index 7d536cd..bd93743 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -92,7 +92,8 @@ extension DocumentLayout { links += AccessibilityText.links(of: block, in: all, math: math, definitions: definitions) } guard !rest.isEmpty else { return items } - if let last = items.last, last.table == nil { + if !items.isEmpty, !hasAccessibilityRemainder { + let last = items[items.count - 1] items[items.count - 1] = AccessibilityItem(key: last.key, frame: last.frame, label: ([last.label] + rest).joined(separator: "\n"), value: last.value, isHeading: last.isHeading, links: last.links + links, table: nil) @@ -108,9 +109,8 @@ extension DocumentLayout { math: (TranscriptMath) -> String, definitions: [String: String]) -> AccessibilityItem.Table { var cells: [AccessibilityItem.Table.Cell] = [] - let rowCount = min(model.rows.count, grid.rowY.count - 1) - let columnCount = min(model.columnCount, grid.columnX.count - 1) - 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) } } /// What decides which items the layout has, found without making them. /// A layout that only adds text to the end of another has the same /// items as that one, with longer text, if their shapes are equal. var accessibilityShape: AccessibilityShape { - guard entryCount > 0 else { return AccessibilityShape(entries: 0, lastHasNoItem: false, lastTableCells: 0) } + guard entryCount > 0 else { + return AccessibilityShape(entries: 0, lastHasNoItem: false, lastTableCells: 0, hasRemainder: hasAccessibilityRemainder) + } let block = entry(at: entryCount - 1).layout.block return AccessibilityShape(entries: entryCount, lastHasNoItem: block.text.isEmpty && block.kind != .rule, - lastTableCells: block.kind.table?.rows.reduce(0) { $0 + $1.count } ?? 0) + lastTableCells: block.kind.table?.rows.reduce(0) { $0 + $1.count } ?? 0, + hasRemainder: hasAccessibilityRemainder) + } + + /// Whether the text that a line limit leaves out gets an item of its + /// own, after the items of the blocks shown. It does when no block shown + /// has an item, or when the last one that has an item is a table. + var hasAccessibilityRemainder: Bool { + guard leavesTextOut, entryCount < document.count, + (entryCount.. 0 { return true } + } else if AccessibilityText.hasItem(entry.layout.block) { + return false + } + } + return true } } @@ -140,6 +173,27 @@ struct AccessibilityShape: Equatable { /// The number of cells in the last block, if it is a table: a row that /// streams in adds elements. let lastTableCells: Int + /// See `DocumentLayout.hasAccessibilityRemainder`. + let hasRemainder: Bool +} + +/// When assistive technologies must hear that the layout changed. +enum AccessibilityLayoutChange { + /// Whether a new layout needs a layout-changed notification. + /// + /// A layout that only adds text to the end of the old one needs it only + /// when elements come or go, which the shape tells. Other layouts, such + /// as the ones that a new width or an image start, need it when an item + /// changed, for example its frame. A layout that only gives code other + /// colors has the same items, so it needs none. + /// + /// - Parameter newItems: the items of the new layout, made only when + /// they are needed. + static func isNeeded(isAppend: Bool, oldShape: AccessibilityShape?, oldItems: [AccessibilityItem], + newShape: AccessibilityShape, newItems: () -> [AccessibilityItem]) -> Bool { + guard let oldShape, oldShape == newShape else { return true } + return !isAppend && newItems() != oldItems + } } /// The words that assistive technologies get for a block. @@ -157,6 +211,12 @@ enum AccessibilityText { 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 { diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 8bb8b8e..ea378f5 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -15,7 +15,8 @@ extension TranscriptTextView { if cache.layout === layout { return cache.elements } var byKey: [String: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] - for item in layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex) { + let items = layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex) + for item in items { let element: UIAccessibilityElement if let table = item.table { let tableElement = cache.byKey[item.key] as? TableAccessibilityElement @@ -33,6 +34,7 @@ extension TranscriptTextView { } cache.layout = layout cache.shape = layout.accessibilityShape + cache.items = items cache.byKey = byKey cache.elements = elements return elements @@ -46,17 +48,21 @@ extension TranscriptTextView { UIAccessibility.post(notification: .layoutChanged, argument: nil) } - /// Tells assistive technologies that elements came or went, or moved, - /// after `layout` was installed. Elements keep their identity, so - /// VoiceOver focus stays on its block. Nothing is posted before an - /// assistive technology has asked for the elements, or when an update - /// only adds text to the last block. + /// Tells assistive technologies that elements came or went, or changed, + /// after `layout` was installed (see `AccessibilityLayoutChange`). + /// 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, window != nil else { return } let shape = layout.accessibilityShape - guard !isAppend || shape != cache.shape else { return } + let isNeeded = AccessibilityLayoutChange.isNeeded(isAppend: isAppend, oldShape: cache.shape, oldItems: cache.items, + newShape: shape) { + _ = accessibilityElements(for: layout) + return cache.items + } cache.shape = shape - UIAccessibility.post(notification: .layoutChanged, argument: nil) + if isNeeded { UIAccessibility.post(notification: .layoutChanged, argument: nil) } } } @@ -234,6 +240,8 @@ final class AccessibilityCache { var layout: DocumentLayout? /// The shape of the layout that assistive technologies last heard about. var shape: AccessibilityShape? + /// The items that the elements were last brought up to date with. + var items: [AccessibilityItem] = [] var byKey: [String: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] } diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index 7397833..45449c6 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -171,3 +171,39 @@ private func items(_ markdown: String, width: CGFloat = 300) -> [AccessibilityIt 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 { + AccessibilityLayoutChange.isNeeded(isAppend: isAppend, oldShape: old.accessibilityShape, oldItems: old.accessibilityItems(), + newShape: new.accessibilityShape, newItems: { new.accessibilityItems() }) +} + +@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)) + // The same layout installed as a new one: the label changed. + #expect(isNeeded(from: before, to: longer, isAppend: false)) + 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)) +} From 56a54e2c6764685a7522a253ab609798ebf06786 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:06:53 -0800 Subject: [PATCH 08/14] Give a table in a list item its marker, and make element keys unique A table that starts a list item lost the list marker, the task state and the position. Now its first cell reads the marker before its text, and has the position as its value. An element key was the block id with "#" and a count, so the ids "same", "same" and "same#1" gave the same key twice. A key is now a struct of the id and the number of blocks before it with that id. A table cell now brings the elements up to date before it gives its row or column, as its other getters do. Co-Authored-By: Claude Opus 5.5 --- .../Layout/AccessibilityContent.swift | 34 +++++++++++++------ .../TranscriptTextView+Accessibility.swift | 18 ++++++---- .../AccessibilityTests.swift | 15 ++++++-- 3 files changed, 48 insertions(+), 19 deletions(-) diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index bd93743..5a5b01c 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -16,6 +16,9 @@ struct AccessibilityItem: Equatable { 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] } @@ -25,12 +28,18 @@ struct AccessibilityItem: Equatable { let cells: [Cell] } - /// The block's id, made 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: String + /// 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. + /// 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". @@ -55,16 +64,18 @@ extension DocumentLayout { let definitions = document.linkDefinitions let positions = AccessibilityText.listPositions(in: document, upTo: entryCount) var uses: [String: Int] = [:] - func key(for block: TranscriptBlock) -> String { + func key(for block: TranscriptBlock) -> AccessibilityItem.Key { let use = uses[block.id, default: 0] uses[block.id] = use + 1 - return use == 0 ? block.id : "\(block.id)#\(use)" + return AccessibilityItem.Key(id: block.id, occurrence: use) } for index in 0.. String, + position: String?, math: (TranscriptMath) -> String, definitions: [String: String]) -> AccessibilityItem.Table { var cells: [AccessibilityItem.Table.Cell] = [] let (rowCount, columnCount) = accessibilityGridSize(model, grid: grid) @@ -114,8 +125,11 @@ extension DocumentLayout { for (column, range) in model.rows[row].prefix(columnCount).enumerated() { let frame = CGRect(x: grid.columnX[column], y: y + grid.rowY[row], width: grid.columnX[column + 1] - grid.columnX[column], height: grid.rowY[row + 1] - grid.rowY[row]) + let text = AccessibilityText.readable(block, in: range, math: math) + let isFirst = cells.isEmpty cells.append(.init(row: row, column: column, frame: frame, - label: AccessibilityText.readable(block, in: range, math: math), + label: isFirst ? AccessibilityText.spoken(text, of: block) : text, + value: isFirst ? position : nil, links: AccessibilityText.links(of: block, in: range, math: math, definitions: definitions))) } } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index ea378f5..64f13f1 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -13,7 +13,7 @@ extension TranscriptTextView { let cache = accessibilityCache ?? AccessibilityCache() accessibilityCache = cache if cache.layout === layout { return cache.elements } - var byKey: [String: UIAccessibilityElement] = [:] + var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] let items = layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex) for item in items { @@ -132,7 +132,7 @@ class TextAccessibilityElement: UIAccessibilityElement { } /// This element, once the elements are up to date. - private var current: TextAccessibilityElement { + fileprivate var current: TextAccessibilityElement { view?.updateAccessibilityElements() return self } @@ -226,13 +226,19 @@ final class CellAccessibilityElement: TextAccessibilityElement, UIAccessibilityC func update(with cell: AccessibilityItem.Table.Cell, inTableAt origin: CGPoint, in view: TranscriptTextView) { row = cell.row column = cell.column - update(label: cell.label, value: nil, isHeading: false, frame: cell.frame, + 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: row, length: 1) } } + nonisolated func accessibilityRowRange() -> NSRange { onMainThread { NSRange(location: cell.row, length: 1) } } - nonisolated func accessibilityColumnRange() -> NSRange { onMainThread { NSRange(location: column, 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 { @@ -242,7 +248,7 @@ final class AccessibilityCache { var shape: AccessibilityShape? /// The items that the elements were last brought up to date with. var items: [AccessibilityItem] = [] - var byKey: [String: UIAccessibilityElement] = [:] + var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] } #endif diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index 45449c6..a8ee9e5 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -82,10 +82,11 @@ private func limited(_ limit: Int?) -> TranscriptStyle { } @Test func blocksWithTheSameIdGetDifferentKeys() { - let document = TranscriptDocument(blocks: [TranscriptBlock(id: "same", text: "One"), TranscriptBlock(id: "same", text: "Two")]) + let document = TranscriptDocument(blocks: [TranscriptBlock(id: "same", text: "One"), TranscriptBlock(id: "same", text: "Two"), + TranscriptBlock(id: "same#1", text: "Three")]) let keys = DocumentLayout(document: document, width: 300).accessibilityItems().map(\.key) - #expect(keys.count == 2) - #expect(Set(keys).count == 2) + #expect(keys.count == 3) + #expect(Set(keys).count == 3) } @Test func aBlockWithoutTextYetChangesTheShapeWhenItGetsSome() { @@ -207,3 +208,11 @@ private func isNeeded(from old: DocumentLayout, to new: DocumentLayout, isAppend #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]) +} From f1ffaf18448be68d9d2631a362f9d1604dba3f61 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:08:44 -0800 Subject: [PATCH 09/14] Read again only the blocks whose layout changed With an assistive technology on, the elements were made from the whole document for each new layout. Each block was read again, and the app's formula closure ran again for each formula. Now the view keeps the words of each block with the block layout that they came from. A block whose layout is the same object as before uses its words again. New link definitions or a new mathAccessibilityLabel make all words again. A table cell read all of the spans of its table, so a table cost its spans times its cells. Now each span goes to the cell that holds its start, by binary search. Co-Authored-By: Claude Opus 5.5 --- .../Layout/AccessibilityContent.swift | 149 +++++++++++++++--- .../TranscriptTextView+Accessibility.swift | 5 +- .../AccessibilityTests.swift | 34 ++++ 3 files changed, 165 insertions(+), 23 deletions(-) diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index 5a5b01c..d7fc93d 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -59,9 +59,13 @@ extension DocumentLayout { /// a table, the text left out gets an item of its own after it. /// /// - Parameter math: the words for a formula. - func accessibilityItems(math: (TranscriptMath) -> String = \.tex) -> [AccessibilityItem] { + /// - 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 { @@ -72,23 +76,22 @@ extension DocumentLayout { 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.. String, - definitions: [String: String]) -> AccessibilityItem.Table { + words: [AccessibilityWords.Words], position: String?) -> AccessibilityItem.Table { var cells: [AccessibilityItem.Table.Cell] = [] let (rowCount, columnCount) = accessibilityGridSize(model, grid: grid) for row in 0.. 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 block.spans.reversed() where range.contains(span.range.lowerBound) && span.range.count == 1 { + 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) } @@ -259,17 +335,46 @@ enum AccessibilityText { /// 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 block.spans where range.contains(span.range.lowerBound) { + 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 diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 64f13f1..9c3f481 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -15,7 +15,7 @@ extension TranscriptTextView { if cache.layout === layout { return cache.elements } var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] - let items = layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex) + let items = layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex, words: cache.words) for item in items { let element: UIAccessibilityElement if let table = item.table { @@ -45,6 +45,7 @@ extension TranscriptTextView { func invalidateAccessibilityElements() { guard let cache = accessibilityCache, cache.layout != nil else { return } cache.layout = nil + cache.words = AccessibilityWords() UIAccessibility.post(notification: .layoutChanged, argument: nil) } @@ -248,6 +249,8 @@ final class AccessibilityCache { var shape: AccessibilityShape? /// The items that the elements were last brought up to date with. var items: [AccessibilityItem] = [] + /// The words of those items, for the current `mathAccessibilityLabel`. + var words = AccessibilityWords() var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] } diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index a8ee9e5..a6e53c9 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -216,3 +216,37 @@ private func isNeeded(from old: DocumentLayout, to new: DocumentLayout, isAppend #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"]) +} From a8b8b6fdae6a7653d4d508769e0c4590c59cbe21 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:17:06 -0800 Subject: [PATCH 10/14] Answer hit tests and edit actions on any thread point(inside:with:), canBecomeFirstResponder, inputView, canPerformAction(_:withSender:), copy(_:) and selectAll(_:) were still main actor overrides. The accessibility hit test reaches point(inside:with:), so an assistive client that hit-tests from another thread stopped the app. These overrides are now nonisolated and do their work on the main thread, as the UITextInput methods do. New tests call these overrides, the inputDelegate setter, writingToolsBehavior and a link action from a background thread. Other new tests check that Select All under a line limit selects and copies all of the text, that the selection grows and is reported again while text streams in after the cut, and that the element reads all of the text. Co-Authored-By: Claude Opus 5.5 --- .../iOS/TranscriptTextView.swift | 58 +++++++++++-------- .../OffMainThreadTests.swift | 52 +++++++++++++++++ .../TextViewAccessibilityTests.swift | 39 +++++++++++++ 3 files changed, 126 insertions(+), 23 deletions(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index ad464a9..fc87a86 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1246,7 +1246,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD // 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") @@ -1267,12 +1271,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 + 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 + } } private func addTextInteractionIfNeeded() { @@ -1284,7 +1290,7 @@ 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`. @@ -1296,26 +1302,32 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD set { onMainThread { 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.. 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) @@ -141,4 +153,44 @@ private func viewWithText() -> TranscriptTextView { } #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 handled = await offMain { [action = Unchecked(value: action)] in action.value.actionHandler?(action.value) ?? false } + #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)?) {} +} #endif diff --git a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift index 9b3f72b..f4a4ccb 100644 --- a/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift +++ b/Tests/TranscriptKitTests/TextViewAccessibilityTests.swift @@ -89,4 +89,43 @@ private func elements(of view: TranscriptTextView) -> [UIAccessibilityElement] { 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.. Date: Mon, 23 Nov 2026 18:17:19 -0800 Subject: [PATCH 11/14] Tell in the README when VoiceOver hears of a layout change Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b6a0348..86eab83 100644 --- a/README.md +++ b/README.md @@ -285,8 +285,10 @@ them off with `.showsWritingTools(false)`, or with `showsWritingTools` on `Trans 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. 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. While text streams in, each -block keeps its element, so VoiceOver focus stays on its block. +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 or changes them. 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. From 51919e96671f0ced030d404217d4a99ed5b53b6f Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:41 -0800 Subject: [PATCH 12/14] Compare a new layout with the layout installed last The decision to post a layout change compared a new layout with the items that the elements were last made with. An append that posted nothing did not make the items again, so they grew old. While a code block streamed in, the next color result then found a longer label and posted. Now the view keeps the geometry of each layout that it installs, once an assistive technology has asked for the elements: the blocks, the number of elements of each, their frames, and whether the text that a line limit leaves out has an item. The geometry does not read the text of the blocks. An append posts when elements come or go. Another layout also posts when an element moved or changed its size. Co-Authored-By: Claude Opus 5.5 --- .../Layout/AccessibilityContent.swift | 90 ++++++++++++------- .../TranscriptTextView+Accessibility.swift | 28 ++---- .../AccessibilityTests.swift | 36 ++++++-- 3 files changed, 94 insertions(+), 60 deletions(-) diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index d7fc93d..1f2b2bc 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -170,17 +170,23 @@ extension DocumentLayout { return model.rows.prefix(rows).reduce(0) { $0 + min($1.count, columns) } } - /// What decides which items the layout has, found without making them. - /// A layout that only adds text to the end of another has the same - /// items as that one, with longer text, if their shapes are equal. - var accessibilityShape: AccessibilityShape { - guard entryCount > 0 else { - return AccessibilityShape(entries: 0, lastHasNoItem: false, lastTableCells: 0, hasRemainder: hasAccessibilityRemainder) + /// 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.. Bool { + hasRemainder == other.hasRemainder && entries.count == other.entries.count + && zip(entries, other.entries).allSatisfy { $0.id == $1.id && $0.elements == $1.elements } + } } -/// When assistive technologies must hear that the layout changed. -enum AccessibilityLayoutChange { - /// Whether a new layout needs a layout-changed notification. - /// - /// A layout that only adds text to the end of the old one needs it only - /// when elements come or go, which the shape tells. Other layouts, such - /// as the ones that a new width or an image start, need it when an item - /// changed, for example its frame. A layout that only gives code other - /// colors has the same items, so it needs none. - /// - /// - Parameter newItems: the items of the new layout, made only when - /// they are needed. - static func isNeeded(isAppend: Bool, oldShape: AccessibilityShape?, oldItems: [AccessibilityItem], - newShape: AccessibilityShape, newItems: () -> [AccessibilityItem]) -> Bool { - guard let oldShape, oldShape == newShape else { return true } - return !isAppend && newItems() != oldItems +/// 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 } } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index 9c3f481..30aee05 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -15,8 +15,7 @@ extension TranscriptTextView { if cache.layout === layout { return cache.elements } var byKey: [AccessibilityItem.Key: UIAccessibilityElement] = [:] var elements: [UIAccessibilityElement] = [] - let items = layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex, words: cache.words) - for item in items { + for item in layout.accessibilityItems(math: mathAccessibilityLabel ?? \.tex, words: cache.words) { let element: UIAccessibilityElement if let table = item.table { let tableElement = cache.byKey[item.key] as? TableAccessibilityElement @@ -32,9 +31,8 @@ extension TranscriptTextView { byKey[item.key] = element elements.append(element) } + if cache.watch.geometry == nil { cache.watch.start(with: layout) } cache.layout = layout - cache.shape = layout.accessibilityShape - cache.items = items cache.byKey = byKey cache.elements = elements return elements @@ -49,21 +47,15 @@ extension TranscriptTextView { UIAccessibility.post(notification: .layoutChanged, argument: nil) } - /// Tells assistive technologies that elements came or went, or changed, - /// after `layout` was installed (see `AccessibilityLayoutChange`). + /// 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, window != nil else { return } - let shape = layout.accessibilityShape - let isNeeded = AccessibilityLayoutChange.isNeeded(isAppend: isAppend, oldShape: cache.shape, oldItems: cache.items, - newShape: shape) { - _ = accessibilityElements(for: layout) - return cache.items - } - cache.shape = shape - if isNeeded { UIAccessibility.post(notification: .layoutChanged, argument: nil) } + 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) } } } @@ -245,10 +237,8 @@ final class CellAccessibilityElement: TextAccessibilityElement, UIAccessibilityC final class AccessibilityCache { /// The layout that the elements were last brought up to date for. var layout: DocumentLayout? - /// The shape of the layout that assistive technologies last heard about. - var shape: AccessibilityShape? - /// The items that the elements were last brought up to date with. - var items: [AccessibilityItem] = [] + /// 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] = [:] diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index a6e53c9..538ce24 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -77,8 +77,8 @@ private func limited(_ limit: Int?) -> TranscriptStyle { #expect(Array(added.accessibilityItems().map(\.key).prefix(2)) == keys) #expect(added.accessibilityItems().count == 3) // Text added to the last block keeps the shape; a new block changes it. - #expect(longer.accessibilityShape == before.accessibilityShape) - #expect(added.accessibilityShape != longer.accessibilityShape) + #expect(longer.accessibilityGeometry.hasSameElements(as: before.accessibilityGeometry)) + #expect(!added.accessibilityGeometry.hasSameElements(as: longer.accessibilityGeometry)) } @Test func blocksWithTheSameIdGetDifferentKeys() { @@ -97,7 +97,7 @@ private func limited(_ limit: Int?) -> TranscriptStyle { let filled = DocumentLayout(document: document, width: 300, reusing: empty) #expect(empty.accessibilityItems().count == 1) #expect(filled.accessibilityItems().count == 2) - #expect(empty.accessibilityShape != filled.accessibilityShape) + #expect(!empty.accessibilityGeometry.hasSameElements(as: filled.accessibilityGeometry)) } private func items(_ markdown: String, width: CGFloat = 300) -> [AccessibilityItem] { @@ -151,7 +151,7 @@ private func items(_ markdown: String, width: CGFloat = 300) -> [AccessibilityIt let before = DocumentLayout(document: parser.document, width: 300) parser.append(" 2 |") let after = DocumentLayout(document: parser.document, width: 300, reusing: before) - #expect(before.accessibilityShape != after.accessibilityShape) + #expect(!before.accessibilityGeometry.hasSameElements(as: after.accessibilityGeometry)) #expect(after.accessibilityItems().first?.table?.cells.count == 4) } @@ -174,8 +174,9 @@ private func items(_ markdown: String, width: CGFloat = 300) -> [AccessibilityIt } private func isNeeded(from old: DocumentLayout, to new: DocumentLayout, isAppend: Bool) -> Bool { - AccessibilityLayoutChange.isNeeded(isAppend: isAppend, oldShape: old.accessibilityShape, oldItems: old.accessibilityItems(), - newShape: new.accessibilityShape, newItems: { new.accessibilityItems() }) + var watch = AccessibilityLayoutWatch() + watch.start(with: old) + return watch.install(new, isAppend: isAppend) } @Test func aLayoutChangeIsPostedOnlyWhenElementsChange() { @@ -189,8 +190,6 @@ private func isNeeded(from old: DocumentLayout, to new: DocumentLayout, isAppend parser.append(" and more") let longer = DocumentLayout(document: parser.document, width: 300, reusing: before) #expect(!isNeeded(from: before, to: longer, isAppend: true)) - // The same layout installed as a new one: the label changed. - #expect(isNeeded(from: before, to: longer, isAppend: false)) parser.append("\n\nA new paragraph") let added = DocumentLayout(document: parser.document, width: 300, reusing: longer) #expect(isNeeded(from: longer, to: added, isAppend: true)) @@ -250,3 +249,24 @@ private func isNeeded(from old: DocumentLayout, to new: DocumentLayout, isAppend 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) +} From d7734e9636c9719163e70d39333c863e323a0be3 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:31:07 -0800 Subject: [PATCH 13/14] Say in the README that a moved element posts a layout change Co-Authored-By: Claude Opus 5.5 --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 86eab83..6e771d3 100644 --- a/README.md +++ b/README.md @@ -288,7 +288,8 @@ position in its list and the number of items, such as "Item 2 of 3". A table is 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 or changes them. Text that streams into the last block does not tell it. +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. From 206cbc9aa2d3ecd4da305e5d90aaa6ce008a8d55 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:34:44 -0800 Subject: [PATCH 14/14] Build the off-main-thread tests for iOS The iOS 27.2 SDK makes conversationContext(_:didChange:) a required method of UITextInputDelegate, so the test delegate did not build for iOS. Two calls also used main actor API in a closure that runs off the main thread, which gave warnings. They now go through the Objective-C runtime, as the other calls in the file do. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKitTests/OffMainThreadTests.swift | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Tests/TranscriptKitTests/OffMainThreadTests.swift b/Tests/TranscriptKitTests/OffMainThreadTests.swift index 2975d9a..41c21b8 100644 --- a/Tests/TranscriptKitTests/OffMainThreadTests.swift +++ b/Tests/TranscriptKitTests/OffMainThreadTests.swift @@ -148,8 +148,11 @@ private func viewWithText() -> TranscriptTextView { _ = 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), start = Unchecked(value: start)] in - tokenizer.value.rangeEnclosingPosition(start.value, with: .word, inDirection: .storage(.forward)) + 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) } @@ -160,7 +163,10 @@ private func viewWithText() -> TranscriptTextView { 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 handled = await offMain { [action = Unchecked(value: action)] in action.value.actionHandler?(action.value) ?? false } + 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"]) @@ -192,5 +198,9 @@ private final class Delegate: NSObject, UITextInputDelegate { 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