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
use crate::Node;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt::Debug;

/// Describe the path traversal of a Node starting from the root node
///
/// The figure below shows `node_idx` in a depth first traversal.
///
/// ```text
///            .─.
///           ( 0 )
///            `-'
///           /   \
///          /     \
///         /       \
///        ▼         ▼
///       .─.         .─.
///      ( 1 )       ( 4 )
///       `-'         `-'
///      /  \          | \ '.
///     /    \         |  \  '.
///    ▼      ▼        |   \   '.
///  .─.      .─.      ▼    ▼     ▼
/// ( 2 )    ( 3 )    .─.   .─.   .─.
///  `─'      `─'    ( 5 ) ( 6 ) ( 7 )
///                   `─'   `─'   `─'
/// ```
///
/// The figure below shows the index of each child node relative to their parent node
///
/// ```text
///             .─.
///            ( 0 )
///             `-'
///            /   \
///           /     \
///          /       \
///         ▼         ▼
///        .─.         .─.
///       ( 0 )       ( 1 )
///        `-'         `-'
///       /  \          | \ '.
///      /    \         |  \  '.
///     ▼      ▼        |   \   '.
///   .─.      .─.      ▼    ▼     ▼
///  ( 0 )    ( 1 )    .─.   .─.   .─.
///   `─'      `─'    ( 0 ) ( 1 ) ( 2 )
///                    `─'   `─'   `─'
/// ```
/// The equivalent idx and path are as follows:
/// ```text
///    0 = []
///    1 = [0]
///    2 = [0,0]
///    3 = [0,1]
///    4 = [1]
///    5 = [1,0]
///    6 = [1,1]
///    7 = [1,2]
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct TreePath {
    /// An array of child index at each level of the dom tree.
    /// The children of the nodes at each child index is traverse
    /// at each traversal the first element of path is removed until
    /// the path becomes empty.
    /// If the path has become empty the node is said to be found.
    ///
    /// Empty path means root node
    pub path: Vec<usize>,
}

impl TreePath {
    /// create a TreePath with node index `node_idx` and traversal path `path`
    pub fn new(path: impl IntoIterator<Item = usize>) -> Self {
        Self {
            path: path.into_iter().collect(),
        }
    }

    /// create a TreePath which starts at empty vec which is the root node of a DOM tree
    pub fn root() -> Self {
        Self { path: vec![] }
    }

    /// add a path node idx
    pub fn push(&mut self, node_idx: usize) {
        self.path.push(node_idx)
    }

    /// create a new TreePath with an added node_index
    /// This is used for traversing into child elements
    pub fn traverse(&self, node_idx: usize) -> Self {
        let mut new_path = self.clone();
        new_path.push(node_idx);
        new_path
    }

    /// backtrack to the parent node path
    pub fn backtrack(&self) -> Self {
        let mut new_path = self.clone();
        new_path.path.pop();
        new_path
    }

    /// remove first node index of this treepath
    /// Everytime a node is traversed, the first element should be removed
    /// until no more index is in this path
    pub fn remove_first(&mut self) -> usize {
        self.path.remove(0)
    }

    /// pluck the next in line node index in this treepath
    pub fn pluck(&mut self) -> usize {
        self.remove_first()
    }

    /// returns tree if the path is empty
    /// This is used for checking if the path has been traversed
    pub fn is_empty(&self) -> bool {
        self.path.is_empty()
    }

    /// find the node using the path of this tree path
    pub fn find_node_by_path<'a, Ns, Tag, Leaf, Att, Val>(
        &self,
        node: &'a Node<Ns, Tag, Leaf, Att, Val>,
    ) -> Option<&'a Node<Ns, Tag, Leaf, Att, Val>>
    where
        Ns: PartialEq + Clone + Debug,
        Tag: PartialEq + Clone + Debug,
        Leaf: PartialEq + Clone + Debug,
        Att: PartialEq + Clone + Debug,
        Val: PartialEq + Clone + Debug,
    {
        let mut path = self.clone();
        traverse_node_by_path(node, &mut path)
    }
}

