1
//! Accessibility Manager for integrating with `accesskit`.
2
//!
3
//! This module provides the `A11yManager` which:
4
//!
5
//! - Maintains the accessibility tree state
6
//! - Generates `TreeUpdate`s after each layout pass
7
//! - Handles `ActionRequest`s from assistive technologies
8
//!
9
//! The manager translates between Azul's internal DOM representation and
10
//! the platform-agnostic `accesskit` tree format.
11

            
12
#[cfg(feature = "a11y")]
13
use std::collections::{BTreeMap, BTreeSet, HashMap};
14

            
15
#[cfg(feature = "a11y")]
16
use accesskit::{Action, ActionRequest, Node, NodeId as A11yNodeId, Rect, Role, Tree, TreeUpdate};
17
use azul_core::{
18
    dom::{
19
        AccessibilityAction, AccessibilityInfo, AccessibilityRole, AccessibilityState, DomId,
20
        DomNodeId, NodeData, NodeId, NodeType, TextSelectionStartEnd,
21
    },
22
    geom::{LogicalPosition, LogicalSize},
23
    styled_dom::NodeHierarchyItem,
24
};
25
use azul_css::AzString;
26

            
27
use crate::{solver3::layout_tree::LayoutNodeHot, window::DomLayoutResult};
28

            
29
/// Is this DOM node exposed to assistive technology?
30
///
31
/// ONE definition, deliberately. It used to be an inline condition inside
32
/// [`A11yManager::update_tree`], which is fine while accesskit is the only
33
/// consumer — but accesskit ships no `UIKit` and no Android backend, so the iOS
34
/// and Android bridges have to build their element lists themselves, and the
35
/// E2E `accessibility_action` op has to decide whether the node a test is
36
/// activating is one a screen reader could ever reach. Three consumers guessing
37
/// separately is three different answers to "can a screen reader see this?".
38
///
39
/// Included: anything carrying explicit `AccessibilityInfo`, anything
40
/// contenteditable, anything focusable, and every node type that is not pure
41
/// metadata (`<head>`, `<meta>`, `<script>`, …) or a pseudo-element.
42
#[must_use]
43
311553
pub fn is_exposed_to_accessibility(node_data: &NodeData) -> bool {
44
311553
    node_data.get_accessibility_info().is_some()
45
292939
        || node_data.is_contenteditable()
46
288937
        || node_data.is_focusable()
47
287223
        || !matches!(
48
288247
            node_data.node_type,
49
            NodeType::Head
50
                | NodeType::Meta
51
                | NodeType::Link
52
                | NodeType::Script
53
                | NodeType::Style
54
                | NodeType::Base
55
                | NodeType::Before
56
                | NodeType::After
57
                | NodeType::Marker
58
                | NodeType::Placeholder
59
                | NodeType::Source
60
                | NodeType::Track
61
                | NodeType::Param
62
                | NodeType::Col
63
                | NodeType::ColGroup
64
                | NodeType::Wbr
65
                | NodeType::Rp
66
                | NodeType::Rtc
67
                | NodeType::Bdo
68
                | NodeType::Bdi
69
                | NodeType::Data
70
                | NodeType::Map
71
                | NodeType::Area
72
                | NodeType::VirtualView
73
        )
74
311553
}
75

            
76
/// Does this declaration actually say what KIND of control the node is?
77
///
78
/// ONE definition, deliberately — three surfaces resolve a node's role (the
79
/// accesskit tree's `A11yManager::build_node`, its no-layout fallback in
80
/// `A11yManager::update_tree`, and the iOS/Android `A11ySnapshot`) and they
81
/// must not disagree about it.
82
///
83
/// `AccessibilityRole::Unknown` is what `AccessibilityInfo::default()` hands
84
/// out, and it is the value `AccessibilityInfo::assign` treats as "not
85
/// specified" when it merges a patch. It therefore means *the declaration is
86
/// silent about the kind of control*, NOT *this control is of an unknown
87
/// kind* — so it must never outrank the element's own type.
88
///
89
/// It used to. Because `build_node` selected the role as "if there is any
90
/// `AccessibilityInfo` at all, its `role` wins", the one-field form the engine
91
/// itself recommends —
92
///
93
/// ```ignore
94
/// slider.dom().with_accessibility_name("Volume")
95
/// ```
96
///
97
/// — replaced the node's real role with `Role::Unknown`, which `VoiceOver` skips
98
/// exactly the way it skips `GenericContainer`. Naming a control DELETED it
99
/// from the accessibility tree, so the more accessibility an app declared the
100
/// less of it a screen reader could reach: 25 of `AzWidgets`' 691 nodes were
101
/// `Unknown` for this reason alone.
102
#[must_use]
103
17426
pub const fn accessibility_role_is_specified(role: &AccessibilityRole) -> bool {
104
17426
    !matches!(role, AccessibilityRole::Unknown)
105
17426
}
106

            
107
/// Cursor/selection info passed to the a11y tree builder.
108
/// Used to set `text_selection` on contenteditable nodes so screen readers
109
/// can announce the cursor position and selection range.
110
#[cfg(feature = "a11y")]
111
#[derive(Debug, Clone, Copy)]
112
pub struct CursorA11yInfo {
113
    pub dom_id: DomId,
114
    pub node_id: NodeId,
115
    /// Byte offset of the selection anchor (start of selection, or cursor pos if no range)
116
    pub anchor_offset: usize,
117
    /// Byte offset of the selection focus (end of selection, or same as anchor for cursor)
118
    pub focus_offset: usize,
119
}
120

            
121
/// Why [`A11yManager::publish`] refused a `TreeUpdate`.
122
///
123
/// Each variant is one invariant `accesskit_consumer::tree::State::update`
124
/// enforces with a `panic!` — and the release build is `panic = "abort"`, so
125
/// the `catch_unwind` the shells wrap the adapter in cannot save the process.
126
/// An update that would trip one of these is never handed over; the caller
127
/// rebuilds the full tree (incremental path) or keeps the last good state
128
/// (full path). This is the 2026-08-29 `AzWriter` crash class: focus parked in a
129
/// DOM that two `RefreshDom` relayouts had rebuilt.
130
#[cfg(feature = "a11y")]
131
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132
pub enum A11yUpdateError {
133
    /// An incremental update (no `tree`) arrived before any full tree.
134
    NoTreeYet,
135
    /// A child id names neither a delivered node nor a node in this update.
136
    UnknownChild {
137
        parent: A11yNodeId,
138
        child: A11yNodeId,
139
    },
140
    /// The update lists one child under two parents (or twice under one).
141
    DuplicateChild(A11yNodeId),
142
    /// An update node is neither the root, nor already delivered, nor the
143
    /// child of another update node — the consumer cannot place it.
144
    OrphanNode(A11yNodeId),
145
    /// The root the update names is not in the resulting tree.
146
    RootMissing(A11yNodeId),
147
    /// `focus` names no node in the resulting tree (tree.rs:75).
148
    FocusNotInTree(A11yNodeId),
149
}
150

            
151
/// The accessibility tree as the platform adapter currently holds it: every
152
/// node id with its child list. [`Self::apply`] replays the consumer's merge
153
/// rules so a bad update is caught HERE, in safe code, instead of aborting
154
/// the process inside the adapter.
155
#[cfg(feature = "a11y")]
156
#[derive(Debug, Clone, Default, PartialEq, Eq)]
157
pub struct A11yTreeMirror {
158
    pub root: Option<A11yNodeId>,
159
    pub children: BTreeMap<A11yNodeId, Vec<A11yNodeId>>,
160
}
161

            
162
#[cfg(feature = "a11y")]
163
impl A11yTreeMirror {
164
    /// Apply `update` exactly the way `accesskit_consumer` would and return
165
    /// the resulting tree — or the invariant the consumer would have
166
    /// panicked on.
167
    ///
168
    /// Merge rules mirrored from `tree.rs::State::update`:
169
    /// - `tree: Some` re-roots; `tree: None` keeps the delivered root (and needs one).
170
    /// - every child an update node lists must exist (delivered or in the update); a child listed
171
    ///   twice is a duplicate.
172
    /// - an update node must be the root, already delivered, or listed as a child by another update
173
    ///   node.
174
    /// - nodes an updated parent no longer lists become unreachable and are dropped (with their
175
    ///   subtrees) — the consumer removes them silently, which is why a focus on such a node is the
176
    ///   classic abort.
177
    /// - root and focus must survive in the reachable set.
178
14789
    pub fn apply(&self, update: &TreeUpdate) -> Result<Self, A11yUpdateError> {
179
14789
        let root = match (&update.tree, self.root) {
180
14669
            (Some(t), _) => t.root,
181
110
            (None, Some(r)) => r,
182
10
            (None, None) => return Err(A11yUpdateError::NoTreeYet),
183
        };
184
14779
        let update_ids: BTreeSet<A11yNodeId> = update.nodes.iter().map(|(id, _)| *id).collect();
185

            
186
14779
        let mut seen_children = BTreeSet::new();
187
845384
        for (id, node) in &update.nodes {
188
830625
            for &child in node.children() {
189
813933
                if !seen_children.insert(child) {
190
10
                    return Err(A11yUpdateError::DuplicateChild(child));
191
813923
                }
192
813923
                if !self.children.contains_key(&child) && !update_ids.contains(&child) {
193
10
                    return Err(A11yUpdateError::UnknownChild { parent: *id, child });
194
813913
                }
195
            }
196
        }
197
839066
        for id in &update_ids {
198
826280
            if *id != root && !self.children.contains_key(id) && !seen_children.contains(id) {
199
1973
                return Err(A11yUpdateError::OrphanNode(*id));
200
824307
            }
201
        }
202

            
203
12786
        let mut merged = self.children.clone();
204
828644
        for (id, node) in &update.nodes {
205
815858
            merged.insert(*id, node.children().to_vec());
206
815858
        }
207
12786
        if !merged.contains_key(&root) {
208
            return Err(A11yUpdateError::RootMissing(root));
209
12786
        }
210
12786
        let mut reachable = BTreeSet::new();
211
12786
        let mut stack = vec![root];
212
828884
        while let Some(n) = stack.pop() {
213
816098
            if reachable.insert(n) {
214
816098
                if let Some(cs) = merged.get(&n) {
215
816098
                    stack.extend(cs.iter().copied());
216
816098
                }
217
            }
218
        }
219
816158
        merged.retain(|id, _| reachable.contains(id));
220
12786
        if !merged.contains_key(&update.focus) {
221
40
            return Err(A11yUpdateError::FocusNotInTree(update.focus));
222
12746
        }
223
12746
        Ok(Self {
224
12746
            root: Some(root),
225
12746
            children: merged,
226
12746
        })
227
14789
    }
228
}
229

            
230
/// Manager for accessibility tree state and updates.
231
///
232
/// The `A11yManager` sits within `LayoutWindow` and is responsible for:
233
///
234
/// 1. Maintaining the current accessibility tree state
235
/// 2. Generating `TreeUpdate`s by comparing layout results with the stored tree
236
/// 3. Translating `ActionRequest`s from screen readers into synthetic Azul events
237
#[cfg(feature = "a11y")]
238
#[derive(Debug)]
239
pub struct A11yManager {
240
    /// The root node ID of the accessibility tree (represents the window).
241
    pub root_id: A11yNodeId,
242
    /// The current accessibility tree state.
243
    pub tree: Option<Tree>,
244
    /// The last generated tree update (for platform adapter consumption).
245
    pub last_tree_update: Option<TreeUpdate>,
246
    /// Whether the full tree has been sent to the platform adapter at least once.
247
    /// After initialization, incremental updates can use `tree: None`.
248
    pub tree_initialized: bool,
249
    /// The tree as the platform adapter currently holds it — advanced by
250
    /// [`Self::take_pending`] when a shell hands `last_tree_update` over.
251
    pub delivered: A11yTreeMirror,
252
    /// `delivered` as it will be once `last_tree_update` is handed over.
253
    pub pending_post: Option<A11yTreeMirror>,
254
    /// The last update [`Self::publish`] refused (diagnostics, tests).
255
    pub last_rejection: Option<A11yUpdateError>,
256
    /// Scroll offsets moved since the last full rebuild — bounds and
257
    /// `scroll_x/y` in the delivered tree are stale until one runs.
258
    pub scroll_dirty: bool,
259
    /// When the last scroll-driven rebuild ran (see
260
    /// [`Self::scroll_rebuild_due`]).
261
    pub last_scroll_rebuild: Option<std::time::Instant>,
262
}
263

            
264
#[cfg(feature = "a11y")]
265
impl Default for A11yManager {
266
1
    fn default() -> Self {
267
1
        Self::new()
268
1
    }
269
}
270

            
271
#[cfg(feature = "a11y")]
272
impl A11yManager {
273
    /// Creates a new `A11yManager` with an empty tree containing only a root window node.
274
    #[must_use]
275
7602
    pub const fn new() -> Self {
276
7602
        let root_id = A11yNodeId(0);
277
7602
        Self {
278
7602
            root_id,
279
7602
            tree: None,
280
7602
            last_tree_update: None,
281
7602
            tree_initialized: false,
282
7602
            delivered: A11yTreeMirror {
283
7602
                root: None,
284
7602
                children: BTreeMap::new(),
285
7602
            },
286
7602
            pending_post: None,
287
7602
            last_rejection: None,
288
7602
            scroll_dirty: false,
289
7602
            last_scroll_rebuild: None,
290
7602
        }
291
7602
    }
292

            
293
    /// THE ONE WAY an update reaches `last_tree_update`.
294
    ///
295
    /// Folds `update` into whatever is still parked (a full update
296
    /// supersedes; an incremental one merges node-by-node so the slot always
297
    /// holds ONE coherent update — replacing a parked full tree with a later
298
    /// incremental used to drop the full tree on the floor), then replays
299
    /// the consumer's merge rules against the tree the adapter actually
300
    /// holds. Refused updates leave the slot exactly as it was and are
301
    /// recorded in `last_rejection`; the caller decides (incremental →
302
    /// rebuild the full tree; full → keep the last good state).
303
14689
    pub fn publish(&mut self, update: TreeUpdate) -> Result<(), A11yUpdateError> {
304
14689
        let prev = self.last_tree_update.take();
305
14689
        let merged = Self::merge_pending(prev.clone(), update);
306
14689
        match self.delivered.apply(&merged) {
307
12706
            Ok(post) => {
308
12706
                if merged.tree.is_some() {
309
12646
                    self.tree_initialized = true;
310
12646
                }
311
12706
                self.pending_post = Some(post);
312
12706
                self.last_tree_update = Some(merged);
313
12706
                Ok(())
314
            }
315
1983
            Err(e) => {
316
1983
                self.last_tree_update = prev;
317
1983
                self.last_rejection = Some(e);
318
1983
                Err(e)
319
            }
320
        }
321
14689
    }
322

            
323
    /// Fold `new` into a still-parked update (see [`Self::publish`]).
324
14689
    fn merge_pending(prev: Option<TreeUpdate>, new: TreeUpdate) -> TreeUpdate {
325
9143
        match prev {
326
5546
            None => new,
327
9143
            Some(_) if new.tree.is_some() => new,
328
4786
            Some(mut parked) => {
329
9572
                for (id, node) in new.nodes {
330
23221
                    if let Some(slot) = parked.nodes.iter_mut().find(|(i, _)| *i == id) {
331
4776
                        slot.1 = node;
332
4776
                    } else {
333
10
                        parked.nodes.push((id, node));
334
10
                    }
335
                }
336
4786
                parked.focus = new.focus;
337
4786
                parked
338
            }
339
        }
340
14689
    }
341

            
342
    /// Hand the parked update to a platform adapter and advance
343
    /// `delivered` to the tree the adapter will hold afterwards. Every shell
344
    /// drains the slot through this — a raw `last_tree_update.take()` would
345
    /// leave the mirror behind and the next incremental update would be
346
    /// validated against the wrong tree.
347
130
    pub fn take_pending(&mut self) -> Option<TreeUpdate> {
348
130
        let update = self.last_tree_update.take()?;
349
130
        if let Some(post) = self.pending_post.take() {
350
130
            self.delivered = post;
351
130
        }
352
130
        Some(update)
353
130
    }
354

            
355
    /// A scroll offset changed: bounds and `scroll_x/y` in the delivered tree
356
    /// are stale. The fast scroll path never re-lays out, so nothing else
357
    /// would ever rebuild the tree — screen readers saw pre-scroll rects.
358
3
    pub const fn mark_scroll_dirty(&mut self) {
359
3
        self.scroll_dirty = true;
360
3
    }
361

            
362
    /// Whether a scroll-driven full rebuild should run NOW: dirty, and at
363
    /// least `min_interval` since the previous one. Clears the flag and
364
    /// stamps the time when it answers `true`; a throttled `false` keeps the
365
    /// flag so the next tick re-asks — the final state of a glide lands
366
    /// within one interval of the last offset change.
367
60
    pub fn scroll_rebuild_due(
368
60
        &mut self,
369
60
        now: std::time::Instant,
370
60
        min_interval: std::time::Duration,
371
60
    ) -> bool {
372
60
        if !self.scroll_dirty {
373
20
            return false;
374
40
        }
375
40
        let due = self
376
40
            .last_scroll_rebuild
377
40
            .is_none_or(|last| now.saturating_duration_since(last) >= min_interval);
378
40
        if due {
379
30
            self.scroll_dirty = false;
380
30
            self.last_scroll_rebuild = Some(now);
381
30
        }
382
40
        due
383
60
    }
384

            
385
    /// Sum of every ANCESTOR scroll container's current offset — what
386
    /// translates a node's static layout position to where it is on screen.
387
    /// A scroller's own box does not move when it scrolls; its content does,
388
    /// so the walk starts at the parent.
389
    /// The accumulated scroll offset of every scrollable ANCESTOR of a node.
390
    ///
391
    /// Layout rects are in CONTENT space; anything drawn or reported in
392
    /// VIEWPORT space (the a11y tree's bounds, the focus ring) has to
393
    /// subtract this or it lands where the node would be if nothing were
394
    /// scrolled. `pub(crate)` because the focus ring needs the very same
395
    /// answer - one projection, not two that can disagree.
396
310523
    pub(crate) fn ancestor_scroll_offset(
397
310523
        dom_id: DomId,
398
310523
        node_hierarchy: &[NodeHierarchyItem],
399
310523
        dom_idx: usize,
400
310523
        scroll_manager: &crate::managers::scroll_state::ScrollManager,
401
310523
    ) -> LogicalPosition {
402
310523
        let mut acc = LogicalPosition::zero();
403
310523
        let mut cur = node_hierarchy
404
310523
            .get(dom_idx)
405
310523
            .and_then(NodeHierarchyItem::parent_id);
406
310523
        let mut guard = 0usize;
407
1799068
        while let Some(parent) = cur {
408
1488545
            guard += 1;
409
1488545
            if guard > 65_536 {
410
                break;
411
1488545
            }
412
1488545
            if let Some(off) = scroll_manager.get_current_offset(dom_id, parent) {
413
8270
                acc.x += off.x;
414
8270
                acc.y += off.y;
415
1480275
            }
416
1488545
            cur = node_hierarchy
417
1488545
                .get(parent.index())
418
1488545
                .and_then(NodeHierarchyItem::parent_id);
419
        }
420
310523
        acc
421
310523
    }
422

            
423
    /// Force the collected child lists to satisfy accesskit's `TreeUpdate`
424
    /// invariants, so a malformed a11y tree can never abort the process (the
425
    /// release build is `panic = "abort"`, so the shell's `catch_unwind` around
426
    /// `update_if_active` cannot catch accesskit's consumer panic).
427
    ///
428
    /// Given `node_ids` (every node present in the update, in order), the
429
    /// `root_id`, and the raw `root_children` + `parent_children_map`, this:
430
    /// - drops any child that names no present node, is its own parent, or was ALREADY claimed by
431
    ///   another parent (accesskit forbids a node having two parents — a GLOBAL duplicate,
432
    ///   tree.rs:225), and clears the child list of a parent that is itself not present;
433
    /// - re-hangs every exposed non-root node that no parent claimed off the root, so every node is
434
    ///   reachable (accesskit tree.rs:307).
435
    ///
436
    /// Root's children win a tie (they are processed first). The result is a
437
    /// forest rooted at `root_id` with each node reachable exactly once.
438
9873
    fn enforce_child_invariants(
439
9873
        node_ids: &[A11yNodeId],
440
9873
        root_id: A11yNodeId,
441
9873
        root_children: &mut Vec<A11yNodeId>,
442
9873
        parent_children_map: &mut HashMap<A11yNodeId, Vec<A11yNodeId>>,
443
9873
    ) {
444
9873
        let valid: std::collections::HashSet<A11yNodeId> = node_ids.iter().copied().collect();
445
9873
        let mut claimed: std::collections::HashSet<A11yNodeId> = std::collections::HashSet::new();
446
10894
        root_children.retain(|c| valid.contains(c) && *c != root_id && claimed.insert(*c));
447
184856
        for (parent, children) in parent_children_map.iter_mut() {
448
184856
            if !valid.contains(parent) {
449
1
                children.clear();
450
1
                continue;
451
184855
            }
452
184855
            let p = *parent;
453
299666
            children.retain(|c| valid.contains(c) && *c != p && claimed.insert(*c));
454
        }
455
330274
        for id in node_ids {
456
320401
            if *id != root_id && !claimed.contains(id) {
457
2
                claimed.insert(*id);
458
2
                root_children.push(*id);
459
320399
            }
460
        }
461
9873
    }
462

            
463
    /// Updates the accessibility tree based on the current layout state.
464
    ///
465
    /// This should be called after each layout pass to synchronize the
466
    /// accessibility tree with the visual representation.
467
    #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
468
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
469
    #[must_use]
470
9872
    pub fn update_tree(
471
9872
        root_id: A11yNodeId,
472
9872
        layout_results: &BTreeMap<DomId, DomLayoutResult>,
473
9872
        scroll_manager: &crate::managers::scroll_state::ScrollManager,
474
9872
        window_title: &AzString,
475
9872
        window_size: LogicalSize,
476
9872
        focused_node: Option<DomNodeId>,
477
9872
        hidpi_factor: f32,
478
9872
        dirty_text_overrides: &BTreeMap<(DomId, NodeId), String>,
479
9872
        cursor_info: Option<CursorA11yInfo>,
480
9872
    ) -> TreeUpdate {
481
9872
        let mut nodes = Vec::new();
482
9872
        let mut root_children = Vec::new();
483

            
484
        // Map from (DomId, NodeId) to A11yNodeId for building parent-child relationships
485
9872
        let mut node_id_map: HashMap<(u32, u32), A11yNodeId> = HashMap::new();
486

            
487
        // Map to collect children for each parent
488
9872
        let mut parent_children_map: HashMap<A11yNodeId, Vec<A11yNodeId>> = HashMap::new();
489

            
490
        // Create root window node and add it to the nodes list
491
9872
        let mut root_node = Node::new(Role::Window);
492
9872
        root_node.set_label(window_title.as_str());
493
9872
        nodes.push((root_id, root_node));
494

            
495
20732
        for (dom_id, layout_result) in layout_results {
496
10860
            let styled_dom = &layout_result.styled_dom;
497
10860
            let node_hierarchy = styled_dom.node_hierarchy.as_ref();
498
10860
            let node_data_slice = styled_dom.node_data.as_ref();
499

            
500
            // First pass: Create a11y nodes for each DOM node
501
311547
            for (dom_idx, node_data) in node_data_slice.iter().enumerate() {
502
311547
                let a11y_info = node_data.get_accessibility_info();
503

            
504
                // Include every node that has a meaningful role — see
505
                // `is_exposed_to_accessibility`, which is the single definition
506
                // shared with every other a11y surface.
507
311547
                let should_create_node = is_exposed_to_accessibility(node_data);
508

            
509
311547
                if !should_create_node {
510
1024
                    continue;
511
310523
                }
512

            
513
                // Generate stable A11yNodeId: offset by 1 to avoid collision with root_id(0)
514
310523
                let a11y_node_id = Self::encode_a11y_node_id(dom_id.inner, dom_idx);
515

            
516
                // Get layout info: absolute position from calculated_positions,
517
                // size from layout node. Uses dom_to_layout to map DOM → layout index.
518
310523
                let dom_node_id = NodeId::new(dom_idx);
519
310523
                let layout_info = layout_result
520
310523
                    .layout_tree
521
310523
                    .dom_to_layout
522
310523
                    .get(&dom_node_id)
523
310523
                    .and_then(|indices| indices.first())
524
310523
                    .and_then(|&layout_idx| {
525
268428
                        let hot = layout_result.layout_tree.get(layout_idx)?;
526
268428
                        let abs_pos = layout_result
527
268428
                            .calculated_positions
528
268428
                            .get(layout_idx.index())
529
268428
                            .copied();
530
268428
                        Some((hot, layout_idx, abs_pos))
531
268428
                    });
532

            
533
                // Screen position = static layout position minus every
534
                // ancestor scroller's offset. Bounds used to be the
535
                // unscrolled layout rects, so after any scroll VoiceOver's
536
                // cursor rectangles sat where the content had been.
537
310523
                let ancestor_scroll =
538
310523
                    Self::ancestor_scroll_offset(*dom_id, node_hierarchy, dom_idx, scroll_manager);
539
310523
                let layout_info = layout_info.map(|(hot, idx, pos)| {
540
                    (
541
268428
                        hot,
542
268428
                        idx,
543
268428
                        pos.map(|p| LogicalPosition {
544
267527
                            x: p.x - ancestor_scroll.x,
545
267527
                            y: p.y - ancestor_scroll.y,
546
267527
                        }),
547
                    )
548
268428
                });
549

            
550
310523
                let a11y_info_ref = a11y_info;
551
310523
                let mut node = if let Some((layout_node, _layout_idx, abs_pos)) = layout_info {
552
268428
                    Self::build_node(
553
268428
                        node_data,
554
268428
                        layout_node,
555
268428
                        abs_pos,
556
268428
                        a11y_info_ref,
557
268428
                        hidpi_factor,
558
268428
                        window_size,
559
                    )
560
                } else {
561
                    // Same rule as `build_node` (which this branch stands in
562
                    // for when the node has no layout yet): only a SPECIFIED
563
                    // role overrides the element's own type.
564
42095
                    let role = match a11y_info_ref {
565
3
                        Some(info) if accessibility_role_is_specified(&info.role) => {
566
                            Self::map_role(&info.role)
567
                        }
568
42095
                        _ => Self::node_type_to_role(&node_data.node_type),
569
                    };
570
42095
                    let mut builder = Node::new(role);
571
42095
                    if let NodeType::Text(text) = &node_data.node_type {
572
27163
                        builder.set_label(text.as_str());
573
27175
                    }
574
42095
                    builder
575
                };
576

            
577
                // MWA-B10: advertise the scroll surface. The INBOUND handler
578
                // (LayoutWindow::process_accessibility_action) has handled
579
                // ScrollUp/Down/Left/Right/SetScrollOffset/ScrollIntoView all
580
                // along — but the tree never declared any scroll action or
581
                // offset, so screen readers had nothing to invoke.
582
807
                if let Some((offset, max_x, max_y)) =
583
310523
                    scroll_manager.a11y_scroll_info(*dom_id, NodeId::new(dom_idx))
584
                {
585
807
                    node.set_scroll_x(f64::from(offset.x));
586
807
                    node.set_scroll_x_min(0.0);
587
807
                    node.set_scroll_x_max(f64::from(max_x));
588
807
                    node.set_scroll_y(f64::from(offset.y));
589
807
                    node.set_scroll_y_min(0.0);
590
807
                    node.set_scroll_y_max(f64::from(max_y));
591
807
                    node.set_clips_children();
592
807
                    if max_y > 0.0 {
593
515
                        node.add_action(Action::ScrollUp);
594
515
                        node.add_action(Action::ScrollDown);
595
515
                    }
596
807
                    if max_x > 0.0 {
597
292
                        node.add_action(Action::ScrollLeft);
598
292
                        node.add_action(Action::ScrollRight);
599
515
                    }
600
807
                    node.add_action(Action::SetScrollOffset);
601
309716
                }
602

            
603
                // Collect child text and promote to this node's label or value.
604
                // Only do this when all children are text nodes — if the node has
605
                // interactive children (links, buttons, inputs), DON'T set a group
606
                // label, so VoiceOver navigates into the children individually.
607
                //
608
                // For edited contenteditable nodes, dirty_text_overrides has the
609
                // current text (from the relayout path) instead of the stale
610
                // StyledDom text.
611
                {
612
310523
                    let hierarchy_item = &node_hierarchy[dom_idx];
613
310523
                    let dom_node_id_key = (*dom_id, NodeId::new(dom_idx));
614

            
615
                    // Use dirty text override if this node was edited since last RefreshDom
616
310523
                    let (text_content, has_non_text_children) =
617
310523
                        dirty_text_overrides.get(&dom_node_id_key).map_or_else(
618
309293
                            || {
619
309293
                                let mut text = String::new();
620
309293
                                let mut has_non_text = false;
621

            
622
309293
                                let mut child = hierarchy_item.first_child_id(NodeId::new(dom_idx));
623
608779
                                while let Some(child_id) = child {
624
299486
                                    if let Some(child_data) = node_data_slice.get(child_id.index())
625
                                    {
626
299486
                                        if let NodeType::Text(t) = &child_data.node_type {
627
117587
                                            if !text.is_empty() {
628
14823
                                                text.push(' ');
629
102888
                                            }
630
117587
                                            text.push_str(t.as_str());
631
181899
                                        } else {
632
181899
                                            has_non_text = true;
633
181899
                                        }
634
                                    }
635
299486
                                    if child_id.index() >= node_hierarchy.len() {
636
                                        break;
637
299486
                                    }
638
299486
                                    child = node_hierarchy[child_id.index()].next_sibling_id();
639
                                }
640
309293
                                (text, has_non_text)
641
309293
                            },
642
1230
                            |override_text| (override_text.clone(), false),
643
                        );
644

            
645
310523
                    if !text_content.is_empty() {
646
87279
                        if node_data.is_contenteditable()
647
85178
                            || matches!(node_data.node_type, NodeType::TextArea | NodeType::Input)
648
                        {
649
2101
                            node.set_value(text_content.as_str());
650
                            // Add text editing actions for contenteditable/input nodes
651
2101
                            node.add_action(Action::SetTextSelection);
652
2101
                            node.add_action(Action::ReplaceSelectedText);
653
2101
                            node.add_action(Action::SetValue);
654

            
655
                            // If cursor/selection is in this node, expose to screen readers
656
2101
                            if let Some(ref ci) = cursor_info {
657
563
                                if ci.dom_id == *dom_id && ci.node_id == NodeId::new(dom_idx) {
658
329
                                    let char_lengths: Vec<u8> =
659
1355
                                        text_content.chars().map(|c| c.len_utf16() as u8).collect();
660
329
                                    node.set_character_lengths(char_lengths.clone());
661

            
662
658
                                    let byte_to_char_idx = |byte_off: usize| -> usize {
663
658
                                        text_content
664
658
                                            .char_indices()
665
1244
                                            .take_while(|(b, _)| *b < byte_off)
666
658
                                            .count()
667
658
                                            .min(char_lengths.len())
668
658
                                    };
669

            
670
329
                                    let anchor_idx = byte_to_char_idx(ci.anchor_offset);
671
329
                                    let focus_idx = byte_to_char_idx(ci.focus_offset);
672

            
673
329
                                    node.set_text_selection(accesskit::TextSelection {
674
329
                                        anchor: accesskit::TextPosition {
675
329
                                            node: a11y_node_id,
676
329
                                            character_index: anchor_idx,
677
329
                                        },
678
329
                                        focus: accesskit::TextPosition {
679
329
                                            node: a11y_node_id,
680
329
                                            character_index: focus_idx,
681
329
                                        },
682
329
                                    });
683
234
                                }
684
1538
                            }
685
85178
                        } else if !has_non_text_children {
686
72748
                            // Only promote text when there are NO interactive children.
687
72748
                            // Otherwise VoiceOver reads the label instead of navigating children.
688
72748
                            node.set_label(text_content.as_str());
689
72883
                        }
690
223244
                    }
691
                }
692

            
693
310523
                node_id_map.insert((dom_id.inner as u32, dom_idx as u32), a11y_node_id);
694
310523
                nodes.push((a11y_node_id, node));
695
            }
696

            
697
            // Second pass: Build parent-child relationships using DOM hierarchy
698
311547
            for (dom_idx, _) in node_data_slice.iter().enumerate() {
699
311547
                let a11y_node_id = match node_id_map.get(&(dom_id.inner as u32, dom_idx as u32)) {
700
310523
                    Some(id) => *id,
701
1024
                    None => continue,
702
                };
703

            
704
310523
                let hierarchy_item = &node_hierarchy[dom_idx];
705

            
706
                // Walk up the DOM tree to find the nearest accessible ancestor.
707
                // parent_id() decodes the 1-based encoding: 0 = None, n+1 = Some(NodeId(n))
708
310523
                let mut current_parent = hierarchy_item.parent_id();
709
310523
                let mut accessible_parent_id = None;
710
310523
                let mut iterations = 0;
711

            
712
310523
                while let Some(parent_node_id) = current_parent {
713
299662
                    iterations += 1;
714
299662
                    if iterations > 10_000 {
715
                        break;
716
299662
                    }
717

            
718
299662
                    let parent_idx = parent_node_id.index();
719
299662
                    if let Some(parent_a11y_id) =
720
299662
                        node_id_map.get(&(dom_id.inner as u32, parent_idx as u32))
721
                    {
722
299662
                        accessible_parent_id = Some(*parent_a11y_id);
723
299662
                        break;
724
                    }
725
                    if parent_idx >= node_hierarchy.len() {
726
                        break;
727
                    }
728
                    current_parent = node_hierarchy[parent_idx].parent_id();
729
                }
730

            
731
310523
                if let Some(parent_id) = accessible_parent_id {
732
299662
                    parent_children_map
733
299662
                        .entry(parent_id)
734
299662
                        .or_default()
735
299662
                        .push(a11y_node_id);
736
299662
                } else {
737
10861
                    root_children.push(a11y_node_id);
738
10861
                }
739
            }
740
        }
741

            
742
        // A11Y CONSISTENCY GUARD. accesskit's tree consumer PANICS on a
743
        // malformed `TreeUpdate` — a focus/child naming no node (tree.rs:75), a
744
        // node claimed as a child by two parents (:225, a GLOBAL "duplicate
745
        // child"), or a node reachable from no parent at all (:307). Because the
746
        // release build is `panic = "abort"`, the `catch_unwind` around
747
        // `update_if_active` in the macOS shell CANNOT save it: the process
748
        // aborts. This merges the MAIN window's DOM with EVERY transient-window
749
        // child DOM into one tree, which is exactly where a dangling/duplicate/
750
        // orphan reference slips in (a focused node from a DOM that just
751
        // regenerated, a subtree whose accessible parent wasn't exposed). Enforce
752
        // the invariants here so a bad tree degrades gracefully — the whole
753
        // "a11y update aborts the app" bug class cannot recur.
754
9872
        let node_ids: Vec<A11yNodeId> = nodes.iter().map(|(id, _)| *id).collect();
755
9872
        Self::enforce_child_invariants(
756
9872
            &node_ids,
757
9872
            root_id,
758
9872
            &mut root_children,
759
9872
            &mut parent_children_map,
760
        );
761

            
762
        // Third pass: Set children on all nodes (including root)
763
330267
        for (node_id, node) in &mut nodes {
764
320395
            if *node_id == root_id {
765
9872
                // Root window node gets top-level DOM nodes as children
766
9872
                node.set_children(root_children.clone());
767
310523
            } else if let Some(children) = parent_children_map.get(node_id) {
768
184852
                node.set_children(children.clone());
769
185555
            }
770
        }
771

            
772
        // Set focus to the currently focused DOM node (from FocusManager).
773
        // If no node is focused, fall back to the first visible content node.
774
        // VoiceOver navigates to the focused element on activation.
775
9872
        let focus = focused_node
776
9872
            .and_then(|dom_node_id| {
777
1778
                let dom_idx = dom_node_id.node.into_crate_internal()?.index();
778
1777
                node_id_map
779
1777
                    .get(&(dom_node_id.dom.inner as u32, dom_idx as u32))
780
1777
                    .copied()
781
1778
            })
782
9872
            .unwrap_or_else(|| {
783
                // Fallback: first non-container node
784
8106
                nodes
785
8106
                    .iter()
786
16175
                    .find(|(id, node)| {
787
16175
                        *id != root_id
788
8069
                            && !matches!(node.role(), Role::GenericContainer | Role::Window)
789
16175
                    })
790
8106
                    .map_or(root_id, |(id, _)| *id)
791
8106
            });
792

            
793
        // Focus MUST name a node in the update (accesskit tree.rs:75). The
794
        // fallback above normally guarantees this, but a `focused_node` mapped
795
        // from a DOM that regenerated between the focus write and this build can
796
        // resolve to an id that was filtered out — degrade to the root instead of
797
        // aborting.
798
9872
        let focus = if node_ids.contains(&focus) {
799
9872
            focus
800
        } else {
801
            root_id
802
        };
803

            
804
9872
        TreeUpdate {
805
9872
            nodes,
806
9872
            tree: Some(Tree::new(root_id)),
807
9872
            focus,
808
9872
            tree_id: accesskit::TreeId::ROOT,
809
9872
        }
810
9872
    }
811

            
812
    /// MWA-B10: outbound twin of `map_accesskit_action` — declares a node's
813
    /// supported actions in the tree (payload-carrying variants map to their
814
    /// action KIND; the payload only exists on inbound requests).
815
27
    const fn map_action_to_accesskit(action: &AccessibilityAction) -> Action {
816
        use azul_core::a11y::AccessibilityAction as A;
817
27
        match action {
818
1
            A::Default => Action::Click,
819
1
            A::Focus => Action::Focus,
820
1
            A::Blur => Action::Blur,
821
1
            A::Collapse => Action::Collapse,
822
1
            A::Expand => Action::Expand,
823
1
            A::ScrollIntoView => Action::ScrollIntoView,
824
2
            A::Increment => Action::Increment,
825
2
            A::Decrement => Action::Decrement,
826
1
            A::ShowContextMenu => Action::ShowContextMenu,
827
1
            A::HideTooltip => Action::HideTooltip,
828
1
            A::ShowTooltip => Action::ShowTooltip,
829
1
            A::ScrollUp => Action::ScrollUp,
830
1
            A::ScrollDown => Action::ScrollDown,
831
1
            A::ScrollLeft => Action::ScrollLeft,
832
1
            A::ScrollRight => Action::ScrollRight,
833
1
            A::ReplaceSelectedText(_) => Action::ReplaceSelectedText,
834
1
            A::ScrollToPoint(_) => Action::ScrollToPoint,
835
1
            A::SetScrollOffset(_) => Action::SetScrollOffset,
836
1
            A::SetTextSelection(_) => Action::SetTextSelection,
837
            A::SetSequentialFocusNavigationStartingPoint => {
838
1
                Action::SetSequentialFocusNavigationStartingPoint
839
            }
840
3
            A::SetValue(_) | A::SetNumericValue(_) => Action::SetValue,
841
2
            A::CustomAction(_) => Action::CustomAction,
842
        }
843
27
    }
844

            
845
    /// Builds an accesskit Node from Azul's `NodeData` and layout information.
846
    #[allow(clippy::cast_sign_loss)] // bounded graphics/coord/font/fixed-point/debug-marker cast
847
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
848
                                                                   // single-purpose
849
                                                                   // layout/render/parse routine
850
                                                                   // (one branch per case)
851
268791
    fn build_node(
852
268791
        node_data: &NodeData,
853
268791
        layout_node: &LayoutNodeHot,
854
268791
        abs_pos: Option<LogicalPosition>,
855
268791
        a11y_info: Option<&AccessibilityInfo>,
856
268791
        hidpi_factor: f32,
857
268791
        window_size: LogicalSize,
858
268791
    ) -> Node {
859
        // Set role based on NodeType or AccessibilityInfo. A DECLARED role
860
        // wins; an `Unknown` one is not a declaration at all — see
861
        // `accessibility_role_is_specified`, which is why naming a control no
862
        // longer erases its role.
863
268791
        let role = if node_data.is_contenteditable() {
864
5203
            Role::MultilineTextInput
865
        } else {
866
17422
            match a11y_info {
867
17422
                Some(info) if accessibility_role_is_specified(&info.role) => {
868
17417
                    Self::map_role(&info.role)
869
                }
870
246171
                _ => Self::node_type_to_role(&node_data.node_type),
871
            }
872
        };
873

            
874
268791
        let mut builder = Node::new(role);
875

            
876
        // Set HTML tag name for screen readers that use it
877
268791
        let tag = node_data.node_type.get_path().to_string();
878
268791
        if !tag.is_empty() {
879
268791
            builder.set_html_tag(tag.as_str());
880
268791
        }
881

            
882
        // === Label and Value ===
883
        // Priority: explicit a11y info > DOM attributes > text content
884
268791
        if let Some(info) = a11y_info {
885
18623
            if let Some(name) = info.accessibility_name.as_option() {
886
16756
                builder.set_label(name.as_str());
887
16756
            }
888
18623
            if let Some(value) = info.accessibility_value.as_option() {
889
561
                builder.set_value(value.as_str());
890
18062
            }
891
18623
            if let Some(desc) = info.description.as_option() {
892
                builder.set_description(desc.as_str());
893
18623
            }
894
250168
        }
895

            
896
        // DOM attribute overrides
897
268791
        if let Some(label) = node_data.get_accessible_label() {
898
2
            builder.set_label(label);
899
268789
        }
900
268791
        if let Some(value) = node_data.get_accessible_value() {
901
2
            builder.set_value(value);
902
268789
        }
903
        // Text node: set as label
904
268791
        if let NodeType::Text(text) = &node_data.node_type {
905
91587
            builder.set_label(text.as_str());
906
177204
        }
907

            
908
        // === States from AccessibilityInfo ===
909
268791
        if let Some(info) = a11y_info {
910
18623
            for state in info.states.as_ref() {
911
700
                match state {
912
1
                    AccessibilityState::Unavailable => {
913
1
                        builder.set_disabled();
914
1
                    }
915
1
                    AccessibilityState::Readonly => {
916
1
                        builder.set_read_only();
917
1
                    }
918
41
                    AccessibilityState::CheckedTrue => {
919
41
                        builder.set_toggled(accesskit::Toggled::True);
920
41
                    }
921
651
                    AccessibilityState::CheckedFalse => {
922
651
                        builder.set_toggled(accesskit::Toggled::False);
923
651
                    }
924
1
                    AccessibilityState::Expanded => {
925
1
                        builder.set_expanded(true);
926
1
                    }
927
1
                    AccessibilityState::Collapsed => {
928
1
                        builder.set_expanded(false);
929
1
                    }
930
1
                    AccessibilityState::Focusable => {
931
1
                        builder.add_action(Action::Focus);
932
1
                    }
933
1
                    AccessibilityState::Selected => {
934
1
                        builder.set_selected(true);
935
1
                    }
936
1
                    AccessibilityState::Busy => {
937
1
                        builder.set_busy();
938
1
                    }
939
1
                    AccessibilityState::Offscreen => {
940
1
                        builder.set_hidden();
941
1
                    }
942
                    _ => {}
943
                }
944
            }
945
250168
        }
946

            
947
        // MWA-B10: declare user-supplied supported actions — the public
948
        // AccessibilityInfo.supported_actions field was never read, so
949
        // API-declared actions never reached assistive technology.
950
268791
        if let Some(info) = a11y_info {
951
18623
            for action in info.supported_actions.as_ref() {
952
4
                builder.add_action(Self::map_action_to_accesskit(action));
953
4
            }
954
250168
        }
955

            
956
        // MWA-B10: every content node can be scrolled into view — the
957
        // inbound handler implements it; declaring it lets screen readers
958
        // use it for navigation.
959
268791
        builder.add_action(Action::ScrollIntoView);
960

            
961
        // === Heading level ===
962
268791
        match &node_data.node_type {
963
452
            NodeType::H1 => {
964
452
                builder.set_level(1);
965
452
            }
966
1
            NodeType::H2 => {
967
1
                builder.set_level(2);
968
1
            }
969
1
            NodeType::H3 => {
970
1
                builder.set_level(3);
971
1
            }
972
1
            NodeType::H4 => {
973
1
                builder.set_level(4);
974
1
            }
975
1
            NodeType::H5 => {
976
1
                builder.set_level(5);
977
1
            }
978
1
            NodeType::H6 => {
979
1
                builder.set_level(6);
980
1
            }
981
268334
            _ => {}
982
        }
983

            
984
        // Wire up HTML attributes to accesskit properties
985
268791
        for attr in node_data.attributes().as_ref() {
986
123286
            match attr {
987
2
                azul_core::dom::AttributeType::AriaLabel(s) => {
988
2
                    builder.set_label(s.as_str());
989
2
                }
990
1
                azul_core::dom::AttributeType::Title(s) | azul_core::dom::AttributeType::Alt(s) => {
991
1
                    builder.set_description(s.as_str());
992
1
                }
993
1204
                azul_core::dom::AttributeType::Placeholder(s) => {
994
1204
                    builder.set_placeholder(s.as_str());
995
1204
                }
996
2
                azul_core::dom::AttributeType::Value(s) => {
997
2
                    builder.set_value(s.as_str());
998
2
                }
999
1
                azul_core::dom::AttributeType::Disabled => {
1
                    builder.set_disabled();
1
                }
1
                azul_core::dom::AttributeType::Readonly => {
1
                    builder.set_read_only();
1
                }
1
                azul_core::dom::AttributeType::CheckedTrue => {
1
                    builder.set_toggled(accesskit::Toggled::True);
1
                }
                azul_core::dom::AttributeType::CheckedFalse => {
                    builder.set_toggled(accesskit::Toggled::False);
                }
1
                azul_core::dom::AttributeType::Required => {
1
                    builder.set_required();
1
                }
1
                azul_core::dom::AttributeType::Hidden => {
1
                    builder.set_hidden();
1
                }
1
                azul_core::dom::AttributeType::Lang(s) => {
1
                    builder.set_language(s.as_str());
1
                }
3
                azul_core::dom::AttributeType::ColSpan(n) => {
3
                    builder.set_column_span(*n as usize);
3
                }
2
                azul_core::dom::AttributeType::RowSpan(n) => {
2
                    builder.set_row_span(*n as usize);
2
                }
122066
                _ => {}
            }
        }
        // Set bounds: absolute position, offset by padding+border, scaled to physical pixels,
        // clipped to window viewport so VoiceOver highlights don't extend off-screen.
268791
        if let (Some(pos), Some(size)) = (abs_pos, layout_node.used_size) {
182781
            let bp = layout_node.box_props.unpack();
182781
            let pad_left = bp.padding.left + bp.border.left;
182781
            let pad_top = bp.padding.top + bp.border.top;
182781
            let pad_right = bp.padding.right + bp.border.right;
182781
            let pad_bottom = bp.padding.bottom + bp.border.bottom;
182781
            let s = f64::from(hidpi_factor);
182781
            let ww = f64::from(window_size.width) * s;
182781
            let wh = f64::from(window_size.height) * s;
182781
            let x0 = (f64::from(pos.x + pad_left) * s).max(0.0).min(ww);
182781
            let y0 = (f64::from(pos.y + pad_top) * s).max(0.0).min(wh);
182781
            let x1 = (f64::from(pos.x + size.width - pad_right) * s)
182781
                .max(0.0)
182781
                .min(ww);
182781
            let y1 = (f64::from(pos.y + size.height - pad_bottom) * s)
182781
                .max(0.0)
182781
                .min(wh);
182781
            if x1 > x0 && y1 > y0 {
146147
                builder.set_bounds(Rect { x0, y0, x1, y1 });
146237
            }
86010
        }
        // Add supported actions based on the DOM node's own properties.
        // VoiceOver uses these to determine what the user can do with the element.
268791
        if node_data.is_focusable() || node_data.is_contenteditable() {
22985
            builder.add_action(Action::Focus);
245806
        }
268791
        if node_data.has_activation_behavior() {
23653
            builder.add_action(Action::Click);
245138
        }
        // ARIA relations + live-region from AccessibilityInfo. aria-labelledby /
        // aria-describedby reference another node; encode its id the SAME way the
        // tree walk does (encode_a11y_node_id) so the relation resolves to a real
        // node. is_live_region maps to accesskit's Live property. These were all
        // previously dropped (screen readers got no labelled-by/described-by
        // relations and no live-region announcements).
268791
        if let Some(info) = a11y_info {
18623
            if let azul_core::dom::OptionDomNodeId::Some(target) = info.labelled_by {
2
                if let Some(id) = Self::a11y_node_id_for(&target) {
1
                    builder.push_labelled_by(id);
1
                }
18621
            }
18623
            if let azul_core::dom::OptionDomNodeId::Some(target) = info.described_by {
2
                if let Some(id) = Self::a11y_node_id_for(&target) {
1
                    builder.push_described_by(id);
1
                }
18621
            }
18623
            if info.is_live_region {
1
                builder.set_live(accesskit::Live::Polite);
18622
            }
250168
        }
        // MWA-C-a11y: aria-live="polite|assertive" HTML attribute — arrives
        // as AriaProperty/Custom (no parsing existed; live regions were only
        // reachable through the explicit AccessibilityInfo.is_live_region
        // flag, so HTML-defined live regions never announced).
268791
        for attr in node_data.attributes() {
123286
            let (name, value) = match attr {
8
                azul_core::dom::AttributeType::AriaProperty(nv)
                | azul_core::dom::AttributeType::Custom(nv) => {
8
                    (nv.attr_name.as_str(), nv.value.as_str())
                }
123278
                _ => continue,
            };
8
            if name.eq_ignore_ascii_case("aria-live") {
8
                match value.to_ascii_lowercase().as_str() {
8
                    "polite" => builder.set_live(accesskit::Live::Polite),
6
                    "assertive" => builder.set_live(accesskit::Live::Assertive),
4
                    _ => builder.set_live(accesskit::Live::Off),
                }
            }
        }
268791
        builder
268791
    }
    /// Encode a `(DomId.inner, node index)` pair into the stable `A11yNodeId` used
    /// throughout the tree (offset by 1 so it never collides with `root_id` 0).
    /// Shared by the tree walk and the aria-labelledby/-describedby relation
    /// mapping, so a relation always resolves to the node the walk emitted.
310549
    const fn encode_a11y_node_id(dom_inner: usize, node_idx: usize) -> A11yNodeId {
310549
        A11yNodeId(((dom_inner as u64) << 32) | ((node_idx as u64) + 1))
310549
    }
    /// Map an aria-labelledby/-describedby target `DomNodeId` to its `A11yNodeId`,
    /// or `None` if the node id can't be resolved.
7
    fn a11y_node_id_for(target: &DomNodeId) -> Option<A11yNodeId> {
7
        let idx = target.node.into_crate_internal()?.index();
4
        Some(Self::encode_a11y_node_id(target.dom.inner, idx))
7
    }
    /// Maps an HTML `NodeType` to an accesskit `Role`.
    ///
    /// Every role used here must pass accesskit's `common_filter` (i.e. NOT be
    /// `GenericContainer` or `TextRun`) or `VoiceOver` will skip the node entirely.
    /// Use `Group` for structural containers, `Paragraph` for text blocks, `Label`
    /// for inline text, and semantic roles for everything else.
    // Exhaustive NodeType -> accessibility Role mapping table; many node types share
    // a Role, but one-arm-per-NodeType is intentional for readability/maintainability.
    #[allow(clippy::match_same_arms)]
288366
    const fn node_type_to_role(node_type: &NodeType) -> Role {
288366
        match node_type {
            // === Text content ===
118752
            NodeType::Text(_) => Role::Label,
58225
            NodeType::P => Role::Paragraph,
1
            NodeType::Pre => Role::Code,
1
            NodeType::BlockQuote => Role::Blockquote,
1
            NodeType::Code => Role::Code,
1
            NodeType::Em | NodeType::I => Role::Emphasis,
1
            NodeType::Strong | NodeType::B => Role::Strong,
1
            NodeType::Mark => Role::Mark,
1
            NodeType::Del => Role::ContentDeletion,
1
            NodeType::Ins => Role::ContentInsertion,
1
            NodeType::Abbr | NodeType::Acronym => Role::Abbr,
1
            NodeType::Q => Role::Blockquote,
1
            NodeType::Time => Role::Time,
            NodeType::Cite | NodeType::Dfn | NodeType::Var | NodeType::Samp | NodeType::Kbd => {
                Role::Label
            }
            NodeType::Small
            | NodeType::Big
            | NodeType::Sub
            | NodeType::Sup
            | NodeType::U
            | NodeType::S => Role::Label,
1
            NodeType::Ruby => Role::Ruby,
1
            NodeType::Rt => Role::RubyAnnotation,
2
            NodeType::Br => Role::LineBreak,
2
            NodeType::Hr => Role::Splitter,
            // === Structural containers ===
            // Group (not GenericContainer) so VoiceOver can navigate into them
8788
            NodeType::Body => Role::Group,
79947
            NodeType::Div => Role::Group,
790
            NodeType::Span => Role::Group,
668
            NodeType::Html => Role::Group,
            // === Semantic sections ===
1
            NodeType::Article => Role::Article,
1
            NodeType::Section => Role::Section,
1
            NodeType::Nav => Role::Navigation,
1
            NodeType::Main => Role::Main,
1
            NodeType::Header => Role::Header,
1
            NodeType::Footer => Role::Footer,
1
            NodeType::Aside => Role::Complementary,
            NodeType::Address => Role::Group,
1
            NodeType::Figure => Role::Figure,
1
            NodeType::FigCaption => Role::FigureCaption,
1
            NodeType::Details => Role::Details,
1
            NodeType::Summary => Role::DisclosureTriangle,
1
            NodeType::Dialog => Role::Dialog,
            // === Headings ===
            NodeType::H1
            | NodeType::H2
            | NodeType::H3
            | NodeType::H4
            | NodeType::H5
465
            | NodeType::H6 => Role::Heading,
            // === Lists ===
483
            NodeType::Ul | NodeType::Ol | NodeType::Dir => Role::List,
1412
            NodeType::Li => Role::ListItem,
1
            NodeType::Dl => Role::DescriptionList,
1
            NodeType::Dt => Role::Term,
1
            NodeType::Dd => Role::Definition,
1
            NodeType::Menu => Role::Menu,
1
            NodeType::MenuItem => Role::MenuItem,
            // === Tables ===
332
            NodeType::Table => Role::Table,
1
            NodeType::Caption => Role::Caption,
13
            NodeType::THead | NodeType::TBody | NodeType::TFoot => Role::RowGroup,
342
            NodeType::Tr => Role::Row,
22
            NodeType::Th => Role::ColumnHeader,
834
            NodeType::Td => Role::Cell,
2
            NodeType::ColGroup | NodeType::Col => Role::GenericContainer,
            // === Forms ===
1
            NodeType::Form => Role::Form,
1
            NodeType::FieldSet => Role::Group,
1
            NodeType::Legend => Role::Legend,
1
            NodeType::Label => Role::Label,
4
            NodeType::Input => Role::TextInput,
3
            NodeType::Button => Role::Button,
1
            NodeType::Select => Role::ComboBox,
            NodeType::OptGroup => Role::Group,
1
            NodeType::SelectOption => Role::ListBoxOption,
2
            NodeType::TextArea => Role::MultilineTextInput,
1
            NodeType::Output => Role::Status,
1
            NodeType::Progress => Role::ProgressIndicator,
1
            NodeType::Meter => Role::Meter,
1
            NodeType::DataList => Role::ListBox,
            // === Links ===
493
            NodeType::A => Role::Link,
            // === Embedded content ===
123
            NodeType::Image(_) => Role::Image,
16580
            NodeType::Icon(_) => Role::Image,
1
            NodeType::Canvas => Role::Canvas,
1
            NodeType::Audio => Role::Audio,
1
            NodeType::Video => Role::Video,
11
            NodeType::Svg => Role::SvgRoot,
2
            NodeType::Object | NodeType::Embed => Role::EmbeddedObject,
            // === Everything else: Group (visible to VoiceOver) ===
25
            _ => Role::Group,
        }
288366
    }
    /// Maps Azul's `AccessibilityRole` to accesskit's Role.
    // Exhaustive AccessibilityRole -> AccessKit Role mapping table (see node_type_to_role).
    #[allow(clippy::match_same_arms)]
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
                                                 // pixel/coord path or to avoid churning call sites
                                                 // for a perf-neutral change)
17482
    const fn map_role(role: &AccessibilityRole) -> Role {
17482
        match role {
1
            AccessibilityRole::TitleBar => Role::TitleBar,
1
            AccessibilityRole::MenuBar => Role::MenuBar,
1
            AccessibilityRole::ScrollBar => Role::ScrollBar,
1
            AccessibilityRole::Grip => Role::Splitter,
1
            AccessibilityRole::Sound => Role::Audio,
1
            AccessibilityRole::Cursor => Role::Caret,
1
            AccessibilityRole::Caret => Role::Caret,
1
            AccessibilityRole::Alert => Role::Alert,
1
            AccessibilityRole::Window => Role::Window,
1
            AccessibilityRole::Client => Role::GenericContainer,
1
            AccessibilityRole::MenuPopup => Role::Menu,
1
            AccessibilityRole::MenuItem => Role::MenuItem,
1
            AccessibilityRole::Tooltip => Role::Tooltip,
1
            AccessibilityRole::Application => Role::Application,
1
            AccessibilityRole::Document => Role::Document,
1
            AccessibilityRole::Pane => Role::Pane,
1
            AccessibilityRole::Chart => Role::Figure,
1
            AccessibilityRole::Dialog => Role::Dialog,
1
            AccessibilityRole::Border => Role::GenericContainer,
161
            AccessibilityRole::Grouping => Role::Group,
1
            AccessibilityRole::Separator => Role::GenericContainer,
1
            AccessibilityRole::Toolbar => Role::Toolbar,
1
            AccessibilityRole::StatusBar => Role::Status,
1
            AccessibilityRole::Table => Role::Table,
1
            AccessibilityRole::ColumnHeader => Role::ColumnHeader,
1
            AccessibilityRole::RowHeader => Role::RowHeader,
1
            AccessibilityRole::Column => Role::GenericContainer, // No Column in accesskit 0.17
1
            AccessibilityRole::Row => Role::Row,
1
            AccessibilityRole::Cell => Role::Cell,
1
            AccessibilityRole::Link => Role::Link,
1
            AccessibilityRole::HelpBalloon => Role::Tooltip,
1
            AccessibilityRole::Character => Role::GenericContainer,
1
            AccessibilityRole::List => Role::List,
1
            AccessibilityRole::ListItem => Role::ListItem,
2
            AccessibilityRole::Outline => Role::Tree,
1
            AccessibilityRole::OutlineItem => Role::TreeItem,
1
            AccessibilityRole::PageTab => Role::Tab,
1
            AccessibilityRole::PropertyPage => Role::TabPanel,
1
            AccessibilityRole::Indicator => Role::Meter,
121
            AccessibilityRole::Graphic => Role::Image,
            // StaticText -> Label in accesskit 0.17
1
            AccessibilityRole::StaticText => Role::Label,
3
            AccessibilityRole::Text => Role::TextInput,
16441
            AccessibilityRole::PushButton => Role::Button,
573
            AccessibilityRole::CheckButton => Role::CheckBox,
121
            AccessibilityRole::RadioButton => Role::RadioButton,
1
            AccessibilityRole::ComboBox => Role::ComboBox,
1
            AccessibilityRole::DropList => Role::ListBox,
1
            AccessibilityRole::ProgressBar => Role::ProgressIndicator,
1
            AccessibilityRole::Dial => Role::Meter,
1
            AccessibilityRole::HotkeyField => Role::TextInput,
3
            AccessibilityRole::Slider => Role::Slider,
1
            AccessibilityRole::SpinButton => Role::SpinButton,
1
            AccessibilityRole::Diagram => Role::Figure,
1
            AccessibilityRole::Animation => Role::GenericContainer,
1
            AccessibilityRole::Equation => Role::Math,
1
            AccessibilityRole::ButtonDropdown => Role::Button,
            // No MenuButton in accesskit 0.17
1
            AccessibilityRole::ButtonMenu => Role::Button,
1
            AccessibilityRole::ButtonDropdownGrid => Role::Button,
1
            AccessibilityRole::Whitespace => Role::GenericContainer,
1
            AccessibilityRole::PageTabList => Role::TabList,
1
            AccessibilityRole::Clock => Role::Timer,
1
            AccessibilityRole::SplitButton => Role::Button,
1
            AccessibilityRole::IpAddress => Role::TextInput,
1
            AccessibilityRole::Unknown => Role::Unknown,
1
            AccessibilityRole::Nothing => Role::GenericContainer,
        }
17482
    }
}
/// Decodes an `A11yNodeId` back into its `(DomId, NodeId)` components.
///
/// The `A11yNodeId` encodes both values in a single u64:
/// - Upper 32 bits: `DomId` (which DOM tree the node belongs to)
/// - Lower 32 bits: `NodeId + 1` (index within that DOM tree, offset by 1 to avoid colliding with
///   the accesskit root node id, matching the encoding in `update_tree`)
#[cfg(feature = "a11y")]
#[must_use]
10
pub const fn decode_a11y_node_id(a11y_node_id: A11yNodeId) -> (DomId, NodeId) {
10
    let raw = a11y_node_id.0;
10
    let dom_id = DomId {
10
        inner: (raw >> 32) as usize,
10
    };
10
    let node_id = NodeId::new(((raw & 0xFFFF_FFFF).wrapping_sub(1)) as usize);
10
    (dom_id, node_id)
10
}
/// Maps an accesskit `ActionRequest` to an Azul `AccessibilityAction`.
///
/// Returns `None` if the action requires data that was not provided or is invalid.
#[cfg(feature = "a11y")]
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[must_use]
48
pub fn map_accesskit_action(request: ActionRequest) -> Option<AccessibilityAction> {
    use azul_css::{props::basic::FloatValue, AzString};
48
    let action = match request.action {
1
        Action::Click => AccessibilityAction::Default,
1
        Action::Focus => AccessibilityAction::Focus,
1
        Action::Blur => AccessibilityAction::Blur,
1
        Action::Collapse => AccessibilityAction::Collapse,
1
        Action::Expand => AccessibilityAction::Expand,
2
        Action::ScrollIntoView => AccessibilityAction::ScrollIntoView,
1
        Action::Increment => AccessibilityAction::Increment,
1
        Action::Decrement => AccessibilityAction::Decrement,
1
        Action::ShowContextMenu => AccessibilityAction::ShowContextMenu,
1
        Action::HideTooltip => AccessibilityAction::HideTooltip,
1
        Action::ShowTooltip => AccessibilityAction::ShowTooltip,
1
        Action::ScrollUp => AccessibilityAction::ScrollUp,
1
        Action::ScrollDown => AccessibilityAction::ScrollDown,
1
        Action::ScrollLeft => AccessibilityAction::ScrollLeft,
1
        Action::ScrollRight => AccessibilityAction::ScrollRight,
        Action::SetSequentialFocusNavigationStartingPoint => {
1
            AccessibilityAction::SetSequentialFocusNavigationStartingPoint
        }
        Action::ReplaceSelectedText => {
2
            let accesskit::ActionData::Value(value) = request.data? else {
1
                return None;
            };
            AccessibilityAction::ReplaceSelectedText(AzString::from(value.as_ref()))
        }
        Action::ScrollToPoint => {
3
            let accesskit::ActionData::ScrollToPoint(point) = request.data? else {
1
                return None;
            };
1
            AccessibilityAction::ScrollToPoint(LogicalPosition {
1
                x: point.x as f32,
1
                y: point.y as f32,
1
            })
        }
        Action::SetScrollOffset => {
3
            let accesskit::ActionData::SetScrollOffset(point) = request.data? else {
1
                return None;
            };
1
            AccessibilityAction::SetScrollOffset(LogicalPosition {
1
                x: point.x as f32,
1
                y: point.y as f32,
1
            })
        }
        Action::SetTextSelection => {
3
            let accesskit::ActionData::SetTextSelection(selection) = request.data? else {
1
                return None;
            };
1
            AccessibilityAction::SetTextSelection(TextSelectionStartEnd {
1
                selection_start: selection.anchor.character_index,
1
                selection_end: selection.focus.character_index,
1
            })
        }
14
        Action::SetValue => match request.data? {
4
            accesskit::ActionData::Value(value) => {
4
                AccessibilityAction::SetValue(AzString::from(value.as_ref()))
            }
8
            accesskit::ActionData::NumericValue(value) => {
8
                AccessibilityAction::SetNumericValue(FloatValue::new(value as f32))
            }
1
            _ => return None,
        },
        Action::CustomAction => {
6
            let accesskit::ActionData::CustomAction(id) = request.data? else {
1
                return None;
            };
4
            AccessibilityAction::CustomAction(id)
        }
    };
36
    Some(action)
48
}
/// Stub implementation when accessibility feature is disabled.
#[cfg(not(feature = "a11y"))]
#[derive(Debug)]
pub struct A11yManager {
    _private: (),
}
#[cfg(not(feature = "a11y"))]
impl A11yManager {
    /// Creates a new stub `A11yManager` (no-op when accessibility is disabled).
    pub fn new() -> Self {
        Self { _private: () }
    }
}
#[cfg(all(test, feature = "a11y"))]
mod a11y_relation_tests {
    use accesskit::NodeId as A11yNodeId;
    use super::A11yManager;
    /// The a11y node-id encoding must stay in lockstep with the tree walk:
    /// `(dom.inner << 32) | (idx + 1)`. `labelled_by/described_by` relations encode
    /// their targets the same way, so any drift here would point a relation at
    /// the wrong (or a nonexistent) node.
    #[test]
1
    fn a11y_node_id_encoding_is_stable_and_offset() {
1
        assert_eq!(A11yManager::encode_a11y_node_id(0, 0), A11yNodeId(1));
1
        assert_eq!(A11yManager::encode_a11y_node_id(0, 5), A11yNodeId(6));
1
        assert_eq!(
1
            A11yManager::encode_a11y_node_id(2, 3),
            A11yNodeId((2u64 << 32) | 4)
        );
        // Never collides with the root window node (id 0).
1
        assert_ne!(A11yManager::encode_a11y_node_id(0, 0), A11yNodeId(0));
1
    }
}
#[cfg(all(test, feature = "a11y"))]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use std::collections::BTreeMap;
    use accesskit::{ActionData, Live, Point, TextPosition, TextSelection, Toggled, TreeId};
    use azul_core::{
        dom::{AttributeNameValue, AttributeType, FormattingContext, OptionDomNodeId},
        styled_dom::NodeHierarchyItemId,
        window::OptionVirtualKeyCodeCombo,
    };
    use azul_css::{css::BoxOrStatic, props::basic::FloatValue, OptionString};
    use super::*;
    use crate::{managers::scroll_state::ScrollManager, solver3::geometry::PackedBoxProps};
    // ---------------------------------------------------------------------
    // fixtures
    // ---------------------------------------------------------------------
    /// A `LayoutNodeHot` with the given used size and packed box props.
    /// `PackedBoxProps` edges are `[top, right, bottom, left]` in tenths of a pixel.
    fn hot(used_size: Option<LogicalSize>, padding: [i16; 4], border: [i16; 4]) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps {
                padding,
                border,
                ..PackedBoxProps::default()
            },
            dom_node_id: Some(NodeId::new(0)),
            used_size,
            formatting_context: FormattingContext::Block {
                establishes_new_context: false,
            },
            parent: None,
        }
    }
    fn plain_hot() -> LayoutNodeHot {
        hot(Some(LogicalSize::new(100.0, 50.0)), [0; 4], [0; 4])
    }
    fn info(role: AccessibilityRole) -> AccessibilityInfo {
        AccessibilityInfo {
            accessibility_name: OptionString::None,
            accessibility_value: OptionString::None,
            description: OptionString::None,
            accelerator: OptionVirtualKeyCodeCombo::None,
            default_action: OptionString::None,
            states: Vec::<AccessibilityState>::new().into(),
            supported_actions: Vec::<AccessibilityAction>::new().into(),
            labelled_by: OptionDomNodeId::None,
            described_by: OptionDomNodeId::None,
            role,
            is_live_region: false,
        }
    }
    fn dom_node(dom: usize, idx: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId { inner: dom },
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
        }
    }
    fn text_node(s: &str) -> NodeData {
        NodeData::create_node(NodeType::Text(BoxOrStatic::heap(AzString::from(s))))
    }
    fn request(action: Action, data: Option<ActionData>) -> ActionRequest {
        ActionRequest {
            action,
            target_tree: TreeId::ROOT,
            target_node: A11yNodeId(1),
            data,
        }
    }
    /// A `DomLayoutResult` carrying a real `StyledDom` but an EMPTY layout
    /// tree. `update_tree`'s tree SHAPE — who is whose child, what is
    /// reachable, where focus lands — is a pure function of `node_data` +
    /// `node_hierarchy`; the layout tree only supplies bounds. So this is
    /// enough to reproduce exactly the tree a real window publishes, with no
    /// solver pass and no fonts.
    fn layout_result_of(styled_dom: azul_core::styled_dom::StyledDom) -> DomLayoutResult {
        use std::{collections::HashMap, sync::Arc};
        use azul_core::geom::LogicalRect;
        use crate::solver3::{display_list::DisplayList, layout_tree::LayoutTree};
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// `update_tree` over a set of real DOMs, one per `DomId`, in id order.
    fn update_over_doms(doms: Vec<azul_core::dom::Dom>) -> TreeUpdate {
        use azul_core::styled_dom::StyledDom;
        let mut layout_results = BTreeMap::new();
        for (i, dom) in doms.into_iter().enumerate() {
            layout_results.insert(
                DomId { inner: i },
                layout_result_of(StyledDom::create_from_dom(dom)),
            );
        }
        let scroll_manager = ScrollManager::new();
        let overrides = BTreeMap::new();
        A11yManager::update_tree(
            A11yNodeId(0),
            &layout_results,
            &scroll_manager,
            &AzString::from("Azul Widget Showcase"),
            LogicalSize::new(1000.0, 700.0),
            None,
            1.0,
            &overrides,
            None,
        )
    }
    /// `update_tree` with no DOMs at all — the smallest legal input.
    fn empty_update(
        window_size: LogicalSize,
        focused_node: Option<DomNodeId>,
        hidpi_factor: f32,
        title: &str,
    ) -> TreeUpdate {
        let layout_results = BTreeMap::new();
        let scroll_manager = ScrollManager::new();
        let overrides = BTreeMap::new();
        A11yManager::update_tree(
            A11yNodeId(0),
            &layout_results,
            &scroll_manager,
            &AzString::from(title),
            window_size,
            focused_node,
            hidpi_factor,
            &overrides,
            None,
        )
    }
    // ---------------------------------------------------------------------
    // A11yManager::new / Default (constructor)
    // ---------------------------------------------------------------------
    #[test]
    fn new_starts_with_root_zero_and_uninitialized_tree() {
        let manager = A11yManager::new();
        assert_eq!(manager.root_id, A11yNodeId(0));
        assert!(manager.tree.is_none());
        assert!(manager.last_tree_update.is_none());
        assert!(
            !manager.tree_initialized,
            "a fresh manager must force a full first TreeUpdate"
        );
    }
    #[test]
    fn default_matches_new() {
        let a = A11yManager::new();
        let b = A11yManager::default();
        assert_eq!(a.root_id, b.root_id);
        assert_eq!(a.tree_initialized, b.tree_initialized);
        assert!(b.tree.is_none() && b.last_tree_update.is_none());
    }
    // ---------------------------------------------------------------------
    // encode_a11y_node_id / decode_a11y_node_id (numeric + round-trip)
    // ---------------------------------------------------------------------
    #[test]
    fn encode_decode_round_trips_over_the_representable_domain() {
        // node_idx must stay < u32::MAX so `idx + 1` cannot carry out of the
        // low 32 bits; dom_inner must stay <= u32::MAX so it cannot shift out.
        let cases: [(usize, usize); 7] = [
            (0, 0),
            (0, 1),
            (1, 0),
            (2, 3),
            (0, u32::MAX as usize - 1),
            (u32::MAX as usize, 0),
            (u32::MAX as usize, u32::MAX as usize - 1),
        ];
        for (dom, idx) in cases {
            let encoded = A11yManager::encode_a11y_node_id(dom, idx);
            let (decoded_dom, decoded_node) = decode_a11y_node_id(encoded);
            assert_eq!(decoded_dom.inner, dom, "dom round-trip for ({dom}, {idx})");
            assert_eq!(
                decoded_node.index(),
                idx,
                "idx round-trip for ({dom}, {idx})"
            );
        }
    }
    #[test]
    fn encoded_ids_never_collide_with_the_root_window_id() {
        // root_id is 0; the +1 offset is the only thing keeping node 0 of dom 0
        // from being mistaken for the window itself.
        for (dom, idx) in [(0usize, 0usize), (0, 1), (5, 0), (u32::MAX as usize, 0)] {
            assert_ne!(
                A11yManager::encode_a11y_node_id(dom, idx),
                A11yNodeId(0),
                "({dom}, {idx}) must not encode to the root id"
            );
        }
    }
    #[test]
    fn encode_is_injective_for_neighbouring_ids() {
        let a = A11yManager::encode_a11y_node_id(0, 1);
        let b = A11yManager::encode_a11y_node_id(1, 0);
        let c = A11yManager::encode_a11y_node_id(0, 2);
        assert_ne!(a, b);
        assert_ne!(a, c);
        assert_ne!(b, c);
    }
    /// Characterisation of a known-lossy boundary: `idx + 1` carries out of the
    /// low 32 bits at `idx == u32::MAX`, silently incrementing the DomId field.
    /// Not reachable with real DOMs (a 4-billion-node tree), but pinned so the
    /// encoding contract can't drift unnoticed. Does not panic.
    #[test]
    fn encode_node_idx_at_u32_max_carries_into_the_dom_field() {
        let encoded = A11yManager::encode_a11y_node_id(0, u32::MAX as usize);
        assert_eq!(encoded, A11yNodeId(1u64 << 32));
        let (dom, node) = decode_a11y_node_id(encoded);
        assert_eq!(dom.inner, 1, "dom 0 aliases onto dom 1 at the carry");
        assert_eq!(node.index(), usize::MAX);
        // Still never collides with the root window node.
        assert_ne!(encoded, A11yNodeId(0));
    }
    /// Decoding the root id itself is nonsense (root is not a DOM node), but it
    /// must not panic: the `wrapping_sub(1)` yields the usize::MAX sentinel.
    #[test]
    fn decode_of_root_id_wraps_instead_of_panicking() {
        let (dom, node) = decode_a11y_node_id(A11yNodeId(0));
        assert_eq!(dom.inner, 0);
        assert_eq!(node.index(), usize::MAX);
    }
    #[test]
    fn decode_of_u64_max_does_not_panic() {
        let (dom, node) = decode_a11y_node_id(A11yNodeId(u64::MAX));
        assert_eq!(dom.inner, u32::MAX as usize);
        assert_eq!(node.index(), u32::MAX as usize - 1);
    }
    // ---------------------------------------------------------------------
    // a11y_node_id_for
    // ---------------------------------------------------------------------
    #[test]
    fn a11y_node_id_for_resolves_to_the_same_id_the_tree_walk_emits() {
        let target = dom_node(2, 3);
        assert_eq!(
            A11yManager::a11y_node_id_for(&target),
            Some(A11yManager::encode_a11y_node_id(2, 3)),
            "a relation must resolve to the node the walk emitted"
        );
    }
    #[test]
    fn a11y_node_id_for_returns_none_for_the_none_sentinel() {
        let target = DomNodeId {
            dom: DomId { inner: 0 },
            node: NodeHierarchyItemId::NONE,
        };
        assert_eq!(A11yManager::a11y_node_id_for(&target), None);
    }
    #[test]
    fn a11y_node_id_for_handles_extreme_dom_ids_without_panicking() {
        let target = dom_node(u32::MAX as usize, 0);
        assert_eq!(
            A11yManager::a11y_node_id_for(&target),
            Some(A11yNodeId((u32::MAX as u64) << 32 | 1))
        );
    }
    // ---------------------------------------------------------------------
    // node_type_to_role
    // ---------------------------------------------------------------------
    #[test]
    fn node_type_to_role_maps_the_documented_roles() {
        let cases: [(NodeType, Role); 18] = [
            (
                NodeType::Text(BoxOrStatic::heap(AzString::from("x"))),
                Role::Label,
            ),
            (NodeType::P, Role::Paragraph),
            (NodeType::Div, Role::Group),
            (NodeType::Body, Role::Group),
            (NodeType::A, Role::Link),
            (NodeType::Button, Role::Button),
            (NodeType::H1, Role::Heading),
            (NodeType::H6, Role::Heading),
            (NodeType::Input, Role::TextInput),
            (NodeType::TextArea, Role::MultilineTextInput),
            (NodeType::Table, Role::Table),
            (NodeType::Tr, Role::Row),
            (NodeType::Td, Role::Cell),
            (NodeType::Th, Role::ColumnHeader),
            (NodeType::Ul, Role::List),
            (NodeType::Li, Role::ListItem),
            (NodeType::Br, Role::LineBreak),
            (NodeType::Hr, Role::Splitter),
        ];
        for (node_type, expected) in cases {
            assert_eq!(
                A11yManager::node_type_to_role(&node_type),
                expected,
                "{node_type:?}"
            );
        }
    }
    #[test]
    fn node_type_to_role_falls_back_to_group_for_unmapped_types() {
        // The `_ => Role::Group` arm: metadata types that never reach the tree
        // must still produce a VoiceOver-visible role rather than a filtered one.
        for node_type in [
            NodeType::Script,
            NodeType::Style,
            NodeType::Meta,
            NodeType::Head,
        ] {
            assert_eq!(A11yManager::node_type_to_role(&node_type), Role::Group);
        }
    }
    /// The doc contract: no role emitted here may be filtered out by accesskit's
    /// `common_filter` (`GenericContainer` / `TextRun`), or VoiceOver skips the
    /// node. `Col`/`ColGroup` are the sole exceptions — see the test below.
    #[test]
    fn node_type_to_role_never_emits_a_voiceover_filtered_role() {
        let node_types = [
            NodeType::Text(BoxOrStatic::heap(AzString::from("x"))),
            NodeType::P,
            NodeType::Pre,
            NodeType::BlockQuote,
            NodeType::Code,
            NodeType::Em,
            NodeType::Strong,
            NodeType::Mark,
            NodeType::Del,
            NodeType::Ins,
            NodeType::Abbr,
            NodeType::Q,
            NodeType::Time,
            NodeType::Ruby,
            NodeType::Rt,
            NodeType::Br,
            NodeType::Hr,
            NodeType::Body,
            NodeType::Div,
            NodeType::Span,
            NodeType::Html,
            NodeType::Article,
            NodeType::Section,
            NodeType::Nav,
            NodeType::Main,
            NodeType::Header,
            NodeType::Footer,
            NodeType::Aside,
            NodeType::Figure,
            NodeType::FigCaption,
            NodeType::Details,
            NodeType::Summary,
            NodeType::Dialog,
            NodeType::H1,
            NodeType::H2,
            NodeType::H3,
            NodeType::H4,
            NodeType::H5,
            NodeType::H6,
            NodeType::Ul,
            NodeType::Ol,
            NodeType::Li,
            NodeType::Dl,
            NodeType::Dt,
            NodeType::Dd,
            NodeType::Menu,
            NodeType::MenuItem,
            NodeType::Table,
            NodeType::Caption,
            NodeType::THead,
            NodeType::TBody,
            NodeType::TFoot,
            NodeType::Tr,
            NodeType::Th,
            NodeType::Td,
            NodeType::Form,
            NodeType::FieldSet,
            NodeType::Legend,
            NodeType::Label,
            NodeType::Input,
            NodeType::Button,
            NodeType::Select,
            NodeType::SelectOption,
            NodeType::TextArea,
            NodeType::Output,
            NodeType::Progress,
            NodeType::Meter,
            NodeType::DataList,
            NodeType::A,
            NodeType::Canvas,
            NodeType::Audio,
            NodeType::Video,
            NodeType::Svg,
            NodeType::Object,
            NodeType::Embed,
            NodeType::Script,
        ];
        for node_type in node_types {
            let role = A11yManager::node_type_to_role(&node_type);
            assert!(
                role != Role::GenericContainer && role != Role::TextRun,
                "{node_type:?} -> {role:?} would be skipped by VoiceOver's common_filter"
            );
        }
    }
    /// `Col`/`ColGroup` do map to the filtered `GenericContainer` role, against the
    /// function's own doc comment. Harmless today only because `update_tree` drops
    /// both node types before they can reach the tree — pinned so that stays true.
    #[test]
    fn col_and_colgroup_map_to_the_filtered_generic_container_role() {
        assert_eq!(
            A11yManager::node_type_to_role(&NodeType::Col),
            Role::GenericContainer
        );
        assert_eq!(
            A11yManager::node_type_to_role(&NodeType::ColGroup),
            Role::GenericContainer
        );
    }
    // ---------------------------------------------------------------------
    // map_role
    // ---------------------------------------------------------------------
    #[test]
    fn map_role_is_total_and_matches_the_documented_table() {
        let cases: [(AccessibilityRole, Role); 65] = [
            (AccessibilityRole::TitleBar, Role::TitleBar),
            (AccessibilityRole::MenuBar, Role::MenuBar),
            (AccessibilityRole::ScrollBar, Role::ScrollBar),
            (AccessibilityRole::Grip, Role::Splitter),
            (AccessibilityRole::Sound, Role::Audio),
            (AccessibilityRole::Cursor, Role::Caret),
            (AccessibilityRole::Caret, Role::Caret),
            (AccessibilityRole::Alert, Role::Alert),
            (AccessibilityRole::Window, Role::Window),
            (AccessibilityRole::Client, Role::GenericContainer),
            (AccessibilityRole::MenuPopup, Role::Menu),
            (AccessibilityRole::MenuItem, Role::MenuItem),
            (AccessibilityRole::Tooltip, Role::Tooltip),
            (AccessibilityRole::Application, Role::Application),
            (AccessibilityRole::Document, Role::Document),
            (AccessibilityRole::Pane, Role::Pane),
            (AccessibilityRole::Chart, Role::Figure),
            (AccessibilityRole::Dialog, Role::Dialog),
            (AccessibilityRole::Border, Role::GenericContainer),
            (AccessibilityRole::Grouping, Role::Group),
            (AccessibilityRole::Separator, Role::GenericContainer),
            (AccessibilityRole::Toolbar, Role::Toolbar),
            (AccessibilityRole::StatusBar, Role::Status),
            (AccessibilityRole::Table, Role::Table),
            (AccessibilityRole::ColumnHeader, Role::ColumnHeader),
            (AccessibilityRole::RowHeader, Role::RowHeader),
            (AccessibilityRole::Column, Role::GenericContainer),
            (AccessibilityRole::Row, Role::Row),
            (AccessibilityRole::Cell, Role::Cell),
            (AccessibilityRole::Link, Role::Link),
            (AccessibilityRole::HelpBalloon, Role::Tooltip),
            (AccessibilityRole::Character, Role::GenericContainer),
            (AccessibilityRole::List, Role::List),
            (AccessibilityRole::ListItem, Role::ListItem),
            (AccessibilityRole::Outline, Role::Tree),
            (AccessibilityRole::OutlineItem, Role::TreeItem),
            (AccessibilityRole::PageTab, Role::Tab),
            (AccessibilityRole::PropertyPage, Role::TabPanel),
            (AccessibilityRole::Indicator, Role::Meter),
            (AccessibilityRole::Graphic, Role::Image),
            (AccessibilityRole::StaticText, Role::Label),
            (AccessibilityRole::Text, Role::TextInput),
            (AccessibilityRole::PushButton, Role::Button),
            (AccessibilityRole::CheckButton, Role::CheckBox),
            (AccessibilityRole::RadioButton, Role::RadioButton),
            (AccessibilityRole::ComboBox, Role::ComboBox),
            (AccessibilityRole::DropList, Role::ListBox),
            (AccessibilityRole::ProgressBar, Role::ProgressIndicator),
            (AccessibilityRole::Dial, Role::Meter),
            (AccessibilityRole::HotkeyField, Role::TextInput),
            (AccessibilityRole::Slider, Role::Slider),
            (AccessibilityRole::SpinButton, Role::SpinButton),
            (AccessibilityRole::Diagram, Role::Figure),
            (AccessibilityRole::Animation, Role::GenericContainer),
            (AccessibilityRole::Equation, Role::Math),
            (AccessibilityRole::ButtonDropdown, Role::Button),
            (AccessibilityRole::ButtonMenu, Role::Button),
            (AccessibilityRole::ButtonDropdownGrid, Role::Button),
            (AccessibilityRole::Whitespace, Role::GenericContainer),
            (AccessibilityRole::PageTabList, Role::TabList),
            (AccessibilityRole::Clock, Role::Timer),
            (AccessibilityRole::SplitButton, Role::Button),
            (AccessibilityRole::IpAddress, Role::TextInput),
            (AccessibilityRole::Unknown, Role::Unknown),
            (AccessibilityRole::Nothing, Role::GenericContainer),
        ];
        for (role, expected) in cases {
            assert_eq!(A11yManager::map_role(&role), expected, "{role:?}");
        }
    }
    // ---------------------------------------------------------------------
    // map_action_to_accesskit / map_accesskit_action (round-trip)
    // ---------------------------------------------------------------------
    /// Every payload-free action must survive outbound -> inbound unchanged:
    /// the tree declares `map_action_to_accesskit(a)`, the screen reader sends
    /// that action back, and `map_accesskit_action` must hand back exactly `a`.
    #[test]
    fn payload_free_actions_round_trip_through_accesskit() {
        let actions = [
            AccessibilityAction::Default,
            AccessibilityAction::Focus,
            AccessibilityAction::Blur,
            AccessibilityAction::Collapse,
            AccessibilityAction::Expand,
            AccessibilityAction::ScrollIntoView,
            AccessibilityAction::Increment,
            AccessibilityAction::Decrement,
            AccessibilityAction::ShowContextMenu,
            AccessibilityAction::HideTooltip,
            AccessibilityAction::ShowTooltip,
            AccessibilityAction::ScrollUp,
            AccessibilityAction::ScrollDown,
            AccessibilityAction::ScrollLeft,
            AccessibilityAction::ScrollRight,
            AccessibilityAction::SetSequentialFocusNavigationStartingPoint,
        ];
        for action in actions {
            let outbound = A11yManager::map_action_to_accesskit(&action);
            let inbound = map_accesskit_action(request(outbound, None));
            assert_eq!(
                inbound,
                Some(action.clone()),
                "{action:?} did not survive the outbound/inbound round-trip"
            );
        }
    }
    #[test]
    fn payload_carrying_actions_map_to_their_action_kind() {
        let cases = [
            (
                AccessibilityAction::ReplaceSelectedText(AzString::from("x")),
                Action::ReplaceSelectedText,
            ),
            (
                AccessibilityAction::ScrollToPoint(LogicalPosition::new(f32::NAN, 0.0)),
                Action::ScrollToPoint,
            ),
            (
                AccessibilityAction::SetScrollOffset(LogicalPosition::new(-1.0, f32::INFINITY)),
                Action::SetScrollOffset,
            ),
            (
                AccessibilityAction::SetTextSelection(TextSelectionStartEnd {
                    selection_start: usize::MAX,
                    selection_end: 0,
                }),
                Action::SetTextSelection,
            ),
            (
                AccessibilityAction::SetValue(AzString::from("")),
                Action::SetValue,
            ),
            (
                AccessibilityAction::SetNumericValue(FloatValue::new(f32::NAN)),
                Action::SetValue,
            ),
            (
                AccessibilityAction::CustomAction(i32::MIN),
                Action::CustomAction,
            ),
        ];
        for (action, expected) in cases {
            assert_eq!(
                A11yManager::map_action_to_accesskit(&action),
                expected,
                "{action:?}"
            );
        }
    }
    #[test]
    fn data_requiring_actions_return_none_when_data_is_missing() {
        for action in [
            Action::ReplaceSelectedText,
            Action::ScrollToPoint,
            Action::SetScrollOffset,
            Action::SetTextSelection,
            Action::SetValue,
            Action::CustomAction,
        ] {
            assert_eq!(
                map_accesskit_action(request(action, None)),
                None,
                "{action:?} must reject a request with no payload"
            );
        }
    }
    #[test]
    fn data_requiring_actions_return_none_on_mismatched_payloads() {
        let mismatches = [
            (Action::ReplaceSelectedText, ActionData::NumericValue(1.0)),
            (Action::ScrollToPoint, ActionData::NumericValue(1.0)),
            (
                Action::SetScrollOffset,
                ActionData::Value(Box::from("not a point")),
            ),
            (Action::SetTextSelection, ActionData::CustomAction(3)),
            (Action::SetValue, ActionData::CustomAction(3)),
            (Action::CustomAction, ActionData::NumericValue(1.0)),
        ];
        for (action, data) in mismatches {
            assert_eq!(
                map_accesskit_action(request(action, Some(data.clone()))),
                None,
                "{action:?} must reject payload {data:?}"
            );
        }
    }
    #[test]
    fn payload_free_actions_ignore_an_unexpected_payload() {
        // ScrollIntoView takes an *optional* hint; a stray payload must not
        // turn the request into a no-op.
        assert_eq!(
            map_accesskit_action(request(
                Action::ScrollIntoView,
                Some(ActionData::NumericValue(1.0))
            )),
            Some(AccessibilityAction::ScrollIntoView)
        );
    }
    #[test]
    fn set_value_accepts_unicode_and_empty_strings() {
        for s in ["", "héllo 🎉", "a\0b", "\u{202e}rtl"] {
            let got = map_accesskit_action(request(
                Action::SetValue,
                Some(ActionData::Value(Box::from(s))),
            ));
            assert_eq!(got, Some(AccessibilityAction::SetValue(AzString::from(s))));
        }
    }
    #[test]
    fn set_numeric_value_saturates_instead_of_panicking() {
        for v in [
            0.0_f64,
            -0.0,
            f64::NAN,
            f64::INFINITY,
            f64::NEG_INFINITY,
            1e300,
            -1e300,
            f64::from(f32::MAX),
        ] {
            let got =
                map_accesskit_action(request(Action::SetValue, Some(ActionData::NumericValue(v))));
            #[allow(clippy::cast_possible_truncation)]
            let expected = AccessibilityAction::SetNumericValue(FloatValue::new(v as f32));
            assert_eq!(got, Some(expected), "NumericValue({v}) must not panic");
        }
    }
    #[test]
    fn scroll_to_point_preserves_nan_and_saturates_out_of_range_f64() {
        let got = map_accesskit_action(request(
            Action::ScrollToPoint,
            Some(ActionData::ScrollToPoint(Point {
                x: f64::NAN,
                y: 1e308,
            })),
        ));
        let Some(AccessibilityAction::ScrollToPoint(p)) = got else {
            panic!("expected ScrollToPoint, got {got:?}");
        };
        assert!(p.x.is_nan(), "NaN must pass through, not trap");
        assert!(
            p.y.is_infinite() && p.y.is_sign_positive(),
            "1e308 must saturate to +inf, got {}",
            p.y
        );
    }
    #[test]
    fn set_scroll_offset_saturates_negative_out_of_range_f64() {
        let got = map_accesskit_action(request(
            Action::SetScrollOffset,
            Some(ActionData::SetScrollOffset(Point {
                x: -1e308,
                y: f64::NEG_INFINITY,
            })),
        ));
        let Some(AccessibilityAction::SetScrollOffset(p)) = got else {
            panic!("expected SetScrollOffset, got {got:?}");
        };
        assert!(p.x.is_infinite() && p.x.is_sign_negative());
        assert!(p.y.is_infinite() && p.y.is_sign_negative());
    }
    #[test]
    fn set_text_selection_passes_through_extreme_character_indices() {
        let got = map_accesskit_action(request(
            Action::SetTextSelection,
            Some(ActionData::SetTextSelection(TextSelection {
                anchor: TextPosition {
                    node: A11yNodeId(1),
                    character_index: usize::MAX,
                },
                focus: TextPosition {
                    node: A11yNodeId(2),
                    character_index: 0,
                },
            })),
        ));
        assert_eq!(
            got,
            Some(AccessibilityAction::SetTextSelection(
                TextSelectionStartEnd {
                    selection_start: usize::MAX,
                    selection_end: 0,
                }
            )),
            "an inverted, out-of-range selection must be forwarded verbatim, not clamped"
        );
    }
    #[test]
    fn custom_action_forwards_extreme_ids() {
        for id in [i32::MIN, -1, 0, i32::MAX] {
            assert_eq!(
                map_accesskit_action(request(
                    Action::CustomAction,
                    Some(ActionData::CustomAction(id))
                )),
                Some(AccessibilityAction::CustomAction(id))
            );
        }
    }
    // ---------------------------------------------------------------------
    // build_node — bounds arithmetic (numeric)
    // ---------------------------------------------------------------------
    #[test]
    fn build_node_bounds_are_padding_inset_and_hidpi_scaled() {
        let node_data = NodeData::create_node(NodeType::Div);
        // padding 5px top/bottom, 2px left/right (packed as tenths of a px).
        let layout_node = hot(
            Some(LogicalSize::new(100.0, 50.0)),
            [50, 20, 50, 20],
            [0; 4],
        );
        let node = A11yManager::build_node(
            &node_data,
            &layout_node,
            Some(LogicalPosition::new(10.0, 20.0)),
            None,
            2.0,
            LogicalSize::new(1000.0, 1000.0),
        );
        let bounds = node.bounds().expect("in-viewport node must have bounds");
        assert_eq!(bounds.x0, 24.0); // (10 + 2) * 2
        assert_eq!(bounds.y0, 50.0); // (20 + 5) * 2
        assert_eq!(bounds.x1, 216.0); // (10 + 100 - 2) * 2
        assert_eq!(bounds.y1, 130.0); // (20 + 50 - 5) * 2
    }
    #[test]
    fn build_node_clips_bounds_to_the_window_viewport() {
        let node_data = NodeData::create_node(NodeType::Div);
        let layout_node = hot(Some(LogicalSize::new(10_000.0, 10_000.0)), [0; 4], [0; 4]);
        let node = A11yManager::build_node(
            &node_data,
            &layout_node,
            Some(LogicalPosition::new(-500.0, -500.0)),
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        let bounds = node.bounds().expect("clipped node still has bounds");
        assert_eq!(
            (bounds.x0, bounds.y0),
            (0.0, 0.0),
            "off-screen origin clamps to 0"
        );
        assert_eq!(
            (bounds.x1, bounds.y1),
            (800.0, 600.0),
            "overflowing extent clamps to the viewport"
        );
    }
    #[test]
    fn build_node_omits_bounds_when_padding_exceeds_the_used_size() {
        // Degenerate box: x1 <= x0, so accesskit must not be handed an inverted rect.
        let node_data = NodeData::create_node(NodeType::Div);
        let layout_node = hot(
            Some(LogicalSize::new(10.0, 10.0)),
            [500, 500, 500, 500],
            [0; 4],
        );
        let node = A11yManager::build_node(
            &node_data,
            &layout_node,
            Some(LogicalPosition::new(0.0, 0.0)),
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.bounds(), None);
    }
    #[test]
    fn build_node_omits_bounds_for_zero_and_nan_hidpi() {
        let node_data = NodeData::create_node(NodeType::Div);
        let layout_node = plain_hot();
        for hidpi in [0.0_f32, f32::NAN, -2.0] {
            let node = A11yManager::build_node(
                &node_data,
                &layout_node,
                Some(LogicalPosition::new(10.0, 20.0)),
                None,
                hidpi,
                LogicalSize::new(800.0, 600.0),
            );
            assert_eq!(
                node.bounds(),
                None,
                "hidpi {hidpi} collapses the rect; no bounds must be set"
            );
        }
    }
    #[test]
    fn build_node_never_emits_an_inverted_rect_for_hostile_geometry() {
        // The `x1 > x0 && y1 > y0` guard is the only thing between accesskit and
        // an inverted/degenerate rect. Sweep the nastiest float inputs at it.
        let node_data = NodeData::create_node(NodeType::Div);
        let sizes = [
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(-100.0, -100.0),
            LogicalSize::new(f32::NAN, f32::NAN),
            LogicalSize::new(f32::INFINITY, f32::INFINITY),
        ];
        let positions = [
            LogicalPosition::new(0.0, 0.0),
            LogicalPosition::new(-f32::MAX, -f32::MAX),
            LogicalPosition::new(f32::NAN, 0.0),
            LogicalPosition::new(f32::INFINITY, f32::NEG_INFINITY),
        ];
        let windows = [
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(800.0, 600.0),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(f32::NAN, f32::NAN),
        ];
        for size in sizes {
            for pos in positions {
                for window in windows {
                    for hidpi in [1.0_f32, 0.5, 3.0, f32::INFINITY] {
                        let layout_node = hot(Some(size), [i16::MAX; 4], [i16::MIN; 4]);
                        let node = A11yManager::build_node(
                            &node_data,
                            &layout_node,
                            Some(pos),
                            None,
                            hidpi,
                            window,
                        );
                        if let Some(b) = node.bounds() {
                            assert!(
                                b.x1 > b.x0 && b.y1 > b.y0,
                                "inverted rect {b:?} for size={size:?} pos={pos:?} \
                                 window={window:?} hidpi={hidpi}"
                            );
                        }
                    }
                }
            }
        }
    }
    #[test]
    fn build_node_omits_bounds_when_layout_info_is_missing() {
        let node_data = NodeData::create_node(NodeType::Div);
        // No absolute position.
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.bounds(), None);
        // No used size.
        let node = A11yManager::build_node(
            &node_data,
            &hot(None, [0; 4], [0; 4]),
            Some(LogicalPosition::new(0.0, 0.0)),
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.bounds(), None);
    }
    // ---------------------------------------------------------------------
    // build_node — roles, labels, states, actions (invariants)
    // ---------------------------------------------------------------------
    #[test]
    fn build_node_always_declares_scroll_into_view() {
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert!(node.supports_action(Action::ScrollIntoView));
    }
    #[test]
    fn build_node_sets_the_html_tag() {
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        let expected = NodeType::Div.get_path().to_string();
        assert_eq!(node.html_tag(), Some(expected.as_str()));
    }
    #[test]
    fn build_node_contenteditable_wins_over_a11y_role_and_gains_focus() {
        let mut node_data = NodeData::create_node(NodeType::Div);
        node_data.set_contenteditable(true);
        // Even an explicit (conflicting) role must not override editability.
        node_data.set_accessibility_info(info(AccessibilityRole::PushButton));
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            node_data.get_accessibility_info(),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.role(), Role::MultilineTextInput);
        assert!(node.supports_action(Action::Focus));
    }
    #[test]
    fn build_node_labels_text_nodes_including_unicode_and_empty() {
        for s in ["", "héllo 🎉", "a\u{202e}b"] {
            let node_data = text_node(s);
            let node = A11yManager::build_node(
                &node_data,
                &plain_hot(),
                None,
                None,
                1.0,
                LogicalSize::new(800.0, 600.0),
            );
            assert_eq!(node.role(), Role::Label);
            assert_eq!(node.label(), Some(s));
        }
    }
    #[test]
    fn build_node_sets_heading_levels_one_through_six() {
        let expected = [
            (NodeType::H1, 1),
            (NodeType::H2, 2),
            (NodeType::H3, 3),
            (NodeType::H4, 4),
            (NodeType::H5, 5),
            (NodeType::H6, 6),
        ];
        for (node_type, level) in expected {
            let node_data = NodeData::create_node(node_type);
            let node = A11yManager::build_node(
                &node_data,
                &plain_hot(),
                None,
                None,
                1.0,
                LogicalSize::new(800.0, 600.0),
            );
            assert_eq!(node.role(), Role::Heading);
            assert_eq!(node.level(), Some(level));
        }
    }
    #[test]
    fn build_node_maps_every_handled_accessibility_state() {
        let states = [
            AccessibilityState::Unavailable,
            AccessibilityState::Readonly,
            AccessibilityState::CheckedTrue,
            AccessibilityState::Expanded,
            AccessibilityState::Selected,
            AccessibilityState::Busy,
            AccessibilityState::Offscreen,
            AccessibilityState::Focusable,
        ];
        let mut a11y = info(AccessibilityRole::CheckButton);
        a11y.states = states.to_vec().into();
        let node_data = NodeData::create_node(NodeType::Div);
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.role(), Role::CheckBox);
        assert!(node.is_disabled());
        assert!(node.is_read_only());
        assert_eq!(node.toggled(), Some(Toggled::True));
        assert_eq!(node.is_expanded(), Some(true));
        assert_eq!(node.is_selected(), Some(true));
        assert!(node.is_busy());
        assert!(node.is_hidden());
        assert!(node.supports_action(Action::Focus));
    }
    #[test]
    fn build_node_collapsed_and_checked_false_are_distinct_from_absent() {
        let mut a11y = info(AccessibilityRole::CheckButton);
        a11y.states = vec![
            AccessibilityState::Collapsed,
            AccessibilityState::CheckedFalse,
        ]
        .into();
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.is_expanded(), Some(false));
        assert_eq!(node.toggled(), Some(Toggled::False));
    }
    #[test]
    fn build_node_declares_api_supplied_supported_actions() {
        let mut a11y = info(AccessibilityRole::Slider);
        a11y.supported_actions = vec![
            AccessibilityAction::Increment,
            AccessibilityAction::Decrement,
            AccessibilityAction::SetValue(AzString::from("x")),
            AccessibilityAction::CustomAction(1),
        ]
        .into();
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert!(node.supports_action(Action::Increment));
        assert!(node.supports_action(Action::Decrement));
        assert!(node.supports_action(Action::SetValue));
        assert!(node.supports_action(Action::CustomAction));
    }
    #[test]
    fn build_node_relations_resolve_to_walk_emitted_ids() {
        let mut a11y = info(AccessibilityRole::Text);
        a11y.labelled_by = OptionDomNodeId::Some(dom_node(2, 3));
        a11y.described_by = OptionDomNodeId::Some(dom_node(0, 0));
        a11y.is_live_region = true;
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(
            node.labelled_by(),
            &[A11yManager::encode_a11y_node_id(2, 3)]
        );
        assert_eq!(
            node.described_by(),
            &[A11yManager::encode_a11y_node_id(0, 0)]
        );
        assert_eq!(node.live(), Some(Live::Polite));
    }
    #[test]
    fn build_node_drops_relations_pointing_at_the_none_sentinel() {
        let mut a11y = info(AccessibilityRole::Text);
        let unresolvable = DomNodeId {
            dom: DomId { inner: 0 },
            node: NodeHierarchyItemId::NONE,
        };
        a11y.labelled_by = OptionDomNodeId::Some(unresolvable);
        a11y.described_by = OptionDomNodeId::Some(unresolvable);
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert!(
            node.labelled_by().is_empty() && node.described_by().is_empty(),
            "an unresolvable relation must be dropped, not encoded as a bogus id"
        );
    }
    // ---------------------------------------------------------------------
    // build_node — HTML attributes
    // ---------------------------------------------------------------------
    #[test]
    fn build_node_parses_aria_live_case_insensitively() {
        for (value, expected) in [
            ("polite", Live::Polite),
            ("POLITE", Live::Polite),
            ("assertive", Live::Assertive),
            ("AsSeRtIvE", Live::Assertive),
            ("off", Live::Off),
            ("", Live::Off),
            ("banana", Live::Off),
            ("🎉", Live::Off),
        ] {
            let mut node_data = NodeData::create_node(NodeType::Div);
            node_data.set_attributes(
                vec![AttributeType::AriaProperty(AttributeNameValue {
                    attr_name: AzString::from("ARIA-LIVE"),
                    value: AzString::from(value),
                })]
                .into(),
            );
            let node = A11yManager::build_node(
                &node_data,
                &plain_hot(),
                None,
                None,
                1.0,
                LogicalSize::new(800.0, 600.0),
            );
            assert_eq!(node.live(), Some(expected), "aria-live={value:?}");
        }
    }
    #[test]
    fn build_node_wires_up_html_attributes() {
        let mut node_data = NodeData::create_node(NodeType::Input);
        node_data.set_attributes(
            vec![
                AttributeType::AriaLabel(AzString::from("label")),
                AttributeType::Title(AzString::from("desc")),
                AttributeType::Placeholder(AzString::from("hint")),
                AttributeType::Value(AzString::from("val")),
                AttributeType::Disabled,
                AttributeType::Readonly,
                AttributeType::Required,
                AttributeType::Hidden,
                AttributeType::CheckedTrue,
                AttributeType::Lang(AzString::from("de")),
                AttributeType::ColSpan(2),
                AttributeType::RowSpan(3),
            ]
            .into(),
        );
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.label(), Some("label"));
        assert_eq!(node.description(), Some("desc"));
        assert_eq!(node.placeholder(), Some("hint"));
        assert_eq!(node.value(), Some("val"));
        assert!(node.is_disabled());
        assert!(node.is_read_only());
        assert!(node.is_required());
        assert!(node.is_hidden());
        assert_eq!(node.toggled(), Some(Toggled::True));
        assert_eq!(node.language(), Some("de"));
        assert_eq!(node.column_span(), Some(2));
        assert_eq!(node.row_span(), Some(3));
    }
    /// `colspan`/`rowspan` are `i32` in the DOM but `usize` in accesskit, and the
    /// conversion is an unchecked `as` cast. A negative span (HTML lets you write
    /// `colspan="-1"`) sign-extends into an astronomically large span instead of
    /// being rejected or clamped. Pinned here: no panic, but the value is garbage.
    #[test]
    fn build_node_negative_col_and_row_span_sign_extend_to_usize_max() {
        let mut node_data = NodeData::create_node(NodeType::Td);
        node_data
            .set_attributes(vec![AttributeType::ColSpan(-1), AttributeType::RowSpan(-1)].into());
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.column_span(), Some(usize::MAX));
        assert_eq!(node.row_span(), Some(usize::MAX));
    }
    #[test]
    fn build_node_zero_span_is_forwarded_unchanged() {
        let mut node_data = NodeData::create_node(NodeType::Td);
        node_data.set_attributes(vec![AttributeType::ColSpan(0)].into());
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            None,
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.column_span(), Some(0));
    }
    #[test]
    fn build_node_dom_attributes_override_accessibility_info() {
        // Documented priority: explicit a11y info < DOM attributes.
        let mut a11y = info(AccessibilityRole::PushButton);
        a11y.accessibility_name = OptionString::Some(AzString::from("from-info"));
        a11y.accessibility_value = OptionString::Some(AzString::from("info-value"));
        let mut node_data = NodeData::create_node(NodeType::Button);
        node_data.set_attributes(
            vec![
                AttributeType::AriaLabel(AzString::from("from-attr")),
                AttributeType::Value(AzString::from("attr-value")),
            ]
            .into(),
        );
        let node = A11yManager::build_node(
            &node_data,
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.label(), Some("from-attr"));
        assert_eq!(node.value(), Some("attr-value"));
    }
    // ---------------------------------------------------------------------
    // update_tree (numeric / no-panic)
    // ---------------------------------------------------------------------
    #[test]
    fn update_tree_with_no_doms_emits_only_the_root_window_node() {
        let update = empty_update(LogicalSize::new(800.0, 600.0), None, 1.0, "title");
        assert_eq!(update.nodes.len(), 1);
        assert_eq!(update.nodes[0].0, A11yNodeId(0));
        assert_eq!(update.nodes[0].1.role(), Role::Window);
        assert_eq!(update.nodes[0].1.label(), Some("title"));
        assert!(update.nodes[0].1.children().is_empty());
        assert!(
            update.tree.is_some(),
            "the first update must carry the tree"
        );
        assert_eq!(update.tree_id, TreeId::ROOT);
        assert_eq!(
            update.focus,
            A11yNodeId(0),
            "with no content nodes, focus must fall back to the root"
        );
    }
    // ---------------------------------------------------------------------
    // Naming a control must not DELETE it (the AzWidgets a11y regression)
    // ---------------------------------------------------------------------
    #[test]
    fn naming_a_node_keeps_the_role_its_element_type_implies() {
        // The one-field form the engine's own lint recommends. It produces
        // `AccessibilityInfo { name: Some(..), role: Unknown, .. }`, and
        // `Unknown` is `Default`'s "not specified" — so the element's own kind
        // must survive. It used to be replaced by `Role::Unknown`, which
        // VoiceOver skips exactly the way it skips `GenericContainer`: naming a
        // control removed it from the tree.
        for (node_type, expected) in [
            (NodeType::Button, Role::Button),
            (NodeType::Div, Role::Group),
            (NodeType::A, Role::Link),
            (NodeType::Input, Role::TextInput),
            (NodeType::H1, Role::Heading),
        ] {
            let a11y = AccessibilityInfo {
                accessibility_name: OptionString::Some(AzString::from("Accent colour")),
                ..Default::default()
            };
            assert_eq!(
                a11y.role,
                AccessibilityRole::Unknown,
                "the fixture must exercise the unspecified-role case"
            );
            let node = A11yManager::build_node(
                &NodeData::create_node(node_type.clone()),
                &plain_hot(),
                None,
                Some(&a11y),
                1.0,
                LogicalSize::new(800.0, 600.0),
            );
            assert_eq!(
                node.role(),
                expected,
                "{node_type:?} lost its role to a name-only declaration"
            );
            assert_eq!(
                node.label(),
                Some("Accent colour"),
                "the name must survive too"
            );
        }
    }
    #[test]
    fn a_declared_role_still_outranks_the_element_type() {
        // The other half of the contract: an explicit role is authoritative.
        let mut a11y = info(AccessibilityRole::Slider);
        a11y.accessibility_name = OptionString::Some(AzString::from("Volume"));
        let node = A11yManager::build_node(
            &NodeData::create_node(NodeType::Div),
            &plain_hot(),
            None,
            Some(&a11y),
            1.0,
            LogicalSize::new(800.0, 600.0),
        );
        assert_eq!(node.role(), Role::Slider);
    }
    #[test]
    fn no_named_node_in_a_widget_showcase_tree_is_announced_as_unknown() {
        // Whole-tree statement of the same bug, over the shape AzWidgets
        // actually builds: a labelled section whose control carries a name and
        // nothing else. `Role::Unknown` must not appear anywhere.
        use azul_core::dom::Dom;
        let labelled = |caption: &str, control: Dom| {
            Dom::create_div()
                .with_child(Dom::create_span_with_text(caption))
                // Exactly what `examples/azul-widgets`' `labelled()` helper
                // does: the caption a sighted user reads IS the control's name.
                .with_child(control.with_accessibility_name(caption))
        };
        let body = Dom::create_body().with_child(
            Dom::create_div()
                .with_child(labelled("Accent colour", Dom::create_div()))
                .with_child(labelled("Volume", Dom::create_div()))
                .with_child(labelled("Subscribe", Dom::create_div())),
        );
        let update = update_over_doms(vec![body]);
        let unknown: Vec<_> = update
            .nodes
            .iter()
            .filter(|(_, n)| n.role() == Role::Unknown)
            .map(|(id, n)| (*id, n.label()))
            .collect();
        assert!(
            unknown.is_empty(),
            "named controls fell out of the tree as Role::Unknown: {unknown:?}"
        );
    }
    #[test]
    fn the_ios_android_snapshot_resolves_roles_the_same_way_the_accesskit_tree_does() {
        // `A11ySnapshot` is the platform-neutral twin for the two shells
        // accesskit has no backend for. It carried the identical defect, and a
        // second copy of a rule is how the two drift apart — both now go
        // through `accessibility_role_is_specified`.
        use azul_core::{dom::Dom, styled_dom::StyledDom};
        use crate::managers::{a11y_snapshot::A11ySnapshot, gpu_state::GpuStateManager};
        let mut layout_results = BTreeMap::new();
        layout_results.insert(
            DomId { inner: 0 },
            layout_result_of(StyledDom::create_from_dom(
                Dom::create_body().with_child(
                    Dom::create_button(
                        "Subscribe",
                        azul_core::a11y::SmallAriaInfo::label("Subscribe"),
                    )
                    .with_accessibility_name("Subscribe"),
                ),
            )),
        );
        let gpu = GpuStateManager::new(
            azul_core::task::Duration::from_millis(0),
            azul_core::task::Duration::from_millis(0),
        );
        let snapshot = A11ySnapshot::build(
            &layout_results,
            &ScrollManager::new(),
            &gpu,
            None,
            "t",
            LogicalSize::new(800.0, 600.0),
        );
        let unknown: Vec<_> = snapshot
            .elements
            .iter()
            .filter(|e| e.role == AccessibilityRole::Unknown)
            .map(|e| e.label.clone())
            .collect();
        assert!(
            unknown.is_empty(),
            "named elements came back with an Unknown role: {unknown:?}"
        );
    }
    #[test]
    fn a_well_formed_multi_dom_tree_passes_through_the_guard_untouched() {
        // The consistency guard exists to neutralise MALFORMED input. On a
        // well-formed one — including the main window merged with a
        // `<transient-window>` child DOM — it must be a NO-OP: every node
        // present, reachable exactly once, nothing re-hung on the root. (The
        // AzWidgets a11y regression was blamed on this guard; it is not the
        // culprit, and this pins that.)
        use azul_core::dom::Dom;
        let page = |name: &str| {
            Dom::create_body()
                .with_child(Dom::create_span_with_text(name))
                .with_child(
                    Dom::create_div()
                        .with_child(Dom::create_span_with_text("one"))
                        .with_child(Dom::create_span_with_text("two")),
                )
        };
        let update = update_over_doms(vec![page("main"), page("popup")]);
        let by_id: HashMap<A11yNodeId, &Node> =
            update.nodes.iter().map(|(id, n)| (*id, n)).collect();
        let root = by_id[&A11yNodeId(0)];
        assert_eq!(
            root.children().len(),
            2,
            "one root child per DOM, and no orphan re-hung alongside them: {:?}",
            root.children()
        );
        let mut reachable = std::collections::HashSet::new();
        let mut stack = vec![A11yNodeId(0)];
        while let Some(id) = stack.pop() {
            assert!(reachable.insert(id), "{id:?} is reachable twice");
            if let Some(n) = by_id.get(&id) {
                stack.extend(n.children().iter().copied());
            }
        }
        assert_eq!(
            reachable.len(),
            update.nodes.len(),
            "the guard dropped nodes from a well-formed tree"
        );
    }
    #[test]
    fn enforce_child_invariants_makes_a_malformed_tree_accesskit_safe() {
        use std::collections::{HashMap, HashSet};
        // Regression for the SIGABRT in accesskit_consumer::tree::State::update
        // (a mouse_up a11y flush): a malformed TreeUpdate ABORTS the process
        // under panic=abort, so the shell's catch_unwind can't save it. This one
        // input carries EVERY accesskit-fatal shape at once — a class-level guard
        // has to neutralise all of them, no matter what the multi-DOM merge emits.
        let root = A11yNodeId(0);
        let node_ids = vec![
            root,
            A11yNodeId(1),
            A11yNodeId(2),
            A11yNodeId(3),
            A11yNodeId(4),
            A11yNodeId(5),
        ];
        //   99 = child that names no present node   -> must be dropped (else
        // tree.rs:75/307-adjacent)   2  = claimed by root AND node 1          -> a node
        // with two parents (tree.rs:225)   3  = claimed by node 1 AND node 2        -> two
        // parents again   4  = its own child                       -> self-cycle
        //   88 = parent that is not a present node   -> its child list must be cleared
        //   5  = only child of missing parent 88     -> orphan; must be re-hung reachable
        // (tree.rs:307)
        let mut root_children = vec![A11yNodeId(1), A11yNodeId(2), A11yNodeId(99)];
        let mut map: HashMap<A11yNodeId, Vec<A11yNodeId>> = HashMap::new();
        map.insert(A11yNodeId(1), vec![A11yNodeId(2), A11yNodeId(3)]);
        map.insert(A11yNodeId(2), vec![A11yNodeId(3)]);
        map.insert(A11yNodeId(4), vec![A11yNodeId(4)]);
        map.insert(A11yNodeId(88), vec![A11yNodeId(5)]);
        A11yManager::enforce_child_invariants(&node_ids, root, &mut root_children, &mut map);
        let valid: HashSet<A11yNodeId> = node_ids.iter().copied().collect();
        let mut all_children: Vec<A11yNodeId> = root_children.clone();
        for children in map.values() {
            all_children.extend(children.iter().copied());
        }
        // 1. No child names a node absent from the update.
        for c in &all_children {
            assert!(valid.contains(c), "dangling child {c:?} survived the guard");
        }
        // 2. No node is a child of two parents (accesskit's GLOBAL duplicate).
        let mut seen = HashSet::new();
        for c in &all_children {
            assert!(seen.insert(*c), "node {c:?} still has two parents");
        }
        // 3. No node is its own child.
        assert!(
            !map.get(&A11yNodeId(4))
                .is_some_and(|ch| ch.contains(&A11yNodeId(4))),
            "self-parent survived the guard"
        );
        // 4. Every present non-root node is reachable exactly once (no orphan).
        let reachable: HashSet<A11yNodeId> = all_children.iter().copied().collect();
        for id in &node_ids {
            if *id == root {
                continue;
            }
            assert!(
                reachable.contains(id),
                "node {id:?} is an orphan (unreachable from root)"
            );
        }
    }
    #[test]
    fn update_tree_survives_degenerate_window_sizes_and_hidpi() {
        let sizes = [
            LogicalSize::new(0.0, 0.0),
            LogicalSize::new(-1.0, -1.0),
            LogicalSize::new(f32::MAX, f32::MAX),
            LogicalSize::new(f32::NAN, f32::NAN),
            LogicalSize::new(f32::INFINITY, f32::NEG_INFINITY),
        ];
        for size in sizes {
            for hidpi in [0.0_f32, 1.0, -1.0, f32::NAN, f32::INFINITY, f32::MIN] {
                let update = empty_update(size, None, hidpi, "t");
                assert_eq!(update.nodes.len(), 1, "size={size:?} hidpi={hidpi}");
                assert_eq!(update.focus, A11yNodeId(0));
            }
        }
    }
    #[test]
    fn update_tree_focus_falls_back_to_root_for_an_unresolvable_focused_node() {
        // A focused node in a DOM that isn't in layout_results at all.
        let update = empty_update(
            LogicalSize::new(800.0, 600.0),
            Some(dom_node(9, 42)),
            1.0,
            "t",
        );
        assert_eq!(update.focus, A11yNodeId(0));
        // A focused node whose NodeHierarchyItemId is the None sentinel.
        let update = empty_update(
            LogicalSize::new(800.0, 600.0),
            Some(DomNodeId {
                dom: DomId { inner: 0 },
                node: NodeHierarchyItemId::NONE,
            }),
            1.0,
            "t",
        );
        assert_eq!(update.focus, A11yNodeId(0));
    }
    #[test]
    fn update_tree_preserves_unicode_and_empty_window_titles() {
        for title in ["", "Ünïcødé 🪟", "a\u{202e}b"] {
            let update = empty_update(LogicalSize::new(800.0, 600.0), None, 1.0, title);
            assert_eq!(update.nodes[0].1.label(), Some(title));
        }
    }
    #[test]
    fn update_tree_honours_a_non_zero_root_id() {
        let layout_results = BTreeMap::new();
        let scroll_manager = ScrollManager::new();
        let overrides = BTreeMap::new();
        let root = A11yNodeId(999);
        let update = A11yManager::update_tree(
            root,
            &layout_results,
            &scroll_manager,
            &AzString::from("t"),
            LogicalSize::new(800.0, 600.0),
            None,
            1.0,
            &overrides,
            None,
        );
        assert_eq!(update.nodes[0].0, root);
        assert_eq!(update.focus, root);
        assert_eq!(
            update.tree.map(|t| t.root),
            Some(root),
            "the declared tree root must match the emitted root node"
        );
    }
}