a11y-perception 0.2.1

Accessibility perception over browser data: AX tree, snapshot, reading-order projection and the diff of two snapshots. Computes, does not collect.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Accessibility Tree (AXTree) data structures
//!
//! Represents Chrome's Accessibility Tree as extracted via CDP.
//! The AXTree provides semantic information about page elements.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// The complete Accessibility Tree for a page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AXTree {
    /// All nodes in the tree, indexed by node_id
    pub nodes: HashMap<String, AXNode>,
    /// The root node ID
    pub root_id: Option<String>,
    /// Node ids in document order.
    ///
    /// `nodes` is a `HashMap`, and Rust randomises hash order per process, so
    /// iterating it directly gave a different sequence on every run of the
    /// same page. Detectors that read the tree as a document — heading-skip
    /// detection, "the first N nodes are the top of the page" — therefore
    /// disagreed with themselves: two consecutive audits of the same URL, one
    /// reported a heading skip, the next did not (plan 49).
    ///
    /// CDP's `getFullAXTree` returns nodes in document order, so preserving
    /// the order they arrived in *is* document order. Hand-built trees in
    /// tests keep the order the test wrote them in, which is what their
    /// author means by it.
    #[serde(default)]
    order: Vec<String>,
}

impl AXTree {
    /// Create a new empty AXTree
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            root_id: None,
            order: Vec::new(),
        }
    }

    /// Build tree from a list of nodes
    pub fn from_nodes(nodes: Vec<AXNode>) -> Self {
        let mut tree = Self::new();

        for node in nodes {
            // First node is typically the root
            if tree.root_id.is_none() {
                tree.root_id = Some(node.node_id.clone());
            }
            if tree
                .nodes
                .insert(node.node_id.clone(), node.clone())
                .is_none()
            {
                tree.order.push(node.node_id);
            }
        }

        tree
    }

    /// All nodes in document order, browser-generated artifacts included.
    ///
    /// Normally this is just `order`. It falls back to reconstructing the
    /// order from the tree structure when `order` does not cover `nodes` —
    /// a snapshot cached before this field existed, or a direct write to the
    /// public `nodes` map. The fallback walks `child_ids` depth-first from
    /// the root and appends whatever that does not reach, sorted by id, so it
    /// is at least deterministic.
    fn ordered_nodes(&self) -> Vec<&AXNode> {
        if self.order.len() == self.nodes.len() {
            return self
                .order
                .iter()
                .filter_map(|id| self.nodes.get(id))
                .collect();
        }
        self.reconstruct_order()
    }

    fn reconstruct_order(&self) -> Vec<&AXNode> {
        let mut out: Vec<&AXNode> = Vec::with_capacity(self.nodes.len());
        let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();

        if let Some(root) = self.root_id.as_deref() {
            let mut stack = vec![root];
            while let Some(id) = stack.pop() {
                if !seen.insert(id) {
                    continue;
                }
                let Some(node) = self.nodes.get(id) else {
                    continue;
                };
                out.push(node);
                // Reversed, so the first child is visited first.
                for child in node.child_ids.iter().rev() {
                    stack.push(child.as_str());
                }
            }
        }

        let mut rest: Vec<&AXNode> = self
            .nodes
            .values()
            .filter(|n| !seen.contains(n.node_id.as_str()))
            .collect();
        rest.sort_by(|a, b| a.node_id.cmp(&b.node_id));
        out.extend(rest);
        out
    }

    /// Get a node by ID
    pub fn get_node(&self, node_id: &str) -> Option<&AXNode> {
        self.nodes.get(node_id)
    }

    /// Den Knoten zu einer Backend-Node-ID finden.
    ///
    /// Die Backend-ID zeigt auf den DOM-Knoten und bleibt über mehrere
    /// `getFullAXTree`-Aufrufe stabil, anders als `node_id`. Sie ist deshalb
    /// der Schlüssel, mit dem der Journey-Layer ein Element wiederfindet, das
    /// er selbst bedient hat.
    pub fn node_by_backend_id(&self, backend_id: i64) -> Option<&AXNode> {
        self.iter_all()
            .find(|n| n.backend_dom_node_id == Some(backend_id))
    }

    /// Ob `backend_id` im Baum unterhalb von `ancestor_backend_id` liegt
    /// (oder dieser Knoten selbst ist).
    ///
    /// Beantwortet „steht der Fokus innerhalb des Dialogs?" am
    /// Accessibility-Tree statt an `element.contains()` im DOM — und damit
    /// auch über Shadow Roots hinweg, die `querySelector` nicht durchdringt.
    pub fn is_within(&self, backend_id: i64, ancestor_backend_id: i64) -> bool {
        let Some(mut node) = self.node_by_backend_id(backend_id) else {
            return false;
        };
        // Die Kette kommt aus einem fremden Prozess; sie wird nicht länger als
        // der Baum, sonst zeigt sie im Kreis.
        for _ in 0..self.nodes.len() {
            if node.backend_dom_node_id == Some(ancestor_backend_id) {
                return true;
            }
            match node.parent_id.as_ref().and_then(|id| self.get_node(id)) {
                Some(parent) => node = parent,
                None => return false,
            }
        }
        false
    }

    /// Get the root node
    pub fn root(&self) -> Option<&AXNode> {
        self.root_id.as_ref().and_then(|id| self.nodes.get(id))
    }

    /// Iterate over all auditable nodes (excludes browser-generated artifacts).
    /// This is the default iterator that all WCAG rules should use.
    ///
    /// Also excluded: everything below a `Video` or `Audio` node. With
    /// `controls`, Chrome exposes the player's own interface there — play,
    /// mute and fullscreen buttons, a timeline `slider` without `valuenow` —
    /// from the browser's shadow DOM. No author wrote it or can fix it, and
    /// ARIA rules reported the timeline as a Critical "missing
    /// aria-valuenow" on every page with a `<video controls>`. Fallback
    /// content inside `<video>` is only rendered where video is unsupported,
    /// so the subtree is never author content. The media node itself stays.
    pub fn iter(&self) -> impl Iterator<Item = &AXNode> {
        let media_ui = self.media_controls();
        self.ordered_nodes()
            .into_iter()
            .filter(move |n| !n.is_browser_generated() && !media_ui.contains(n.node_id.as_str()))
    }

    /// Ids of all nodes below a `Video` or `Audio` node — the browser's
    /// player interface. See [`iter`](Self::iter).
    fn media_controls(&self) -> std::collections::HashSet<&str> {
        let mut out = std::collections::HashSet::new();
        let mut stack: Vec<&str> = self
            .nodes
            .values()
            .filter(|n| matches!(n.role.as_deref(), Some("Video") | Some("Audio")))
            .flat_map(|n| n.child_ids.iter().map(String::as_str))
            .collect();
        while let Some(id) = stack.pop() {
            if !out.insert(id) {
                continue;
            }
            if let Some(node) = self.nodes.get(id) {
                stack.extend(node.child_ids.iter().map(String::as_str));
            }
        }
        out
    }

    /// Iterate over ALL nodes including browser-generated artifacts.
    /// Only use this for tree traversal, parent/child lookups, or non-WCAG analysis.
    pub fn iter_all(&self) -> impl Iterator<Item = &AXNode> {
        self.ordered_nodes().into_iter()
    }

    /// The page's visible text, each run counted once.
    ///
    /// Chrome puts a text run's characters on a `StaticText` node and repeats
    /// them on that node's `InlineTextBox` children, one per line box. The
    /// accessible name of a `heading` or a `link` is computed from the same
    /// `StaticText` descendants. So the page's text has to be read from
    /// `StaticText` and nowhere else, or it is counted two or three times.
    ///
    /// Measured on two cached trees (plan 50): of all characters carried in a
    /// `name`, 72-76 % sit on browser-generated roles; `StaticText` and
    /// `InlineTextBox` hold near-identical totals spread over different node
    /// counts; 30 of 44 heading names and 71 of 87 link names repeat a
    /// `StaticText` verbatim. `paragraph` nodes exist but never carry a name
    /// of their own, so a role filter naming `paragraph` matches nothing.
    ///
    /// [`iter`](Self::iter) excludes all of this deliberately — a WCAG rule
    /// must not report a finding against a node the author never wrote.
    /// Anything *measuring* text wants this instead.
    pub fn text_nodes(&self) -> impl Iterator<Item = &AXNode> {
        self.ordered_nodes().into_iter().filter(|n| n.is_text())
    }

    /// Total length of the page's visible text. See [`text_nodes`](Self::text_nodes).
    pub fn visible_text_len(&self) -> usize {
        self.text_nodes()
            .filter_map(|n| n.name.as_ref())
            .map(|name| name.len())
            .sum()
    }

    /// Get all nodes with a specific role (excludes browser-generated nodes)
    pub fn nodes_with_role(&self, role: &str) -> Vec<&AXNode> {
        self.iter()
            .filter(|n| n.role.as_deref() == Some(role))
            .collect()
    }

    /// Get all image nodes
    pub fn images(&self) -> Vec<&AXNode> {
        self.iter()
            .filter(|n| matches!(n.role.as_deref(), Some("image") | Some("img")))
            .collect()
    }

    /// Get all heading nodes
    pub fn headings(&self) -> Vec<&AXNode> {
        self.iter()
            .filter(|n| matches!(n.role.as_deref(), Some("heading")))
            .collect()
    }

    /// Get all form control nodes (excluding buttons, which are checked separately)
    pub fn form_controls(&self) -> Vec<&AXNode> {
        self.iter()
            .filter(|n| {
                matches!(
                    n.role.as_deref(),
                    Some("textbox")
                        | Some("checkbox")
                        | Some("radio")
                        | Some("combobox")
                        | Some("listbox")
                        | Some("spinbutton")
                        | Some("slider")
                        | Some("searchbox")
                )
            })
            .collect()
    }

    /// Get all link nodes
    pub fn links(&self) -> Vec<&AXNode> {
        self.nodes_with_role("link")
    }

    /// Count total nodes
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Check if tree is empty
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }
}

