summaryrefslogtreecommitdiffstats
path: root/pure/src/widget/tree.rs
blob: 3a5f4433163f0fc1072c188c85fbd4156c0afc22 (plain) (blame)
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
use crate::widget::Element;

use std::any::{self, Any};

pub struct Tree {
    pub tag: any::TypeId,
    pub state: State,
    pub children: Vec<Tree>,
}

impl Tree {
    pub fn empty() -> Self {
        Self {
            tag: any::TypeId::of::<()>(),
            state: State(Box::new(())),
            children: Vec::new(),
        }
    }

    pub fn new<Message, Renderer>(
        element: &Element<'_, Message, Renderer>,
    ) -> Self {
        Self {
            tag: element.as_widget().tag(),
            state: State(element.as_widget().state()),
            children: element.as_widget().children_state(),
        }
    }

    pub fn diff<Message, Renderer>(
        &mut self,
        new: &Element<'_, Message, Renderer>,
    ) {
        if self.tag == new.as_widget().tag() {
            new.as_widget().diff(self)
        } else {
            *self = Self::new(new);
        }
    }

    pub fn diff_children<Message, Renderer>(
        &mut self,
        new_children: &[Element<'_, Message, Renderer>],
    ) {
        if self.children.len() > new_children.len() {
            self.children.truncate(new_children.len());
        }

        for (child_state, new) in
            self.children.iter_mut().zip(new_children.iter())
        {
            child_state.diff(new);
        }

        if self.children.len() < new_children.len() {
            self.children.extend(
                new_children[self.children.len()..].iter().map(Self::new),
            );
        }
    }
}

pub struct State(Box<dyn Any>);

impl State {
    pub fn downcast_ref<T>(&self) -> &T
    where
        T: 'static,
    {
        self.0.downcast_ref().expect("Downcast widget state")
    }

    pub fn downcast_mut<T>(&mut self) -> &mut T
    where
        T: 'static,
    {
        self.0.downcast_mut().expect("Downcast widget state")
    }
}