dioxus_native_core/utils/
persistant_iterator.rs

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
use smallvec::SmallVec;

use crate::{
    node::FromAnyValue,
    node_watcher::NodeWatcher,
    prelude::{NodeMut, NodeRef},
    real_dom::{NodeImmutable, RealDom},
    NodeId,
};
use std::{
    fmt::Debug,
    sync::{Arc, Mutex},
};

/// The element produced by the iterator
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ElementProduced {
    id: NodeId,
    movement: IteratorMovement,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// The method by which the iterator produced an element
pub enum IteratorMovement {
    /// The iterator produced an element by progressing to the next node
    Progressed,
    /// The iterator reached the end of the tree and looped back to the root
    Looped,
}

impl ElementProduced {
    /// Get the id of the element produced
    pub fn id(&self) -> NodeId {
        self.id
    }

    /// The movement the iterator made to produce the element
    pub fn movement(&self) -> &IteratorMovement {
        &self.movement
    }

    fn looped(id: NodeId) -> Self {
        Self {
            id,
            movement: IteratorMovement::Looped,
        }
    }

    fn progressed(id: NodeId) -> Self {
        Self {
            id,
            movement: IteratorMovement::Progressed,
        }
    }
}

struct PersistantElementIterUpdater<V> {
    stack: Arc<Mutex<smallvec::SmallVec<[NodeId; 5]>>>,
    phantom: std::marker::PhantomData<V>,
}

impl<V: FromAnyValue + Sync + Send> NodeWatcher<V> for PersistantElementIterUpdater<V> {
    fn on_node_moved(&mut self, node: NodeMut<V>) {
        // if any element is moved, update its parents in the stack
        let mut stack = self.stack.lock().unwrap();
        let moved = node.id();
        let rdom = node.real_dom();
        if let Some(r) = stack.iter().position(|el_id| *el_id == moved) {
            let back = &stack[r..];
            let mut new = SmallVec::new();
            let mut parent = node.parent_id();
            while let Some(p) = parent.and_then(|id| rdom.get(id)) {
                new.push(p.id());
                parent = p.parent_id();
            }
            new.extend(back.iter().copied());
            *stack = new;
        }
    }

    fn on_node_removed(&mut self, node: NodeMut<V>) {
        // if any element is removed in the chain, remove it and its children from the stack
        let mut stack = self.stack.lock().unwrap();
        let removed = node.id();
        if let Some(r) = stack.iter().position(|el_id| *el_id == removed) {
            stack.truncate(r);
        }
    }
}

/// Focus systems need a iterator that can persist through changes in the [crate::prelude::RealDom]
/// This iterator traverses the tree depth first.
/// You can iterate through it with [PersistantElementIter::next] and [PersistantElementIter::prev].
/// The iterator loops around when it reaches the end or the beginning.
pub struct PersistantElementIter {
    // stack of elements and fragments, the last element is the last element that was yielded
    stack: Arc<Mutex<smallvec::SmallVec<[NodeId; 5]>>>,
}

impl PersistantElementIter {
    /// Create a new iterator in the RealDom
    pub fn create<V: FromAnyValue + Send + Sync>(rdom: &mut RealDom<V>) -> Self {
        let inner = Arc::new(Mutex::new(smallvec::smallvec![rdom.root_id()]));

        rdom.add_node_watcher(PersistantElementIterUpdater {
            stack: inner.clone(),
            phantom: std::marker::PhantomData,
        });

        PersistantElementIter { stack: inner }
    }

    /// get the next element
    pub fn next<V: FromAnyValue + Send + Sync>(&mut self, rdom: &RealDom<V>) -> ElementProduced {
        let mut stack = self.stack.lock().unwrap();
        if stack.is_empty() {
            let id = rdom.root_id();
            let new = id;
            stack.push(new);
            ElementProduced::looped(id)
        } else {
            let mut look_in_children = true;
            loop {
                if let Some(current) = stack.last().and_then(|last| rdom.get(*last)) {
                    // if the current element has children, add the first child to the stack and return it
                    if look_in_children {
                        if let Some(first) = current.children().first() {
                            let new = first.id();
                            stack.push(new);
                            return ElementProduced::progressed(new);
                        }
                    }
                    stack.pop();
                    if let Some(new) = current.next() {
                        // the next element exists, add it to the stack and return it
                        let new = new.id();
                        stack.push(new);
                        return ElementProduced::progressed(new);
                    }
                    // otherwise, continue the loop and go to the parent
                } else {
                    // if there is no parent, loop back to the root
                    let new = rdom.root_id();
                    stack.clear();
                    stack.push(new);
                    return ElementProduced::looped(new);
                }
                look_in_children = false;
            }
        }
    }

    /// get the previous element
    pub fn prev<V: FromAnyValue + Send + Sync>(&mut self, rdom: &RealDom<V>) -> ElementProduced {
        // recursively add the last child element to the stack
        fn push_back<V: FromAnyValue + Send + Sync>(
            stack: &mut smallvec::SmallVec<[NodeId; 5]>,
            node: NodeRef<V>,
        ) -> NodeId {
            stack.push(node.id());
            if let Some(last) = node.children().last() {
                push_back(stack, *last)
            } else {
                node.id()
            }
        }
        let mut stack = self.stack.lock().unwrap();
        if stack.is_empty() {
            let id = rdom.root_id();
            let last = push_back(&mut stack, rdom.get(id).unwrap());
            ElementProduced::looped(last)
        } else if let Some(current) = stack.pop().and_then(|last| rdom.get(last)) {
            if let Some(new) = current.prev() {
                // the next element exists, add it to the stack and return it
                let new = push_back(&mut stack, new);
                ElementProduced::progressed(new)
            }
            // otherwise, yeild the parent
            else if let Some(parent) = stack.last() {
                // if there is a parent, return it
                ElementProduced::progressed(*parent)
            } else {
                // if there is no parent, loop back to the root
                let id = rdom.root_id();
                let last = push_back(&mut stack, rdom.get(id).unwrap());
                ElementProduced::looped(last)
            }
        } else {
            // if there is no parent, loop back to the root
            let id = rdom.root_id();
            let last = push_back(&mut stack, rdom.get(id).unwrap());
            ElementProduced::looped(last)
        }
    }
}

#[test]
#[allow(unused_variables)]
fn traverse() {
    use crate::dioxus::DioxusState;
    use crate::prelude::*;
    use dioxus::prelude::*;
    #[allow(non_snake_case)]
    fn Base(cx: Scope) -> Element {
        render!(
            div{
                div{
                    "hello"
                    p{
                        "world"
                    }
                    "hello world"
                }
            }
        )
    }

    let mut vdom = VirtualDom::new(Base);
    let mutations = vdom.rebuild();

    let mut rdom: RealDom = RealDom::new([]);

    let mut iter = PersistantElementIter::create(&mut rdom);
    let mut dioxus_state = DioxusState::create(&mut rdom);
    dioxus_state.apply_mutations(&mut rdom, mutations);

    let div_tag = "div".to_string();
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: div_tag, .. })
    ));
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: div_tag, .. })
    ));
    let text1 = "hello".to_string();
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text1)
    ));
    let p_tag = "p".to_string();
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: p_tag, .. })
    ));
    let text2 = "world".to_string();
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text2)
    ));
    let text3 = "hello world".to_string();
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text3)
    ));
    assert!(matches!(
        &*rdom.get(iter.next(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: div_tag, .. })
    ));

    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text3)
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text2)
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: p_tag, .. })
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text1)
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: div_tag, .. })
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: div_tag, .. })
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: div_tag, .. })
    ));
    assert!(matches!(
        &*rdom.get(iter.prev(&rdom).id()).unwrap().node_type(),
        NodeType::Text(text3)
    ));
}