impl Default for AXTree {
    fn default() -> Self {
        Self::new()
    }
}

/// A single node in the Accessibility Tree
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AXNode {
    /// Unique identifier for this node
    pub node_id: String,
    /// Whether this node is ignored for accessibility
    #[serde(default)]
    pub ignored: bool,
    /// Reasons why this node is ignored
    #[serde(default)]
    pub ignored_reasons: Vec<AXProperty>,
    /// The accessibility role (e.g., "button", "heading", "image")
    pub role: Option<String>,
    /// The accessible name (what screen readers announce)
    pub name: Option<String>,
    /// Source of the accessible name
    pub name_source: Option<NameSource>,
    /// The accessible description
    pub description: Option<String>,
    /// The accessible value (for form controls)
    pub value: Option<String>,
    /// Additional properties
    #[serde(default)]
    pub properties: Vec<AXProperty>,
    /// Child node IDs
    #[serde(default)]
    pub child_ids: Vec<String>,
    /// Parent node ID
    pub parent_id: Option<String>,
    /// Backend DOM node ID (for correlation with DOM)
    pub backend_dom_node_id: Option<i64>,
}

impl AXNode {
    /// Check if this node has an accessible name
    pub fn has_name(&self) -> bool {
        self.name.as_ref().is_some_and(|n| !n.trim().is_empty())
    }

