simple_dioxus.rs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. use dioxus::prelude::*;
  2. use dioxus_native_core::exports::shipyard::Component;
  3. use dioxus_native_core::node_ref::*;
  4. use dioxus_native_core::prelude::*;
  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. fn app(cx: Scope) -> Element {
  148. let count = use_state(cx, || 0);
  149. use_future(cx, (count,), |(count,)| async move {
  150. loop {
  151. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  152. count.set(*count + 1);
  153. }
  154. });
  155. cx.render(rsx! {
  156. div{
  157. color: "red",
  158. "{count}",
  159. Comp {}
  160. }
  161. })
  162. }
  163. fn Comp(cx: Scope) -> Element {
  164. cx.render(rsx! {
  165. div{
  166. border: "",
  167. "hello world"
  168. }
  169. })
  170. }
  171. // create the vdom, the real_dom, and the binding layer between them
  172. let mut vdom = VirtualDom::new(app);
  173. let mut rdom: RealDom = RealDom::new([
  174. Border::to_type_erased(),
  175. TextColor::to_type_erased(),
  176. Size::to_type_erased(),
  177. ]);
  178. let mut dioxus_intigration_state = DioxusState::create(&mut rdom);
  179. let mutations = vdom.rebuild();
  180. // update the structure of the real_dom tree
  181. dioxus_intigration_state.apply_mutations(&mut rdom, mutations);
  182. let mut ctx = SendAnyMap::new();
  183. // set the font size to 3.3
  184. ctx.insert(FontSize(3.3));
  185. // update the State for nodes in the real_dom tree
  186. let _to_rerender = rdom.update_state(ctx);
  187. // we need to run the vdom in a async runtime
  188. tokio::runtime::Builder::new_current_thread()
  189. .enable_all()
  190. .build()?
  191. .block_on(async {
  192. loop {
  193. // wait for the vdom to update
  194. vdom.wait_for_work().await;
  195. // get the mutations from the vdom
  196. let mutations = vdom.render_immediate();
  197. // update the structure of the real_dom tree
  198. dioxus_intigration_state.apply_mutations(&mut rdom, mutations);
  199. // update the state of the real_dom tree
  200. let mut ctx = SendAnyMap::new();
  201. // set the font size to 3.3
  202. ctx.insert(FontSize(3.3));
  203. let _to_rerender = rdom.update_state(ctx);
  204. // render...
  205. rdom.traverse_depth_first(|node| {
  206. let indent = " ".repeat(node.height() as usize);
  207. let color = *node.get::<TextColor>().unwrap();
  208. let size = *node.get::<Size>().unwrap();
  209. let border = *node.get::<Border>().unwrap();
  210. let id = node.id();
  211. let node = node.node_type();
  212. let node_type = &*node;
  213. println!("{indent}{id:?} {color:?} {size:?} {border:?} {node_type:?}");
  214. });
  215. }
  216. })
  217. }