tirbofish/dropbear
main / crates / kino-ui / src / tree.rs · 1900 bytes
crates/kino-ui/src/tree.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
use crate::{KinoState, WidgetId};
#[cfg_attr(any(feature = "ser"), typetag::serde(tag = "type"))]
pub trait WidgetDescriptor: Send + Sync + 'static {
fn id(&self) -> WidgetId;
fn is_container(&self) -> bool {
false
}
fn label(&self) -> &'static str;
fn submit(self: Box<Self>, children: Vec<WidgetNode>, kino: &mut KinoState);
fn clone_boxed(&self) -> Box<dyn WidgetDescriptor>;
}
impl Clone for Box<dyn WidgetDescriptor> {
fn clone(&self) -> Self {
self.clone_boxed()
}
}
#[cfg_attr(any(feature = "ser"), derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone)]
pub struct WidgetNode {
pub id: WidgetId,
pub widget: Box<dyn WidgetDescriptor>,
pub children: Vec<WidgetNode>,
}
impl WidgetNode {
pub fn new(widget: impl WidgetDescriptor) -> Self {
let id = widget.id();
Self {
id,
widget: Box::new(widget),
children: vec![],
}
}
pub fn with_child(mut self, child: WidgetNode) -> Self {
self.children.push(child);
self
}
pub fn with_children(mut self, children: impl IntoIterator<Item = WidgetNode>) -> Self {
self.children.extend(children);
self
}
}
#[cfg_attr(feature = "ser", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone)]
pub struct WidgetTree {
pub roots: Vec<WidgetNode>,
}
impl Default for WidgetTree {
fn default() -> Self {
Self { roots: vec![] }
}
}
impl WidgetTree {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, node: WidgetNode) {
self.roots.push(node);
}
pub fn submit(self, kino: &mut KinoState) {
for node in self.roots {
submit_node(node, kino);
}
}
}
pub(crate) fn submit_node(node: WidgetNode, kino: &mut KinoState) {
node.widget.submit(node.children, kino);
}