pixel_widgets/node/
mod.rs1use std::collections::hash_map::DefaultHasher;
2use std::hash::{Hash, Hasher};
3use std::ops::{Deref, DerefMut};
4
5use crate::draw::Primitive;
6use crate::event::Event;
7use crate::layout::{Rectangle, Size};
8use crate::style::tree::Query;
9use crate::tracker::ManagedStateTracker;
10use crate::widget::{Context, Widget};
11use crate::Component;
12
13pub(crate) mod component_node;
14pub(crate) mod widget_node;
15
16pub struct Node<'a, Message>(Box<dyn GenericNode<'a, Message> + 'a>);
18
19#[doc(hidden)]
20pub trait GenericNode<'a, Message>: Send {
21 fn get_key(&self) -> u64;
22
23 fn set_key(&mut self, key: u64);
24
25 fn set_class(&mut self, class: &'a str);
26
27 fn acquire_state(&mut self, tracker: &mut ManagedStateTracker<'a>);
28
29 fn size(&self) -> (Size, Size);
30
31 fn hit(&self, layout: Rectangle, clip: Rectangle, x: f32, y: f32) -> bool;
32
33 fn focused(&self) -> bool;
34
35 fn draw(&mut self, layout: Rectangle, clip: Rectangle) -> Vec<Primitive<'a>>;
36
37 fn style(&mut self, query: &mut Query, position: (usize, usize));
38
39 fn add_matches(&mut self, query: &mut Query);
40
41 fn remove_matches(&mut self, query: &mut Query);
42
43 fn event(&mut self, layout: Rectangle, clip: Rectangle, event: Event, context: &mut Context<Message>);
44
45 fn poll(&mut self, context: &mut Context<Message>);
46}
47
48pub trait IntoNode<'a, Message: 'a>: 'a + Sized {
52 fn into_node(self) -> Node<'a, Message>;
54
55 fn class(self, class: &'a str) -> Node<'a, Message> {
57 let mut node = self.into_node();
58 node.set_class(class);
59 node
60 }
61
62 fn key<K: Hash>(self, key: K) -> Node<'a, Message> {
64 let mut hasher = DefaultHasher::new();
65 key.hash(&mut hasher);
66 let mut node = self.into_node();
67 node.set_key(hasher.finish());
68 node
69 }
70}
71
72impl<'a, Message: 'a> Node<'a, Message> {
73 pub fn from_widget<W: 'a + Widget<'a, Message>>(widget: W) -> Self {
75 Self(Box::new(widget_node::WidgetNode::new(widget)) as Box<_>)
76 }
77
78 pub fn from_component<C: 'a + Component<Output = Message>>(component: C) -> Self {
80 Self(Box::new(component_node::ComponentNode::new(component)) as Box<_>)
81 }
82}
83
84impl<'a, Message> Deref for Node<'a, Message> {
85 type Target = dyn GenericNode<'a, Message> + 'a;
86
87 fn deref(&self) -> &Self::Target {
88 &*self.0
89 }
90}
91
92impl<'a, Message> DerefMut for Node<'a, Message> {
93 fn deref_mut(&mut self) -> &mut Self::Target {
94 &mut *self.0
95 }
96}
97
98impl<'a, Message: 'a> IntoNode<'a, Message> for Node<'a, Message> {
99 fn into_node(self) -> Node<'a, Message> {
100 self
101 }
102}