impl<const N: usize> From<[usize; N]> for TreePath {
    fn from(array: [usize; N]) -> Self {
        Self {
            path: array.to_vec(),
        }
    }
}

impl From<Vec<usize>> for TreePath {
    fn from(vec: Vec<usize>) -> Self {
        Self { path: vec }
    }
}

fn traverse_node_by_path<'a, Ns, Tag, Leaf, Att, Val>(
    node: &'a Node<Ns, Tag, Leaf, Att, Val>,
    path: &mut TreePath,
) -> Option<&'a Node<Ns, Tag, Leaf, Att, Val>>
where
    Ns: PartialEq + Clone + Debug,
    Tag: PartialEq + Clone + Debug,
    Leaf: PartialEq + Clone + Debug,
    Att: PartialEq + Clone + Debug,
    Val: PartialEq + Clone + Debug,
{
    if path.path.is_empty() {
        Some(node)
    } else {
        let idx = path.path.remove(0);
        if let Some(child) = node.children().get(idx) {
            traverse_node_by_path(child, path)
        } else {
            None
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use crate::*;
    use alloc::format;
    use alloc::string::String;
    use alloc::string::ToString;

    type MyNode = Node<
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
    >;

    #[test]
    fn test_traverse() {
        let path = TreePath::from([0]);

        assert_eq!(path.traverse(1), TreePath::from([0, 1]));
    }

    fn sample_node() -> MyNode {
        let node: MyNode = element(
            "div",
            vec![attr("class", "[]"), attr("id", "0")],
            vec![
                element(
                    "div",
                    vec![attr("class", "[0]"), attr("id", "1")],
                    vec![
                        element(
                            "div",
                            vec![attr("class", "[0,0]"), attr("id", "2")],
                            vec![],
                        ),
                        element(
                            "div",
                            vec![attr("class", "[0,1]"), attr("id", "3")],
                            vec![],
                        ),
                    ],
                ),
                element(
                    "div",
                    vec![attr("class", "[1]"), attr("id", "4")],
                    vec![
                        element(
                            "div",
                            vec![attr("class", "[1,0]"), attr("id", "5")],
                            vec![],
                        ),
                        element(
                            "div",
                            vec![attr("class", "[1,1]"), attr("id", "6")],
                            vec![],
                        ),
                        element(
                            "div",
                            vec![attr("class", "[1,2]"), attr("id", "7")],
                            vec![],
                        ),
                    ],
                ),
            ],
        );
        node
    }

    // index is the index of this code with respect to it's sibling
    fn assert_traverse_match(
        node: &MyNode,
        node_idx: &mut usize,
        path: Vec<usize>,
    ) {
        let id = node.attribute_value(&"id").unwrap()[0];
        let class = node.attribute_value(&"class").unwrap()[0];
        assert_eq!(id.to_string(), node_idx.to_string());
        assert_eq!(class.to_string(), format_vec(&path));
        for (i, child) in node.children().iter().enumerate() {
            *node_idx += 1;
            let mut child_path = path.clone();
            child_path.push(i);
            assert_traverse_match(child, node_idx, child_path);
        }
    }

    fn traverse_tree_path(
        node: &MyNode,
        path: &TreePath,
        node_idx: &mut usize,
    ) {
        let id = node.attribute_value(&"id").unwrap()[0];
        let class = node.attribute_value(&"class").unwrap()[0];
        assert_eq!(id.to_string(), node_idx.to_string());
        assert_eq!(class.to_string(), format_vec(&path.path));
        for (i, child) in node.children().iter().enumerate() {
            *node_idx += 1;
            let mut child_path = path.clone();
            child_path.path.push(i);
            traverse_tree_path(child, &child_path, node_idx);
        }
    }

    fn format_vec(v: &[usize]) -> String {
        format!(
            "[{}]",
            v.iter()
                .map(|v| v.to_string())
                .collect::<Vec<_>>()
                .join(",")
        )
    }

    #[test]
    fn should_match_paths() {
        let node = sample_node();
        assert_traverse_match(&node, &mut 0, vec![]);
        traverse_tree_path(&node, &TreePath::new(vec![]), &mut 0);
    }

    #[test]
    fn should_find_root_node() {
        let node = sample_node();
        let path = TreePath::new(vec![]);
        let root = path.find_node_by_path(&node);
        assert_eq!(Some(&node), root);
    }

    #[test]
    fn should_find_node1() {
        let node = sample_node();
        let path = TreePath::new(vec![0]);
        let found = path.find_node_by_path(&node);
        let expected = element(
            "div",
            vec![attr("class", "[0]"), attr("id", "1")],
            vec![
                element(
                    "div",
                    vec![attr("class", "[0,0]"), attr("id", "2")],
                    vec![],
                ),
                element(
                    "div",
                    vec![attr("class", "[0,1]"), attr("id", "3")],
                    vec![],
                ),
            ],
        );
        assert_eq!(Some(&expected), found);
    }

    #[test]
    fn should_find_node2() {
        let node = sample_node();
        let path = TreePath::new(vec![0, 0]);
        let found = path.find_node_by_path(&node);
        let expected = element(
            "div",
            vec![attr("class", "[0,0]"), attr("id", "2")],
            vec![],
        );
        assert_eq!(Some(&expected), found);
    }

    #[test]
    fn should_find_node3() {
        let node = sample_node();
        let path = TreePath::new(vec![0, 1]);
        let found = path.find_node_by_path(&node);
        let expected = element(
            "div",
            vec![attr("class", "[0,1]"), attr("id", "3")],
            vec![],
        );
        assert_eq!(Some(&expected), found);
    }

    #[test]
    fn should_find_node4() {
        let node = sample_node();
        let path = TreePath::new(vec![1]);
        let found = path.find_node_by_path(&node);
        let expected = element(
            "div",
            vec![attr("class", "[1]"), attr("id", "4")],
            vec![
                element(
                    "div",
                    vec![attr("class", "[1,0]"), attr("id", "5")],
                    vec![],
                ),
                element(
                    "div",
                    vec![attr("class", "[1,1]"), attr("id", "6")],
                    vec![],
                ),
                element(
                    "div",
                    vec![attr("class", "[1,2]"), attr("id", "7")],
                    vec![],
                ),
            ],
        );
        assert_eq!(Some(&expected), found);
    }

    #[test]
    fn should_find_node5() {
        let node = sample_node();
        let path = TreePath::new(vec![1, 0]);
        let found = path.find_node_by_path(&node);
        let expected = element(
            "div",
            vec![attr("class", "[1,0]"), attr("id", "5")],
            vec![],
        );
        assert_eq!(Some(&expected), found);
    }

    #[test]
    fn should_find_node6() {
        let node = sample_node();
        let path = TreePath::new(vec![1, 1]);
        let found = path.find_node_by_path(&node);
        let expected = element(
            "div",
            vec![attr("class", "[1,1]"), attr("id", "6")],
            vec![],
        );
        assert_eq!(Some(&expected), found);
    }

    #[test]
    fn should_find_none_in_013() {
        let node = sample_node();
        let path = TreePath::new(vec![0, 1, 3]);
        let found = path.find_node_by_path(&node);
        assert_eq!(None, found);
    }

    #[test]
    fn should_find_none_in_00000() {
        let node = sample_node();
        let path = TreePath::new(vec![0, 0, 0, 0]);
        let found = path.find_node_by_path(&node);
        assert_eq!(None, found);
    }

    #[test]
    fn should_find_none_in_007() {
        let node = sample_node();
        let path = TreePath::new(vec![0, 0, 7]);
        let bond = path.find_node_by_path(&node);
        assert_eq!(None, bond);
    }
}