Skip to main content

ftui_a11y/
tree.rs

1//! Accessibility tree construction and diffing.
2//!
3//! During each render pass, widgets push [`A11yNodeInfo`] into an
4//! [`A11yTreeBuilder`]. At the end of the pass the builder is consumed
5//! to produce an immutable [`A11yTree`] snapshot. Consecutive snapshots
6//! can be diffed to produce an [`A11yTreeDiff`] describing exactly what
7//! changed -- this is the data a platform accessibility bridge would
8//! push to the OS.
9
10use ahash::{AHashMap, AHashSet};
11
12use crate::node::{A11yNodeInfo, A11yRole, LiveRegion};
13
14const MAX_TRAVERSAL_DEPTH: usize = 1000;
15
16// ── Builder ────────────────────────────────────────────────────────────
17
18/// Accumulates accessibility nodes during a render pass.
19///
20/// Usage:
21/// 1. Create with [`A11yTreeBuilder::new`].
22/// 2. Add nodes via [`add_node`](Self::add_node).
23/// 3. Optionally designate the root and focused node.
24/// 4. Call [`build`](Self::build) to freeze.
25#[derive(Debug, Clone)]
26pub struct A11yTreeBuilder {
27    nodes: AHashMap<u64, A11yNodeInfo>,
28    root: Option<u64>,
29    focused: Option<u64>,
30}
31
32impl Default for A11yTreeBuilder {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl A11yTreeBuilder {
39    /// Create an empty builder.
40    #[inline]
41    pub fn new() -> Self {
42        Self {
43            nodes: AHashMap::new(),
44            root: None,
45            focused: None,
46        }
47    }
48
49    /// The explicitly focused node, if `set_focused` was called.
50    #[inline]
51    #[must_use]
52    pub fn focused(&self) -> Option<u64> {
53        self.focused
54    }
55
56    /// Create a builder pre-sized for `capacity` nodes (avoids reallocs).
57    #[inline]
58    pub fn with_capacity(capacity: usize) -> Self {
59        Self {
60            nodes: AHashMap::with_capacity(capacity),
61            root: None,
62            focused: None,
63        }
64    }
65
66    /// Insert or replace a node.
67    #[inline]
68    pub fn add_node(&mut self, node: A11yNodeInfo) {
69        self.nodes.insert(node.id, node);
70    }
71
72    /// Designate the root node ID.
73    #[inline]
74    pub fn set_root(&mut self, id: u64) {
75        self.root = Some(id);
76    }
77
78    /// Designate the currently focused node.
79    #[inline]
80    pub fn set_focused(&mut self, id: Option<u64>) {
81        self.focused = id;
82    }
83
84    /// The root id chosen so far, if any.
85    #[inline]
86    #[must_use]
87    pub fn root(&self) -> Option<u64> {
88        self.root
89    }
90
91    /// A node added so far.
92    #[inline]
93    #[must_use]
94    pub fn node(&self, id: u64) -> Option<&A11yNodeInfo> {
95        self.nodes.get(&id)
96    }
97
98    /// Mutable access to a node added so far (used to wire children in).
99    #[inline]
100    pub fn node_mut(&mut self, id: u64) -> Option<&mut A11yNodeInfo> {
101        self.nodes.get_mut(&id)
102    }
103
104    /// Number of nodes added so far.
105    #[inline]
106    #[must_use]
107    pub fn len(&self) -> usize {
108        self.nodes.len()
109    }
110
111    /// Whether no node has been added.
112    #[inline]
113    #[must_use]
114    pub fn is_empty(&self) -> bool {
115        self.nodes.is_empty()
116    }
117
118    /// Consume the builder and produce an immutable tree snapshot.
119    #[inline]
120    pub fn build(self) -> A11yTree {
121        A11yTree {
122            nodes: self.nodes,
123            root: self.root,
124            focused: self.focused,
125        }
126    }
127}
128
129// ── Immutable tree ─────────────────────────────────────────────────────
130
131/// Immutable snapshot of the accessibility tree after a render pass.
132///
133/// The tree is a flat map keyed by node ID; parent/child relationships
134/// are encoded inside each [`A11yNodeInfo`]. This makes traversal O(1)
135/// per hop and diffing O(n) in the number of nodes.
136#[derive(Debug, Clone)]
137pub struct A11yTree {
138    nodes: AHashMap<u64, A11yNodeInfo>,
139    root: Option<u64>,
140    focused: Option<u64>,
141}
142
143impl Default for A11yTree {
144    fn default() -> Self {
145        Self::empty()
146    }
147}
148
149impl A11yTree {
150    /// Create an empty tree (no nodes, no root, no focus).
151    #[inline]
152    pub fn empty() -> Self {
153        Self {
154            nodes: AHashMap::new(),
155            root: None,
156            focused: None,
157        }
158    }
159
160    /// Look up a node by ID.
161    #[inline]
162    pub fn node(&self, id: u64) -> Option<&A11yNodeInfo> {
163        self.nodes.get(&id)
164    }
165
166    /// The root node, if set and present.
167    #[inline]
168    pub fn root(&self) -> Option<&A11yNodeInfo> {
169        self.root.and_then(|id| self.nodes.get(&id))
170    }
171
172    /// The root node ID, if set.
173    #[inline]
174    pub fn root_id(&self) -> Option<u64> {
175        self.root
176    }
177
178    /// The focused node, if set and present.
179    #[inline]
180    pub fn focused(&self) -> Option<&A11yNodeInfo> {
181        self.focused.and_then(|id| self.nodes.get(&id))
182    }
183
184    /// The focused node ID, if set.
185    #[inline]
186    pub fn focused_id(&self) -> Option<u64> {
187        self.focused
188    }
189
190    /// Iterate over all nodes in unspecified order.
191    #[inline]
192    pub fn nodes(&self) -> impl Iterator<Item = &A11yNodeInfo> {
193        self.nodes.values()
194    }
195
196    /// Total number of nodes.
197    #[inline]
198    pub fn node_count(&self) -> usize {
199        self.nodes.len()
200    }
201
202    /// Whether the tree contains zero nodes.
203    #[inline]
204    pub fn is_empty(&self) -> bool {
205        self.nodes.is_empty()
206    }
207
208    /// Get all children of a given node ID, in the order stored.
209    pub fn children_of(&self, id: u64) -> Vec<&A11yNodeInfo> {
210        self.nodes
211            .get(&id)
212            .map(|n| {
213                n.children
214                    .iter()
215                    .filter_map(|cid| self.nodes.get(cid))
216                    .collect()
217            })
218            .unwrap_or_default()
219    }
220
221    /// One text line per node in `order` (document order as collected by the
222    /// frame): `{indent}{role:?} "{name}" [{states}] @{x},{y} {w}x{h}`, with
223    /// the indent equal to the node's depth. This is the format the
224    /// accessibility panel and the tree snapshots share. Ids missing from the
225    /// tree are skipped.
226    #[must_use]
227    pub fn dump_text(&self, order: &[u64]) -> String {
228        let mut out = String::new();
229        for &id in order {
230            let Some(node) = self.node(id) else {
231                continue;
232            };
233            // `ancestors` includes the node itself, so depth = chain - 1.
234            let depth = self.ancestors(id).len().saturating_sub(1);
235            let mut states: Vec<&str> = Vec::new();
236            if node.state.focused {
237                states.push("focused");
238            }
239            if node.state.disabled {
240                states.push("disabled");
241            }
242            if node.state.selected {
243                states.push("selected");
244            }
245            match node.state.checked {
246                Some(true) => states.push("checked"),
247                Some(false) => states.push("unchecked"),
248                None => {}
249            }
250            match node.state.expanded {
251                Some(true) => states.push("expanded"),
252                Some(false) => states.push("collapsed"),
253                None => {}
254            }
255            if node.state.readonly {
256                states.push("readonly");
257            }
258            if node.state.required {
259                states.push("required");
260            }
261            if node.state.busy {
262                states.push("busy");
263            }
264            let name = node.name.as_deref().unwrap_or("");
265            let b = node.bounds;
266            out.push_str(&format!(
267                "{}{:?} \"{}\" [{}] @{},{} {}x{}\n",
268                "  ".repeat(depth),
269                node.role,
270                name,
271                states.join(","),
272                b.x,
273                b.y,
274                b.width,
275                b.height
276            ));
277        }
278        out
279    }
280
281    /// Walk ancestors from `id` up to the root (inclusive), returning
282    /// their IDs. Returns an empty vec if `id` is not found.
283    ///
284    /// Includes cycle protection: stops after visiting 1000 nodes to
285    /// prevent infinite loops on malformed cyclic parent chains.
286    pub fn ancestors(&self, id: u64) -> Vec<u64> {
287        let mut path = Vec::new();
288        let mut visited = AHashSet::new();
289        let mut current = Some(id);
290        while let Some(cid) = current {
291            if path.len() >= MAX_TRAVERSAL_DEPTH || !visited.insert(cid) {
292                break;
293            }
294            if let Some(node) = self.nodes.get(&cid) {
295                path.push(cid);
296                current = node.parent;
297            } else {
298                break;
299            }
300        }
301        path
302    }
303
304    /// Produce deterministic screen-reader mirror lines for this snapshot.
305    ///
306    /// Traversal starts at the root and follows explicit child order. Any
307    /// disconnected nodes are appended by sorted node ID so malformed partial
308    /// trees still produce stable diagnostics. Presentational nodes are skipped.
309    pub fn screen_reader_mirror(&self, policy: ScreenReaderPolicy) -> ScreenReaderMirror {
310        let mut order = Vec::with_capacity(self.nodes.len());
311        let mut visited = AHashSet::with_capacity(self.nodes.len());
312
313        if let Some(root) = self.root {
314            self.collect_mirror_order(root, 0, &mut visited, &mut order);
315        }
316
317        let mut disconnected: Vec<u64> = self
318            .nodes
319            .keys()
320            .copied()
321            .filter(|id| !visited.contains(id))
322            .collect();
323        disconnected.sort_unstable();
324
325        for id in disconnected {
326            self.collect_mirror_order(id, 0, &mut visited, &mut order);
327        }
328
329        let mut lines = Vec::new();
330        let mut omitted_nodes = 0;
331
332        for (id, depth) in order {
333            let Some(node) = self.nodes.get(&id) else {
334                continue;
335            };
336            if node.role == A11yRole::Presentation {
337                continue;
338            }
339            if lines.len() >= policy.max_mirror_nodes {
340                omitted_nodes += 1;
341                continue;
342            }
343
344            let indent = "  ".repeat(depth.min(16));
345            let summary = node_summary(node, self.focused == Some(id), true, &[]);
346            let mut line = String::with_capacity(indent.len() + summary.len());
347            line.push_str(&indent);
348            line.push_str(&summary);
349            lines.push(limit_text(line, policy.max_text_chars));
350        }
351
352        ScreenReaderMirror {
353            lines,
354            omitted_nodes,
355        }
356    }
357
358    /// Extract bounded screen-reader announcements from the previous snapshot.
359    pub fn screen_reader_announcements_since(
360        &self,
361        previous: &A11yTree,
362        policy: ScreenReaderPolicy,
363    ) -> ScreenReaderAnnouncements {
364        self.diff(previous)
365            .screen_reader_announcements(self, policy)
366    }
367
368    fn collect_mirror_order(
369        &self,
370        id: u64,
371        depth: usize,
372        visited: &mut AHashSet<u64>,
373        order: &mut Vec<(u64, usize)>,
374    ) {
375        if depth >= MAX_TRAVERSAL_DEPTH || !visited.insert(id) {
376            return;
377        }
378
379        let Some(node) = self.nodes.get(&id) else {
380            return;
381        };
382
383        order.push((id, depth));
384        for child_id in &node.children {
385            self.collect_mirror_order(*child_id, depth + 1, visited, order);
386        }
387    }
388
389    /// Diff this tree against a previous snapshot to find changes.
390    ///
391    /// Returns an [`A11yTreeDiff`] describing additions, removals,
392    /// property changes, and focus transitions.
393    pub fn diff(&self, previous: &A11yTree) -> A11yTreeDiff {
394        let mut added = Vec::new();
395        let mut removed = Vec::new();
396        let mut changed = Vec::new();
397
398        // Nodes in self but not in previous => added.
399        // Nodes in both => check for property changes.
400        for (&id, node) in &self.nodes {
401            match previous.nodes.get(&id) {
402                None => added.push(id),
403                Some(old) => {
404                    let changes = diff_node(old, node);
405                    if !changes.is_empty() {
406                        changed.push((id, changes));
407                    }
408                }
409            }
410        }
411
412        // Nodes in previous but not in self => removed.
413        for &id in previous.nodes.keys() {
414            if !self.nodes.contains_key(&id) {
415                removed.push(id);
416            }
417        }
418        added.sort_unstable();
419        removed.sort_unstable();
420        changed.sort_unstable_by_key(|(id, _)| *id);
421
422        let focus_changed = if self.focused != previous.focused {
423            Some((previous.focused, self.focused))
424        } else {
425            None
426        };
427
428        A11yTreeDiff {
429            added,
430            removed,
431            changed,
432            focus_changed,
433        }
434    }
435}
436
437// ── Diff types ─────────────────────────────────────────────────────────
438
439/// Changes between two accessibility tree snapshots.
440///
441/// Produced by [`A11yTree::diff`]. A platform bridge would translate
442/// these into OS accessibility events.
443#[derive(Debug, Clone)]
444pub struct A11yTreeDiff {
445    /// Node IDs that are new in the current tree.
446    pub added: Vec<u64>,
447    /// Node IDs that were in the previous tree but are gone now.
448    pub removed: Vec<u64>,
449    /// Node IDs whose properties changed, with details.
450    pub changed: Vec<(u64, Vec<A11yChange>)>,
451    /// Focus transition: `Some((old_focus, new_focus))`.
452    /// Either side may be `None` if focus was gained/lost entirely.
453    pub focus_changed: Option<(Option<u64>, Option<u64>)>,
454}
455
456impl A11yTreeDiff {
457    /// Returns `true` if nothing changed between the two snapshots.
458    #[inline]
459    pub fn is_empty(&self) -> bool {
460        self.added.is_empty()
461            && self.removed.is_empty()
462            && self.changed.is_empty()
463            && self.focus_changed.is_none()
464    }
465
466    /// Convert this diff into bounded screen-reader announcements.
467    ///
468    /// Focus changes are announced first, followed by retained-focus control
469    /// state changes, live-region policy changes, and live content. Within a
470    /// reason class, assertive announcements precede polite ones, then node ID
471    /// determines the order.
472    ///
473    /// When the tree's focused ID stays on an existing non-presentational
474    /// node, changes to `disabled`, `readonly`, `required`, `checked`,
475    /// `expanded`, and `selected` produce one announcement of the changed
476    /// states. Both directions are explicit, including removal of optional
477    /// checked/expanded semantics. These independent states do not move focus
478    /// or change widget behavior. A node's `state.focused` flag alone does not
479    /// establish focus.
480    ///
481    /// Retained-focus sliders and scrollbars also announce value changes,
482    /// preferring `value_text` to `value_now`. Numeric-only changes hidden by
483    /// a nonempty value description stay silent, even in live regions.
484    /// Text-input values, progress updates, and busy changes still require a
485    /// live region; this policy does not reread an entire field on every key
486    /// or turn background progress into unsolicited speech.
487    ///
488    /// Unfocused changes require a live region. Changes to just `disabled`,
489    /// `readonly`, and `required` remain silent off focus even in live regions.
490    /// The complete property changes remain available in the raw diff.
491    /// Entering a control uses its normal focus summary, not a second state
492    /// announcement. Standalone focused-state announcements are polite.
493    /// Same-node live updates are coalesced before applying the batch cap:
494    /// focus/state reasons take precedence, but live content and urgency are
495    /// retained. Cleared flags are included explicitly in a coalesced summary;
496    /// default false flags are not added to ordinary focus or mirror output.
497    ///
498    /// This is a text-bridge policy, not a requirement to add ARIA live
499    /// regions. WAI-ARIA defines the [state semantics], while [Core-AAM]
500    /// describes native accessibility events. A bridge using native events
501    /// should not also replay this text for the same transition (bd-inkss).
502    ///
503    /// [state semantics]: https://www.w3.org/TR/wai-aria-1.2/#aria-disabled
504    /// [Core-AAM]: https://www.w3.org/TR/core-aam-1.2/#mapping_events_state-change
505    pub fn screen_reader_announcements(
506        &self,
507        current: &A11yTree,
508        policy: ScreenReaderPolicy,
509    ) -> ScreenReaderAnnouncements {
510        let mut candidates = Vec::new();
511
512        if let Some((_, Some(new_focus))) = self.focus_changed
513            && let Some(node) = current.node(new_focus)
514            && node.role != A11yRole::Presentation
515            && let Some(text) =
516                announcement_text(node, current.focused == Some(new_focus), false, &[])
517        {
518            candidates.push(ScreenReaderAnnouncement {
519                node_id: Some(new_focus),
520                urgency: LiveRegion::Polite,
521                reason: AnnouncementReason::FocusChanged,
522                text,
523            });
524        }
525
526        for id in &self.added {
527            if let Some(node) = current.node(*id)
528                && let Some(urgency) = node.live_region
529                && let Some(text) = announcement_text(node, current.focused == Some(*id), true, &[])
530            {
531                push_announcement(
532                    &mut candidates,
533                    ScreenReaderAnnouncement {
534                        node_id: Some(*id),
535                        urgency,
536                        reason: AnnouncementReason::LiveRegionAdded,
537                        text,
538                    },
539                );
540            }
541        }
542
543        for (id, changes) in &self.changed {
544            let Some(node) = current.node(*id) else {
545                continue;
546            };
547            if node.role == A11yRole::Presentation {
548                continue;
549            }
550
551            let control_changes = if self.focus_changed.is_none() && current.focused == Some(*id) {
552                changed_control_states(node, changes)
553            } else {
554                Vec::new()
555            };
556            // Some false states (not checked, collapsed) and range values are
557            // already in the full summary. Add only missing transition text.
558            let cleared_states: Vec<_> = control_changes
559                .iter()
560                .filter_map(|(summarized, text)| (!*summarized).then_some(text.as_str()))
561                .collect();
562
563            if let Some(urgency) = node.live_region
564                && let Some(reason) = announcement_reason(node, changes)
565                && let Some(text) =
566                    announcement_text(node, current.focused == Some(*id), true, &cleared_states)
567            {
568                push_announcement(
569                    &mut candidates,
570                    ScreenReaderAnnouncement {
571                        node_id: Some(*id),
572                        urgency,
573                        reason: if control_changes.is_empty() {
574                            reason
575                        } else {
576                            AnnouncementReason::FocusedStateChanged
577                        },
578                        text,
579                    },
580                );
581            } else if !control_changes.is_empty() {
582                let states: Vec<_> = control_changes
583                    .iter()
584                    .map(|(_, text)| text.as_str())
585                    .collect();
586                candidates.push(ScreenReaderAnnouncement {
587                    node_id: Some(*id),
588                    urgency: LiveRegion::Polite,
589                    reason: AnnouncementReason::FocusedStateChanged,
590                    text: format!("{}. {}", node_heading(node), states.join(", ")),
591                });
592            }
593        }
594
595        candidates
596            .sort_by(|left, right| announcement_sort_key(left).cmp(&announcement_sort_key(right)));
597
598        let max = policy.max_announcements;
599        let dropped_count = candidates.len().saturating_sub(max);
600        let announcements = candidates
601            .into_iter()
602            .take(max)
603            .map(|mut announcement| {
604                announcement.text = limit_text(announcement.text, policy.max_text_chars);
605                announcement
606            })
607            .collect();
608
609        ScreenReaderAnnouncements {
610            announcements,
611            dropped_count,
612        }
613    }
614}
615
616/// Bounded output policy for screen-reader mirrors and announcements.
617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
618pub struct ScreenReaderPolicy {
619    /// Maximum non-presentational nodes to include in mirror output.
620    pub max_mirror_nodes: usize,
621    /// Maximum announcements to emit for one diff.
622    pub max_announcements: usize,
623    /// Maximum Unicode scalar values in each mirror line or announcement.
624    pub max_text_chars: usize,
625}
626
627impl Default for ScreenReaderPolicy {
628    fn default() -> Self {
629        Self {
630            max_mirror_nodes: 128,
631            max_announcements: 8,
632            max_text_chars: 240,
633        }
634    }
635}
636
637/// Deterministic text mirror for assistive-technology bridges.
638#[derive(Debug, Clone, PartialEq, Eq)]
639pub struct ScreenReaderMirror {
640    /// Pre-order, human-readable lines for the accessible tree.
641    pub lines: Vec<String>,
642    /// Number of non-presentational nodes dropped by the mirror cap.
643    pub omitted_nodes: usize,
644}
645
646impl ScreenReaderMirror {
647    /// Join mirror lines with newlines for platform bridges that expect text.
648    #[must_use]
649    pub fn text(&self) -> String {
650        self.lines.join("\n")
651    }
652}
653
654/// Bounded announcement batch for one tree transition.
655#[derive(Debug, Clone, PartialEq, Eq)]
656pub struct ScreenReaderAnnouncements {
657    /// Announcements retained after applying [`ScreenReaderPolicy`].
658    pub announcements: Vec<ScreenReaderAnnouncement>,
659    /// Number of otherwise valid announcements dropped by the batch cap.
660    pub dropped_count: usize,
661}
662
663/// One screen-reader announcement derived from focus, control state, or live-region changes.
664#[derive(Debug, Clone, PartialEq, Eq)]
665pub struct ScreenReaderAnnouncement {
666    /// Node that caused the announcement, when known.
667    pub node_id: Option<u64>,
668    /// Politeness / interruption level.
669    pub urgency: LiveRegion,
670    /// Why this announcement was emitted.
671    pub reason: AnnouncementReason,
672    /// Bounded, normalized text.
673    pub text: String,
674}
675
676/// Reason a screen-reader announcement was emitted.
677#[derive(Debug, Clone, Copy, PartialEq, Eq)]
678pub enum AnnouncementReason {
679    /// Keyboard focus moved to this node.
680    FocusChanged,
681    /// A control state or slider/scrollbar value changed while this node kept focus.
682    /// May include a simultaneous live update, retaining its urgency.
683    FocusedStateChanged,
684    /// A live region appeared in the current tree.
685    LiveRegionAdded,
686    /// Live-region text or user-facing state changed.
687    LiveContentChanged,
688    /// The live-region policy itself changed.
689    LiveRegionChanged,
690}
691
692/// A single property change on an accessibility node.
693#[derive(Debug, Clone, PartialEq)]
694pub enum A11yChange {
695    /// The accessible name changed.
696    NameChanged {
697        old: Option<String>,
698        new: Option<String>,
699    },
700    /// The role changed (unusual but possible during dynamic UIs).
701    RoleChanged { old: A11yRole, new: A11yRole },
702    /// A state flag changed. `field` is the flag name, `description`
703    /// is a human-readable summary of the new value.
704    StateChanged { field: String, description: String },
705    /// The bounding rectangle moved or resized.
706    BoundsChanged,
707    /// The set of child IDs changed.
708    ChildrenChanged,
709    /// The live-region policy changed.
710    LiveRegionChanged {
711        old: Option<LiveRegion>,
712        new: Option<LiveRegion>,
713    },
714    /// The accessible description changed.
715    DescriptionChanged {
716        old: Option<String>,
717        new: Option<String>,
718    },
719    /// The keyboard shortcut hint changed.
720    ShortcutChanged {
721        old: Option<String>,
722        new: Option<String>,
723    },
724    /// The parent node ID changed.
725    ParentChanged { old: Option<u64>, new: Option<u64> },
726}
727
728// ── Internal diff helpers ──────────────────────────────────────────────
729
730fn diff_node(old: &A11yNodeInfo, new: &A11yNodeInfo) -> Vec<A11yChange> {
731    let mut changes = Vec::new();
732
733    if old.name != new.name {
734        changes.push(A11yChange::NameChanged {
735            old: old.name.clone(),
736            new: new.name.clone(),
737        });
738    }
739
740    if old.role != new.role {
741        changes.push(A11yChange::RoleChanged {
742            old: old.role,
743            new: new.role,
744        });
745    }
746
747    if old.bounds != new.bounds {
748        changes.push(A11yChange::BoundsChanged);
749    }
750
751    if old.children != new.children {
752        changes.push(A11yChange::ChildrenChanged);
753    }
754
755    if old.live_region != new.live_region {
756        changes.push(A11yChange::LiveRegionChanged {
757            old: old.live_region,
758            new: new.live_region,
759        });
760    }
761
762    if old.description != new.description {
763        changes.push(A11yChange::DescriptionChanged {
764            old: old.description.clone(),
765            new: new.description.clone(),
766        });
767    }
768
769    if old.shortcut != new.shortcut {
770        changes.push(A11yChange::ShortcutChanged {
771            old: old.shortcut.clone(),
772            new: new.shortcut.clone(),
773        });
774    }
775
776    if old.parent != new.parent {
777        changes.push(A11yChange::ParentChanged {
778            old: old.parent,
779            new: new.parent,
780        });
781    }
782
783    // Diff individual state fields.
784    diff_state(&old.state, &new.state, &mut changes);
785
786    changes
787}
788
789fn diff_state(
790    old: &crate::node::A11yState,
791    new: &crate::node::A11yState,
792    changes: &mut Vec<A11yChange>,
793) {
794    macro_rules! check_bool {
795        ($field:ident) => {
796            if old.$field != new.$field {
797                changes.push(A11yChange::StateChanged {
798                    field: stringify!($field).to_owned(),
799                    description: new.$field.to_string(),
800                });
801            }
802        };
803    }
804
805    macro_rules! check_option {
806        ($field:ident) => {
807            if old.$field != new.$field {
808                changes.push(A11yChange::StateChanged {
809                    field: stringify!($field).to_owned(),
810                    description: format!("{:?}", new.$field),
811                });
812            }
813        };
814    }
815
816    check_bool!(focused);
817    check_bool!(disabled);
818    check_option!(checked);
819    check_option!(expanded);
820    check_bool!(selected);
821    check_bool!(readonly);
822    check_bool!(required);
823    check_bool!(busy);
824    check_option!(value_now);
825    check_option!(value_min);
826    check_option!(value_max);
827
828    if old.value_text != new.value_text {
829        changes.push(A11yChange::StateChanged {
830            field: "value_text".to_owned(),
831            description: new.value_text.as_deref().unwrap_or("<none>").to_owned(),
832        });
833    }
834}
835
836/// Classifies live-region content changes (`LiveRegionChanged` / `LiveContentChanged`).
837///
838/// Rationale for state-field partitioning (`bd-inkss`):
839/// - `busy`, `checked`, `expanded`, `selected`, and spoken values (`value_text` /
840///   `value_now` via [`announced_value_changed`]) trigger `LiveContentChanged`
841///   on explicit live regions even when the node is not focused.
842/// - `disabled`, `readonly`, and `required` are intentionally excluded here so
843///   unfocused rows in a refreshing table or form do not chatter; when those
844///   flags change on the currently focused node, [`changed_control_states`]
845///   surfaces them as [`AnnouncementReason::FocusedStateChanged`].
846/// - `focused` is announced separately by [`AnnouncementReason::FocusChanged`].
847/// - `value_min` and `value_max` are range bounds metadata, not user-facing events.
848fn announcement_reason(node: &A11yNodeInfo, changes: &[A11yChange]) -> Option<AnnouncementReason> {
849    if changes
850        .iter()
851        .any(|change| matches!(change, A11yChange::LiveRegionChanged { .. }))
852    {
853        return Some(AnnouncementReason::LiveRegionChanged);
854    }
855
856    let content_changed = changes.iter().any(|change| {
857        matches!(
858            change,
859            A11yChange::NameChanged { .. }
860                | A11yChange::DescriptionChanged { .. }
861                | A11yChange::RoleChanged { .. }
862        ) || matches!(
863            change,
864            A11yChange::StateChanged { field, .. }
865                if matches!(field.as_str(), "busy" | "checked" | "expanded" | "selected")
866        )
867    });
868    (content_changed || announced_value_changed(node, changes))
869        .then_some(AnnouncementReason::LiveContentChanged)
870}
871
872fn state_field_changed(changes: &[A11yChange], field: &str) -> bool {
873    changes.iter().any(|change| {
874        matches!(change, A11yChange::StateChanged { field: changed, .. } if changed.as_str() == field)
875    })
876}
877
878/// The spoken value uses text in preference to its underlying number. Keep
879/// numeric-only updates in the raw diff without repeating the same text.
880fn announced_value_changed(node: &A11yNodeInfo, changes: &[A11yChange]) -> bool {
881    state_field_changed(changes, "value_text")
882        || (state_field_changed(changes, "value_now")
883            && normalized_option(node.state.value_text.as_deref()).is_none())
884}
885
886fn value_summary(state: &crate::node::A11yState) -> Option<String> {
887    normalized_option(state.value_text.as_deref())
888        .or_else(|| state.value_now.map(|value| value.to_string()))
889}
890
891/// Changed control states in stable order. The bool says whether the current
892/// snapshot summary already contains the text, NOT whether the state is true.
893/// Read typed state rather than parsing diff debug descriptions.
894fn changed_control_states(node: &A11yNodeInfo, changes: &[A11yChange]) -> Vec<(bool, String)> {
895    let mut states = Vec::new();
896    for (field, set, on, off) in [
897        ("disabled", node.state.disabled, "disabled", "enabled"),
898        (
899            "readonly",
900            node.state.readonly,
901            "read only",
902            "not read only",
903        ),
904        ("required", node.state.required, "required", "not required"),
905    ] {
906        if state_field_changed(changes, field) {
907            states.push((set, if set { on } else { off }.to_owned()));
908        }
909    }
910    for (field, value, on, off, absent) in [
911        (
912            "checked",
913            node.state.checked,
914            "checked",
915            "not checked",
916            "not checkable",
917        ),
918        (
919            "expanded",
920            node.state.expanded,
921            "expanded",
922            "collapsed",
923            "not expandable",
924        ),
925    ] {
926        if state_field_changed(changes, field) {
927            let text = match value {
928                Some(true) => on,
929                Some(false) => off,
930                None => absent,
931            };
932            states.push((value.is_some(), text.to_owned()));
933        }
934    }
935    if state_field_changed(changes, "selected") {
936        states.push((
937            node.state.selected,
938            if node.state.selected {
939                "selected"
940            } else {
941                "not selected"
942            }
943            .to_owned(),
944        ));
945    }
946    if matches!(
947        node.role,
948        A11yRole::Slider | A11yRole::ScrollBar | A11yRole::RadioButton | A11yRole::MenuItem
949    ) && announced_value_changed(node, changes)
950    {
951        let value = value_summary(&node.state);
952        states.push((
953            value.is_some(),
954            value.map_or_else(
955                || "value unavailable".to_owned(),
956                |value| format!("value {value}"),
957            ),
958        ));
959    }
960    states
961}
962
963/// The optional focus candidate is inserted first, before either node loop.
964/// Added and changed IDs are disjoint in a tree diff, so only that candidate
965/// can overlap a live announcement. Coalesce by node, never by text, in O(1).
966fn push_announcement(
967    candidates: &mut Vec<ScreenReaderAnnouncement>,
968    announcement: ScreenReaderAnnouncement,
969) {
970    if let Some(focus) = candidates.first_mut()
971        && focus.reason == AnnouncementReason::FocusChanged
972        && focus.node_id == announcement.node_id
973    {
974        if announcement.urgency == LiveRegion::Assertive {
975            focus.urgency = LiveRegion::Assertive;
976        }
977    } else {
978        candidates.push(announcement);
979    }
980}
981
982fn announcement_sort_key(announcement: &ScreenReaderAnnouncement) -> (u8, u8, Option<u64>, &str) {
983    let reason_rank = match announcement.reason {
984        AnnouncementReason::FocusChanged => 0,
985        AnnouncementReason::FocusedStateChanged => 1,
986        AnnouncementReason::LiveRegionChanged => 2,
987        AnnouncementReason::LiveRegionAdded | AnnouncementReason::LiveContentChanged => 3,
988    };
989    let urgency_rank = match announcement.urgency {
990        LiveRegion::Assertive => 0,
991        LiveRegion::Polite => 1,
992    };
993    (
994        reason_rank,
995        urgency_rank,
996        announcement.node_id,
997        announcement.text.as_str(),
998    )
999}
1000
1001fn announcement_text(
1002    node: &A11yNodeInfo,
1003    focused: bool,
1004    require_content: bool,
1005    cleared_states: &[&str],
1006) -> Option<String> {
1007    if node.role == A11yRole::Presentation {
1008        return None;
1009    }
1010    if require_content && !has_announcement_content(node) && cleared_states.is_empty() {
1011        return None;
1012    }
1013
1014    let text = node_summary(node, focused, false, cleared_states);
1015    normalized_text(&text)
1016}
1017
1018fn has_announcement_content(node: &A11yNodeInfo) -> bool {
1019    normalized_option(node.name.as_deref()).is_some()
1020        || normalized_option(node.description.as_deref()).is_some()
1021        || !state_summaries(&node.state).is_empty()
1022}
1023
1024fn node_heading(node: &A11yNodeInfo) -> String {
1025    let mut heading = node.role.to_string();
1026    if let Some(name) = normalized_option(node.name.as_deref()) {
1027        heading.push_str(": ");
1028        heading.push_str(&name);
1029    }
1030    heading
1031}
1032
1033fn node_summary(
1034    node: &A11yNodeInfo,
1035    focused: bool,
1036    include_live_region: bool,
1037    cleared_states: &[&str],
1038) -> String {
1039    let mut parts = vec![node_heading(node)];
1040
1041    if let Some(description) = normalized_option(node.description.as_deref())
1042        && normalized_option(node.name.as_deref()) != Some(description.clone())
1043    {
1044        parts.push(description);
1045    }
1046
1047    let mut states = state_summaries(&node.state);
1048    states.extend(cleared_states.iter().map(|text| (*text).to_owned()));
1049    if focused || node.state.focused {
1050        states.insert(0, "focused".to_owned());
1051    }
1052    if !states.is_empty() {
1053        parts.push(states.join(", "));
1054    }
1055
1056    if let Some(shortcut) = normalized_option(node.shortcut.as_deref()) {
1057        parts.push(format!("shortcut {shortcut}"));
1058    }
1059
1060    if include_live_region && let Some(region) = node.live_region {
1061        parts.push(format!("live {region}"));
1062    }
1063
1064    parts.join(". ")
1065}
1066
1067fn state_summaries(state: &crate::node::A11yState) -> Vec<String> {
1068    let mut states = Vec::new();
1069    if state.disabled {
1070        states.push("disabled".to_owned());
1071    }
1072    if let Some(checked) = state.checked {
1073        states.push(if checked { "checked" } else { "not checked" }.to_owned());
1074    }
1075    if let Some(expanded) = state.expanded {
1076        states.push(if expanded { "expanded" } else { "collapsed" }.to_owned());
1077    }
1078    if state.selected {
1079        states.push("selected".to_owned());
1080    }
1081    if state.readonly {
1082        states.push("read only".to_owned());
1083    }
1084    if state.required {
1085        states.push("required".to_owned());
1086    }
1087    if state.busy {
1088        states.push("busy".to_owned());
1089    }
1090    if let Some(value) = value_summary(state) {
1091        states.push(format!("value {value}"));
1092    }
1093    states
1094}
1095
1096fn normalized_option(value: Option<&str>) -> Option<String> {
1097    value.and_then(normalized_text)
1098}
1099
1100fn normalized_text(value: &str) -> Option<String> {
1101    let mut normalized = String::new();
1102    for word in value.split_whitespace() {
1103        if !normalized.is_empty() {
1104            normalized.push(' ');
1105        }
1106        normalized.push_str(word);
1107    }
1108    (!normalized.is_empty()).then_some(normalized)
1109}
1110
1111fn limit_text(text: String, max_chars: usize) -> String {
1112    if max_chars == 0 {
1113        return String::new();
1114    }
1115    if text.chars().count() <= max_chars {
1116        return text;
1117    }
1118    text.chars().take(max_chars).collect()
1119}
1120
1121#[cfg(test)]
1122mod focused_state_tests {
1123    use super::{A11yChange, A11yTree, A11yTreeBuilder, AnnouncementReason, ScreenReaderPolicy};
1124    use crate::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
1125    use crate::preferences::AccessibilityPreferences;
1126    use ftui_core::geometry::Rect;
1127
1128    fn control(bits: u8) -> A11yNodeInfo {
1129        let mut node = A11yNodeInfo::new(1, A11yRole::TextInput, Rect::new(0, 0, 20, 1))
1130            .with_name(" Email \n address ")
1131            .with_description("Help")
1132            .with_shortcut("Alt+E");
1133        node.state = A11yState {
1134            disabled: bits & 1 != 0,
1135            readonly: bits & 2 != 0,
1136            required: bits & 4 != 0,
1137            ..A11yState::default()
1138        };
1139        node
1140    }
1141
1142    fn snapshot(nodes: Vec<A11yNodeInfo>, focus: Option<u64>) -> A11yTree {
1143        let mut builder = A11yTreeBuilder::new();
1144        for node in nodes {
1145            builder.add_node(node);
1146        }
1147        builder.set_focused(focus);
1148        builder.build()
1149    }
1150
1151    #[test]
1152    fn focused_control_flags_announce_both_directions_without_requiring_live_regions() {
1153        for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1154            for (from, to, field, text) in [
1155                (0, 1, "disabled", "disabled"),
1156                (1, 0, "disabled", "enabled"),
1157                (0, 2, "readonly", "read only"),
1158                (2, 0, "readonly", "not read only"),
1159                (0, 4, "required", "required"),
1160                (4, 0, "required", "not required"),
1161            ] {
1162                let mut old = control(from);
1163                let mut new = control(to);
1164                old.live_region = region;
1165                new.live_region = region;
1166                // The tree ID is authoritative, even with state.focused false.
1167                assert!(!old.state.focused && !new.state.focused);
1168                let before = snapshot(vec![old], Some(1));
1169                let after = snapshot(vec![new], Some(1));
1170                let diff = after.diff(&before);
1171                assert!(diff.focus_changed.is_none());
1172                let expected_value = (to != 0).to_string();
1173                assert!(diff.changed[0].1.iter().any(|change| {
1174                    matches!(
1175                        change,
1176                        A11yChange::StateChanged { field: actual, description }
1177                            if actual == field && description == &expected_value
1178                    )
1179                }));
1180
1181                let batch = diff.screen_reader_announcements(&after, ScreenReaderPolicy::default());
1182                assert_eq!(batch.announcements.len(), 1, "{field}: {from} -> {to}");
1183                assert_eq!(batch.dropped_count, 0);
1184                let announcement = &batch.announcements[0];
1185                assert_eq!(announcement.node_id, Some(1));
1186                assert_eq!(announcement.reason, AnnouncementReason::FocusedStateChanged);
1187                // A state-only change is not an assertive live-content update.
1188                assert_eq!(announcement.urgency, LiveRegion::Polite);
1189                assert_eq!(
1190                    announcement.text,
1191                    format!("textInput: Email address. {text}")
1192                );
1193            }
1194        }
1195    }
1196
1197    #[test]
1198    fn focused_control_flags_coalesce_and_do_not_repeat_on_unchanged_frames() {
1199        let before = snapshot(vec![control(0)], Some(1));
1200        let after = snapshot(vec![control(7)], Some(1));
1201        for (old, new, expected) in [
1202            (&before, &after, "disabled, read only, required"),
1203            (&after, &before, "enabled, not read only, not required"),
1204        ] {
1205            let batch = new.screen_reader_announcements_since(old, ScreenReaderPolicy::default());
1206            assert_eq!(batch.announcements.len(), 1);
1207            assert_eq!(
1208                batch.announcements[0].text,
1209                format!("textInput: Email address. {expected}")
1210            );
1211            let unchanged =
1212                new.screen_reader_announcements_since(new, ScreenReaderPolicy::default());
1213            assert!(unchanged.announcements.is_empty());
1214            assert_eq!(unchanged.dropped_count, 0);
1215        }
1216        // Clearing states must not make default false states verbose in snapshots.
1217        assert_eq!(
1218            before
1219                .screen_reader_mirror(ScreenReaderPolicy::default())
1220                .text(),
1221            "textInput: Email address. Help. focused. shortcut Alt+E"
1222        );
1223    }
1224
1225    #[test]
1226    fn focused_control_delta_does_not_repeat_unchanged_flags_or_imply_editability() {
1227        let before = snapshot(vec![control(7)], Some(1));
1228        let after = snapshot(vec![control(5)], Some(1));
1229        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1230        assert_eq!(batch.announcements.len(), 1);
1231        // Still disabled and required: removing readonly does not mean operable.
1232        assert_eq!(
1233            batch.announcements[0].text,
1234            "textInput: Email address. not read only"
1235        );
1236    }
1237
1238    #[test]
1239    fn off_focus_and_presentational_control_flags_are_diffed_but_not_spoken() {
1240        for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1241            for (role, focus) in [
1242                (A11yRole::TextInput, None),
1243                (A11yRole::TextInput, Some(2)),
1244                (A11yRole::TextInput, Some(999)),
1245                (A11yRole::Presentation, Some(1)),
1246            ] {
1247                for (from, to) in [(0, 7), (7, 0)] {
1248                    let mut old = control(from);
1249                    let mut new = control(to);
1250                    old.role = role;
1251                    new.role = role;
1252                    old.live_region = region;
1253                    new.live_region = region;
1254                    // A stale per-node focus flag must not opt into state speech.
1255                    old.state.focused = true;
1256                    new.state.focused = true;
1257                    let other = A11yNodeInfo::new(2, A11yRole::Button, Rect::new(0, 1, 5, 1));
1258                    let before = snapshot(vec![old, other.clone()], focus);
1259                    let after = snapshot(vec![new, other], focus);
1260                    let diff = after.diff(&before);
1261                    assert_eq!(diff.changed.len(), 1);
1262                    assert_eq!(diff.changed[0].1.len(), 3);
1263                    let batch =
1264                        diff.screen_reader_announcements(&after, ScreenReaderPolicy::default());
1265                    assert!(
1266                        batch.announcements.is_empty(),
1267                        "{role:?}, {focus:?}, {region:?}"
1268                    );
1269                    assert_eq!(batch.dropped_count, 0);
1270                }
1271            }
1272        }
1273    }
1274
1275    #[test]
1276    fn focus_handoff_uses_destination_summary_and_silences_outgoing_state_changes() {
1277        let mut other_before = control(0);
1278        other_before.id = 2;
1279        let mut other_after = control(7);
1280        other_after.id = 2;
1281        let before = snapshot(vec![control(0), other_before], Some(2));
1282        let after = snapshot(vec![control(7), other_after], Some(1));
1283        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1284        assert_eq!(batch.announcements.len(), 1);
1285        assert_eq!(
1286            batch.announcements[0].reason,
1287            AnnouncementReason::FocusChanged
1288        );
1289        assert_eq!(batch.announcements[0].node_id, Some(1));
1290        assert_eq!(
1291            batch.announcements[0].text,
1292            "textInput: Email address. Help. focused, disabled, read only, required. shortcut Alt+E"
1293        );
1294
1295        let lost = snapshot(vec![control(0)], None);
1296        let removed = snapshot(Vec::new(), Some(1));
1297        for next in [lost, removed] {
1298            let batch =
1299                next.screen_reader_announcements_since(&after, ScreenReaderPolicy::default());
1300            assert!(batch.announcements.is_empty());
1301            assert_eq!(batch.dropped_count, 0);
1302        }
1303    }
1304
1305    #[test]
1306    fn new_focus_and_live_region_addition_coalesce_before_counting_drops() {
1307        let focused = control(7).with_live_region(LiveRegion::Assertive);
1308        let other = A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 20, 1))
1309            .with_name("Other update")
1310            .with_live_region(LiveRegion::Polite);
1311        let after = snapshot(vec![focused, other], Some(1));
1312        for cap in [0, 1, 2] {
1313            let batch = after.screen_reader_announcements_since(
1314                &A11yTree::empty(),
1315                ScreenReaderPolicy {
1316                    max_announcements: cap,
1317                    ..ScreenReaderPolicy::default()
1318                },
1319            );
1320            assert_eq!(batch.announcements.len(), cap);
1321            assert_eq!(batch.dropped_count, 2 - cap);
1322            if cap > 0 {
1323                assert_eq!(batch.announcements[0].node_id, Some(1));
1324                assert_eq!(
1325                    batch.announcements[0].reason,
1326                    AnnouncementReason::FocusChanged
1327                );
1328                assert_eq!(batch.announcements[0].urgency, LiveRegion::Assertive);
1329            }
1330        }
1331
1332        // Equal text from different nodes is not a duplicate focus/live event.
1333        let first = control(0).with_live_region(LiveRegion::Polite);
1334        let mut second = first.clone();
1335        second.id = 2;
1336        let equal_text = snapshot(vec![second, first], None)
1337            .screen_reader_announcements_since(&A11yTree::empty(), ScreenReaderPolicy::default());
1338        assert_eq!(equal_text.announcements.len(), 2);
1339        assert_eq!(
1340            equal_text.announcements[0].text,
1341            equal_text.announcements[1].text
1342        );
1343        assert_eq!(equal_text.announcements[0].node_id, Some(1));
1344        assert_eq!(equal_text.announcements[1].node_id, Some(2));
1345    }
1346
1347    #[test]
1348    fn new_focus_and_existing_live_content_or_policy_changes_are_announced_once() {
1349        for change_policy in [false, true] {
1350            let old = control(0).with_live_region(LiveRegion::Polite);
1351            let mut new = control(7).with_live_region(if change_policy {
1352                LiveRegion::Assertive
1353            } else {
1354                LiveRegion::Polite
1355            });
1356            new.description = Some("Updated help".to_owned());
1357            let before = snapshot(vec![old], None);
1358            let after = snapshot(vec![new], Some(1));
1359            let batch =
1360                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1361            assert_eq!(batch.announcements.len(), 1);
1362            assert_eq!(batch.dropped_count, 0);
1363            assert_eq!(
1364                batch.announcements[0].reason,
1365                AnnouncementReason::FocusChanged
1366            );
1367            assert_eq!(
1368                batch.announcements[0].urgency,
1369                if change_policy {
1370                    LiveRegion::Assertive
1371                } else {
1372                    LiveRegion::Polite
1373                }
1374            );
1375            assert_eq!(
1376                batch.announcements[0].text,
1377                "textInput: Email address. Updated help. focused, disabled, read only, required. shortcut Alt+E"
1378            );
1379        }
1380    }
1381
1382    #[test]
1383    fn retained_focus_and_live_content_keep_both_directions_content_and_urgency_once() {
1384        for region in [LiveRegion::Polite, LiveRegion::Assertive] {
1385            for (from, to, states) in [
1386                (0, 7, "disabled, read only, required, value new"),
1387                (7, 0, "value new, enabled, not read only, not required"),
1388            ] {
1389                let old = control(from).with_live_region(region);
1390                let mut new = control(to)
1391                    .with_live_region(region)
1392                    .with_name(" Updated \n email ")
1393                    .with_description("New help");
1394                new.state.value_text = Some("new".to_owned());
1395                let before = snapshot(vec![old], Some(1));
1396                let after = snapshot(vec![new], Some(1));
1397                let batch =
1398                    after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1399                assert_eq!(batch.announcements.len(), 1);
1400                assert_eq!(batch.dropped_count, 0);
1401                assert_eq!(
1402                    batch.announcements[0].reason,
1403                    AnnouncementReason::FocusedStateChanged
1404                );
1405                assert_eq!(batch.announcements[0].urgency, region);
1406                assert_eq!(
1407                    batch.announcements[0].text,
1408                    format!(
1409                        "textInput: Updated email. New help. focused, {states}. shortcut Alt+E"
1410                    )
1411                );
1412                // Actionable focused-state changes are not motion-like churn.
1413                let filtered = AccessibilityPreferences::all()
1414                    .motion_profile()
1415                    .filter_announcements(&batch);
1416                assert_eq!(filtered.announcements, batch.announcements);
1417                assert_eq!(filtered.coalesced_count, 0);
1418                assert_eq!(filtered.downgraded_count, 0);
1419            }
1420        }
1421    }
1422
1423    #[test]
1424    fn clearing_unnamed_focused_states_survives_live_policy_changes() {
1425        for (old_region, new_region) in [
1426            (None, Some(LiveRegion::Assertive)),
1427            (Some(LiveRegion::Polite), Some(LiveRegion::Assertive)),
1428            (Some(LiveRegion::Assertive), None),
1429        ] {
1430            let mut old = control(7);
1431            let mut new = control(0);
1432            for node in [&mut old, &mut new] {
1433                node.name = None;
1434                node.description = None;
1435                node.shortcut = None;
1436            }
1437            old.live_region = old_region;
1438            new.live_region = new_region;
1439            let before = snapshot(vec![old], Some(1));
1440            let after = snapshot(vec![new], Some(1));
1441            let batch =
1442                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1443            assert_eq!(batch.announcements.len(), 1);
1444            assert_eq!(
1445                batch.announcements[0].reason,
1446                AnnouncementReason::FocusedStateChanged
1447            );
1448            assert_eq!(
1449                batch.announcements[0].urgency,
1450                new_region.unwrap_or(LiveRegion::Polite)
1451            );
1452            assert_eq!(
1453                batch.announcements[0].text,
1454                if new_region.is_some() {
1455                    "textInput. focused, enabled, not read only, not required"
1456                } else {
1457                    "textInput. enabled, not read only, not required"
1458                }
1459            );
1460        }
1461    }
1462
1463    #[test]
1464    fn focused_state_order_and_caps_are_deterministic_and_unicode_safe() {
1465        let before = snapshot(vec![control(0)], Some(1));
1466        let focused = control(7).with_name("\u{00c9}mail \u{754c} \u{1f980}");
1467        let live = A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 20, 1))
1468            .with_name("Background update")
1469            .with_live_region(LiveRegion::Assertive);
1470        let after = snapshot(vec![live, focused], Some(1));
1471        let full = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1472        assert_eq!(full.announcements.len(), 2);
1473        assert_eq!(
1474            full.announcements[0].reason,
1475            AnnouncementReason::FocusedStateChanged
1476        );
1477        assert_eq!(full.announcements[0].node_id, Some(1));
1478        assert_eq!(full.announcements[1].node_id, Some(2));
1479        for cap in [0, 1, 2] {
1480            for chars in [0, 1, 20, 240] {
1481                let policy = ScreenReaderPolicy {
1482                    max_announcements: cap,
1483                    max_text_chars: chars,
1484                    ..ScreenReaderPolicy::default()
1485                };
1486                let batch = after.screen_reader_announcements_since(&before, policy);
1487                assert_eq!(
1488                    batch,
1489                    after.screen_reader_announcements_since(&before, policy)
1490                );
1491                assert_eq!(batch.announcements.len(), cap);
1492                assert_eq!(batch.dropped_count, 2 - cap);
1493                for (actual, expected) in batch.announcements.iter().zip(&full.announcements) {
1494                    assert_eq!(actual.node_id, expected.node_id);
1495                    assert_eq!(
1496                        actual.text,
1497                        expected.text.chars().take(chars).collect::<String>()
1498                    );
1499                }
1500            }
1501        }
1502    }
1503
1504    #[test]
1505    fn unrelated_focused_layout_and_hint_changes_stay_quiet() {
1506        let before = snapshot(vec![control(0)], Some(1));
1507        let mut new = control(0);
1508        new.state.focused = true;
1509        new.bounds = Rect::new(4, 5, 30, 2);
1510        new.shortcut = Some("Ctrl+E".to_owned());
1511        let after = snapshot(vec![new], Some(1));
1512        assert!(!after.diff(&before).is_empty());
1513        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1514        assert!(batch.announcements.is_empty());
1515        assert_eq!(batch.dropped_count, 0);
1516    }
1517
1518    fn interaction_node(role: A11yRole, state: A11yState) -> A11yNodeInfo {
1519        let mut node = A11yNodeInfo::new(7, role, Rect::new(0, 0, 20, 1)).with_name("Control");
1520        node.state = state;
1521        node
1522    }
1523
1524    #[test]
1525    fn retained_focus_announces_activation_states_and_removed_capabilities() {
1526        for (field, role, from, to, text) in [
1527            (
1528                "checked",
1529                A11yRole::Checkbox,
1530                None,
1531                Some(false),
1532                "not checked",
1533            ),
1534            ("checked", A11yRole::Checkbox, None, Some(true), "checked"),
1535            (
1536                "checked",
1537                A11yRole::Checkbox,
1538                Some(false),
1539                Some(true),
1540                "checked",
1541            ),
1542            (
1543                "checked",
1544                A11yRole::Checkbox,
1545                Some(true),
1546                Some(false),
1547                "not checked",
1548            ),
1549            (
1550                "checked",
1551                A11yRole::Checkbox,
1552                Some(false),
1553                None,
1554                "not checkable",
1555            ),
1556            (
1557                "checked",
1558                A11yRole::Checkbox,
1559                Some(true),
1560                None,
1561                "not checkable",
1562            ),
1563            ("expanded", A11yRole::Button, None, Some(false), "collapsed"),
1564            ("expanded", A11yRole::Button, None, Some(true), "expanded"),
1565            (
1566                "expanded",
1567                A11yRole::Button,
1568                Some(false),
1569                Some(true),
1570                "expanded",
1571            ),
1572            (
1573                "expanded",
1574                A11yRole::Button,
1575                Some(true),
1576                Some(false),
1577                "collapsed",
1578            ),
1579            (
1580                "expanded",
1581                A11yRole::Button,
1582                Some(false),
1583                None,
1584                "not expandable",
1585            ),
1586            (
1587                "expanded",
1588                A11yRole::Button,
1589                Some(true),
1590                None,
1591                "not expandable",
1592            ),
1593            (
1594                "selected",
1595                A11yRole::Tab,
1596                Some(false),
1597                Some(true),
1598                "selected",
1599            ),
1600            (
1601                "selected",
1602                A11yRole::Tab,
1603                Some(true),
1604                Some(false),
1605                "not selected",
1606            ),
1607        ] {
1608            for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1609                let mut old = interaction_node(role, A11yState::default());
1610                let mut new = old.clone();
1611                match field {
1612                    "checked" => {
1613                        old.state.checked = from;
1614                        new.state.checked = to;
1615                    }
1616                    "expanded" => {
1617                        old.state.expanded = from;
1618                        new.state.expanded = to;
1619                    }
1620                    "selected" => {
1621                        old.state.selected = from.unwrap();
1622                        new.state.selected = to.unwrap();
1623                    }
1624                    _ => unreachable!(),
1625                }
1626                old.live_region = region;
1627                new.live_region = region;
1628                let before = snapshot(vec![old], Some(7));
1629                let after = snapshot(vec![new], Some(7));
1630                let batch =
1631                    after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1632                assert_eq!(batch.announcements.len(), 1, "{field}: {from:?} -> {to:?}");
1633                assert_eq!(batch.dropped_count, 0);
1634                let announcement = &batch.announcements[0];
1635                assert_eq!(announcement.node_id, Some(7));
1636                assert_eq!(announcement.reason, AnnouncementReason::FocusedStateChanged);
1637                assert_eq!(announcement.urgency, region.unwrap_or(LiveRegion::Polite));
1638                let focus = if region.is_some() { "focused, " } else { "" };
1639                assert_eq!(announcement.text, format!("{role}: Control. {focus}{text}"));
1640                let filtered = AccessibilityPreferences::all()
1641                    .motion_profile()
1642                    .filter_announcements(&batch);
1643                assert_eq!(filtered.announcements, batch.announcements);
1644                assert_eq!(filtered.coalesced_count, 0);
1645                assert_eq!(filtered.downgraded_count, 0);
1646                assert!(
1647                    after
1648                        .screen_reader_announcements_since(&after, ScreenReaderPolicy::default())
1649                        .announcements
1650                        .is_empty()
1651                );
1652            }
1653        }
1654    }
1655
1656    #[test]
1657    fn activation_changes_do_not_speak_for_unfocused_or_presentational_nodes() {
1658        for (role, focus) in [
1659            (A11yRole::Checkbox, None),
1660            (A11yRole::Checkbox, Some(999)),
1661            (A11yRole::Presentation, Some(7)),
1662        ] {
1663            let old = interaction_node(
1664                role,
1665                A11yState {
1666                    focused: true,
1667                    checked: Some(false),
1668                    expanded: Some(false),
1669                    ..A11yState::default()
1670                },
1671            );
1672            let mut new = old.clone();
1673            new.state.checked = Some(true);
1674            new.state.expanded = Some(true);
1675            new.state.selected = true;
1676            let before = snapshot(vec![old], focus);
1677            let after = snapshot(vec![new], focus);
1678            assert_eq!(after.diff(&before).changed[0].1.len(), 3);
1679            let batch =
1680                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1681            assert!(batch.announcements.is_empty());
1682            assert_eq!(batch.dropped_count, 0);
1683        }
1684    }
1685
1686    #[test]
1687    fn off_focus_activation_changes_still_honor_explicit_live_regions() {
1688        let old = interaction_node(
1689            A11yRole::Checkbox,
1690            A11yState {
1691                checked: Some(false),
1692                ..A11yState::default()
1693            },
1694        )
1695        .with_live_region(LiveRegion::Assertive);
1696        let mut new = old.clone();
1697        new.state.checked = Some(true);
1698        let batch = snapshot(vec![new], None).screen_reader_announcements_since(
1699            &snapshot(vec![old], None),
1700            ScreenReaderPolicy::default(),
1701        );
1702        assert_eq!(batch.announcements.len(), 1);
1703        assert_eq!(
1704            batch.announcements[0].reason,
1705            AnnouncementReason::LiveContentChanged
1706        );
1707        assert_eq!(batch.announcements[0].urgency, LiveRegion::Assertive);
1708        assert_eq!(batch.announcements[0].text, "checkbox: Control. checked");
1709    }
1710
1711    #[test]
1712    fn retained_focus_choice_value_text_changes_announce_without_live_regions() {
1713        for role in [A11yRole::RadioButton, A11yRole::MenuItem] {
1714            let old = interaction_node(
1715                role,
1716                A11yState {
1717                    value_now: Some(0.0),
1718                    value_text: Some("First".to_owned()),
1719                    ..A11yState::default()
1720                },
1721            );
1722            let mut new = old.clone();
1723            new.state.value_now = Some(1.0);
1724            new.state.value_text = Some("Second".to_owned());
1725            let before = snapshot(vec![old], Some(7));
1726            let after = snapshot(vec![new], Some(7));
1727            let batch =
1728                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1729            assert_eq!(batch.announcements.len(), 1);
1730            assert_eq!(batch.dropped_count, 0);
1731            assert_eq!(
1732                batch.announcements[0].reason,
1733                AnnouncementReason::FocusedStateChanged
1734            );
1735            assert_eq!(
1736                batch.announcements[0].text,
1737                format!("{role}: Control. value Second")
1738            );
1739        }
1740    }
1741
1742    #[test]
1743    fn retained_focus_range_values_use_text_numeric_fallback_and_explicit_absence() {
1744        for role in [A11yRole::Slider, A11yRole::ScrollBar] {
1745            for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1746                for (from_number, from_text, to_number, to_text, expected) in [
1747                    (Some(10.0), None, Some(20.0), None, "value 20"),
1748                    (
1749                        Some(10.0),
1750                        Some("Low"),
1751                        Some(20.0),
1752                        Some("  Very\n high "),
1753                        "value Very high",
1754                    ),
1755                    (Some(10.0), Some("Low"), Some(20.0), None, "value 20"),
1756                    (
1757                        Some(10.0),
1758                        Some("Low"),
1759                        Some(20.0),
1760                        Some(" \n "),
1761                        "value 20",
1762                    ),
1763                    (Some(10.0), None, None, None, "value unavailable"),
1764                    (None, Some("Low"), None, None, "value unavailable"),
1765                ] {
1766                    let mut old = interaction_node(
1767                        role,
1768                        A11yState {
1769                            value_now: from_number,
1770                            value_text: from_text.map(str::to_owned),
1771                            ..A11yState::default()
1772                        },
1773                    );
1774                    let mut new = old.clone();
1775                    new.state.value_now = to_number;
1776                    new.state.value_text = to_text.map(str::to_owned);
1777                    old.live_region = region;
1778                    new.live_region = region;
1779                    let batch = snapshot(vec![new], Some(7)).screen_reader_announcements_since(
1780                        &snapshot(vec![old], Some(7)),
1781                        ScreenReaderPolicy::default(),
1782                    );
1783                    assert_eq!(batch.announcements.len(), 1);
1784                    assert_eq!(batch.dropped_count, 0);
1785                    assert_eq!(
1786                        batch.announcements[0].reason,
1787                        AnnouncementReason::FocusedStateChanged
1788                    );
1789                    assert_eq!(
1790                        batch.announcements[0].urgency,
1791                        region.unwrap_or(LiveRegion::Polite)
1792                    );
1793                    let focus = if region.is_some() { "focused, " } else { "" };
1794                    assert_eq!(
1795                        batch.announcements[0].text,
1796                        format!("{role}: Control. {focus}{expected}")
1797                    );
1798                    assert_eq!(batch.announcements[0].text.matches("value ").count(), 1);
1799                }
1800            }
1801        }
1802    }
1803
1804    #[test]
1805    fn numeric_changes_hidden_by_value_text_remain_in_diff_without_speech() {
1806        for role in [A11yRole::Slider, A11yRole::ScrollBar, A11yRole::ProgressBar] {
1807            for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1808                for focus in [None, Some(7)] {
1809                    let mut old = interaction_node(
1810                        role,
1811                        A11yState {
1812                            value_now: Some(10.0),
1813                            value_text: Some("Medium".to_owned()),
1814                            ..A11yState::default()
1815                        },
1816                    );
1817                    old.live_region = region;
1818                    let mut new = old.clone();
1819                    new.state.value_now = Some(11.0);
1820                    let before = snapshot(vec![old], focus);
1821                    let after = snapshot(vec![new], focus);
1822                    let diff = after.diff(&before);
1823                    assert_eq!(diff.changed[0].1.len(), 1);
1824                    assert!(matches!(
1825                        &diff.changed[0].1[0],
1826                        A11yChange::StateChanged { field, .. } if field == "value_now"
1827                    ));
1828                    let batch =
1829                        diff.screen_reader_announcements(&after, ScreenReaderPolicy::default());
1830                    assert!(batch.announcements.is_empty());
1831                    assert_eq!(batch.dropped_count, 0);
1832                }
1833            }
1834        }
1835    }
1836
1837    #[test]
1838    fn focused_text_edits_background_progress_and_range_metadata_stay_quiet() {
1839        for role in [A11yRole::TextInput, A11yRole::ProgressBar, A11yRole::Label] {
1840            let old = interaction_node(role, A11yState::default());
1841            let mut new = old.clone();
1842            new.state.value_text = Some("new content".to_owned());
1843            new.state.value_now = Some(20.0);
1844            new.state.busy = true;
1845            let before = snapshot(vec![old], Some(7));
1846            let after = snapshot(vec![new], Some(7));
1847            assert!(!after.diff(&before).is_empty());
1848            assert!(
1849                after
1850                    .screen_reader_announcements_since(&before, ScreenReaderPolicy::default())
1851                    .announcements
1852                    .is_empty()
1853            );
1854        }
1855        let old = interaction_node(A11yRole::Slider, A11yState::default());
1856        let mut new = old.clone();
1857        new.state.value_min = Some(0.0);
1858        new.state.value_max = Some(100.0);
1859        let batch = snapshot(vec![new], Some(7)).screen_reader_announcements_since(
1860            &snapshot(vec![old], Some(7)),
1861            ScreenReaderPolicy::default(),
1862        );
1863        assert!(batch.announcements.is_empty());
1864    }
1865
1866    #[test]
1867    fn combined_interaction_changes_share_one_bounded_live_announcement() {
1868        for region in [None, Some(LiveRegion::Assertive)] {
1869            let mut old = interaction_node(
1870                A11yRole::Slider,
1871                A11yState {
1872                    disabled: true,
1873                    required: true,
1874                    expanded: Some(true),
1875                    selected: true,
1876                    value_now: Some(10.0),
1877                    ..A11yState::default()
1878                },
1879            );
1880            old.live_region = region;
1881            let mut new = old.clone();
1882            new.state.disabled = false;
1883            new.state.required = false;
1884            new.state.expanded = Some(false);
1885            new.state.selected = false;
1886            new.state.value_now = Some(20.0);
1887            let background = A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 20, 1))
1888                .with_name("Background")
1889                .with_live_region(LiveRegion::Assertive);
1890            let before = snapshot(vec![old], Some(7));
1891            let after = snapshot(vec![background, new], Some(7));
1892            for cap in [0, 1, 2] {
1893                let batch = after.screen_reader_announcements_since(
1894                    &before,
1895                    ScreenReaderPolicy {
1896                        max_announcements: cap,
1897                        ..ScreenReaderPolicy::default()
1898                    },
1899                );
1900                assert_eq!(batch.announcements.len(), cap);
1901                assert_eq!(batch.dropped_count, 2 - cap);
1902                if cap > 0 {
1903                    assert_eq!(batch.announcements[0].node_id, Some(7));
1904                    assert_eq!(
1905                        batch.announcements[0].reason,
1906                        AnnouncementReason::FocusedStateChanged
1907                    );
1908                    assert_eq!(
1909                        batch.announcements[0].text,
1910                        if region.is_some() {
1911                            "slider: Control. focused, collapsed, value 20, enabled, not required, not selected"
1912                        } else {
1913                            "slider: Control. enabled, not required, collapsed, not selected, value 20"
1914                        }
1915                    );
1916                }
1917            }
1918        }
1919    }
1920
1921    #[test]
1922    fn arriving_focus_coalesces_activation_and_range_changes_with_live_content() {
1923        let old = interaction_node(A11yRole::Slider, A11yState::default())
1924            .with_live_region(LiveRegion::Assertive);
1925        let mut new = old.clone();
1926        new.state.value_now = Some(20.0);
1927        new.state.selected = true;
1928        new.state.expanded = Some(true);
1929        let batch = snapshot(vec![new], Some(7)).screen_reader_announcements_since(
1930            &snapshot(vec![old], None),
1931            ScreenReaderPolicy::default(),
1932        );
1933        assert_eq!(batch.announcements.len(), 1);
1934        assert_eq!(batch.dropped_count, 0);
1935        assert_eq!(
1936            batch.announcements[0].reason,
1937            AnnouncementReason::FocusChanged
1938        );
1939        assert_eq!(batch.announcements[0].urgency, LiveRegion::Assertive);
1940        assert_eq!(
1941            batch.announcements[0].text,
1942            "slider: Control. focused, expanded, selected, value 20"
1943        );
1944    }
1945}