    /// Check if this node is focusable
    pub fn is_focusable(&self) -> bool {
        self.get_property_bool("focusable").unwrap_or(false)
    }

    /// Check if this node is interactive
    pub fn is_interactive(&self) -> bool {
        matches!(
            self.role.as_deref(),
            Some("button")
                | Some("link")
                | Some("textbox")
                | Some("checkbox")
                | Some("radio")
                | Some("combobox")
                | Some("menuitem")
                | Some("tab")
        ) || self.is_focusable()
    }

    /// Get heading level (1-6) if this is a heading
    pub fn heading_level(&self) -> Option<u8> {
        if self.role.as_deref() != Some("heading") {
            return None;
        }

        self.get_property_int("level").map(|l| l.clamp(1, 6) as u8)
    }

    /// Get a boolean property value
    pub fn get_property_bool(&self, name: &str) -> Option<bool> {
        self.properties
            .iter()
            .find(|p| p.name == name)
            .and_then(|p| p.value.as_bool())
    }

    /// Get an integer property value
    pub fn get_property_int(&self, name: &str) -> Option<i64> {
        self.properties
            .iter()
            .find(|p| p.name == name)
            .and_then(|p| p.value.as_int())
    }

    /// Get a string property value
    pub fn get_property_str(&self, name: &str) -> Option<&str> {
        self.properties
            .iter()
            .find(|p| p.name == name)
            .and_then(|p| p.value.as_str())
    }