#[test]
#[allow(unused_variables)]
fn persist_removes() {
    use crate::dioxus::DioxusState;
    use crate::prelude::*;
    use dioxus::prelude::*;
    #[allow(non_snake_case)]
    fn Base(cx: Scope) -> Element {
        let children = match cx.generation() % 2 {
            0 => 3,
            1 => 2,
            _ => unreachable!(),
        };
        render!(
            div{
                (0..children).map(|i|{
                    rsx!{
                        p{
                            key: "{i}",
                            "{i}"
                        }
                    }
                })
            }
        )
    }
    let mut vdom = VirtualDom::new(Base);

    let mut rdom: RealDom = RealDom::new([]);

    let build = vdom.rebuild();
    println!("{build:#?}");
    // this will end on the node that is removed
    let mut iter1 = PersistantElementIter::create(&mut rdom);
    // this will end on the after node that is removed
    let mut iter2 = PersistantElementIter::create(&mut rdom);
    let mut dioxus_state = DioxusState::create(&mut rdom);
    dioxus_state.apply_mutations(&mut rdom, build);

    // root
    iter1.next(&rdom).id();
    iter2.next(&rdom).id();
    // div
    iter1.next(&rdom).id();
    iter2.next(&rdom).id();
    // p
    iter1.next(&rdom).id();
    iter2.next(&rdom).id();
    // "1"
    iter1.next(&rdom).id();
    iter2.next(&rdom).id();
    // p
    iter1.next(&rdom).id();
    iter2.next(&rdom).id();
    // "2"
    iter1.next(&rdom).id();
    iter2.next(&rdom).id();
    // p
    iter2.next(&rdom).id();
    // "3"
    iter2.next(&rdom).id();

    vdom.mark_dirty(ScopeId::ROOT);
    let update = vdom.render_immediate();
    println!("{update:#?}");
    dioxus_state.apply_mutations(&mut rdom, update);

    let root_tag = "Root".to_string();
    let idx = iter1.next(&rdom).id();
    assert!(matches!(
        &*rdom.get(idx).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: root_tag, .. })
    ));

    let idx = iter2.next(&rdom).id();
    assert!(matches!(
        &*rdom.get(idx).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: root_tag, .. })
    ));
}

