Crossmate/Views/Puzzle/GridAccessibility.swift (24943B)
1import SwiftUI
2
3
4
5struct CellAccessibilityDescriber {
6 let puzzle: Puzzle
7
8
9
10 let authorNames: [String: String]
11
12
13
14
15
16 func label(atRow row: Int, atCol col: Int) -> String {
17 var parts: [String] = []
18 for direction in [Puzzle.Direction.across, .down] {
19 let cells = puzzle.wordCells(atRow: row, col: col, direction: direction)
20 guard let number = cells.first?.number,
21 let index = cells.firstIndex(where: { $0.row == row && $0.col == col })
22 else { continue }
23 let name = direction == .across ? "Across" : "Down"
24 parts.append("\(number) \(name), letter \(index + 1) of \(cells.count)")
25 }
26 if parts.isEmpty {
27 parts.append("Row \(row + 1), Column \(col + 1)")
28 }
29 let special = puzzle.cells[row][col].special
30 if special == .circled { parts.append("circled") }
31 if special == .shaded { parts.append("shaded") }
32 return parts.joined(separator: "; ")
33 }
34
35
36
37
38 func clueLabel(number: Int, direction: Puzzle.Direction) -> String? {
39 let clues = direction == .across ? puzzle.acrossClues : puzzle.downClues
40 guard let clue = clues.first(where: { $0.number == number }) else { return nil }
41 let name = direction == .across ? "Across" : "Down"
42 return "\(number) \(name): \(clue.text)"
43 }
44
45
46
47
48
49
50 func clueAnnouncement(
51 atRow row: Int,
52 atCol col: Int,
53 direction: Puzzle.Direction,
54 squares: [[Square]]
55 ) -> String? {
56 let cells = puzzle.wordCells(atRow: row, col: col, direction: direction)
57 guard let number = cells.first?.number,
58 let heading = clueLabel(number: number, direction: direction)
59 else { return nil }
60 let filled = cells.count { !squares[$0.row][$0.col].entry.isEmpty }
61 var progress = "\(cells.count) letters"
62 if filled == cells.count {
63 progress += ", all filled"
64 } else if filled > 0 {
65 progress += ", \(filled) filled"
66 }
67 return "\(heading). \(progress)"
68 }
69
70
71
72
73
74
75 func peerFillAnnouncement(
76 playerName: String,
77 positions: Set<GridPosition>,
78 squares: [[Square]]
79 ) -> String? {
80 guard let first = positions.first else { return nil }
81 for direction in [Puzzle.Direction.across, .down] {
82 let cells = puzzle.wordCells(atRow: first.row, col: first.col, direction: direction)
83 guard let number = cells.first?.number else { continue }
84 let wordPositions = Set(cells.map { GridPosition(row: $0.row, col: $0.col) })
85 guard positions.isSubset(of: wordPositions) else { continue }
86 let word = "\(number) \(direction == .across ? "Across" : "Down")"
87 let complete = cells.allSatisfy {
88 !squares[$0.row][$0.col].entry.isEmpty || $0.expectsBlank
89 }
90 if complete { return "\(playerName) filled \(word)" }
91 if positions.count == 1 { return "\(playerName) filled a square in \(word)" }
92 return "\(playerName) filled \(positions.count) squares in \(word)"
93 }
94 return positions.count == 1
95 ? "\(playerName) filled a square"
96 : "\(playerName) filled \(positions.count) squares"
97 }
98
99
100
101
102 func checkAnnouncement(for cells: [Puzzle.Cell], squares: [[Square]]) -> String {
103 let open = cells.filter { !$0.isBlock }
104 let filled = open.filter { !squares[$0.row][$0.col].entry.isEmpty }
105 guard !filled.isEmpty else { return "Nothing to check" }
106 let wrong = filled.count { squares[$0.row][$0.col].mark.isCheckedWrong }
107 if open.count == 1 {
108 return wrong > 0 ? "Incorrect" : "Correct"
109 }
110 if wrong > 0 {
111 return wrong == 1 ? "1 square incorrect" : "\(wrong) squares incorrect"
112 }
113 let empty = open.count - filled.count
114 if empty == 0 { return "All correct" }
115 return empty == 1
116 ? "No mistakes, 1 square empty"
117 : "No mistakes, \(empty) squares empty"
118 }
119
120
121
122 func revealAnnouncement(atRow row: Int, atCol col: Int, squares: [[Square]]) -> String? {
123 let entry = squares[row][col].entry
124 guard !entry.isEmpty else { return nil }
125 return "Revealed \(entry)"
126 }
127
128
129
130
131
132 func completionAnnouncement(for state: Game.CompletionState) -> String? {
133 switch state {
134 case .incomplete: nil
135 case .filledWithErrors: "The grid is full, but something isn't right"
136 case .solved: "Puzzle solved. Congratulations!"
137 }
138 }
139
140
141
142
143
144 func value(for square: Square) -> String {
145 guard !square.entry.isEmpty else { return "Empty" }
146 var parts = [square.entry]
147 if square.mark.isPencil { parts.append("draft") }
148 if square.mark.isRevealed { parts.append("revealed") }
149 if square.mark.isCheckedWrong { parts.append("incorrect") }
150 if let authorID = square.letterAuthorID, let name = authorNames[authorID] {
151 parts.append("filled by \(name)")
152 }
153 return parts.joined(separator: ", ")
154 }
155}
156
157extension View {
158
159
160
161
162
163 func puzzleGridAccessibility(
164 session: PlayerSession,
165 roster: PlayerRoster,
166 revealConfirmation: RevealConfirmation,
167 showsSharedAnnotations: Bool,
168 isReplaying: Bool,
169 gridSize: CGSize,
170 spacing: CGFloat
171 ) -> some View {
172 modifier(PuzzleGridAccessibility(
173 session: session,
174 roster: roster,
175 revealConfirmation: revealConfirmation,
176 showsSharedAnnotations: showsSharedAnnotations,
177 isReplaying: isReplaying,
178 gridSize: gridSize,
179 spacing: spacing
180 ))
181 }
182}
183
184private struct PuzzleGridAccessibility: ViewModifier {
185 let session: PlayerSession
186 let roster: PlayerRoster
187 let revealConfirmation: RevealConfirmation
188 let showsSharedAnnotations: Bool
189 let isReplaying: Bool
190 let gridSize: CGSize
191 let spacing: CGFloat
192
193 @Environment(\.accessibilityVoiceOverEnabled) private var voiceOverEnabled
194 @AccessibilityFocusState private var focusedCell: GridPosition?
195
196 @Namespace private var rotorNamespace
197
198
199
200 @State private var pendingPeerFills: [String: Set<GridPosition>] = [:]
201 @State private var peerFillFlushTask: Task<Void, Never>?
202
203
204
205
206
207
208 private var isActive: Bool {
209 if voiceOverEnabled { return true }
210 #if DEBUG
211 return ProcessInfo.processInfo.arguments.contains("-ForceGridAccessibility")
212 #else
213 return false
214 #endif
215 }
216
217 func body(content: Content) -> some View {
218
219
220
221
222 if isActive, !isReplaying, gridSize != .zero {
223 content
224 .accessibilityChildren { cellElements }
225
226
227
228 .onChange(of: selection) { _, newValue in
229 focusedCell = newValue
230 }
231
232
233
234
235
236
237 .onChange(of: focusedCell) { _, newValue in
238 guard let newValue, newValue != selection else { return }
239 session.select(row: newValue.row, col: newValue.col)
240 }
241
242
243
244
245 .onChange(of: currentClueRef) { _, newValue in
246 guard newValue != nil else { return }
247 announceCurrentClue()
248 }
249 .accessibilityRotor("Across clues") { clueRotorEntries(for: .across) }
250 .accessibilityRotor("Down clues") { clueRotorEntries(for: .down) }
251 .accessibilityRotor("Incomplete clues") { incompleteClueRotorEntries }
252
253
254
255
256 .onChange(of: session.game.squares) { oldValue, newValue in
257 collectPeerFills(from: oldValue, to: newValue)
258 }
259 .onChange(of: session.completionEvent) { _, event in
260 guard let event else { return }
261 announce(describer.completionAnnouncement(for: event.state))
262 }
263 .onAppear { focusedCell = selection }
264 .onDisappear { peerFillFlushTask?.cancel() }
265 } else {
266 content
267 }
268 }
269
270 private var selection: GridPosition {
271 GridPosition(row: session.selectedRow, col: session.selectedCol)
272 }
273
274
275
276
277
278 private var currentClueRef: Puzzle.ClueRef? {
279 session.puzzle.clue(
280 atRow: session.selectedRow,
281 col: session.selectedCol,
282 direction: session.direction
283 ).map { Puzzle.ClueRef(number: $0.number, direction: session.direction) }
284 }
285
286 private var describer: CellAccessibilityDescriber {
287 CellAccessibilityDescriber(puzzle: session.puzzle, authorNames: [:])
288 }
289
290 private func announceCurrentClue() {
291 announce(describer.clueAnnouncement(
292 atRow: session.selectedRow,
293 atCol: session.selectedCol,
294 direction: session.direction,
295 squares: session.game.squares
296 ))
297 }
298
299
300
301
302
303 private func announce(_ text: String?, lowPriority: Bool = false) {
304 guard let text else { return }
305 if lowPriority {
306 var attributed = AttributedString(text)
307 attributed.accessibilitySpeechAnnouncementPriority = .low
308 AccessibilityNotification.Announcement(attributed).post()
309 } else {
310 AccessibilityNotification.Announcement(text).post()
311 }
312 }
313
314
315
316 private func checkAndAnnounce(wholeWord: Bool) {
317 let cells: [Puzzle.Cell]
318 if wholeWord {
319 session.checkCurrentWord()
320 cells = session.puzzle.wordCells(
321 atRow: session.selectedRow,
322 col: session.selectedCol,
323 direction: session.direction
324 )
325 } else {
326 session.checkSquare()
327 cells = [session.puzzle.cells[session.selectedRow][session.selectedCol]]
328 }
329 announce(describer.checkAnnouncement(for: cells, squares: session.game.squares))
330 }
331
332
333
334
335
336
337
338 private func collectPeerFills(from old: [[Square]], to new: [[Square]]) {
339 guard old.count == new.count else { return }
340 let localAuthorID = roster.entries.first(where: { $0.isLocal })?.authorID
341 var found = false
342 for row in 0..<new.count {
343 guard old[row].count == new[row].count else { continue }
344 for col in 0..<new[row].count {
345 let after = new[row][col]
346 guard after.entry != old[row][col].entry,
347 !after.entry.isEmpty,
348 let author = after.letterAuthorID,
349 author != localAuthorID
350 else { continue }
351 pendingPeerFills[author, default: []].insert(GridPosition(row: row, col: col))
352 found = true
353 }
354 }
355 guard found else { return }
356 peerFillFlushTask?.cancel()
357 peerFillFlushTask = Task {
358 try? await Task.sleep(for: .seconds(2))
359 guard !Task.isCancelled else { return }
360 flushPeerFills()
361 }
362 }
363
364 private func flushPeerFills() {
365 let fills = pendingPeerFills
366 pendingPeerFills = [:]
367 guard !fills.isEmpty else { return }
368 let names = Dictionary(
369 roster.entries.map { ($0.authorID, $0.name) },
370 uniquingKeysWith: { first, _ in first }
371 )
372 let squares = session.game.squares
373 let texts = fills.keys.sorted().compactMap { author in
374 describer.peerFillAnnouncement(
375 playerName: names[author] ?? "A collaborator",
376 positions: fills[author] ?? [],
377 squares: squares
378 )
379 }
380 guard !texts.isEmpty else { return }
381 announce(texts.joined(separator: ". "), lowPriority: true)
382 }
383
384
385
386 private struct ClueRotorEntry: Identifiable {
387 let ref: Puzzle.ClueRef
388 let label: String
389 let position: GridPosition
390
391 var id: Puzzle.ClueRef { ref }
392 }
393
394 private func clueRotorEntries(for refs: [Puzzle.ClueRef]) -> [ClueRotorEntry] {
395 let puzzle = session.puzzle
396 let describer = CellAccessibilityDescriber(puzzle: puzzle, authorNames: [:])
397 return refs.compactMap { ref in
398 guard let cell = puzzle.cell(numbered: ref.number),
399 let label = describer.clueLabel(number: ref.number, direction: ref.direction)
400 else { return nil }
401 return ClueRotorEntry(
402 ref: ref,
403 label: label,
404 position: GridPosition(row: cell.row, col: cell.col)
405 )
406 }
407 }
408
409
410
411
412
413 @AccessibilityRotorContentBuilder
414 private func clueRotorEntries(
415 for direction: Puzzle.Direction
416 ) -> some AccessibilityRotorContent {
417 let clues = direction == .across ? session.puzzle.acrossClues : session.puzzle.downClues
418 let refs = clues.map { Puzzle.ClueRef(number: $0.number, direction: direction) }
419 ForEach(clueRotorEntries(for: refs)) { entry in
420 AccessibilityRotorEntry(
421 Text(entry.label),
422 id: entry.position,
423 in: rotorNamespace
424 ) {
425 session.selectClue(direction: entry.ref.direction, number: entry.ref.number)
426 }
427 }
428 }
429
430
431
432
433
434 @AccessibilityRotorContentBuilder
435 private var incompleteClueRotorEntries: some AccessibilityRotorContent {
436 ForEach(clueRotorEntries(for: incompleteClueRefs)) { entry in
437 AccessibilityRotorEntry(
438 Text(entry.label),
439 id: entry.position,
440 in: rotorNamespace
441 ) {
442 session.selectClue(direction: entry.ref.direction, number: entry.ref.number)
443 }
444 }
445 }
446
447 private var incompleteClueRefs: [Puzzle.ClueRef] {
448 let puzzle = session.puzzle
449 let squares = session.game.squares
450 var refs: [Puzzle.ClueRef] = []
451 for direction in [Puzzle.Direction.across, .down] {
452 let clues = direction == .across ? puzzle.acrossClues : puzzle.downClues
453 for clue in clues {
454 guard let start = puzzle.cell(numbered: clue.number) else { continue }
455 let cells = puzzle.wordCells(
456 atRow: start.row, col: start.col, direction: direction
457 )
458 let isIncomplete = cells.contains {
459 squares[$0.row][$0.col].entry.isEmpty && !$0.expectsBlank
460 }
461 if isIncomplete {
462 refs.append(Puzzle.ClueRef(number: clue.number, direction: direction))
463 }
464 }
465 }
466 return refs
467 }
468
469
470
471
472
473 private var cellElements: some View {
474 let puzzle = session.puzzle
475 let geometry = PuzzleGridGeometry(
476 size: gridSize,
477 columns: puzzle.width,
478 rows: puzzle.height,
479 spacing: spacing
480 )
481 let describer = CellAccessibilityDescriber(
482 puzzle: puzzle,
483 authorNames: authorNames
484 )
485 let selection = self.selection
486 return ZStack(alignment: .topLeading) {
487 ForEach(openPositions, id: \.self) { pos in
488 let rect = geometry.cellRect(row: pos.row, col: pos.col)
489 Color.clear
490 .accessibilityElement()
491 .accessibilityLabel(describer.label(atRow: pos.row, atCol: pos.col))
492 .accessibilityValue(describer.value(for: session.game.squares[pos.row][pos.col]))
493 .accessibilityAddTraits(pos == selection ? .isSelected : [])
494
495
496 .accessibilityAction {
497 session.select(row: pos.row, col: pos.col)
498 }
499 .accessibilityFocused($focusedCell, equals: pos)
500 .accessibilityRotorEntry(id: pos, in: rotorNamespace)
501
502
503
504
505
506
507
508
509 .accessibilityActions {
510 Button("Switch Direction") { session.toggleDirection() }
511 if session.mutator.isEditable, session.game.completionState != .solved {
512 Button("Check Square") { checkAndAnnounce(wholeWord: false) }
513 Button("Check Word") { checkAndAnnounce(wholeWord: true) }
514 Button("Reveal Square") { revealConfirmation.request(.square) }
515 }
516 }
517 .frame(width: rect.width, height: rect.height)
518 .position(x: rect.midX, y: rect.midY)
519 }
520 }
521 .frame(width: gridSize.width, height: gridSize.height, alignment: .topLeading)
522 }
523
524 private var openPositions: [GridPosition] {
525 let puzzle = session.puzzle
526 var positions: [GridPosition] = []
527 for row in 0..<puzzle.height {
528 for col in 0..<puzzle.width where !puzzle.cells[row][col].isBlock {
529 positions.append(GridPosition(row: row, col: col))
530 }
531 }
532 return positions
533 }
534
535
536
537 private var authorNames: [String: String] {
538 guard showsSharedAnnotations else { return [:] }
539 return Dictionary(
540 roster.entries.map { ($0.authorID, $0.isLocal ? "you" : $0.name) },
541 uniquingKeysWith: { first, _ in first }
542 )
543 }
544}