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
836fn announcement_reason(node: &A11yNodeInfo, changes: &[A11yChange]) -> Option<AnnouncementReason> {
837    if changes
838        .iter()
839        .any(|change| matches!(change, A11yChange::LiveRegionChanged { .. }))
840    {
841        return Some(AnnouncementReason::LiveRegionChanged);
842    }
843
844    let content_changed = changes.iter().any(|change| {
845        matches!(
846            change,
847            A11yChange::NameChanged { .. }
848                | A11yChange::DescriptionChanged { .. }
849                | A11yChange::RoleChanged { .. }
850        ) || matches!(
851            change,
852            A11yChange::StateChanged { field, .. }
853                if matches!(field.as_str(), "busy" | "checked" | "expanded" | "selected")
854        )
855    });
856    (content_changed || announced_value_changed(node, changes))
857        .then_some(AnnouncementReason::LiveContentChanged)
858}
859
860fn state_field_changed(changes: &[A11yChange], field: &str) -> bool {
861    changes.iter().any(|change| {
862        matches!(change, A11yChange::StateChanged { field: changed, .. } if changed.as_str() == field)
863    })
864}
865
866/// The spoken value uses text in preference to its underlying number. Keep
867/// numeric-only updates in the raw diff without repeating the same text.
868fn announced_value_changed(node: &A11yNodeInfo, changes: &[A11yChange]) -> bool {
869    state_field_changed(changes, "value_text")
870        || (state_field_changed(changes, "value_now")
871            && normalized_option(node.state.value_text.as_deref()).is_none())
872}
873
874fn value_summary(state: &crate::node::A11yState) -> Option<String> {
875    normalized_option(state.value_text.as_deref())
876        .or_else(|| state.value_now.map(|value| value.to_string()))
877}
878
879/// Changed control states in stable order. The bool says whether the current
880/// snapshot summary already contains the text, NOT whether the state is true.
881/// Read typed state rather than parsing diff debug descriptions.
882fn changed_control_states(node: &A11yNodeInfo, changes: &[A11yChange]) -> Vec<(bool, String)> {
883    let mut states = Vec::new();
884    for (field, set, on, off) in [
885        ("disabled", node.state.disabled, "disabled", "enabled"),
886        (
887            "readonly",
888            node.state.readonly,
889            "read only",
890            "not read only",
891        ),
892        ("required", node.state.required, "required", "not required"),
893    ] {
894        if state_field_changed(changes, field) {
895            states.push((set, if set { on } else { off }.to_owned()));
896        }
897    }
898    for (field, value, on, off, absent) in [
899        (
900            "checked",
901            node.state.checked,
902            "checked",
903            "not checked",
904            "not checkable",
905        ),
906        (
907            "expanded",
908            node.state.expanded,
909            "expanded",
910            "collapsed",
911            "not expandable",
912        ),
913    ] {
914        if state_field_changed(changes, field) {
915            let text = match value {
916                Some(true) => on,
917                Some(false) => off,
918                None => absent,
919            };
920            states.push((value.is_some(), text.to_owned()));
921        }
922    }
923    if state_field_changed(changes, "selected") {
924        states.push((
925            node.state.selected,
926            if node.state.selected {
927                "selected"
928            } else {
929                "not selected"
930            }
931            .to_owned(),
932        ));
933    }
934    if matches!(
935        node.role,
936        A11yRole::Slider | A11yRole::ScrollBar | A11yRole::RadioButton | A11yRole::MenuItem
937    ) && announced_value_changed(node, changes)
938    {
939        let value = value_summary(&node.state);
940        states.push((
941            value.is_some(),
942            value.map_or_else(
943                || "value unavailable".to_owned(),
944                |value| format!("value {value}"),
945            ),
946        ));
947    }
948    states
949}
950
951/// The optional focus candidate is inserted first, before either node loop.
952/// Added and changed IDs are disjoint in a tree diff, so only that candidate
953/// can overlap a live announcement. Coalesce by node, never by text, in O(1).
954fn push_announcement(
955    candidates: &mut Vec<ScreenReaderAnnouncement>,
956    announcement: ScreenReaderAnnouncement,
957) {
958    if let Some(focus) = candidates.first_mut()
959        && focus.reason == AnnouncementReason::FocusChanged
960        && focus.node_id == announcement.node_id
961    {
962        if announcement.urgency == LiveRegion::Assertive {
963            focus.urgency = LiveRegion::Assertive;
964        }
965    } else {
966        candidates.push(announcement);
967    }
968}
969
970fn announcement_sort_key(announcement: &ScreenReaderAnnouncement) -> (u8, u8, Option<u64>, &str) {
971    let reason_rank = match announcement.reason {
972        AnnouncementReason::FocusChanged => 0,
973        AnnouncementReason::FocusedStateChanged => 1,
974        AnnouncementReason::LiveRegionChanged => 2,
975        AnnouncementReason::LiveRegionAdded | AnnouncementReason::LiveContentChanged => 3,
976    };
977    let urgency_rank = match announcement.urgency {
978        LiveRegion::Assertive => 0,
979        LiveRegion::Polite => 1,
980    };
981    (
982        reason_rank,
983        urgency_rank,
984        announcement.node_id,
985        announcement.text.as_str(),
986    )
987}
988
989fn announcement_text(
990    node: &A11yNodeInfo,
991    focused: bool,
992    require_content: bool,
993    cleared_states: &[&str],
994) -> Option<String> {
995    if node.role == A11yRole::Presentation {
996        return None;
997    }
998    if require_content && !has_announcement_content(node) && cleared_states.is_empty() {
999        return None;
1000    }
1001
1002    let text = node_summary(node, focused, false, cleared_states);
1003    normalized_text(&text)
1004}
1005
1006fn has_announcement_content(node: &A11yNodeInfo) -> bool {
1007    normalized_option(node.name.as_deref()).is_some()
1008        || normalized_option(node.description.as_deref()).is_some()
1009        || !state_summaries(&node.state).is_empty()
1010}
1011
1012fn node_heading(node: &A11yNodeInfo) -> String {
1013    let mut heading = node.role.to_string();
1014    if let Some(name) = normalized_option(node.name.as_deref()) {
1015        heading.push_str(": ");
1016        heading.push_str(&name);
1017    }
1018    heading
1019}
1020
1021fn node_summary(
1022    node: &A11yNodeInfo,
1023    focused: bool,
1024    include_live_region: bool,
1025    cleared_states: &[&str],
1026) -> String {
1027    let mut parts = vec![node_heading(node)];
1028
1029    if let Some(description) = normalized_option(node.description.as_deref())
1030        && normalized_option(node.name.as_deref()) != Some(description.clone())
1031    {
1032        parts.push(description);
1033    }
1034
1035    let mut states = state_summaries(&node.state);
1036    states.extend(cleared_states.iter().map(|text| (*text).to_owned()));
1037    if focused || node.state.focused {
1038        states.insert(0, "focused".to_owned());
1039    }
1040    if !states.is_empty() {
1041        parts.push(states.join(", "));
1042    }
1043
1044    if let Some(shortcut) = normalized_option(node.shortcut.as_deref()) {
1045        parts.push(format!("shortcut {shortcut}"));
1046    }
1047
1048    if include_live_region && let Some(region) = node.live_region {
1049        parts.push(format!("live {region}"));
1050    }
1051
1052    parts.join(". ")
1053}
1054
1055fn state_summaries(state: &crate::node::A11yState) -> Vec<String> {
1056    let mut states = Vec::new();
1057    if state.disabled {
1058        states.push("disabled".to_owned());
1059    }
1060    if let Some(checked) = state.checked {
1061        states.push(if checked { "checked" } else { "not checked" }.to_owned());
1062    }
1063    if let Some(expanded) = state.expanded {
1064        states.push(if expanded { "expanded" } else { "collapsed" }.to_owned());
1065    }
1066    if state.selected {
1067        states.push("selected".to_owned());
1068    }
1069    if state.readonly {
1070        states.push("read only".to_owned());
1071    }
1072    if state.required {
1073        states.push("required".to_owned());
1074    }
1075    if state.busy {
1076        states.push("busy".to_owned());
1077    }
1078    if let Some(value) = value_summary(state) {
1079        states.push(format!("value {value}"));
1080    }
1081    states
1082}
1083
1084fn normalized_option(value: Option<&str>) -> Option<String> {
1085    value.and_then(normalized_text)
1086}
1087
1088fn normalized_text(value: &str) -> Option<String> {
1089    let mut normalized = String::new();
1090    for word in value.split_whitespace() {
1091        if !normalized.is_empty() {
1092            normalized.push(' ');
1093        }
1094        normalized.push_str(word);
1095    }
1096    (!normalized.is_empty()).then_some(normalized)
1097}
1098
1099fn limit_text(text: String, max_chars: usize) -> String {
1100    if max_chars == 0 {
1101        return String::new();
1102    }
1103    if text.chars().count() <= max_chars {
1104        return text;
1105    }
1106    text.chars().take(max_chars).collect()
1107}
1108
1109#[cfg(test)]
1110mod focused_state_tests {
1111    use super::{A11yChange, A11yTree, A11yTreeBuilder, AnnouncementReason, ScreenReaderPolicy};
1112    use crate::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
1113    use crate::preferences::AccessibilityPreferences;
1114    use ftui_core::geometry::Rect;
1115
1116    fn control(bits: u8) -> A11yNodeInfo {
1117        let mut node = A11yNodeInfo::new(1, A11yRole::TextInput, Rect::new(0, 0, 20, 1))
1118            .with_name(" Email \n address ")
1119            .with_description("Help")
1120            .with_shortcut("Alt+E");
1121        node.state = A11yState {
1122            disabled: bits & 1 != 0,
1123            readonly: bits & 2 != 0,
1124            required: bits & 4 != 0,
1125            ..A11yState::default()
1126        };
1127        node
1128    }
1129
1130    fn snapshot(nodes: Vec<A11yNodeInfo>, focus: Option<u64>) -> A11yTree {
1131        let mut builder = A11yTreeBuilder::new();
1132        for node in nodes {
1133            builder.add_node(node);
1134        }
1135        builder.set_focused(focus);
1136        builder.build()
1137    }
1138
1139    #[test]
1140    fn focused_control_flags_announce_both_directions_without_requiring_live_regions() {
1141        for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1142            for (from, to, field, text) in [
1143                (0, 1, "disabled", "disabled"),
1144                (1, 0, "disabled", "enabled"),
1145                (0, 2, "readonly", "read only"),
1146                (2, 0, "readonly", "not read only"),
1147                (0, 4, "required", "required"),
1148                (4, 0, "required", "not required"),
1149            ] {
1150                let mut old = control(from);
1151                let mut new = control(to);
1152                old.live_region = region;
1153                new.live_region = region;
1154                // The tree ID is authoritative, even with state.focused false.
1155                assert!(!old.state.focused && !new.state.focused);
1156                let before = snapshot(vec![old], Some(1));
1157                let after = snapshot(vec![new], Some(1));
1158                let diff = after.diff(&before);
1159                assert!(diff.focus_changed.is_none());
1160                let expected_value = (to != 0).to_string();
1161                assert!(diff.changed[0].1.iter().any(|change| {
1162                    matches!(
1163                        change,
1164                        A11yChange::StateChanged { field: actual, description }
1165                            if actual == field && description == &expected_value
1166                    )
1167                }));
1168
1169                let batch = diff.screen_reader_announcements(&after, ScreenReaderPolicy::default());
1170                assert_eq!(batch.announcements.len(), 1, "{field}: {from} -> {to}");
1171                assert_eq!(batch.dropped_count, 0);
1172                let announcement = &batch.announcements[0];
1173                assert_eq!(announcement.node_id, Some(1));
1174                assert_eq!(announcement.reason, AnnouncementReason::FocusedStateChanged);
1175                // A state-only change is not an assertive live-content update.
1176                assert_eq!(announcement.urgency, LiveRegion::Polite);
1177                assert_eq!(
1178                    announcement.text,
1179                    format!("textInput: Email address. {text}")
1180                );
1181            }
1182        }
1183    }
1184
1185    #[test]
1186    fn focused_control_flags_coalesce_and_do_not_repeat_on_unchanged_frames() {
1187        let before = snapshot(vec![control(0)], Some(1));
1188        let after = snapshot(vec![control(7)], Some(1));
1189        for (old, new, expected) in [
1190            (&before, &after, "disabled, read only, required"),
1191            (&after, &before, "enabled, not read only, not required"),
1192        ] {
1193            let batch = new.screen_reader_announcements_since(old, ScreenReaderPolicy::default());
1194            assert_eq!(batch.announcements.len(), 1);
1195            assert_eq!(
1196                batch.announcements[0].text,
1197                format!("textInput: Email address. {expected}")
1198            );
1199            let unchanged =
1200                new.screen_reader_announcements_since(new, ScreenReaderPolicy::default());
1201            assert!(unchanged.announcements.is_empty());
1202            assert_eq!(unchanged.dropped_count, 0);
1203        }
1204        // Clearing states must not make default false states verbose in snapshots.
1205        assert_eq!(
1206            before
1207                .screen_reader_mirror(ScreenReaderPolicy::default())
1208                .text(),
1209            "textInput: Email address. Help. focused. shortcut Alt+E"
1210        );
1211    }
1212
1213    #[test]
1214    fn focused_control_delta_does_not_repeat_unchanged_flags_or_imply_editability() {
1215        let before = snapshot(vec![control(7)], Some(1));
1216        let after = snapshot(vec![control(5)], Some(1));
1217        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1218        assert_eq!(batch.announcements.len(), 1);
1219        // Still disabled and required: removing readonly does not mean operable.
1220        assert_eq!(
1221            batch.announcements[0].text,
1222            "textInput: Email address. not read only"
1223        );
1224    }
1225
1226    #[test]
1227    fn off_focus_and_presentational_control_flags_are_diffed_but_not_spoken() {
1228        for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1229            for (role, focus) in [
1230                (A11yRole::TextInput, None),
1231                (A11yRole::TextInput, Some(2)),
1232                (A11yRole::TextInput, Some(999)),
1233                (A11yRole::Presentation, Some(1)),
1234            ] {
1235                for (from, to) in [(0, 7), (7, 0)] {
1236                    let mut old = control(from);
1237                    let mut new = control(to);
1238                    old.role = role;
1239                    new.role = role;
1240                    old.live_region = region;
1241                    new.live_region = region;
1242                    // A stale per-node focus flag must not opt into state speech.
1243                    old.state.focused = true;
1244                    new.state.focused = true;
1245                    let other = A11yNodeInfo::new(2, A11yRole::Button, Rect::new(0, 1, 5, 1));
1246                    let before = snapshot(vec![old, other.clone()], focus);
1247                    let after = snapshot(vec![new, other], focus);
1248                    let diff = after.diff(&before);
1249                    assert_eq!(diff.changed.len(), 1);
1250                    assert_eq!(diff.changed[0].1.len(), 3);
1251                    let batch =
1252                        diff.screen_reader_announcements(&after, ScreenReaderPolicy::default());
1253                    assert!(
1254                        batch.announcements.is_empty(),
1255                        "{role:?}, {focus:?}, {region:?}"
1256                    );
1257                    assert_eq!(batch.dropped_count, 0);
1258                }
1259            }
1260        }
1261    }
1262
1263    #[test]
1264    fn focus_handoff_uses_destination_summary_and_silences_outgoing_state_changes() {
1265        let mut other_before = control(0);
1266        other_before.id = 2;
1267        let mut other_after = control(7);
1268        other_after.id = 2;
1269        let before = snapshot(vec![control(0), other_before], Some(2));
1270        let after = snapshot(vec![control(7), other_after], Some(1));
1271        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1272        assert_eq!(batch.announcements.len(), 1);
1273        assert_eq!(
1274            batch.announcements[0].reason,
1275            AnnouncementReason::FocusChanged
1276        );
1277        assert_eq!(batch.announcements[0].node_id, Some(1));
1278        assert_eq!(
1279            batch.announcements[0].text,
1280            "textInput: Email address. Help. focused, disabled, read only, required. shortcut Alt+E"
1281        );
1282
1283        let lost = snapshot(vec![control(0)], None);
1284        let removed = snapshot(Vec::new(), Some(1));
1285        for next in [lost, removed] {
1286            let batch =
1287                next.screen_reader_announcements_since(&after, ScreenReaderPolicy::default());
1288            assert!(batch.announcements.is_empty());
1289            assert_eq!(batch.dropped_count, 0);
1290        }
1291    }
1292
1293    #[test]
1294    fn new_focus_and_live_region_addition_coalesce_before_counting_drops() {
1295        let focused = control(7).with_live_region(LiveRegion::Assertive);
1296        let other = A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 20, 1))
1297            .with_name("Other update")
1298            .with_live_region(LiveRegion::Polite);
1299        let after = snapshot(vec![focused, other], Some(1));
1300        for cap in [0, 1, 2] {
1301            let batch = after.screen_reader_announcements_since(
1302                &A11yTree::empty(),
1303                ScreenReaderPolicy {
1304                    max_announcements: cap,
1305                    ..ScreenReaderPolicy::default()
1306                },
1307            );
1308            assert_eq!(batch.announcements.len(), cap);
1309            assert_eq!(batch.dropped_count, 2 - cap);
1310            if cap > 0 {
1311                assert_eq!(batch.announcements[0].node_id, Some(1));
1312                assert_eq!(
1313                    batch.announcements[0].reason,
1314                    AnnouncementReason::FocusChanged
1315                );
1316                assert_eq!(batch.announcements[0].urgency, LiveRegion::Assertive);
1317            }
1318        }
1319
1320        // Equal text from different nodes is not a duplicate focus/live event.
1321        let first = control(0).with_live_region(LiveRegion::Polite);
1322        let mut second = first.clone();
1323        second.id = 2;
1324        let equal_text = snapshot(vec![second, first], None)
1325            .screen_reader_announcements_since(&A11yTree::empty(), ScreenReaderPolicy::default());
1326        assert_eq!(equal_text.announcements.len(), 2);
1327        assert_eq!(
1328            equal_text.announcements[0].text,
1329            equal_text.announcements[1].text
1330        );
1331        assert_eq!(equal_text.announcements[0].node_id, Some(1));
1332        assert_eq!(equal_text.announcements[1].node_id, Some(2));
1333    }
1334
1335    #[test]
1336    fn new_focus_and_existing_live_content_or_policy_changes_are_announced_once() {
1337        for change_policy in [false, true] {
1338            let old = control(0).with_live_region(LiveRegion::Polite);
1339            let mut new = control(7).with_live_region(if change_policy {
1340                LiveRegion::Assertive
1341            } else {
1342                LiveRegion::Polite
1343            });
1344            new.description = Some("Updated help".to_owned());
1345            let before = snapshot(vec![old], None);
1346            let after = snapshot(vec![new], Some(1));
1347            let batch =
1348                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1349            assert_eq!(batch.announcements.len(), 1);
1350            assert_eq!(batch.dropped_count, 0);
1351            assert_eq!(
1352                batch.announcements[0].reason,
1353                AnnouncementReason::FocusChanged
1354            );
1355            assert_eq!(
1356                batch.announcements[0].urgency,
1357                if change_policy {
1358                    LiveRegion::Assertive
1359                } else {
1360                    LiveRegion::Polite
1361                }
1362            );
1363            assert_eq!(
1364                batch.announcements[0].text,
1365                "textInput: Email address. Updated help. focused, disabled, read only, required. shortcut Alt+E"
1366            );
1367        }
1368    }
1369
1370    #[test]
1371    fn retained_focus_and_live_content_keep_both_directions_content_and_urgency_once() {
1372        for region in [LiveRegion::Polite, LiveRegion::Assertive] {
1373            for (from, to, states) in [
1374                (0, 7, "disabled, read only, required, value new"),
1375                (7, 0, "value new, enabled, not read only, not required"),
1376            ] {
1377                let old = control(from).with_live_region(region);
1378                let mut new = control(to)
1379                    .with_live_region(region)
1380                    .with_name(" Updated \n email ")
1381                    .with_description("New help");
1382                new.state.value_text = Some("new".to_owned());
1383                let before = snapshot(vec![old], Some(1));
1384                let after = snapshot(vec![new], Some(1));
1385                let batch =
1386                    after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1387                assert_eq!(batch.announcements.len(), 1);
1388                assert_eq!(batch.dropped_count, 0);
1389                assert_eq!(
1390                    batch.announcements[0].reason,
1391                    AnnouncementReason::FocusedStateChanged
1392                );
1393                assert_eq!(batch.announcements[0].urgency, region);
1394                assert_eq!(
1395                    batch.announcements[0].text,
1396                    format!(
1397                        "textInput: Updated email. New help. focused, {states}. shortcut Alt+E"
1398                    )
1399                );
1400                // Actionable focused-state changes are not motion-like churn.
1401                let filtered = AccessibilityPreferences::all()
1402                    .motion_profile()
1403                    .filter_announcements(&batch);
1404                assert_eq!(filtered.announcements, batch.announcements);
1405                assert_eq!(filtered.coalesced_count, 0);
1406                assert_eq!(filtered.downgraded_count, 0);
1407            }
1408        }
1409    }
1410
1411    #[test]
1412    fn clearing_unnamed_focused_states_survives_live_policy_changes() {
1413        for (old_region, new_region) in [
1414            (None, Some(LiveRegion::Assertive)),
1415            (Some(LiveRegion::Polite), Some(LiveRegion::Assertive)),
1416            (Some(LiveRegion::Assertive), None),
1417        ] {
1418            let mut old = control(7);
1419            let mut new = control(0);
1420            for node in [&mut old, &mut new] {
1421                node.name = None;
1422                node.description = None;
1423                node.shortcut = None;
1424            }
1425            old.live_region = old_region;
1426            new.live_region = new_region;
1427            let before = snapshot(vec![old], Some(1));
1428            let after = snapshot(vec![new], Some(1));
1429            let batch =
1430                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1431            assert_eq!(batch.announcements.len(), 1);
1432            assert_eq!(
1433                batch.announcements[0].reason,
1434                AnnouncementReason::FocusedStateChanged
1435            );
1436            assert_eq!(
1437                batch.announcements[0].urgency,
1438                new_region.unwrap_or(LiveRegion::Polite)
1439            );
1440            assert_eq!(
1441                batch.announcements[0].text,
1442                if new_region.is_some() {
1443                    "textInput. focused, enabled, not read only, not required"
1444                } else {
1445                    "textInput. enabled, not read only, not required"
1446                }
1447            );
1448        }
1449    }
1450
1451    #[test]
1452    fn focused_state_order_and_caps_are_deterministic_and_unicode_safe() {
1453        let before = snapshot(vec![control(0)], Some(1));
1454        let focused = control(7).with_name("\u{00c9}mail \u{754c} \u{1f980}");
1455        let live = A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 20, 1))
1456            .with_name("Background update")
1457            .with_live_region(LiveRegion::Assertive);
1458        let after = snapshot(vec![live, focused], Some(1));
1459        let full = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1460        assert_eq!(full.announcements.len(), 2);
1461        assert_eq!(
1462            full.announcements[0].reason,
1463            AnnouncementReason::FocusedStateChanged
1464        );
1465        assert_eq!(full.announcements[0].node_id, Some(1));
1466        assert_eq!(full.announcements[1].node_id, Some(2));
1467        for cap in [0, 1, 2] {
1468            for chars in [0, 1, 20, 240] {
1469                let policy = ScreenReaderPolicy {
1470                    max_announcements: cap,
1471                    max_text_chars: chars,
1472                    ..ScreenReaderPolicy::default()
1473                };
1474                let batch = after.screen_reader_announcements_since(&before, policy);
1475                assert_eq!(
1476                    batch,
1477                    after.screen_reader_announcements_since(&before, policy)
1478                );
1479                assert_eq!(batch.announcements.len(), cap);
1480                assert_eq!(batch.dropped_count, 2 - cap);
1481                for (actual, expected) in batch.announcements.iter().zip(&full.announcements) {
1482                    assert_eq!(actual.node_id, expected.node_id);
1483                    assert_eq!(
1484                        actual.text,
1485                        expected.text.chars().take(chars).collect::<String>()
1486                    );
1487                }
1488            }
1489        }
1490    }
1491
1492    #[test]
1493    fn unrelated_focused_layout_and_hint_changes_stay_quiet() {
1494        let before = snapshot(vec![control(0)], Some(1));
1495        let mut new = control(0);
1496        new.state.focused = true;
1497        new.bounds = Rect::new(4, 5, 30, 2);
1498        new.shortcut = Some("Ctrl+E".to_owned());
1499        let after = snapshot(vec![new], Some(1));
1500        assert!(!after.diff(&before).is_empty());
1501        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1502        assert!(batch.announcements.is_empty());
1503        assert_eq!(batch.dropped_count, 0);
1504    }
1505
1506    fn interaction_node(role: A11yRole, state: A11yState) -> A11yNodeInfo {
1507        let mut node = A11yNodeInfo::new(7, role, Rect::new(0, 0, 20, 1)).with_name("Control");
1508        node.state = state;
1509        node
1510    }
1511
1512    #[test]
1513    fn retained_focus_announces_activation_states_and_removed_capabilities() {
1514        for (field, role, from, to, text) in [
1515            (
1516                "checked",
1517                A11yRole::Checkbox,
1518                None,
1519                Some(false),
1520                "not checked",
1521            ),
1522            ("checked", A11yRole::Checkbox, None, Some(true), "checked"),
1523            (
1524                "checked",
1525                A11yRole::Checkbox,
1526                Some(false),
1527                Some(true),
1528                "checked",
1529            ),
1530            (
1531                "checked",
1532                A11yRole::Checkbox,
1533                Some(true),
1534                Some(false),
1535                "not checked",
1536            ),
1537            (
1538                "checked",
1539                A11yRole::Checkbox,
1540                Some(false),
1541                None,
1542                "not checkable",
1543            ),
1544            (
1545                "checked",
1546                A11yRole::Checkbox,
1547                Some(true),
1548                None,
1549                "not checkable",
1550            ),
1551            ("expanded", A11yRole::Button, None, Some(false), "collapsed"),
1552            ("expanded", A11yRole::Button, None, Some(true), "expanded"),
1553            (
1554                "expanded",
1555                A11yRole::Button,
1556                Some(false),
1557                Some(true),
1558                "expanded",
1559            ),
1560            (
1561                "expanded",
1562                A11yRole::Button,
1563                Some(true),
1564                Some(false),
1565                "collapsed",
1566            ),
1567            (
1568                "expanded",
1569                A11yRole::Button,
1570                Some(false),
1571                None,
1572                "not expandable",
1573            ),
1574            (
1575                "expanded",
1576                A11yRole::Button,
1577                Some(true),
1578                None,
1579                "not expandable",
1580            ),
1581            (
1582                "selected",
1583                A11yRole::Tab,
1584                Some(false),
1585                Some(true),
1586                "selected",
1587            ),
1588            (
1589                "selected",
1590                A11yRole::Tab,
1591                Some(true),
1592                Some(false),
1593                "not selected",
1594            ),
1595        ] {
1596            for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1597                let mut old = interaction_node(role, A11yState::default());
1598                let mut new = old.clone();
1599                match field {
1600                    "checked" => {
1601                        old.state.checked = from;
1602                        new.state.checked = to;
1603                    }
1604                    "expanded" => {
1605                        old.state.expanded = from;
1606                        new.state.expanded = to;
1607                    }
1608                    "selected" => {
1609                        old.state.selected = from.unwrap();
1610                        new.state.selected = to.unwrap();
1611                    }
1612                    _ => unreachable!(),
1613                }
1614                old.live_region = region;
1615                new.live_region = region;
1616                let before = snapshot(vec![old], Some(7));
1617                let after = snapshot(vec![new], Some(7));
1618                let batch =
1619                    after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1620                assert_eq!(batch.announcements.len(), 1, "{field}: {from:?} -> {to:?}");
1621                assert_eq!(batch.dropped_count, 0);
1622                let announcement = &batch.announcements[0];
1623                assert_eq!(announcement.node_id, Some(7));
1624                assert_eq!(announcement.reason, AnnouncementReason::FocusedStateChanged);
1625                assert_eq!(announcement.urgency, region.unwrap_or(LiveRegion::Polite));
1626                let focus = if region.is_some() { "focused, " } else { "" };
1627                assert_eq!(announcement.text, format!("{role}: Control. {focus}{text}"));
1628                let filtered = AccessibilityPreferences::all()
1629                    .motion_profile()
1630                    .filter_announcements(&batch);
1631                assert_eq!(filtered.announcements, batch.announcements);
1632                assert_eq!(filtered.coalesced_count, 0);
1633                assert_eq!(filtered.downgraded_count, 0);
1634                assert!(
1635                    after
1636                        .screen_reader_announcements_since(&after, ScreenReaderPolicy::default())
1637                        .announcements
1638                        .is_empty()
1639                );
1640            }
1641        }
1642    }
1643
1644    #[test]
1645    fn activation_changes_do_not_speak_for_unfocused_or_presentational_nodes() {
1646        for (role, focus) in [
1647            (A11yRole::Checkbox, None),
1648            (A11yRole::Checkbox, Some(999)),
1649            (A11yRole::Presentation, Some(7)),
1650        ] {
1651            let old = interaction_node(
1652                role,
1653                A11yState {
1654                    focused: true,
1655                    checked: Some(false),
1656                    expanded: Some(false),
1657                    ..A11yState::default()
1658                },
1659            );
1660            let mut new = old.clone();
1661            new.state.checked = Some(true);
1662            new.state.expanded = Some(true);
1663            new.state.selected = true;
1664            let before = snapshot(vec![old], focus);
1665            let after = snapshot(vec![new], focus);
1666            assert_eq!(after.diff(&before).changed[0].1.len(), 3);
1667            let batch =
1668                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1669            assert!(batch.announcements.is_empty());
1670            assert_eq!(batch.dropped_count, 0);
1671        }
1672    }
1673
1674    #[test]
1675    fn off_focus_activation_changes_still_honor_explicit_live_regions() {
1676        let old = interaction_node(
1677            A11yRole::Checkbox,
1678            A11yState {
1679                checked: Some(false),
1680                ..A11yState::default()
1681            },
1682        )
1683        .with_live_region(LiveRegion::Assertive);
1684        let mut new = old.clone();
1685        new.state.checked = Some(true);
1686        let batch = snapshot(vec![new], None).screen_reader_announcements_since(
1687            &snapshot(vec![old], None),
1688            ScreenReaderPolicy::default(),
1689        );
1690        assert_eq!(batch.announcements.len(), 1);
1691        assert_eq!(
1692            batch.announcements[0].reason,
1693            AnnouncementReason::LiveContentChanged
1694        );
1695        assert_eq!(batch.announcements[0].urgency, LiveRegion::Assertive);
1696        assert_eq!(batch.announcements[0].text, "checkbox: Control. checked");
1697    }
1698
1699    #[test]
1700    fn retained_focus_choice_value_text_changes_announce_without_live_regions() {
1701        for role in [A11yRole::RadioButton, A11yRole::MenuItem] {
1702            let old = interaction_node(
1703                role,
1704                A11yState {
1705                    value_now: Some(0.0),
1706                    value_text: Some("First".to_owned()),
1707                    ..A11yState::default()
1708                },
1709            );
1710            let mut new = old.clone();
1711            new.state.value_now = Some(1.0);
1712            new.state.value_text = Some("Second".to_owned());
1713            let before = snapshot(vec![old], Some(7));
1714            let after = snapshot(vec![new], Some(7));
1715            let batch =
1716                after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1717            assert_eq!(batch.announcements.len(), 1);
1718            assert_eq!(batch.dropped_count, 0);
1719            assert_eq!(
1720                batch.announcements[0].reason,
1721                AnnouncementReason::FocusedStateChanged
1722            );
1723            assert_eq!(
1724                batch.announcements[0].text,
1725                format!("{role}: Control. value Second")
1726            );
1727        }
1728    }
1729
1730    #[test]
1731    fn retained_focus_range_values_use_text_numeric_fallback_and_explicit_absence() {
1732        for role in [A11yRole::Slider, A11yRole::ScrollBar] {
1733            for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1734                for (from_number, from_text, to_number, to_text, expected) in [
1735                    (Some(10.0), None, Some(20.0), None, "value 20"),
1736                    (
1737                        Some(10.0),
1738                        Some("Low"),
1739                        Some(20.0),
1740                        Some("  Very\n high "),
1741                        "value Very high",
1742                    ),
1743                    (Some(10.0), Some("Low"), Some(20.0), None, "value 20"),
1744                    (
1745                        Some(10.0),
1746                        Some("Low"),
1747                        Some(20.0),
1748                        Some(" \n "),
1749                        "value 20",
1750                    ),
1751                    (Some(10.0), None, None, None, "value unavailable"),
1752                    (None, Some("Low"), None, None, "value unavailable"),
1753                ] {
1754                    let mut old = interaction_node(
1755                        role,
1756                        A11yState {
1757                            value_now: from_number,
1758                            value_text: from_text.map(str::to_owned),
1759                            ..A11yState::default()
1760                        },
1761                    );
1762                    let mut new = old.clone();
1763                    new.state.value_now = to_number;
1764                    new.state.value_text = to_text.map(str::to_owned);
1765                    old.live_region = region;
1766                    new.live_region = region;
1767                    let batch = snapshot(vec![new], Some(7)).screen_reader_announcements_since(
1768                        &snapshot(vec![old], Some(7)),
1769                        ScreenReaderPolicy::default(),
1770                    );
1771                    assert_eq!(batch.announcements.len(), 1);
1772                    assert_eq!(batch.dropped_count, 0);
1773                    assert_eq!(
1774                        batch.announcements[0].reason,
1775                        AnnouncementReason::FocusedStateChanged
1776                    );
1777                    assert_eq!(
1778                        batch.announcements[0].urgency,
1779                        region.unwrap_or(LiveRegion::Polite)
1780                    );
1781                    let focus = if region.is_some() { "focused, " } else { "" };
1782                    assert_eq!(
1783                        batch.announcements[0].text,
1784                        format!("{role}: Control. {focus}{expected}")
1785                    );
1786                    assert_eq!(batch.announcements[0].text.matches("value ").count(), 1);
1787                }
1788            }
1789        }
1790    }
1791
1792    #[test]
1793    fn numeric_changes_hidden_by_value_text_remain_in_diff_without_speech() {
1794        for role in [A11yRole::Slider, A11yRole::ScrollBar, A11yRole::ProgressBar] {
1795            for region in [None, Some(LiveRegion::Polite), Some(LiveRegion::Assertive)] {
1796                for focus in [None, Some(7)] {
1797                    let mut old = interaction_node(
1798                        role,
1799                        A11yState {
1800                            value_now: Some(10.0),
1801                            value_text: Some("Medium".to_owned()),
1802                            ..A11yState::default()
1803                        },
1804                    );
1805                    old.live_region = region;
1806                    let mut new = old.clone();
1807                    new.state.value_now = Some(11.0);
1808                    let before = snapshot(vec![old], focus);
1809                    let after = snapshot(vec![new], focus);
1810                    let diff = after.diff(&before);
1811                    assert_eq!(diff.changed[0].1.len(), 1);
1812                    assert!(matches!(
1813                        &diff.changed[0].1[0],
1814                        A11yChange::StateChanged { field, .. } if field == "value_now"
1815                    ));
1816                    let batch =
1817                        diff.screen_reader_announcements(&after, ScreenReaderPolicy::default());
1818                    assert!(batch.announcements.is_empty());
1819                    assert_eq!(batch.dropped_count, 0);
1820                }
1821            }
1822        }
1823    }
1824
1825    #[test]
1826    fn focused_text_edits_background_progress_and_range_metadata_stay_quiet() {
1827        for role in [A11yRole::TextInput, A11yRole::ProgressBar, A11yRole::Label] {
1828            let old = interaction_node(role, A11yState::default());
1829            let mut new = old.clone();
1830            new.state.value_text = Some("new content".to_owned());
1831            new.state.value_now = Some(20.0);
1832            new.state.busy = true;
1833            let before = snapshot(vec![old], Some(7));
1834            let after = snapshot(vec![new], Some(7));
1835            assert!(!after.diff(&before).is_empty());
1836            assert!(
1837                after
1838                    .screen_reader_announcements_since(&before, ScreenReaderPolicy::default())
1839                    .announcements
1840                    .is_empty()
1841            );
1842        }
1843        let old = interaction_node(A11yRole::Slider, A11yState::default());
1844        let mut new = old.clone();
1845        new.state.value_min = Some(0.0);
1846        new.state.value_max = Some(100.0);
1847        let batch = snapshot(vec![new], Some(7)).screen_reader_announcements_since(
1848            &snapshot(vec![old], Some(7)),
1849            ScreenReaderPolicy::default(),
1850        );
1851        assert!(batch.announcements.is_empty());
1852    }
1853
1854    #[test]
1855    fn combined_interaction_changes_share_one_bounded_live_announcement() {
1856        for region in [None, Some(LiveRegion::Assertive)] {
1857            let mut old = interaction_node(
1858                A11yRole::Slider,
1859                A11yState {
1860                    disabled: true,
1861                    required: true,
1862                    expanded: Some(true),
1863                    selected: true,
1864                    value_now: Some(10.0),
1865                    ..A11yState::default()
1866                },
1867            );
1868            old.live_region = region;
1869            let mut new = old.clone();
1870            new.state.disabled = false;
1871            new.state.required = false;
1872            new.state.expanded = Some(false);
1873            new.state.selected = false;
1874            new.state.value_now = Some(20.0);
1875            let background = A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 20, 1))
1876                .with_name("Background")
1877                .with_live_region(LiveRegion::Assertive);
1878            let before = snapshot(vec![old], Some(7));
1879            let after = snapshot(vec![background, new], Some(7));
1880            for cap in [0, 1, 2] {
1881                let batch = after.screen_reader_announcements_since(
1882                    &before,
1883                    ScreenReaderPolicy {
1884                        max_announcements: cap,
1885                        ..ScreenReaderPolicy::default()
1886                    },
1887                );
1888                assert_eq!(batch.announcements.len(), cap);
1889                assert_eq!(batch.dropped_count, 2 - cap);
1890                if cap > 0 {
1891                    assert_eq!(batch.announcements[0].node_id, Some(7));
1892                    assert_eq!(
1893                        batch.announcements[0].reason,
1894                        AnnouncementReason::FocusedStateChanged
1895                    );
1896                    assert_eq!(
1897                        batch.announcements[0].text,
1898                        if region.is_some() {
1899                            "slider: Control. focused, collapsed, value 20, enabled, not required, not selected"
1900                        } else {
1901                            "slider: Control. enabled, not required, collapsed, not selected, value 20"
1902                        }
1903                    );
1904                }
1905            }
1906        }
1907    }
1908
1909    #[test]
1910    fn arriving_focus_coalesces_activation_and_range_changes_with_live_content() {
1911        let old = interaction_node(A11yRole::Slider, A11yState::default())
1912            .with_live_region(LiveRegion::Assertive);
1913        let mut new = old.clone();
1914        new.state.value_now = Some(20.0);
1915        new.state.selected = true;
1916        new.state.expanded = Some(true);
1917        let batch = snapshot(vec![new], Some(7)).screen_reader_announcements_since(
1918            &snapshot(vec![old], None),
1919            ScreenReaderPolicy::default(),
1920        );
1921        assert_eq!(batch.announcements.len(), 1);
1922        assert_eq!(batch.dropped_count, 0);
1923        assert_eq!(
1924            batch.announcements[0].reason,
1925            AnnouncementReason::FocusChanged
1926        );
1927        assert_eq!(batch.announcements[0].urgency, LiveRegion::Assertive);
1928        assert_eq!(
1929            batch.announcements[0].text,
1930            "slider: Control. focused, expanded, selected, value 20"
1931        );
1932    }
1933}