    /// `aria-haspopup`, so wie CDP die Eigenschaft benennt.
    ///
    /// Die Kennung im Protokoll ist `hasPopup`, mit großem P. Ein
    /// `get_property_str("haspopup")` trifft sie nie — und tat es an zwei
    /// Stellen nicht: `patterns::modal_dialog` und `patterns::disclosure_menu`
    /// fragten so nach dem Auslöser und bekamen immer `None`. Beide Journeys
    /// haben dadurch nie einen Kandidaten gesehen; über 171 gelaufene Seiten
    /// lief keine einzige Modal- oder Menü-Journey.
    ///
    /// Deshalb steht der Name genau einmal im Code, hier.
    pub fn haspopup(&self) -> Option<&str> {
        self.get_property_str("hasPopup")
    }

    /// Der Wert einer Eigenschaft als Text, unabhängig von seinem CDP-Typ.
    ///
    /// Nötig, weil ARIA-Zustände in Chromes Baum uneinheitlich ankommen:
    /// `expanded` als `Bool`, `invalid` als Token-`String` ("false" / "true" /
    /// "grammar" / "spelling"), `level` als `Int`. Wer sie einzeln über
    /// `get_property_bool` liest, übersieht die Token-Fälle stillschweigend —
    /// genau daran hing #566, und im Diff hing `invalid` daran ein zweites Mal.
    ///
    /// Knotenverweise und Listen haben keinen sinnvollen Skalarwert und
    /// liefern `None`; für sie ist [`has_property`](Self::has_property) da.
    pub fn property_value_str(&self, name: &str) -> Option<String> {
        let value = &self.properties.iter().find(|p| p.name == name)?.value;
        match value {
            AXValue::Bool(b) => Some(b.to_string()),
            AXValue::Int(i) => Some(i.to_string()),
            AXValue::Float(f) => Some(f.to_string()),
            AXValue::String(s) => Some(s.clone()),
            AXValue::Node { .. } | AXValue::List(_) => None,
        }
    }

    /// Returns true if a property with this name exists, regardless of value type.
    /// Use this for relationship attributes (controls, owns, …) whose CDP values are
    /// node references rather than plain strings.
    pub fn has_property(&self, name: &str) -> bool {
        self.properties.iter().any(|p| p.name == name)
    }

    /// Get the first idref from a relationship property.
    /// Handles both `AXValue::String` (test fixtures / enriched properties) and
    /// `AXValue::Node` (real CDP idref/idrefList traffic).
    pub fn get_property_idref(&self, name: &str) -> Option<&str> {
        self.properties
            .iter()
            .find(|p| p.name == name)
            .and_then(|p| match &p.value {
                AXValue::String(s) => Some(s.as_str()),
                AXValue::Node { related_nodes } => related_nodes.first()?.idref.as_deref(),
                _ => None,
            })
    }

    /// Get all idrefs from a multi-target relationship property (e.g. aria-owns).
    /// Handles both `AXValue::String` (space-separated IDs) and `AXValue::Node`.
    pub fn get_property_idrefs(&self, name: &str) -> Vec<&str> {
        self.properties
            .iter()
            .find(|p| p.name == name)
            .map(|p| match &p.value {
                AXValue::String(s) => s.split_whitespace().collect(),
                AXValue::Node { related_nodes } => related_nodes
                    .iter()
                    .filter_map(|n| n.idref.as_deref())
                    .collect(),
                _ => vec![],
            })
            .unwrap_or_default()
    }

