Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/SheetUI/Tests/SheetUITests/AccessibilityTests.swift10// Module : SheetUITests11// Repository : https://git.spboucher.ai/orix-sheet12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import AppKit88import ApplicationServices89import Foundation90import SwiftUI91import Testing92import SheetCore93@testable import SheetUI9495// MARK: - Colour contrast (WCAG 2.1)9697/// Relative luminance and contrast ratio as defined by WCAG 2.1.98enum WCAG {99 static func luminance(_ hex: UInt32) -> Double {100 func channel(_ v: UInt32) -> Double {101 let c = Double(v & 0xFF) / 255102 return c <= 0.03928 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4)103 }104 return 0.2126 * channel(hex >> 16) + 0.7152 * channel(hex >> 8) + 0.0722 * channel(hex)105 }106 static func ratio(_ a: UInt32, _ b: UInt32) -> Double {107 let la = luminance(a), lb = luminance(b)108 return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)109 }110 /// `fg` at `alpha` over `bg`.111 static func blend(_ fg: UInt32, over bg: UInt32, alpha: Double) -> UInt32 {112 var out: UInt32 = 0113 for shift in [16, 8, 0] as [UInt32] {114 let f = Double((fg >> shift) & 0xFF), b = Double((bg >> shift) & 0xFF)115 out |= UInt32((f * alpha + b * (1 - alpha)).rounded()) << shift116 }117 return out118 }119 static func hex(_ c: NSColor) -> UInt32 {120 let s = c.usingColorSpace(.sRGB) ?? c121 return UInt32((s.redComponent * 255).rounded()) << 16 | UInt32((s.greenComponent * 255).rounded()) << 8 | UInt32((s.blueComponent * 255).rounded())122 }123}124125@MainActor @Suite struct ContrastTests {126 struct Pair { let name: String; let fg: UInt32; let bg: UInt32; let minimum: Double }127128 /// Every foreground/background pair that SheetUI and the app target actually draw.129 static func pairs(dark: Bool) -> [Pair] {130 let t = ORIX.Tokens.self131 func h(_ token: ORIX.Token) -> UInt32 { token.hex(dark: dark) }132 let surfaces: [(String, UInt32)] = [("surface", h(t.surface)), ("canvas", h(t.canvas)), ("surfaceRaised", h(t.surfaceRaised))]133 var out = [Pair]()134 // text (4.5:1)135 for (sn, s) in surfaces {136 out.append(Pair(name: "textPrimary on \(sn)", fg: h(t.textPrimary), bg: s, minimum: 4.5))137 out.append(Pair(name: "textSecondary on \(sn)", fg: h(t.textSecondary), bg: s, minimum: 4.5))138 out.append(Pair(name: "textTertiary on \(sn)", fg: h(t.textTertiary), bg: s, minimum: 4.5))139 out.append(Pair(name: "accentText on \(sn)", fg: h(t.accentText), bg: s, minimum: 4.5))140 out.append(Pair(name: "danger (text) on \(sn)", fg: h(t.danger), bg: s, minimum: 4.5))141 out.append(Pair(name: "warning (text) on \(sn)", fg: h(t.warning), bg: s, minimum: 4.5))142 out.append(Pair(name: "success (text) on \(sn)", fg: h(t.success), bg: s, minimum: 4.5))143 // glyphs, focus and selection marks (3:1)144 out.append(Pair(name: "accent (glyph) on \(sn)", fg: h(t.accent), bg: s, minimum: 3))145 }146 // selected tool button: glyph on the 16 % accent tint over the surface147 let tint = WCAG.blend(h(t.accent), over: h(t.surface), alpha: 0.16)148 out.append(Pair(name: "accentText on selected tool button", fg: h(t.accentText), bg: tint, minimum: 3))149 out.append(Pair(name: "white label on accentFill (prominent button)", fg: 0xFFFFFF, bg: h(t.accentFill), minimum: 4.5))150 out.append(Pair(name: "textPrimary on error strip (danger 10 %)", fg: h(t.textPrimary), bg: WCAG.blend(h(t.danger), over: h(t.surface), alpha: 0.10), minimum: 4.5))151 // the grid152 let g = GridPalette.resolve(dark: dark)153 let bg = WCAG.hex(g.background)154 out.append(Pair(name: "grid text on grid background", fg: WCAG.hex(g.text), bg: bg, minimum: 4.5))155 out.append(Pair(name: "grid text on selection fill", fg: WCAG.hex(g.text), bg: WCAG.blend(WCAG.hex(g.selectionFill), over: bg, alpha: g.selectionFill.alphaComponent), minimum: 4.5))156 out.append(Pair(name: "grid error text on grid background", fg: WCAG.hex(g.error), bg: bg, minimum: 4.5))157 out.append(Pair(name: "header text on header", fg: WCAG.hex(g.headerText), bg: WCAG.hex(g.headerBackground), minimum: 4.5))158 out.append(Pair(name: "selected header text on selected header", fg: WCAG.hex(g.headerTextSelected), bg: WCAG.hex(g.headerSelected), minimum: 4.5))159 out.append(Pair(name: "selection border on grid background", fg: WCAG.hex(g.selectionBorder), bg: bg, minimum: 3))160 out.append(Pair(name: "frozen-pane line on grid background", fg: WCAG.hex(g.frozenLine), bg: bg, minimum: 3))161 // with Increase Contrast the structure lines themselves reach 3:1162 let hc = GridPalette.resolve(dark: dark, increaseContrast: true)163 out.append(Pair(name: "gridline on background (Increase Contrast)", fg: WCAG.hex(hc.gridline), bg: WCAG.hex(hc.background), minimum: 3))164 out.append(Pair(name: "header separator on header (Increase Contrast)", fg: WCAG.hex(hc.headerBorder), bg: WCAG.hex(hc.headerBackground), minimum: 3))165 out.append(Pair(name: "header text on header (Increase Contrast)", fg: WCAG.hex(hc.headerText), bg: WCAG.hex(hc.headerBackground), minimum: 7))166 out.append(Pair(name: "selection border on background (Increase Contrast)", fg: WCAG.hex(hc.selectionBorder), bg: WCAG.hex(hc.background), minimum: 4.5))167 return out168 }169170 @Test(arguments: [false, true]) func paletteMeetsWCAG(dark: Bool) {171 var table = "| Pair (\(dark ? "dark" : "light")) | Foreground | Background | Ratio | Required |\n|---|---|---|---|---|\n"172 for p in Self.pairs(dark: dark) {173 let r = WCAG.ratio(p.fg, p.bg)174 table += "| \(p.name) | #\(String(format: "%06X", p.fg)) | #\(String(format: "%06X", p.bg)) | \(String(format: "%.2f", r)) | \(p.minimum) |\n"175 #expect(r >= p.minimum, "\(p.name) (\(dark ? "dark" : "light")): \(String(format: "%.2f", r)) < \(p.minimum)")176 }177 print(table)178 }179180 @Test func wcagReferenceValues() {181 #expect(abs(WCAG.ratio(0x000000, 0xFFFFFF) - 21) < 0.001)182 #expect(abs(WCAG.ratio(0x777777, 0xFFFFFF) - 4.48) < 0.01)183 }184185 @Test func increaseContrastStrengthensTheGrid() {186 for dark in [false, true] {187 let normal = GridPalette.resolve(dark: dark), strong = GridPalette.resolve(dark: dark, increaseContrast: true)188 let bg = WCAG.hex(normal.background)189 #expect(WCAG.ratio(WCAG.hex(strong.gridline), bg) > WCAG.ratio(WCAG.hex(normal.gridline), bg))190 #expect(WCAG.ratio(WCAG.hex(strong.frozenLine), bg) > WCAG.ratio(WCAG.hex(normal.frozenLine), bg))191 #expect(strong.selectionFill.alphaComponent > normal.selectionFill.alphaComponent)192 #expect(strong.increasedContrast && !normal.increasedContrast)193 }194 }195}196197// MARK: - Localization198199@Suite struct LocalizationTests {200 @Test func missingKeyFallsBackToTheKeyText() {201 #expect(L("Thème déjà traduit par un module") == "Thème déjà traduit par un module")202 #expect(L("zz-not-a-key %d", 3) == "zz-not-a-key 3")203 #expect(L("") == "")204 #expect(LK("Paste") == "Paste")205 }206207 /// The catalog source: every key has a translated fr-CA unit with the same format arguments.208 @Test func catalogIsCompleteInCanadianFrench() throws {209 let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()210 .appendingPathComponent("Sources/SheetUI/Resources/Localizable.xcstrings")211 let doc = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])212 #expect(doc["sourceLanguage"] as? String == "en")213 let strings = try #require(doc["strings"] as? [String: [String: Any]])214 #expect(strings.count > 300)215 let spec = try NSRegularExpression(pattern: "%(?:\\d+\\$)?[-+0 #]*\\d*(?:\\.\\d+)?(?:ll|l|h)?([@dfsu])")216 func kinds(_ s: String) -> [String] {217 spec.matches(in: s, range: NSRange(s.startIndex..., in: s)).map { (s as NSString).substring(with: $0.range(at: 1)) }.sorted()218 }219 for (key, entry) in strings {220 let unit = ((entry["localizations"] as? [String: Any])?["fr-CA"] as? [String: Any])?["stringUnit"] as? [String: Any]221 #expect(unit?["state"] as? String == "translated", "no fr-CA translation for \(key)")222 let value = unit?["value"] as? String ?? ""223 #expect(!value.isEmpty, "empty fr-CA translation for \(key)")224 #expect(kinds(key) == kinds(value), "format arguments differ for \(key)")225 }226 for key in ["Paste Values", "Freeze Panes", "Merge Cells", "Wrap Text", "Typing", "Sort", "Insert", "Data", "Analyze", "Tools", "Number", "Lookup & Reference"] {227 #expect(strings[key] != nil, "missing key \(key)")228 }229 }230231 /// When the build compiled the catalog (Xcode, recent `swift build`), the French table answers.232 @Test func compiledFrenchTableWhenAvailable() {233 guard let fr = SheetUILocalization.bundle(forLanguage: "fr-CA") else { return }234 #expect(fr.localizedString(forKey: "Paste Values", value: nil, table: nil) == "Coller les valeurs")235 #expect(fr.localizedString(forKey: "Freeze Panes", value: nil, table: nil) == "Figer les volets")236 #expect(fr.localizedString(forKey: "%@: %@", value: nil, table: nil) == "%1$@\u{00A0}: %2$@")237 #expect(String(format: fr.localizedString(forKey: "selection %@, %d rows by %d columns", value: nil, table: nil), "B2:C4", 3, 2) == "sélection B2:C4, 3 lignes sur 2 colonnes")238 }239240 @MainActor @Test func undoNamesAreLocalizedThroughTheCatalog() {241 let s = WorkbookSession(workbook: Workbook(sheetNames: ["Sheet1"]), locale: Locale(identifier: "en_US"))242 let um = UndoManager()243 um.groupsByEvent = false244 s.undoManager = um245 um.beginUndoGrouping()246 s.select(cell: CellRef(0, 0)); s.beginEdit(text: "12"); #expect(s.commitEdit(move: nil))247 um.endUndoGrouping()248 #expect(um.undoActionName == L("Typing"))249 um.beginUndoGrouping(); s.toggleBold(); um.endUndoGrouping()250 #expect(um.undoActionName == L("Bold"))251 um.beginUndoGrouping(); s.perform("Custom feature label") { $0.editMeta(sheet: 0) { $0.showGridlines = false } }; um.endUndoGrouping()252 #expect(um.undoActionName == "Custom feature label")253 #expect(WorkspaceAction.Group.allCases.map(\.localizedTitle) == [L("Insert"), L("Data"), L("Analyze"), L("Tools")])254 }255}256257// MARK: - Accessibility tree258259/// Reads the accessibility tree of an offscreen window of this process through the system260/// accessibility API (AXUIElement), i.e. exactly what VoiceOver, Voice Control or Accessibility261/// Inspector receive. SwiftUI only materialises its elements for a real client, so walking262/// `accessibilityChildren()` on the hosting view is not enough.263///264/// The process must be allowed to use the accessibility API (System Settings ▸ Privacy & Security ▸265/// Accessibility, for the terminal or IDE that runs the tests); the tree tests are disabled otherwise.266@MainActor267enum AXTree {268 struct Node: Sendable { let role: String; let subrole: String; let label: String; let value: String; let identifier: String; let depth: Int }269270 static var isAvailable: Bool { AXIsProcessTrusted() }271272 static func read(pid: pid_t, windowTitle: String) -> [Node] {273 let app = AXUIElementCreateApplication(pid)274 AXUIElementSetMessagingTimeout(app, 5)275 func attribute(_ e: AXUIElement, _ name: String) -> CFTypeRef? {276 var v: CFTypeRef?277 return AXUIElementCopyAttributeValue(e, name as CFString, &v) == .success ? v : nil278 }279 func text(_ v: CFTypeRef?) -> String {280 if let s = v as? String { return s }281 if let n = v as? NSNumber { return n.stringValue }282 if let a = v as? NSAttributedString { return a.string }283 return ""284 }285 var out = [Node]()286 func walk(_ e: AXUIElement, _ depth: Int) {287 guard out.count < 5_000, depth < 60 else { return }288 var label = [kAXDescriptionAttribute, kAXTitleAttribute].map { text(attribute(e, $0)) }.first { !$0.isEmpty } ?? ""289 if label.isEmpty, let t = attribute(e, kAXTitleUIElementAttribute), CFGetTypeID(t) == AXUIElementGetTypeID() {290 let title = t as! AXUIElement291 label = [kAXValueAttribute, kAXTitleAttribute, kAXDescriptionAttribute].map { text(attribute(title, $0)) }.first { !$0.isEmpty } ?? ""292 }293 out.append(Node(role: text(attribute(e, kAXRoleAttribute)), subrole: text(attribute(e, kAXSubroleAttribute)), label: label, value: text(attribute(e, kAXValueAttribute)),294 identifier: text(attribute(e, kAXIdentifierAttribute)), depth: depth))295 for child in (attribute(e, kAXChildrenAttribute) as? [AXUIElement]) ?? [] { walk(child, depth + 1) }296 }297 for w in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] where text(attribute(w, kAXTitleAttribute)) == windowTitle { walk(w, 0) }298 return out299 }300301 /// The accessibility elements of `window`, as an assistive client sees them. For a client inside302 /// the same process the system API calls straight into AppKit on the calling thread, so this runs303 /// on the main thread like every real accessibility request.304 static func nodes(of window: NSWindow) -> [Node] { read(pid: getpid(), windowTitle: window.title) }305306 static func settle(_ seconds: Double = 0.3) { RunLoop.main.run(until: Date().addingTimeInterval(seconds)) }307308 /// Puts `view` in a window placed outside every screen and returns it with its accessibility elements.309 static func host<V: View>(_ view: V, size: NSSize = NSSize(width: 1280, height: 800)) -> (NSWindow, [Node]) {310 let app = NSApplication.shared311 if app.activationPolicy() == .prohibited { app.setActivationPolicy(.accessory); app.finishLaunching() }312 let window = NSWindow(contentRect: NSRect(origin: NSPoint(x: -30_000, y: -30_000), size: size), styleMask: [.titled, .resizable], backing: .buffered, defer: false)313 window.isReleasedWhenClosed = false314 window.title = "ax-test-" + UUID().uuidString315 let hosting = NSHostingView(rootView: view)316 hosting.frame = NSRect(origin: .zero, size: size)317 window.contentView = hosting318 window.orderFrontRegardless()319 hosting.layoutSubtreeIfNeeded()320 settle()321 return (window, isAvailable ? nodes(of: window) : [])322 }323}324325@MainActor @Suite(.serialized, .enabled(if: AXIsProcessTrusted(), "the test runner is not allowed to use the accessibility API")) struct AccessibilityTreeTests {326 static func demoSession() -> WorkbookSession {327 let s = WorkbookSession(workbook: Workbook(sheetNames: ["Budget", "Data"]), locale: Locale(identifier: "en_US"))328 let rows: [[String]] = [["Category", "Planned", "Actual"], ["Housing", "1850", "1850"], ["Groceries", "720", "784.35"], ["Total", "=SUM(B2:B3)", "=SUM(C2:C3)"]]329 s.perform("Demo") { e in330 for (r, row) in rows.enumerated() { for (c, text) in row.enumerated() { try? e.setInput(sheet: 0, row: r, col: c, text, parser: s.parser) } }331 }332 return s333 }334335 /// Parts of standard controls that the system describes itself through their subrole (window336 /// title-bar buttons, scroller pages, stepper arrows): they carry no label of ours by design.337 static let systemSubroles: Set<String> = ["AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton", "AXIncrementPage", "AXDecrementPage",338 "AXIncrementArrow", "AXDecrementArrow", "AXToolbarButton"]339340 static let controlRoles: Set<String> = ["AXButton", "AXTextField", "AXPopUpButton", "AXCheckBox", "AXMenuButton", "AXRadioButton", "AXSlider", "AXIncrementor", "AXDisclosureTriangle", "AXComboBox"]341342 /// Every control of the workbook window (toolbar, formula bar, navigator, format inspector, tabs,343 /// status bar, grid) has a non-empty accessibility label. Prints the counts per role.344 @Test(arguments: ["format", "functions"]) func everyControlOfTheWorkbookWindowIsLabelled(pane: String) throws {345 let session = Self.demoSession()346 session.inspectorPane = pane347 let (window, nodes) = AXTree.host(WorkbookView(session: session))348 defer { window.close() }349 var counts: [String: Int] = [:], unlabelled: [String] = []350 var systemParts = 0351 for n in nodes where Self.controlRoles.contains(n.role) {352 if Self.systemSubroles.contains(n.subrole) { systemParts += 1; continue }353 counts[n.role, default: 0] += 1354 if n.label.trimmingCharacters(in: .whitespaces).isEmpty { unlabelled.append("\(n.role)/\(n.subrole) id=\(n.identifier) value=\(n.value)") }355 }356 print("AX audit [\(pane) inspector]: \(nodes.count) elements; controls by role: \(counts.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: ", ")); system-described parts (scroller pages, stepper arrows, title-bar buttons): \(systemParts); unlabelled: \(unlabelled.count)")357 #expect(unlabelled.isEmpty, "unlabelled controls: \(unlabelled.joined(separator: "; "))")358 #expect(counts["AXButton", default: 0] >= 15)359 #expect(counts["AXTextField", default: 0] >= 2)360 #expect(nodes.contains { $0.identifier == "grid" && $0.role == "AXTable" })361 #expect(nodes.contains { $0.identifier == "formula-bar" && !$0.label.isEmpty })362 #expect(nodes.contains { $0.identifier == "name-box" && !$0.label.isEmpty })363 }364365 @Test func findBarControlsAreLabelled() {366 let session = Self.demoSession()367 let (window, _) = AXTree.host(WorkbookView(session: session))368 defer { window.close() }369 NotificationCenter.default.post(name: .orixShowFind, object: session)370 AXTree.settle(0.5)371 let nodes = AXTree.nodes(of: window)372 let controls = nodes.filter { Self.controlRoles.contains($0.role) && !Self.systemSubroles.contains($0.subrole) }373 #expect(controls.contains { $0.identifier == "find-field" })374 #expect(controls.filter { $0.role == "AXCheckBox" }.count >= 4)375 #expect(controls.allSatisfy { !$0.label.isEmpty }, "unlabelled: \(controls.filter { $0.label.isEmpty })")376 }377378 @Test func gridDescribesCellsWithHeaderContext() throws {379 let session = Self.demoSession()380 let (window, _) = AXTree.host(WorkbookView(session: session))381 defer { window.close() }382 let grid = try #require(session.gridView)383 session.select(cell: CellRef(a1: "B3")!)384 #expect(grid.accessibilityRole() == .table)385 #expect(grid.accessibilityLabel() == L("%@, spreadsheet grid", "Budget"))386 #expect(grid.accessibilityCellLabel(CellRef(a1: "B3")!) == L("%@, %@ column", "B3", "Planned"))387 #expect(grid.accessibilityCellLabel(CellRef(a1: "B1")!) == "B1") // the header row itself388 let value = try #require(grid.accessibilityValue() as? String)389 #expect(value.contains("B3") && value.contains("Planned") && value.contains("720"))390 // formula and selected range are part of the description391 session.select(RangeRef(a1: "B4:C4")!, active: CellRef(a1: "B4")!)392 let v2 = try #require(grid.accessibilityValue() as? String)393 #expect(v2.contains("=SUM(B2:B3)") && v2.contains("B4:C4") && v2.contains(grid.displayText(3, 1)))394 // children: the visible non-empty cells, each with a label, a value and a frame395 let children = try #require(grid.accessibilityChildren()).compactMap { $0 as? GridCellElement }396 #expect(children.count == 12)397 #expect(children.allSatisfy { !($0.accessibilityLabel() ?? "").isEmpty && $0.accessibilityRole() == .cell && $0.accessibilityFrame().width > 0 })398 let c3 = try #require(children.first { $0.ref == CellRef(a1: "C3")! })399 #expect(c3.accessibilityLabel() == L("%@, %@ column", "C3", "Actual"))400 #expect((c3.accessibilityValue() as? String) == grid.displayText(2, 2))401 #expect(grid.displayText(2, 2).hasPrefix("784"))402 #expect((grid.accessibilityFocusedUIElement as? GridCellElement)?.ref == CellRef(a1: "B4")!)403 #expect((grid.accessibilitySelectedCells() ?? []).count == 2)404 // an empty active cell stays reachable405 session.select(cell: CellRef(a1: "E7")!)406 #expect((try #require(grid.accessibilityChildren())).compactMap { $0 as? GridCellElement }.contains { $0.ref == CellRef(a1: "E7")! })407 #expect((grid.accessibilityValue() as? String)?.contains(L("empty")) == true)408 }409410 @Test func pressingACellStartsEditingAndChildrenStayBounded() throws {411 let session = Self.demoSession()412 session.perform("Fill") { e in413 for r in 10..<400 { for c in 0..<40 { e.set(sheet: 0, row: r, col: c, .value(.number(Double(r * c)))) } }414 }415 let (window, _) = AXTree.host(WorkbookView(session: session))416 defer { window.close() }417 let grid = try #require(session.gridView)418 grid.setZoom(0.25) // as many cells on screen as possible419 let children = try #require(grid.accessibilityChildren())420 #expect(children.count <= GridView.maxAccessibilityChildren + 2)421 grid.setZoom(1)422 let cell = grid.accessibilityElement(for: CellRef(a1: "C3")!)423 #expect(cell.accessibilityPerformPress())424 #expect(session.isEditing && session.editCell == CellRef(a1: "C3")! && session.editText.hasPrefix("784"))425 session.cancelEdit()426 cell.setAccessibilityFocused(true)427 #expect(session.selection.active == CellRef(a1: "C3")!)428 #expect(grid.accessibilityPerformPress() && session.isEditing)429 session.cancelEdit()430 }431432 @Test func componentsExposeLocalizedLabelsAndState() {433 let (window, nodes) = AXTree.host(VStack {434 ToolButton("bold", help: "Bold (⌘B)", isOn: true) {}435 ToolButton("italic", help: "Italic (⌘I)", isOn: false) {}436 ToolButton("plus", localizedHelp: "Déjà traduit") {}437 SectionHeader(localized: "Titre du module")438 InspectorSection(localized: "Section du module") { Text("x") }439 MetricChip(localized: "Lignes", "12")440 MetricChip("Sum", "42")441 EmptyStateView(systemImage: "tray", localizedTitle: "Rien ici", localizedMessage: "Ajoutez un élément.", localizedActionTitle: "Ajouter") {}442 }, size: NSSize(width: 500, height: 500))443 defer { window.close() }444 let buttons = nodes.filter { $0.role == "AXButton" }445 #expect(buttons.contains { $0.label == L("Bold (⌘B)") && $0.value == L("On") })446 #expect(buttons.contains { $0.label == L("Italic (⌘I)") && $0.value == L("Off") })447 #expect(buttons.contains { $0.label == "Déjà traduit" && $0.value.isEmpty })448 #expect(buttons.contains { $0.label == "Ajouter" })449 let texts = nodes.map { $0.label + "|" + $0.value }.joined(separator: "\n")450 #expect(texts.contains("TITRE DU MODULE") && texts.contains("SECTION DU MODULE") && texts.contains("Rien ici"))451 #expect(nodes.contains { $0.label == "Lignes" && $0.value == "12" })452 #expect(nodes.contains { $0.label == L("Sum") && $0.value == "42" })453 }454}455