#[test]
#[allow(unused_variables)]
fn persist_instertions_before() {
    use crate::dioxus::DioxusState;
    use crate::prelude::*;
    use dioxus::prelude::*;
    #[allow(non_snake_case)]
    fn Base(cx: Scope) -> Element {
        let children = match cx.generation() % 2 {
            0 => 3,
            1 => 2,
            _ => unreachable!(),
        };
        render!(
            div{
                (0..children).map(|i|{
                    rsx!{
                        p{
                            key: "{i}",
                            "{i}"
                        }
                    }
                })
            }
        )
    }
    let mut vdom = VirtualDom::new(Base);

    let mut rdom: RealDom = RealDom::new([]);
    let mut dioxus_state = DioxusState::create(&mut rdom);

    let build = vdom.rebuild();
    dioxus_state.apply_mutations(&mut rdom, build);

    let mut iter = PersistantElementIter::create(&mut rdom);
    // div
    iter.next(&rdom).id();
    // p
    iter.next(&rdom).id();
    // "1"
    iter.next(&rdom).id();
    // p
    iter.next(&rdom).id();
    // "2"
    iter.next(&rdom).id();

    vdom.mark_dirty(ScopeId::ROOT);
    let update = vdom.render_immediate();
    dioxus_state.apply_mutations(&mut rdom, update);

    let p_tag = "div".to_string();
    let idx = iter.next(&rdom).id();
    assert!(matches!(
        &*rdom.get(idx).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: p_tag, .. })
    ));
}

#[test]
#[allow(unused_variables)]
fn persist_instertions_after() {
    use crate::dioxus::DioxusState;
    use crate::prelude::*;
    use dioxus::prelude::*;
    #[allow(non_snake_case)]
    fn Base(cx: Scope) -> Element {
        let children = match cx.generation() % 2 {
            0 => 3,
            1 => 2,
            _ => unreachable!(),
        };
        render!(
            div{
                (0..children).map(|i|{
                    rsx!{
                        p{
                            key: "{i}",
                            "{i}"
                        }
                    }
                })
            }
        )
    }
    let mut vdom = VirtualDom::new(Base);

    let mut rdom: RealDom = RealDom::new([]);
    let mut iter = PersistantElementIter::create(&mut rdom);
    let mut dioxus_state = DioxusState::create(&mut rdom);

    let build = vdom.rebuild();
    dioxus_state.apply_mutations(&mut rdom, build);

    // div
    iter.next(&rdom).id();
    // p
    iter.next(&rdom).id();
    // "hello"
    iter.next(&rdom).id();
    // p
    iter.next(&rdom).id();
    // "world"
    iter.next(&rdom).id();

    let update = vdom.rebuild();
    dioxus_state.apply_mutations(&mut rdom, update);

    let p_tag = "p".to_string();
    let idx = iter.next(&rdom).id();
    assert!(matches!(
        &*rdom.get(idx).unwrap().node_type(),
        NodeType::Element(ElementNode { tag: p_tag, .. })
    ));
    let text = "hello world".to_string();
    let idx = iter.next(&rdom).id();
    assert!(matches!(
        &*rdom.get(idx).unwrap().node_type(),
        NodeType::Text(text)
    ));
}