simple.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. use dioxus_native_core::exports::shipyard::Component;
  2. use dioxus_native_core::node_ref::*;
  3. use dioxus_native_core::prelude::*;
  4. use dioxus_native_core::real_dom::NodeTypeMut;
  5. use dioxus_native_core_macro::partial_derive_state;
  6. struct FontSize(f64);
  7. // All states need to derive Component
  8. #[derive(Default, Debug, Copy, Clone, Component)]
  9. struct Size(f64, f64);
  10. /// Derive some of the boilerplate for the State implementation
  11. #[partial_derive_state]
  12. impl State for Size {
  13. type ParentDependencies = ();
  14. // The size of the current node depends on the size of its children
  15. type ChildDependencies = (Self,);
  16. type NodeDependencies = ();
  17. // Size only cares about the width, height, and text parts of the current node
  18. const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
  19. // Get access to the width and height attributes
  20. .with_attrs(AttributeMaskBuilder::Some(&["width", "height"]))
  21. // Get access to the text of the node
  22. .with_text();
  23. fn update<'a>(
  24. &mut self,
  25. node_view: NodeView<()>,
  26. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  27. _parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  28. children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  29. context: &SendAnyMap,
  30. ) -> bool {
  31. let font_size = context.get::<FontSize>().unwrap().0;
  32. let mut width;
  33. let mut height;
  34. if let Some(text) = node_view.text() {
  35. // if the node has text, use the text to size our object
  36. width = text.len() as f64 * font_size;
  37. height = font_size;
  38. } else {
  39. // otherwise, the size is the maximum size of the children
  40. width = children
  41. .iter()
  42. .map(|(item,)| item.0)
  43. .reduce(|accum, item| if accum >= item { accum } else { item })
  44. .unwrap_or(0.0);
  45. height = children
  46. .iter()
  47. .map(|(item,)| item.1)
  48. .reduce(|accum, item| if accum >= item { accum } else { item })
  49. .unwrap_or(0.0);
  50. }
  51. // if the node contains a width or height attribute it overrides the other size
  52. for a in node_view.attributes().into_iter().flatten() {
  53. match &*a.attribute.name {
  54. "width" => width = a.value.as_float().unwrap(),
  55. "height" => height = a.value.as_float().unwrap(),
  56. // because Size only depends on the width and height, no other attributes will be passed to the member
  57. _ => panic!(),
  58. }
  59. }
  60. // to determine what other parts of the dom need to be updated we return a boolean that marks if this member changed
  61. let changed = (width != self.0) || (height != self.1);
  62. *self = Self(width, height);
  63. changed
  64. }
  65. }
  66. #[derive(Debug, Clone, Copy, PartialEq, Default, Component)]
  67. struct TextColor {
  68. r: u8,
  69. g: u8,
  70. b: u8,
  71. }
  72. #[partial_derive_state]
  73. impl State for TextColor {
  74. // TextColor depends on the TextColor part of the parent
  75. type ParentDependencies = (Self,);
  76. type ChildDependencies = ();
  77. type NodeDependencies = ();
  78. // TextColor only cares about the color attribute of the current node
  79. const NODE_MASK: NodeMaskBuilder<'static> =
  80. // Get access to the color attribute
  81. NodeMaskBuilder::new().with_attrs(AttributeMaskBuilder::Some(&["color"]));
  82. fn update<'a>(
  83. &mut self,
  84. node_view: NodeView<()>,
  85. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  86. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  87. _children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  88. _context: &SendAnyMap,
  89. ) -> bool {
  90. // TextColor only depends on the color tag, so getting the first tag is equivilent to looking through all tags
  91. let new = match node_view
  92. .attributes()
  93. .and_then(|mut attrs| attrs.next())
  94. .and_then(|attr| attr.value.as_text())
  95. {
  96. // if there is a color tag, translate it
  97. Some("red") => TextColor { r: 255, g: 0, b: 0 },
  98. Some("green") => TextColor { r: 0, g: 255, b: 0 },
  99. Some("blue") => TextColor { r: 0, g: 0, b: 255 },
  100. Some(color) => panic!("unknown color {color}"),
  101. // otherwise check if the node has a parent and inherit that color
  102. None => match parent {
  103. Some((parent,)) => *parent,
  104. None => Self::default(),
  105. },
  106. };
  107. // check if the member has changed
  108. let changed = new != *self;
  109. *self = new;
  110. changed
  111. }
  112. }
  113. #[derive(Debug, Clone, Copy, PartialEq, Default, Component)]
  114. struct Border(bool);
  115. #[partial_derive_state]
  116. impl State for Border {
  117. // TextColor depends on the TextColor part of the parent
  118. type ParentDependencies = (Self,);
  119. type ChildDependencies = ();
  120. type NodeDependencies = ();
  121. // Border does not depended on any other member in the current node
  122. const NODE_MASK: NodeMaskBuilder<'static> =
  123. // Get access to the border attribute
  124. NodeMaskBuilder::new().with_attrs(AttributeMaskBuilder::Some(&["border"]));
  125. fn update<'a>(
  126. &mut self,
  127. node_view: NodeView<()>,
  128. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  129. _parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  130. _children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  131. _context: &SendAnyMap,
  132. ) -> bool {
  133. // check if the node contians a border attribute
  134. let new = Self(
  135. node_view
  136. .attributes()
  137. .and_then(|mut attrs| attrs.next().map(|a| a.attribute.name == "border"))
  138. .is_some(),
  139. );
  140. // check if the member has changed
  141. let changed = new != *self;
  142. *self = new;
  143. changed
  144. }
  145. }
  146. fn main() -> Result<(), Box<dyn std::error::Error>> {
  147. let mut rdom: RealDom = RealDom::new([
  148. Border::to_type_erased(),
  149. TextColor::to_type_erased(),
  150. Size::to_type_erased(),
  151. ]);
  152. let mut count = 0;
  153. // intial render
  154. let text_id = rdom.create_node(format!("Count: {count}")).id();
  155. let mut root = rdom.get_mut(rdom.root_id()).unwrap();
  156. // set the color to red
  157. if let NodeTypeMut::Element(mut element) = root.node_type_mut() {
  158. element.set_attribute(("color", "style"), "red".to_string());
  159. }
  160. root.add_child(text_id);
  161. let mut ctx = SendAnyMap::new();
  162. // set the font size to 3.3
  163. ctx.insert(FontSize(3.3));
  164. // update the State for nodes in the real_dom tree
  165. let _to_rerender = rdom.update_state(ctx);
  166. // we need to run the vdom in a async runtime
  167. tokio::runtime::Builder::new_current_thread()
  168. .enable_all()
  169. .build()?
  170. .block_on(async {
  171. loop {
  172. // update the count
  173. count += 1;
  174. let mut text = rdom.get_mut(text_id).unwrap();
  175. if let NodeTypeMut::Text(mut text) = text.node_type_mut() {
  176. *text = format!("Count: {count}");
  177. }
  178. let mut ctx = SendAnyMap::new();
  179. ctx.insert(FontSize(3.3));
  180. let _to_rerender = rdom.update_state(ctx);
  181. // render...
  182. rdom.traverse_depth_first(|node| {
  183. let indent = " ".repeat(node.height() as usize);
  184. let color = *node.get::<TextColor>().unwrap();
  185. let size = *node.get::<Size>().unwrap();
  186. let border = *node.get::<Border>().unwrap();
  187. let id = node.id();
  188. println!("{indent}{id:?} {color:?} {size:?} {border:?}");
  189. });
  190. // wait 1 second
  191. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  192. }
  193. })
  194. }