iced_accessibility/
a11y_tree.rs

1use crate::{A11yId, A11yNode, IdEq};
2
3#[derive(Debug, Clone, Default)]
4/// Accessible tree of nodes
5pub struct A11yTree {
6    /// The root of the current widget, children of the parent widget or the Window if there is no parent widget
7    root: Vec<A11yNode>,
8    /// The children of a widget and its children
9    children: Vec<A11yNode>,
10}
11
12impl A11yTree {
13    /// Create a new A11yTree
14    /// XXX if you use this method, you will need to manually add the children of the root nodes
15    pub fn new(root: Vec<A11yNode>, children: Vec<A11yNode>) -> Self {
16        Self { root, children }
17    }
18
19    pub fn leaf<T: Into<A11yId>>(node: accesskit::NodeBuilder, id: T) -> Self {
20        Self {
21            root: vec![A11yNode::new(node, id)],
22            children: vec![],
23        }
24    }
25
26    /// Helper for creating an A11y tree with a single root node and some children
27    pub fn node_with_child_tree(mut root: A11yNode, child_tree: Self) -> Self {
28        root.add_children(
29            child_tree.root.iter().map(|n| n.id()).cloned().collect(),
30        );
31        Self {
32            root: vec![root],
33            children: child_tree
34                .children
35                .into_iter()
36                .chain(child_tree.root)
37                .collect(),
38        }
39    }
40
41    /// Joins multiple trees into a single tree
42    pub fn join<T: Iterator<Item = Self>>(trees: T) -> Self {
43        trees.fold(Self::default(), |mut acc, A11yTree { root, children }| {
44            acc.root.extend(root);
45            acc.children.extend(children);
46            acc
47        })
48    }
49
50    pub fn root(&self) -> &Vec<A11yNode> {
51        &self.root
52    }
53
54    pub fn children(&self) -> &Vec<A11yNode> {
55        &self.children
56    }
57
58    pub fn root_mut(&mut self) -> &mut Vec<A11yNode> {
59        &mut self.root
60    }
61
62    pub fn children_mut(&mut self) -> &mut Vec<A11yNode> {
63        &mut self.children
64    }
65
66    pub fn contains(&self, id: &A11yId) -> bool {
67        self.root.iter().any(|n| IdEq::eq(n.id(), id))
68            || self.children.iter().any(|n| IdEq::eq(n.id(), id))
69    }
70}
71
72impl From<A11yTree> for Vec<(accesskit::NodeId, accesskit::Node)> {
73    fn from(tree: A11yTree) -> Vec<(accesskit::NodeId, accesskit::Node)> {
74        tree.root
75            .into_iter()
76            .map(|node| node.into())
77            .chain(tree.children.into_iter().map(|node| node.into()))
78            .collect()
79    }
80}