Skip to main content

gpui/window/
a11y.rs

1//! Accessibility support, provided by [AccessKit][accesskit].
2//!
3//! There are user-facing guide-level docs [here](crate::_accessibility).
4//!
5//! ## Architecture
6//!
7//! ```text
8//!                              ┌────────────────────────────────┐   ┌─────────────────────┐
9//!                           ┌─▶│ AccessKit Adapter (MacOS)      │◀─▶│ MacOS System APIs   │
10//!                           │  └────────────────────────────────┘   └─────────────────────┘
11//!                           │
12//! ┌──────┐   ┌───────────┐  │  ┌────────────────────────────────┐   ┌─────────────────────┐
13//! │ GPUI │◀─▶│ AccessKit │◀─┼─▶│ AccessKit Adapter (Windows)    │◀─▶│ Windows System APIs │
14//! └──────┘   └───────────┘  │  └────────────────────────────────┘   └─────────────────────┘
15//!                           │
16//!                           │  ┌────────────────────────────────┐   ┌─────────────────────┐
17//!                           └─▶│ AccessKit Adapter (Linux)      │◀─▶│ dbus                │
18//!                              └────────────────────────────────┘   └─────────────────────┘
19//! ```
20//!
21//! In order for GPUI apps to be usable for people using assistive technology,
22//! we must do a few things:
23//! - Inform the system when the UI changes meaningfully. This includes:
24//!   - Reporting new/removed/changed UI elements
25//!   - *Not* reporting irrelevant UI changes, e.g. an invisible `div()` being
26//!     added.
27//!   - Reporting the appearance and capabilities of each UI element. For example:
28//!     - What does this piece of text say?
29//!     - How far along is this progress bar?
30//!     - Can this node be focused?
31//!     - Can this node have a value directly assigned? (e.g. a slider)
32//! - Allowing the system to interact with the UI by dispatching actions to
33//!   nodes. Note that AccessKit has its own [`Action`] type, which is not the
34//!   [`crate::Action`] trait.
35//! - Activate and deactivate accessibility features when requested by the
36//!   system.
37//!
38//! Activating and deactivating at the right time is trivial, so I won't go into
39//! detail here. The other two are almost orthogonal in implementation.
40//!
41//! The state for both lives in the [`A11y`] struct in this module.
42//!
43//! ### Reporting UI changes
44//!
45//! Every frame, we build a [`TreeUpdate`] and send it to the platform-specific
46//! adapter. A [`TreeUpdate`] is a representation of a subset of the UI tree.
47//! When the adapter receives the update, it diffs it against the previous
48//! update, and calls platform-specific APIs to inform screen readers about the
49//! changes. Nodes may have been created, destroyed, or updated.
50//!
51//! Each node has an ID, and this ID *should* be stable across frames. If a
52//! node's ID changes, then, from AccessKit's point of view, it is a different
53//! node.
54//!
55//! We derive the node ID from the [`GlobalElementId`] in
56//! [`GlobalElementId::accesskit_node_id`]. Nodes without [`GlobalElementId`]s
57//! cannot produce an AccessKit [`NodeId`], and so are not included in the
58//! accessibility tree. We try to warn when using accessibility APIs on
59//! [`div()`] without setting an ID.
60//!
61//! This all happens in [`Drawable::prepaint`]. The [`A11y`] struct maintains a
62//! stack of nodes during prepainting, which we can use to calculate the
63//! [`NodeId`]s, and record parent-child relationships. Once all [`Element`]s in
64//! a frame have been prepainted, we send the resulting [`TreeUpdate`] object to
65//! the adapter and the screen reader can announce the changes.
66//!
67//! #### Synthetic children
68//!
69//! Additionally, some nodes can register "synthetic children" using
70//! [`Element::a11y_synthetic_children`]. Normally, one accesskit node is pushed
71//! for every [`Element`] with a role and id. However, sometimes a single
72//! element may want to produce many accesskit nodes. These extra nodes are
73//! referred to as "synthetic children" of the element providing a non-default
74//! [`Element::a11y_synthetic_children`] implementation.
75//!
76//! The user is provided a builder-style API using [`A11ySubtreeBuilder`], which
77//! allows them to create push nodes that are children of the current node, as
78//! well as modify the current node itself.
79//!
80//! GPUI calls this callback *after* prepainting (and just before popping the
81//! corresponding element), since this step may need prepaint information to be
82//! available. In the future, we may want to add prepaint information more
83//! generally to [`Element::write_a11y_info`], but for now that's not necessary.
84//!
85//! ### Responding to actions
86//!
87//! On adapter creation, we provide a callback to the adapter, which can be used
88//! to dispatch actions. This callback forwards to [`A11y::action_listeners`], a
89//! mapping from [`NodeId`]s to action handlers (basically just `Box<dyn
90//! Fn()>`).
91//!
92//! This is populated in:
93//! - [`Window::on_a11y_action`], which is called by:
94//! - [`Interactivity::paint`], which is called by:
95//! - [`StatefulInteractiveElement::on_a11y_action`], which is a public-facing API
96//!
97//! These are cleared at the start of a frame, and re-populated during painting.
98//!
99//! [`NodeId`]: accesskit::NodeId
100
101use crate::*;
102
103pub(crate) mod debug;
104
105use crate::{App, Bounds, FocusId, Pixels, SharedString, Window};
106use accesskit::{Action, NodeId, TreeUpdate};
107use collections::{FxHashMap, FxHashSet};
108use smallvec::SmallVec;
109use std::hash::{Hash, Hasher};
110use std::sync::{
111    Arc,
112    atomic::{AtomicBool, Ordering},
113};
114
115/// The fixed AccessKit node ID used for the root of every window's a11y tree.
116pub(crate) const ROOT_NODE_ID: NodeId = NodeId(0);
117
118/// A listener for an accessibility action on a specific node.
119pub(crate) type A11yActionListener =
120    Box<dyn FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static>;
121
122/// Per-window accessibility state.
123///
124/// Manages the AccessKit tree that is built each frame and the mappings
125/// needed to dispatch incoming action requests back to the right elements.
126pub(crate) struct A11y {
127    /// Whether accessibility has been [forcibly disabled] for this window.
128    ///
129    /// [forcibly disabled]: crate::Application::new_inaccessible
130    force_disabled: bool,
131    /// Whether a11y features have been requested by the system.
132    ///
133    /// Updated by AccessKit using callbacks provided to the adapter. Can change
134    /// halfway through a frame.
135    active_flag: Arc<AtomicBool>,
136    /// Whether a11y features are active for *this specific frame*.
137    ///
138    /// At the start of each frame, we load [`Self::active_flag`] (using
139    /// [`Self::sync_active_flag`]) and use this to determine whether we
140    /// should construct a [`TreeUpdate`] for this frame. It's important that
141    /// this value is stable within a frame, because the builder API exposed by
142    /// this type maintains a stack of nodes and each must be pushed and popped
143    /// exactly once.
144    ///
145    /// At the end of the frame, we re-call [`Self::sync_active_flag`] to
146    /// determine whether we should actually send the finished [`TreeUpdate`].
147    active_this_frame: bool,
148    pub(crate) nodes: A11yNodeBuilder,
149    pub(crate) focus_ids: FxHashMap<NodeId, FocusId>,
150    pub(crate) node_bounds: FxHashMap<NodeId, Bounds<Pixels>>,
151    pub(crate) action_listeners: FxHashMap<NodeId, Vec<(Action, A11yActionListener)>>,
152    /// The window's title, used to label the root node so assistive
153    /// technology can tell windows apart.
154    window_title: Option<SharedString>,
155    /// The focus id we most recently reported as having no accessibility node,
156    /// used to log at most once per focus change rather than every frame.
157    last_focus_without_node: Option<FocusId>,
158    /// Retains the last tree update (and, in debug builds, per-node provenance)
159    /// so it can be dumped via [`crate::Window::debug_a11y_tree_json`].
160    debug: debug::A11yDebug,
161    /// Maps a view's [`EntityId`] to its `Render` type name
162    #[cfg(debug_assertions)]
163    pub(crate) view_type_names: FxHashMap<EntityId, &'static str>,
164}
165
166impl A11y {
167    pub(crate) fn new(
168        active_flag: Arc<AtomicBool>,
169        force_disabled: bool,
170        window_title: Option<SharedString>,
171    ) -> Self {
172        Self {
173            force_disabled,
174            active_flag,
175            active_this_frame: false,
176            nodes: A11yNodeBuilder::new(),
177            focus_ids: FxHashMap::default(),
178            node_bounds: FxHashMap::default(),
179            action_listeners: FxHashMap::default(),
180            window_title,
181            last_focus_without_node: None,
182            debug: debug::A11yDebug::default(),
183            #[cfg(debug_assertions)]
184            view_type_names: FxHashMap::default(),
185        }
186    }
187
188    /// Logs (once per focus change) that the focused element is not exposed to
189    /// assistive technology because it has no accessibility node. When this
190    /// happens, screen readers fall back to announcing the whole window instead
191    /// of the focused element. The fix is to give the element both an
192    /// `.id(...)` and a `.role(...)`.
193    pub(crate) fn note_focus_without_node(&mut self, focus_id: FocusId, reason: &str) {
194        if self.last_focus_without_node != Some(focus_id) {
195            self.last_focus_without_node = Some(focus_id);
196            log::info!(
197                "a11y: focused element ({focus_id:?}) has no accessibility node \
198                 ({reason}); assistive technology will announce the whole window \
199                 instead. Give it both an `.id(...)` and a `.role(...)` to expose it."
200            );
201        }
202    }
203
204    pub(crate) fn set_window_title(&mut self, title: impl Into<SharedString>) {
205        self.window_title = Some(title.into());
206    }
207
208    /// Ensures that [`Self::is_active`] returns up to date information.
209    ///
210    /// See the docs for [`Self::active_flag`] and [`Self::active_this_frame`]
211    /// for more commentary.
212    pub(crate) fn sync_active_flag(&mut self) {
213        self.active_this_frame = !self.force_disabled && self.active_flag.load(Ordering::SeqCst);
214    }
215
216    pub(crate) fn is_active(&self) -> bool {
217        self.active_this_frame
218    }
219
220    pub(crate) fn set_focusable(&mut self, node_id: NodeId, focus_id: FocusId) {
221        self.focus_ids.insert(node_id, focus_id);
222    }
223
224    /// Report `node_id` as the currently-focused node, if it is present in the
225    /// tree.
226    ///
227    /// Must only be called once per frame.
228    pub(crate) fn set_focus(&mut self, node_id: NodeId) {
229        // A focused node must have been registered as focusable this frame.
230        if !self.focus_ids.contains_key(&node_id) {
231            if cfg!(debug_assertions) {
232                panic!("set_focus called for a node that was not registered with set_focusable");
233            } else {
234                log::warn!(
235                    "a11y: set_focus called for a node that was not registered with \
236                     set_focusable ({node_id:?})"
237                );
238            }
239        }
240        if self.nodes.has_node(node_id) {
241            // The focused element is properly exposed; reset the dedup so a
242            // later focus on a node-less element logs again.
243            self.last_focus_without_node = None;
244            let focus_id = self.focus_ids.get(&node_id).copied();
245            let existing_focus_id = self
246                .nodes
247                .focus
248                .and_then(|existing| self.focus_ids.get(&existing).copied());
249            if focus_id.is_some() && focus_id == existing_focus_id {
250                // Composite controls can expose nested role-bearing nodes for
251                // one logical GPUI focus handle (for example a spinbutton
252                // around its editable text node). Prefer the deepest node
253                // visited during prepaint, while retaining the assertion for
254                // genuinely competing focus handles.
255                self.nodes.focus = Some(node_id);
256            } else {
257                self.nodes.set_focus(node_id);
258            }
259        } else {
260            // The element registered a focus handle and an id, but never got a
261            // node because it has no role.
262            if let Some(focus_id) = self.focus_ids.get(&node_id).copied() {
263                self.note_focus_without_node(focus_id, "it has an id but no role");
264            }
265        }
266    }
267
268    pub(crate) fn set_active_descendant(&mut self, node_id: NodeId) {
269        // The active descendant must be a descendant of the focused container,
270        // not the focused node itself.
271        if self.nodes.node_is_focused(node_id) {
272            if cfg!(debug_assertions) {
273                panic!("set_active_descendant called on the focused node");
274            } else {
275                log::warn!("a11y: set_active_descendant called on the focused node ({node_id:?})");
276            }
277            return;
278        }
279        if self.nodes.has_node(node_id) && self.nodes.focus_is_ancestor_of_current() {
280            self.nodes.set_active_descendant(node_id);
281        }
282    }
283
284    /// Clear per-frame state and push the root node to start a new frame.
285    pub(crate) fn begin_frame(&mut self) {
286        self.focus_ids.clear();
287        self.node_bounds.clear();
288        self.action_listeners.clear();
289        self.nodes.begin_frame(self.window_title.as_ref());
290    }
291
292    /// Finalize the tree and produce a [`TreeUpdate`] for the platform adapter.
293    pub(crate) fn end_frame(&mut self, frame: debug::FrameDebugInfo) -> TreeUpdate {
294        let update = self.nodes.finalize();
295        self.debug.capture(
296            &update,
297            self.nodes.focus,
298            self.nodes.active_descendant,
299            self.window_title.as_ref(),
300            frame,
301        );
302        #[cfg(debug_assertions)]
303        self.debug.capture_node_info(&self.nodes.node_info);
304        update
305    }
306
307    pub(crate) fn debug_tree_json(&self) -> Option<String> {
308        self.debug.to_json()
309    }
310}
311
312/// Builder API for synthetic children. See the docs for
313/// [`Element::a11y_synthetic_children`].
314pub struct A11ySubtreeBuilder<'a> {
315    parent_id: NodeId,
316    nodes: &'a mut A11yNodeBuilder,
317    /// Provenance of the real element whose `a11y_synthetic_children` is
318    /// running.
319    #[cfg(debug_assertions)]
320    creator: debug::NodeCreator,
321}
322
323impl<'a> A11ySubtreeBuilder<'a> {
324    pub(crate) fn new(parent_id: NodeId, nodes: &'a mut A11yNodeBuilder) -> Self {
325        Self {
326            parent_id,
327            nodes,
328            #[cfg(debug_assertions)]
329            creator: debug::NodeCreator::default(),
330        }
331    }
332
333    #[cfg(debug_assertions)]
334    pub(crate) fn with_creator(mut self, creator: debug::NodeCreator) -> Self {
335        self.creator = creator;
336        self
337    }
338
339    /// Derive a [`NodeId`] for a synthetic child.
340    ///
341    /// The generated ID is based on the hash of `key`, as well as the parent's
342    /// ID. This means that `key`s must be unique within the same
343    /// [`Element::a11y_synthetic_children`] call, but may be duplicated across
344    /// different calls.
345    pub fn synthetic_node_id(&self, key: impl Hash) -> NodeId {
346        let mut hasher = std::hash::DefaultHasher::default();
347        self.parent_id.0.hash(&mut hasher);
348        key.hash(&mut hasher);
349        NodeId(hasher.finish())
350    }
351
352    /// Append a synthetic leaf node as a child of this element's node.
353    ///
354    /// Returns `false` if a node with this id is already present in the tree,
355    /// in which case the node is discarded.
356    pub fn push_child(&mut self, id: NodeId, node: accesskit::Node) -> bool {
357        let pushed = self.nodes.push_leaf(id, node);
358        #[cfg(debug_assertions)]
359        if pushed {
360            self.nodes.record_node_info(
361                id,
362                debug::NodeDebugInfo {
363                    synthetic: true,
364                    view: self.creator.view,
365                    element_id: self.creator.element_id.clone(),
366                    source_location: self.creator.source_location,
367                },
368            );
369        }
370        pushed
371    }
372
373    /// A mutable reference to the parent node.
374    pub fn parent_node(&mut self) -> &mut accesskit::Node {
375        self.nodes
376            .current_node_mut()
377            .expect("A11ySubtreeBuilder exists only while its element's node is on the stack")
378    }
379}
380
381pub(crate) struct A11yNodeBuilder {
382    ids_stack: SmallVec<[NodeId; 16]>,
383    nodes_stack: SmallVec<[accesskit::Node; 16]>,
384    /// This is the exact type required by accesskit, so we can't just make it a
385    /// `HashMap<NodeId, Node>` to remove the need for `seen_ids`
386    all_nodes: Vec<(NodeId, accesskit::Node)>,
387    seen_ids: FxHashSet<NodeId>,
388    /// The node that GPUI considers focused. Note that this may be different to
389    /// what is reported to accesskit - see [`Self::active_descendant`]
390    focus: Option<NodeId>,
391    /// If a node calls `.aria_active_descendant()`, AND an ancestor is focused,
392    /// override it as the focused node. This supports the "active descendant"
393    /// pattern, which allows a focused container to act as if a descendant is
394    /// focused.
395    active_descendant: Option<NodeId>,
396    #[cfg(debug_assertions)]
397    node_info: FxHashMap<NodeId, debug::NodeDebugInfo>,
398}
399
400impl A11yNodeBuilder {
401    fn new() -> Self {
402        Self {
403            ids_stack: SmallVec::new(),
404            nodes_stack: SmallVec::new(),
405            all_nodes: Vec::new(),
406            seen_ids: FxHashSet::default(),
407            focus: None,
408            active_descendant: None,
409            #[cfg(debug_assertions)]
410            node_info: FxHashMap::default(),
411        }
412    }
413
414    /// Records provenance for a node already pushed this frame. Debug builds only.
415    #[cfg(debug_assertions)]
416    pub(crate) fn record_node_info(&mut self, id: NodeId, info: debug::NodeDebugInfo) {
417        self.node_info.insert(id, info);
418    }
419
420    #[must_use]
421    fn can_push(&mut self, id: NodeId) -> bool {
422        debug_assert!(!self.ids_stack.is_empty(), "node pushed before push_root");
423
424        if !self.seen_ids.insert(id) {
425            debug_assert!(
426                false,
427                "Duplicate a11y node id: {id:?}. In a release build, this node would be silently discarded from the a11y tree."
428            );
429            return false;
430        }
431
432        true
433    }
434
435    /// Push a new node onto the stack. It becomes a child of the current
436    /// top-of-stack node.
437    ///
438    /// Returns `true` if the node was successfully pushed.
439    pub(crate) fn push(&mut self, id: NodeId, node: accesskit::Node) -> bool {
440        if !self.can_push(id) {
441            return false;
442        }
443
444        if let Some(parent) = self.nodes_stack.last_mut() {
445            parent.push_child(id);
446        }
447        self.ids_stack.push(id);
448        self.nodes_stack.push(node);
449        true
450    }
451
452    /// Add a leaf node as a child of the current top-of-stack node, without
453    /// pushing it onto the stack. Semantically equivalent to a [`Self::push`]
454    /// followed by a [`Self::pop`].
455    ///
456    /// Returns `true` if the node was successfully pushed.
457    pub(crate) fn push_leaf(&mut self, id: NodeId, node: accesskit::Node) -> bool {
458        if !self.can_push(id) {
459            return false;
460        }
461
462        if let Some(parent) = self.nodes_stack.last_mut() {
463            parent.push_child(id);
464        }
465        self.all_nodes.push((id, node));
466        true
467    }
468
469    pub(crate) fn current_node_mut(&mut self) -> Option<&mut accesskit::Node> {
470        self.nodes_stack.last_mut()
471    }
472
473    /// Pop the current node off the stack and finalize it into the all_nodes
474    /// list.
475    pub(crate) fn pop(&mut self) {
476        debug_assert!(self.ids_stack.len() > 1, "pop would remove the root node");
477
478        if let (Some(id), Some(node)) = (self.ids_stack.pop(), self.nodes_stack.pop()) {
479            self.all_nodes.push((id, node));
480        }
481    }
482
483    /// Push the root node to start a new frame.
484    fn begin_frame(&mut self, window_title: Option<&SharedString>) {
485        self.all_nodes.clear();
486        self.ids_stack.clear();
487        self.nodes_stack.clear();
488        self.seen_ids.clear();
489        #[cfg(debug_assertions)]
490        self.node_info.clear();
491        let mut root_node = accesskit::Node::new(accesskit::Role::Window);
492        if let Some(title) = window_title {
493            root_node.set_label(title.to_string());
494        }
495
496        self.ids_stack.push(ROOT_NODE_ID);
497        self.nodes_stack.push(root_node);
498        self.focus = None;
499        self.active_descendant = None;
500    }
501
502    /// Returns whether a node with the given ID has been pushed in this frame.
503    pub(crate) fn has_node(&self, id: NodeId) -> bool {
504        id == ROOT_NODE_ID || self.seen_ids.contains(&id)
505    }
506
507    /// Returns whether `id` is the node currently reported as focused.
508    pub(crate) fn node_is_focused(&self, id: NodeId) -> bool {
509        self.focus == Some(id)
510    }
511
512    pub(crate) fn focus_is_ancestor_of_current(&self) -> bool {
513        let Some(focus) = self.focus else {
514            return false;
515        };
516
517        // The current node is on top of the stack; everything below it is an
518        // ancestor.
519        let ancestor_count = self.ids_stack.len().saturating_sub(1);
520        self.ids_stack[..ancestor_count].contains(&focus)
521    }
522
523    pub(crate) fn set_active_descendant(&mut self, id: NodeId) {
524        if self
525            .active_descendant
526            .is_some_and(|existing| existing != id)
527        {
528            if cfg!(debug_assertions) {
529                panic!("active descendant claimed by multiple nodes in one frame");
530            } else {
531                log::warn!(
532                    "a11y: multiple nodes claimed the active descendant this frame; \
533                     using last-wins ({id:?})"
534                );
535            }
536        }
537        self.active_descendant = Some(id);
538    }
539
540    pub(crate) fn set_focus(&mut self, id: NodeId) {
541        if self.focus.is_some() {
542            if cfg!(debug_assertions) {
543                panic!("set_focus called more than once in a single frame");
544            } else {
545                log::warn!(
546                    "a11y: set_focus called more than once in a single frame; \
547                     using last-wins ({id:?})"
548                );
549            }
550        }
551        self.focus = Some(id);
552    }
553
554    fn finalize(&mut self) -> TreeUpdate {
555        // Stack should contain only the root node
556        debug_assert_eq!(self.ids_stack.len(), 1);
557        debug_assert_eq!(self.ids_stack[0], ROOT_NODE_ID);
558
559        if self.ids_stack.len() != 1 {
560            log::error!(
561                "a11y: Stack imbalance at end of frame: expected 1 (root), got {}. \
562                 Some elements may have pushed without popping.",
563                self.ids_stack.len()
564            );
565        }
566
567        // Pop remaining nodes (should just be the root).
568        while !self.ids_stack.is_empty() {
569            if let (Some(id), Some(node)) = (self.ids_stack.pop(), self.nodes_stack.pop()) {
570                self.all_nodes.push((id, node));
571            }
572        }
573
574        let focus = match self.active_descendant {
575            Some(id) if self.has_node(id) => id,
576            Some(id) => {
577                if cfg!(debug_assertions) {
578                    panic!("active_descendant set to {id:?}, which is not in the tree");
579                } else {
580                    log::warn!("active_descendant set to {id:?}, which is not in the tree");
581                    self.focus.unwrap_or(ROOT_NODE_ID)
582                }
583            }
584
585            _ => self.focus.unwrap_or(ROOT_NODE_ID),
586        };
587
588        let nodes = std::mem::take(&mut self.all_nodes);
589        let update = TreeUpdate {
590            nodes,
591            tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
592            tree_id: accesskit::TreeId::ROOT,
593            focus,
594        };
595
596        Self::repair_tree_update(update)
597    }
598
599    /// Accesskit panics on invalid [`TreeUpdate`]s. This function defensively
600    /// checks invariants that accesskit panics on, and tries to fix them.
601    fn repair_tree_update(mut update: TreeUpdate) -> TreeUpdate {
602        let node_ids: FxHashSet<NodeId> = update.nodes.iter().map(|(id, _)| *id).collect();
603
604        // Focus must point to a node in the tree.
605        if !node_ids.contains(&update.focus) {
606            log::error!(
607                "a11y: Focused node {:?} is not in the tree ({} nodes). \
608                 Falling back to root. This is a bug in the a11y tree builder.",
609                update.focus,
610                update.nodes.len()
611            );
612            update.focus = ROOT_NODE_ID;
613        }
614
615        // Every child reference must point to a node in the update.
616        for (id, node) in &mut update.nodes {
617            let has_invalid_child = node
618                .children()
619                .iter()
620                .any(|child_id| !node_ids.contains(child_id));
621            if has_invalid_child {
622                let children = node.children();
623                let invalid_count = children
624                    .iter()
625                    .filter(|child_id| !node_ids.contains(child_id))
626                    .count();
627                log::error!(
628                    "a11y: Node {:?} references {} children not present in the tree. \
629                     Stripping invalid child references.",
630                    id,
631                    invalid_count
632                );
633                let valid: Vec<NodeId> = children
634                    .iter()
635                    .copied()
636                    .filter(|child_id| node_ids.contains(child_id))
637                    .collect();
638                node.set_children(valid);
639            }
640        }
641
642        update
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    // Import specific items rather than glob-importing `super`, which would pull
649    // in gpui's own `test` attribute macro and shadow the standard one.
650    use super::{A11y, A11yNodeBuilder, ROOT_NODE_ID};
651    use crate::FocusId;
652    use accesskit::{NodeId, Role};
653    use std::sync::{Arc, atomic::AtomicBool};
654
655    fn test_node() -> accesskit::Node {
656        accesskit::Node::new(Role::GenericContainer)
657    }
658
659    fn new_builder() -> A11yNodeBuilder {
660        let mut builder = A11yNodeBuilder::new();
661        builder.begin_frame(None);
662        builder
663    }
664
665    fn new_a11y() -> A11y {
666        let mut a11y = A11y::new(Arc::new(AtomicBool::new(true)), false, None);
667        a11y.begin_frame();
668        a11y
669    }
670
671    #[test]
672    fn active_descendant_honored_when_container_focused() {
673        let mut builder = new_builder();
674        let container = NodeId(1);
675        let item = NodeId(2);
676
677        assert!(builder.push(container, test_node()));
678        builder.set_focus(container);
679        assert!(builder.push(item, test_node()));
680
681        // The item is on top of the stack; the focused container is its
682        // ancestor, so the claim is honored.
683        assert!(builder.focus_is_ancestor_of_current());
684        builder.set_active_descendant(item);
685
686        builder.pop(); // item
687        builder.pop(); // container
688        let update = builder.finalize();
689        assert_eq!(update.focus, item);
690    }
691
692    #[test]
693    fn active_descendant_honored_for_deep_descendant() {
694        let mut builder = new_builder();
695        let container = NodeId(1);
696        let group = NodeId(2);
697        let item = NodeId(3);
698
699        assert!(builder.push(container, test_node()));
700        builder.set_focus(container);
701        assert!(builder.push(group, test_node()));
702        assert!(builder.push(item, test_node()));
703
704        // The item is a grandchild of the focused container; depth doesn't
705        // matter, the focused ancestor is still on the stack.
706        assert!(builder.focus_is_ancestor_of_current());
707        builder.set_active_descendant(item);
708
709        builder.pop(); // item
710        builder.pop(); // group
711        builder.pop(); // container
712        let update = builder.finalize();
713        assert_eq!(update.focus, item);
714    }
715
716    #[test]
717    fn active_descendant_ignored_when_focus_in_other_subtree() {
718        let mut builder = new_builder();
719        let focused_container = NodeId(1);
720        let focused_leaf = NodeId(2);
721        let other_container = NodeId(3);
722        let other_item = NodeId(4);
723
724        // First subtree holds real focus.
725        assert!(builder.push(focused_container, test_node()));
726        assert!(builder.push(focused_leaf, test_node()));
727        builder.set_focus(focused_leaf);
728        builder.pop(); // focused_leaf
729        builder.pop(); // focused_container
730
731        // Second subtree: its item would claim the active descendant, but the
732        // focus is not on any of its ancestors, so the gate rejects it.
733        assert!(builder.push(other_container, test_node()));
734        assert!(builder.push(other_item, test_node()));
735        assert!(!builder.focus_is_ancestor_of_current());
736        builder.pop(); // other_item
737        builder.pop(); // other_container
738
739        let update = builder.finalize();
740        assert_eq!(update.focus, focused_leaf);
741    }
742
743    #[test]
744    fn active_descendant_ignored_when_nothing_focused() {
745        let mut builder = new_builder();
746        let container = NodeId(1);
747        let item = NodeId(2);
748
749        assert!(builder.push(container, test_node()));
750        assert!(builder.push(item, test_node()));
751
752        // Nothing is focused (focus defaults to the root window node), so the
753        // gate rejects the claim.
754        assert!(!builder.focus_is_ancestor_of_current());
755        builder.pop();
756        builder.pop();
757
758        let update = builder.finalize();
759        assert_eq!(update.focus, ROOT_NODE_ID);
760    }
761
762    #[test]
763    fn regular_focus_used_when_no_active_descendant() {
764        let mut builder = new_builder();
765        let focused = NodeId(1);
766
767        assert!(builder.push(focused, test_node()));
768        builder.set_focus(focused);
769        builder.pop();
770
771        let update = builder.finalize();
772        assert_eq!(update.focus, focused);
773    }
774
775    #[test]
776    fn focus_is_ancestor_excludes_self_and_non_ancestors() {
777        let mut builder = new_builder();
778        let container = NodeId(1);
779        let item = NodeId(2);
780
781        assert!(builder.push(container, test_node()));
782        builder.set_focus(container);
783
784        // With the focused container itself on top, it is not its own (strict)
785        // ancestor, so the gate is false.
786        assert!(!builder.focus_is_ancestor_of_current());
787
788        assert!(builder.push(item, test_node()));
789        // Now the focused container is a strict ancestor of the item on top.
790        assert!(builder.focus_is_ancestor_of_current());
791
792        builder.pop();
793        builder.pop();
794    }
795
796    // The double-claim guard panics only in debug builds; in release it falls
797    // back to last-wins with a warning.
798    #[test]
799    #[cfg_attr(
800        debug_assertions,
801        should_panic(expected = "active descendant claimed by multiple nodes")
802    )]
803    fn multiple_active_descendant_claims_panic_in_debug() {
804        let mut builder = new_builder();
805        builder.set_active_descendant(NodeId(1));
806        builder.set_active_descendant(NodeId(2));
807    }
808
809    // Setting focus twice in one frame means two elements both claimed window
810    // focus; that panics in debug and falls back to last-wins in release.
811    #[test]
812    #[cfg_attr(
813        debug_assertions,
814        should_panic(expected = "set_focus called more than once")
815    )]
816    fn setting_focus_twice_panics_in_debug() {
817        let mut builder = new_builder();
818        builder.set_focus(NodeId(1));
819        builder.set_focus(NodeId(2));
820    }
821
822    // Focusing a node that was never registered as focusable is a bug: panic in
823    // debug, warn in release.
824    #[test]
825    #[cfg_attr(
826        debug_assertions,
827        should_panic(expected = "was not registered with set_focusable")
828    )]
829    fn set_focus_without_set_focusable() {
830        let mut a11y = new_a11y();
831        let node = NodeId(1);
832        assert!(a11y.nodes.push(node, test_node()));
833        // set_focusable was never called for `node`.
834        a11y.set_focus(node);
835    }
836
837    // The focused node cannot also be its own active descendant: panic in
838    // debug, warn in release.
839    #[test]
840    #[cfg_attr(debug_assertions, should_panic(expected = "on the focused node"))]
841    fn set_active_descendant_on_focused_node() {
842        let mut a11y = new_a11y();
843        let node = NodeId(1);
844        assert!(a11y.nodes.push(node, test_node()));
845        a11y.set_focusable(node, FocusId::default());
846        a11y.set_focus(node);
847        a11y.set_active_descendant(node);
848    }
849
850    // Two sibling children of a focused container both claim the active
851    // descendant (both pass the focus gate). The second claim is a bug: panic
852    // in debug, last-wins + warn in release.
853    #[test]
854    #[cfg_attr(
855        debug_assertions,
856        should_panic(expected = "active descendant claimed by multiple nodes")
857    )]
858    fn two_siblings_claiming_active_descendant() {
859        let mut a11y = new_a11y();
860        let container = NodeId(1);
861        let first = NodeId(2);
862        let second = NodeId(3);
863
864        assert!(a11y.nodes.push(container, test_node()));
865        a11y.set_focusable(container, FocusId::default());
866        a11y.set_focus(container);
867
868        assert!(a11y.nodes.push(first, test_node()));
869        a11y.set_active_descendant(first);
870        a11y.nodes.pop(); // first
871
872        assert!(a11y.nodes.push(second, test_node()));
873        a11y.set_active_descendant(second);
874        a11y.nodes.pop(); // second
875
876        a11y.nodes.pop(); // container
877    }
878
879    // Node A is focused; node C (a child of the unfocused node B) claims the
880    // active descendant. The final tree must still report A as focused.
881    #[test]
882    fn active_descendant_in_unfocused_subtree_keeps_real_focus() {
883        let mut a11y = new_a11y();
884        let a = NodeId(1);
885        let b = NodeId(2);
886        let c = NodeId(3);
887
888        assert!(a11y.nodes.push(a, test_node()));
889        a11y.set_focusable(a, FocusId::default());
890        a11y.set_focus(a);
891        a11y.nodes.pop(); // a
892
893        assert!(a11y.nodes.push(b, test_node()));
894        assert!(a11y.nodes.push(c, test_node()));
895        a11y.set_active_descendant(c);
896        a11y.nodes.pop(); // c
897        a11y.nodes.pop(); // b
898
899        let update = a11y.end_frame(Default::default());
900        assert_eq!(update.focus, a);
901    }
902}