custom_attr.rs 8.1 KB

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