1use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6use crate::component::ComponentInstance;
7use crate::events::delegation::EventDelegate;
8use crate::events::Event;
9
10#[derive(Debug, Clone)]
12#[allow(dead_code)]
13pub struct Node {
14 component: Option<ComponentInstance>,
16
17 attributes: HashMap<String, String>,
19
20 children: Vec<Node>,
22
23 id: usize,
25
26 event_delegate: Option<Arc<Mutex<EventDelegate>>>,
28}
29
30#[allow(dead_code)]
31impl Node {
32 pub fn new(component: Option<ComponentInstance>) -> Self {
34 static NEXT_ID: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
35 let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
36
37 Self {
38 component,
39 attributes: HashMap::new(),
40 children: Vec::new(),
41 id,
42 event_delegate: Some(Arc::new(Mutex::new(EventDelegate::new(Some(id))))),
43 }
44 }
45
46 pub fn id(&self) -> Option<usize> {
48 Some(self.id)
49 }
50
51 pub fn id_value(&self) -> usize {
53 self.id
54 }
55
56 pub fn children(&self) -> &[Node] {
58 &self.children
59 }
60
61 pub fn children_mut(&mut self) -> &mut Vec<Node> {
63 &mut self.children
64 }
65
66 pub fn event_delegate(&self) -> Option<Arc<Mutex<EventDelegate>>> {
68 self.event_delegate.clone()
69 }
70
71 pub fn add_child(&mut self, child: Node) {
73 if let Some(parent_delegate) = &self.event_delegate {
75 if let Some(child_delegate) = &child.event_delegate {
76 if let Ok(mut child_delegate) = child_delegate.lock() {
77 child_delegate.set_parent(parent_delegate.clone());
78 }
79
80 if let Ok(mut parent_delegate) = parent_delegate.lock() {
81 parent_delegate.add_child(child_delegate.clone());
82 }
83 }
84 }
85
86 self.children.push(child);
87 }
88
89 pub fn add_attribute(&mut self, key: String, value: String) {
91 self.attributes.insert(key, value);
92 }
93
94 pub fn dispatch_event<E: Event + Clone + 'static>(&self, event: &E) {
96 if let Some(delegate) = &self.event_delegate {
97 if let Ok(delegate) = delegate.lock() {
98 delegate.dispatch(event, self.id());
99 }
100 }
101 }
102
103 pub fn component(&self) -> Option<&ComponentInstance> {
105 self.component.as_ref()
106 }
107
108 pub fn component_mut(&mut self) -> Option<&mut ComponentInstance> {
110 self.component.as_mut()
111 }
112
113 pub fn attributes(&self) -> &HashMap<String, String> {
115 &self.attributes
116 }
117}
118
119impl Default for Node {
120 fn default() -> Self {
121 static NEXT_ID: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
122 let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
123
124 Self {
125 component: None,
126 attributes: HashMap::new(),
127 children: Vec::new(),
128 id,
129 event_delegate: Some(Arc::new(Mutex::new(EventDelegate::new(Some(id))))),
130 }
131 }
132}