custom_renderer.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. use dioxus::html::input_data::keyboard_types::{Code, Key, Modifiers};
  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::utils::cursor::{Cursor, Pos};
  7. use dioxus_native_core_macro::partial_derive_state;
  8. // ANCHOR: state_impl
  9. struct FontSize(f64);
  10. // All states need to derive Component
  11. #[derive(Default, Debug, Copy, Clone, Component)]
  12. struct Size(f64, f64);
  13. /// Derive some of the boilerplate for the State implementation
  14. #[partial_derive_state]
  15. impl State for Size {
  16. type ParentDependencies = ();
  17. // The size of the current node depends on the size of its children
  18. type ChildDependencies = (Self,);
  19. type NodeDependencies = ();
  20. // Size only cares about the width, height, and text parts of the current node
  21. const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
  22. // Get access to the width and height attributes
  23. .with_attrs(AttributeMaskBuilder::Some(&["width", "height"]))
  24. // Get access to the text of the node
  25. .with_text();
  26. fn update<'a>(
  27. &mut self,
  28. node_view: NodeView<()>,
  29. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  30. _parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  31. children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  32. context: &SendAnyMap,
  33. ) -> bool {
  34. let font_size = context.get::<FontSize>().unwrap().0;
  35. let mut width;
  36. let mut height;
  37. if let Some(text) = node_view.text() {
  38. // if the node has text, use the text to size our object
  39. width = text.len() as f64 * font_size;
  40. height = font_size;
  41. } else {
  42. // otherwise, the size is the maximum size of the children
  43. width = children
  44. .iter()
  45. .map(|(item,)| item.0)
  46. .reduce(|accum, item| if accum >= item { accum } else { item })
  47. .unwrap_or(0.0);
  48. height = children
  49. .iter()
  50. .map(|(item,)| item.1)
  51. .reduce(|accum, item| if accum >= item { accum } else { item })
  52. .unwrap_or(0.0);
  53. }
  54. // if the node contains a width or height attribute it overrides the other size
  55. for a in node_view.attributes().into_iter().flatten() {
  56. match &*a.attribute.name {
  57. "width" => width = a.value.as_float().unwrap(),
  58. "height" => height = a.value.as_float().unwrap(),
  59. // because Size only depends on the width and height, no other attributes will be passed to the member
  60. _ => panic!(),
  61. }
  62. }
  63. // to determine what other parts of the dom need to be updated we return a boolean that marks if this member changed
  64. let changed = (width != self.0) || (height != self.1);
  65. *self = Self(width, height);
  66. changed
  67. }
  68. }
  69. #[derive(Debug, Clone, Copy, PartialEq, Default, Component)]
  70. struct TextColor {
  71. r: u8,
  72. g: u8,
  73. b: u8,
  74. }
  75. #[partial_derive_state]
  76. impl State for TextColor {
  77. // TextColor depends on the TextColor part of the parent
  78. type ParentDependencies = (Self,);
  79. type ChildDependencies = ();
  80. type NodeDependencies = ();
  81. // TextColor only cares about the color attribute of the current node
  82. const NODE_MASK: NodeMaskBuilder<'static> =
  83. // Get access to the color attribute
  84. NodeMaskBuilder::new().with_attrs(AttributeMaskBuilder::Some(&["color"]));
  85. fn update<'a>(
  86. &mut self,
  87. node_view: NodeView<()>,
  88. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  89. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  90. _children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  91. _context: &SendAnyMap,
  92. ) -> bool {
  93. // TextColor only depends on the color tag, so getting the first tag is equivilent to looking through all tags
  94. let new = match node_view
  95. .attributes()
  96. .and_then(|mut attrs| attrs.next())
  97. .and_then(|attr| attr.value.as_text())
  98. {
  99. // if there is a color tag, translate it
  100. Some("red") => TextColor { r: 255, g: 0, b: 0 },
  101. Some("green") => TextColor { r: 0, g: 255, b: 0 },
  102. Some("blue") => TextColor { r: 0, g: 0, b: 255 },
  103. Some(color) => panic!("unknown color {color}"),
  104. // otherwise check if the node has a parent and inherit that color
  105. None => match parent {
  106. Some((parent,)) => *parent,
  107. None => Self::default(),
  108. },
  109. };
  110. // check if the member has changed
  111. let changed = new != *self;
  112. *self = new;
  113. changed
  114. }
  115. }
  116. #[derive(Debug, Clone, Copy, PartialEq, Default, Component)]
  117. struct Border(bool);
  118. #[partial_derive_state]
  119. impl State for Border {
  120. // TextColor depends on the TextColor part of the parent
  121. type ParentDependencies = (Self,);
  122. type ChildDependencies = ();
  123. type NodeDependencies = ();
  124. // Border does not depended on any other member in the current node
  125. const NODE_MASK: NodeMaskBuilder<'static> =
  126. // Get access to the border attribute
  127. NodeMaskBuilder::new().with_attrs(AttributeMaskBuilder::Some(&["border"]));
  128. fn update<'a>(
  129. &mut self,
  130. node_view: NodeView<()>,
  131. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  132. _parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  133. _children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  134. _context: &SendAnyMap,
  135. ) -> bool {
  136. // check if the node contians a border attribute
  137. let new = Self(
  138. node_view
  139. .attributes()
  140. .and_then(|mut attrs| attrs.next().map(|a| a.attribute.name == "border"))
  141. .is_some(),
  142. );
  143. // check if the member has changed
  144. let changed = new != *self;
  145. *self = new;
  146. changed
  147. }
  148. }
  149. // ANCHOR_END: state_impl
  150. // ANCHOR: rendering
  151. fn main() -> Result<(), Box<dyn std::error::Error>> {
  152. fn app(cx: Scope) -> Element {
  153. let count = use_state(cx, || 0);
  154. use_future(cx, (count,), |(count,)| async move {
  155. loop {
  156. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  157. count.set(*count + 1);
  158. }
  159. });
  160. cx.render(rsx! {
  161. div{
  162. color: "red",
  163. "{count}"
  164. }
  165. })
  166. }
  167. // create the vdom, the real_dom, and the binding layer between them
  168. let mut vdom = VirtualDom::new(app);
  169. let mut rdom: RealDom = RealDom::new([
  170. Border::to_type_erased(),
  171. TextColor::to_type_erased(),
  172. Size::to_type_erased(),
  173. ]);
  174. let mut dioxus_intigration_state = DioxusState::create(&mut rdom);
  175. let mutations = vdom.rebuild();
  176. // update the structure of the real_dom tree
  177. dioxus_intigration_state.apply_mutations(&mut rdom, mutations);
  178. let mut ctx = SendAnyMap::new();
  179. // set the font size to 3.3
  180. ctx.insert(FontSize(3.3));
  181. // update the State for nodes in the real_dom tree
  182. let _to_rerender = rdom.update_state(ctx);
  183. // we need to run the vdom in a async runtime
  184. tokio::runtime::Builder::new_current_thread()
  185. .enable_all()
  186. .build()?
  187. .block_on(async {
  188. loop {
  189. // wait for the vdom to update
  190. vdom.wait_for_work().await;
  191. // get the mutations from the vdom
  192. let mutations = vdom.render_immediate();
  193. // update the structure of the real_dom tree
  194. dioxus_intigration_state.apply_mutations(&mut rdom, mutations);
  195. // update the state of the real_dom tree
  196. let mut ctx = SendAnyMap::new();
  197. // set the font size to 3.3
  198. ctx.insert(FontSize(3.3));
  199. let _to_rerender = rdom.update_state(ctx);
  200. // render...
  201. rdom.traverse_depth_first(|node| {
  202. let indent = " ".repeat(node.height() as usize);
  203. let color = *node.get::<TextColor>().unwrap();
  204. let size = *node.get::<Size>().unwrap();
  205. let border = *node.get::<Border>().unwrap();
  206. let id = node.id();
  207. let node = node.node_type();
  208. let node_type = &*node;
  209. println!("{indent}{id:?} {color:?} {size:?} {border:?} {node_type:?}");
  210. });
  211. }
  212. })
  213. }
  214. // ANCHOR_END: rendering
  215. // ANCHOR: derive_state
  216. // All states must derive Component (https://docs.rs/shipyard/latest/shipyard/derive.Component.html)
  217. // They also must implement Default or provide a custom implementation of create in the State trait
  218. #[derive(Default, Component)]
  219. struct MyState;
  220. /// Derive some of the boilerplate for the State implementation
  221. #[partial_derive_state]
  222. impl State for MyState {
  223. // The states of the parent nodes this state depends on
  224. type ParentDependencies = ();
  225. // The states of the child nodes this state depends on
  226. type ChildDependencies = (Self,);
  227. // The states of the current node this state depends on
  228. type NodeDependencies = ();
  229. // The parts of the current text, element, or placeholder node in the tree that this state depends on
  230. const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
  231. // How to update the state of the current node based on the state of the parent nodes, child nodes, and the current node
  232. // Returns true if the node was updated and false if the node was not updated
  233. fn update<'a>(
  234. &mut self,
  235. // The view of the current node limited to the parts this state depends on
  236. _node_view: NodeView<()>,
  237. // The state of the current node that this state depends on
  238. _node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  239. // The state of the parent nodes that this state depends on
  240. _parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  241. // The state of the child nodes that this state depends on
  242. _children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  243. // The context of the current node used to pass global state into the tree
  244. _context: &SendAnyMap,
  245. ) -> bool {
  246. todo!()
  247. }
  248. // partial_derive_state will generate a default implementation of all the other methods
  249. }
  250. // ANCHOR_END: derive_state
  251. #[allow(unused)]
  252. // ANCHOR: cursor
  253. fn text_editing() {
  254. let mut cursor = Cursor::default();
  255. let mut text = String::new();
  256. // handle keyboard input with a max text length of 10
  257. cursor.handle_input(
  258. &Code::ArrowRight,
  259. &Key::ArrowRight,
  260. &Modifiers::empty(),
  261. &mut text,
  262. 10,
  263. );
  264. // mannually select text between characters 0-5 on the first line (this could be from dragging with a mouse)
  265. cursor.start = Pos::new(0, 0);
  266. cursor.end = Some(Pos::new(5, 0));
  267. // delete the selected text and move the cursor to the start of the selection
  268. cursor.delete_selection(&mut text);
  269. }
  270. // ANCHOR_END: cursor