    /// Check if the node has a specific role
    pub fn has_role(&self, role: &str) -> bool {
        self.role.as_deref() == Some(role)
    }

    /// Returns true if this node is a browser-generated artifact that no WCAG
    /// rule should evaluate. These roles are injected by the rendering engine
    /// and do not represent author content — flagging them is always a false
    /// positive.
    /// Whether this node carries a run of the page's visible text.
    ///
    /// The single definition of "text" for anything measuring how much a page
    /// says — see [`AXTree::text_nodes`]
    /// for why it is `StaticText` and nothing else.
    pub fn is_text(&self) -> bool {
        self.role.as_deref() == Some("StaticText")
            && self.name.as_deref().is_some_and(|name| !name.is_empty())
    }

    pub fn is_browser_generated(&self) -> bool {
        matches!(
            self.role.as_deref(),
            Some("StaticText")
                | Some("InlineTextBox")
                | Some("LineBreak")
                | Some("ListMarker")
                | Some("LayoutTable")
                | Some("LayoutTableRow")
                | Some("LayoutTableCell")
        )
    }

    /// Get the required property (for form validation)
    pub fn is_required(&self) -> bool {
        self.get_property_bool("required").unwrap_or(false)
    }

    /// Get the invalid property (for form validation).
    ///
    /// `aria-invalid` is an ARIA *token* attribute ("false" / "true" /
    /// "grammar" / "spelling"), not a boolean one — confirmed live, real CDP
    /// traffic carries it as `AXValue::String`, never `AXValue::Bool`, so
    /// `get_property_bool("invalid")` always returned `None` and this always
    /// reported `false` regardless of the actual attribute (#566). Any value
    /// other than the explicit "false" (or the property being absent, i.e.
    /// aria-invalid never set) counts as invalid.
    pub fn is_invalid(&self) -> bool {
        self.get_property_str("invalid")
            .map(|v| v != "false")
            .unwrap_or(false)
    }
}

/// Source of an accessible name
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum NameSource {
    /// Name from attribute (aria-label, alt, title)
    Attribute,
    /// Name from associated label element
    RelatedElement,
    /// Name from content/children
    Contents,
    /// Name from placeholder
    Placeholder,
    /// Name from title attribute
    Title,
}

/// A property of an AXNode
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AXProperty {
    /// Property name
    pub name: String,
    /// Property value
    pub value: AXValue,
}

/// Value of an AXProperty
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AXValue {
    /// Boolean value
    Bool(bool),
    /// Integer value
    Int(i64),
    /// Float value
    Float(f64),
    /// String value
    String(String),
    /// Related node
    Node { related_nodes: Vec<RelatedNode> },
    /// List of values
    List(Vec<AXValue>),
}

impl AXValue {
    /// Get as boolean if applicable
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            AXValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Get as integer if applicable
    pub fn as_int(&self) -> Option<i64> {
        match self {
            AXValue::Int(i) => Some(*i),
            AXValue::Float(f) => Some(*f as i64),
            _ => None,
        }
    }

    /// Get as string if applicable
    pub fn as_str(&self) -> Option<&str> {
        match self {
            AXValue::String(s) => Some(s),
            _ => None,
        }
    }
}

