simple_dioxus.rs 8.6 KB

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