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
use serde::{Serialize, Deserialize};

use crate::{Alignment, Id, IdPath, IdPathBuf, Identified};

use super::{ModifierNode, ShapeNode};

/// A rendered UI component tree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Node {
    Empty {}, // Intentionally not a unit variant for uniform serialization

    // Widget
    Text { content: String },
    TextField { content: String },
    Button { label: Box<Identified<Node>> },
    Picker { title: String, selection: Id, content: Box<Identified<Node>> },

    // Aggregation
    Child { wrapped: Box<Identified<Node>> },
    Group { children: Vec<Identified<Node>> },

    // Layout
    VStack { spacing: f64, wrapped: Box<Identified<Node>> },
    HStack { spacing: f64, wrapped: Box<Identified<Node>> },
    ZStack { wrapped: Box<Identified<Node>> },
    List { wrapped: Box<Identified<Node>> },
    Overlay { wrapped: Box<Identified<Node>>, alignment: Alignment, overlayed: Box<Identified<Node>> },

    // Wrapper
    Shape { shape: ShapeNode },
    Modified { wrapped: Box<Identified<Node>>, modifier: ModifierNode, }
}

impl Node {
    pub fn children(&self) -> Vec<(IdPathBuf, &Node)> {
        self.children_from(IdPath::root())
    }

    pub fn children_from(&self, path: &IdPath) -> Vec<(IdPathBuf, &Node)> {
        match self {
            Self::Group { children } => children.iter()
                .flat_map(|c| c.value().children_from(&path.child(c.id().clone())).into_iter())
                .collect(),
            _ => vec![(path.to_owned(), self)]
        }
    }
}

impl Default for Node {
    fn default() -> Self {
        Node::Empty {}
    }
}