/// A related node reference
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelatedNode {
    /// The related node's backend DOM node ID
    pub backend_dom_node_id: Option<i64>,
    /// The related node's IDREF
    pub idref: Option<String>,
    /// Text content of the related node
    pub text: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_node(id: &str, role: &str, name: Option<&str>) -> AXNode {
        AXNode {
            node_id: id.to_string(),
            ignored: false,
            ignored_reasons: vec![],
            role: Some(role.to_string()),
            name: name.map(String::from),
            name_source: None,
            description: None,
            value: None,
            properties: vec![],
            child_ids: vec![],
            parent_id: None,
            backend_dom_node_id: None,
        }
    }

    /// Plan 49: `nodes` is a `HashMap`, and two maps in one process do not
    /// even agree with each other, so iterating it directly made the tree a
    /// different document on every run. Built twice, iterated twice — the
    /// sequence has to be the same all four times.
    #[test]
    fn iteration_follows_document_order_not_hash_order() {
        let ids: Vec<String> = (0..64).map(|i| format!("n{i}")).collect();
        let build = || {
            AXTree::from_nodes(
                ids.iter()
                    .map(|id| create_test_node(id, "heading", Some("x")))
                    .collect(),
            )
        };

        let first = build();
        let second = build();
        let seq = |t: &AXTree| -> Vec<String> { t.iter_all().map(|n| n.node_id.clone()).collect() };

        assert_eq!(seq(&first), ids, "construction order is document order");
        assert_eq!(seq(&first), seq(&second), "two builds must agree");
        assert_eq!(seq(&first), seq(&first), "one tree must agree with itself");
    }

    /// A tree that lost its order — an artifact cached before the field
    /// existed, or a direct write to the public `nodes` map — is rebuilt from
    /// `child_ids` rather than falling back to hash order.
    #[test]
    fn a_tree_without_stored_order_is_rebuilt_from_its_children() {
        let mut root = create_test_node("root", "WebArea", Some("Page"));
        root.child_ids = vec!["a".into(), "b".into(), "c".into()];
        let nodes = vec![
            root,
            create_test_node("a", "heading", Some("A")),
            create_test_node("b", "heading", Some("B")),
            create_test_node("c", "heading", Some("C")),
        ];

        let mut tree = AXTree::from_nodes(nodes);
        // Simulate the lost order.
        tree.order.clear();
        let seq: Vec<String> = tree.iter_all().map(|n| n.node_id.clone()).collect();
        assert_eq!(seq, vec!["root", "a", "b", "c"]);

        // And an unreachable node still lands in a defined place.
        tree.nodes.insert(
            "zz".to_string(),
            create_test_node("zz", "heading", Some("Z")),
        );
        tree.order.clear();
        let seq: Vec<String> = tree.iter_all().map(|n| n.node_id.clone()).collect();
        assert_eq!(seq, vec!["root", "a", "b", "c", "zz"]);
    }

    /// Plan 50: text has to be counted once. Chrome repeats a `StaticText`
    /// run on its `InlineTextBox` children, and a heading's or link's name is
    /// computed from the same `StaticText` descendants, so any wider filter
    /// counts the same words two or three times.
    #[test]
    fn text_is_counted_once_per_run() {
        let mut heading = create_test_node("h", "heading", Some("Ueberschrift"));
        heading.child_ids = vec!["h-text".into()];
        let mut link = create_test_node("l", "link", Some("Mehr erfahren"));
        link.child_ids = vec!["l-text".into()];

        let tree = AXTree::from_nodes(vec![
            create_test_node("root", "RootWebArea", Some("Seite")),
            heading,
            create_test_node("h-text", "StaticText", Some("Ueberschrift")),
            create_test_node("h-box", "InlineTextBox", Some("Ueberschrift")),
            link,
            create_test_node("l-text", "StaticText", Some("Mehr erfahren")),
            create_test_node("p-text", "StaticText", Some("Fliesstext.")),
        ]);

        let texts: Vec<&str> = tree
            .text_nodes()
            .map(|n| n.name.as_deref().unwrap_or(""))
            .collect();
        assert_eq!(texts, vec!["Ueberschrift", "Mehr erfahren", "Fliesstext."]);
        assert_eq!(
            tree.visible_text_len(),
            "Ueberschrift".len() + "Mehr erfahren".len() + "Fliesstext.".len(),
        );
    }

    /// An empty name is not text — an unnamed `StaticText` node contributes
    /// nothing and must not make a page look like it says something.
    #[test]
    fn an_unnamed_static_text_node_is_not_text() {
        let tree = AXTree::from_nodes(vec![
            create_test_node("root", "RootWebArea", Some("Seite")),
            create_test_node("empty", "StaticText", Some("")),
            create_test_node("none", "StaticText", None),
        ]);
        assert_eq!(tree.text_nodes().count(), 0);
        assert_eq!(tree.visible_text_len(), 0);
    }

    #[test]
    fn test_axtree_from_nodes() {
        let nodes = vec![
            create_test_node("1", "WebArea", Some("Page")),
            create_test_node("2", "heading", Some("Title")),
            create_test_node("3", "image", None),
        ];

        let tree = AXTree::from_nodes(nodes);
        assert_eq!(tree.len(), 3);
        assert_eq!(tree.root_id, Some("1".to_string()));
    }

    #[test]
    fn test_axtree_images() {
        let nodes = vec![
            create_test_node("1", "WebArea", Some("Page")),
            create_test_node("2", "image", Some("Logo")),
            create_test_node("3", "image", None),
            create_test_node("4", "heading", Some("Title")),
        ];

        let tree = AXTree::from_nodes(nodes);
        let images = tree.images();
        assert_eq!(images.len(), 2);
    }

    #[test]
    fn test_axtree_headings() {
        let nodes = vec![
            create_test_node("1", "WebArea", Some("Page")),
            create_test_node("2", "heading", Some("Title")),
            create_test_node("3", "heading", Some("Subtitle")),
        ];

        let tree = AXTree::from_nodes(nodes);
        let headings = tree.headings();
        assert_eq!(headings.len(), 2);
    }

    #[test]
    fn test_axnode_has_name() {
        let node_with_name = create_test_node("1", "image", Some("Logo"));
        let node_without_name = create_test_node("2", "image", None);
        let node_empty_name = create_test_node("3", "image", Some("  "));

        assert!(node_with_name.has_name());
        assert!(!node_without_name.has_name());
        assert!(!node_empty_name.has_name());
    }

    #[test]
    fn test_axnode_heading_level() {
        let mut heading = create_test_node("1", "heading", Some("Title"));
        heading.properties.push(AXProperty {
            name: "level".to_string(),
            value: AXValue::Int(2),
        });

        assert_eq!(heading.heading_level(), Some(2));

        let non_heading = create_test_node("2", "paragraph", Some("Text"));
        assert_eq!(non_heading.heading_level(), None);
    }

    fn with_children(mut node: AXNode, children: &[&str]) -> AXNode {
        node.child_ids = children.iter().map(|c| c.to_string()).collect();
        node
    }

    /// The player interface Chrome exposes under `<video controls>` is not
    /// author content: rules iterating the tree must not see it. The media
    /// node itself and everything outside it stay.
    #[test]
    fn media_player_controls_are_not_auditable() {
        let tree = AXTree::from_nodes(vec![
            with_children(create_test_node("1", "RootWebArea", None), &["2", "3", "7"]),
            create_test_node("2", "heading", Some("Clip")),
            with_children(create_test_node("3", "Video", None), &["4"]),
            with_children(create_test_node("4", "generic", None), &["5", "6"]),
            create_test_node("5", "button", Some("Wiedergeben")),
            create_test_node("6", "slider", Some("Video-Zeitachse")),
            create_test_node("7", "slider", Some("Author volume")),
        ]);
        let roles: Vec<(&str, &str)> = tree
            .iter()
            .map(|n| (n.node_id.as_str(), n.role.as_deref().unwrap_or("")))
            .collect();
        assert_eq!(
            roles,
            vec![
                ("1", "RootWebArea"),
                ("2", "heading"),
                ("3", "Video"),
                ("7", "slider")
            ]
        );
        assert_eq!(tree.form_controls().len(), 1, "only the author's slider");
        // Nothing is dropped from the full traversal.
        assert_eq!(tree.iter_all().count(), 7);
    }

    #[test]
    fn audio_player_controls_are_not_auditable() {
        let tree = AXTree::from_nodes(vec![
            with_children(create_test_node("1", "RootWebArea", None), &["2"]),
            with_children(create_test_node("2", "Audio", None), &["3"]),
            create_test_node("3", "button", Some("Stumm")),
        ]);
        assert_eq!(tree.iter().count(), 2);
    }
}