simple_dioxus.rs 8.7 KB

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