freya_testing/
test_utils.rs

1use freya_core::{
2    dom::{
3        DioxusDOM,
4        DioxusNode,
5        SafeDOM,
6    },
7    node::get_node_state,
8};
9use freya_native_core::{
10    real_dom::NodeImmutable,
11    tree::TreeRef,
12    NodeId,
13};
14
15use crate::test_node::TestNode;
16
17#[derive(Clone)]
18pub struct TestUtils {
19    pub(crate) sdom: SafeDOM,
20}
21
22impl TestUtils {
23    /// Get the SafeDOM.
24    pub(crate) fn sdom(&self) -> &SafeDOM {
25        &self.sdom
26    }
27
28    /// Get a Node by the given ID
29    pub fn get_node_by_id(&self, node_id: NodeId) -> TestNode {
30        let utils = self.clone();
31
32        let dom = self.sdom.get();
33        let rdom = dom.rdom();
34
35        let height = rdom.tree_ref().height(node_id).unwrap();
36        let children_ids = rdom.tree_ref().children_ids(node_id);
37        let node: DioxusNode = rdom.get(node_id).unwrap();
38
39        let state = get_node_state(&node);
40        let node_type = node.node_type().clone();
41
42        TestNode {
43            node_id,
44            utils,
45            children_ids,
46            height,
47            state,
48            node_type,
49        }
50    }
51
52    /// Get a list of Nodes matching the text
53    pub fn get_node_matching_inside_id(
54        &self,
55        node_id: NodeId,
56        matcher: impl Fn(&DioxusNode) -> bool,
57    ) -> Vec<TestNode> {
58        fn traverse_dom(rdom: &DioxusDOM, start_id: NodeId, mut f: impl FnMut(&DioxusNode)) {
59            let mut stack = vec![start_id];
60            let tree = rdom.tree_ref();
61            while let Some(id) = stack.pop() {
62                if let Some(node) = rdom.get(id) {
63                    f(&node);
64                    let children = tree.children_ids_advanced(id, true);
65                    stack.extend(children.iter().copied().rev());
66                }
67            }
68        }
69
70        let dom = self.sdom.get();
71        let rdom = dom.rdom();
72
73        let mut nodes = Vec::default();
74
75        traverse_dom(rdom, node_id, |node| {
76            if matcher(node) {
77                let utils = self.clone();
78
79                let height = node.height();
80                let children_ids = node.child_ids();
81
82                let state = get_node_state(node);
83                let node_type = node.node_type().clone();
84
85                nodes.push(TestNode {
86                    node_id,
87                    utils,
88                    children_ids,
89                    height,
90                    state,
91                    node_type,
92                });
93            }
94        });
95
96        nodes
97    }
98}