custom_element.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. use dioxus::prelude::*;
  2. use dioxus_native_core::{custom_element::CustomElement, prelude::*};
  3. use dioxus_native_core_macro::partial_derive_state;
  4. use shipyard::Component;
  5. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Component)]
  6. pub struct ColorState {
  7. color: usize,
  8. }
  9. #[partial_derive_state]
  10. impl State for ColorState {
  11. type ParentDependencies = (Self,);
  12. type ChildDependencies = ();
  13. type NodeDependencies = ();
  14. // The color state should not be effected by the shadow dom
  15. const TRAVERSE_SHADOW_DOM: bool = false;
  16. const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
  17. .with_attrs(AttributeMaskBuilder::Some(&["color"]))
  18. .with_element();
  19. fn update<'a>(
  20. &mut self,
  21. view: NodeView,
  22. _: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  23. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  24. _: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  25. _: &SendAnyMap,
  26. ) -> bool {
  27. if let Some(size) = view
  28. .attributes()
  29. .into_iter()
  30. .flatten()
  31. .find(|attr| attr.attribute.name == "color")
  32. {
  33. self.color = size
  34. .value
  35. .as_float()
  36. .or_else(|| size.value.as_int().map(|i| i as f64))
  37. .or_else(|| size.value.as_text().and_then(|i| i.parse().ok()))
  38. .unwrap_or(0.0) as usize;
  39. } else if let Some((parent,)) = parent {
  40. *self = *parent;
  41. }
  42. true
  43. }
  44. fn create<'a>(
  45. node_view: NodeView<()>,
  46. node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  47. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  48. children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  49. context: &SendAnyMap,
  50. ) -> Self {
  51. let mut myself = Self::default();
  52. myself.update(node_view, node, parent, children, context);
  53. myself
  54. }
  55. }
  56. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Component)]
  57. pub struct LayoutState {
  58. size: usize,
  59. }
  60. #[partial_derive_state]
  61. impl State for LayoutState {
  62. type ParentDependencies = (Self,);
  63. type ChildDependencies = ();
  64. type NodeDependencies = ();
  65. // The layout state should be effected by the shadow dom
  66. const TRAVERSE_SHADOW_DOM: bool = true;
  67. const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
  68. .with_attrs(AttributeMaskBuilder::Some(&["size"]))
  69. .with_element();
  70. fn update<'a>(
  71. &mut self,
  72. view: NodeView,
  73. _: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  74. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  75. _: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  76. _: &SendAnyMap,
  77. ) -> bool {
  78. if let Some(size) = view
  79. .attributes()
  80. .into_iter()
  81. .flatten()
  82. .find(|attr| attr.attribute.name == "size")
  83. {
  84. self.size = size
  85. .value
  86. .as_float()
  87. .or_else(|| size.value.as_int().map(|i| i as f64))
  88. .or_else(|| size.value.as_text().and_then(|i| i.parse().ok()))
  89. .unwrap_or(0.0) as usize;
  90. } else if let Some((parent,)) = parent {
  91. if parent.size > 0 {
  92. self.size = parent.size - 1;
  93. }
  94. }
  95. true
  96. }
  97. fn create<'a>(
  98. node_view: NodeView<()>,
  99. node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  100. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  101. children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  102. context: &SendAnyMap,
  103. ) -> Self {
  104. let mut myself = Self::default();
  105. myself.update(node_view, node, parent, children, context);
  106. myself
  107. }
  108. }
  109. mod dioxus_elements {
  110. macro_rules! builder_constructors {
  111. (
  112. $(
  113. $(#[$attr:meta])*
  114. $name:ident {
  115. $(
  116. $(#[$attr_method:meta])*
  117. $fil:ident: $vil:ident,
  118. )*
  119. };
  120. )*
  121. ) => {
  122. $(
  123. #[allow(non_camel_case_types)]
  124. $(#[$attr])*
  125. pub struct $name;
  126. #[allow(non_upper_case_globals, unused)]
  127. impl $name {
  128. pub const TAG_NAME: &'static str = stringify!($name);
  129. pub const NAME_SPACE: Option<&'static str> = None;
  130. $(
  131. pub const $fil: (&'static str, Option<&'static str>, bool) = (stringify!($fil), None, false);
  132. )*
  133. }
  134. impl GlobalAttributes for $name {}
  135. )*
  136. }
  137. }
  138. pub trait GlobalAttributes {}
  139. pub trait SvgAttributes {}
  140. builder_constructors! {
  141. customelementslot {
  142. size: attr,
  143. color: attr,
  144. };
  145. customelementnoslot {
  146. size: attr,
  147. color: attr,
  148. };
  149. testing132 {
  150. color: attr,
  151. };
  152. }
  153. }
  154. struct CustomElementWithSlot {
  155. root: NodeId,
  156. slot: NodeId,
  157. }
  158. impl CustomElement for CustomElementWithSlot {
  159. const NAME: &'static str = "customelementslot";
  160. fn create(mut node: NodeMut<()>) -> Self {
  161. let dom = node.real_dom_mut();
  162. let child = dom.create_node(ElementNode {
  163. tag: "div".into(),
  164. namespace: None,
  165. attributes: Default::default(),
  166. listeners: Default::default(),
  167. });
  168. let slot_id = child.id();
  169. let mut root = dom.create_node(ElementNode {
  170. tag: "div".into(),
  171. namespace: None,
  172. attributes: Default::default(),
  173. listeners: Default::default(),
  174. });
  175. root.add_child(slot_id);
  176. Self {
  177. root: root.id(),
  178. slot: slot_id,
  179. }
  180. }
  181. fn slot(&self) -> Option<NodeId> {
  182. Some(self.slot)
  183. }
  184. fn roots(&self) -> Vec<NodeId> {
  185. vec![self.root]
  186. }
  187. fn attributes_changed(
  188. &mut self,
  189. node: NodeMut<()>,
  190. attributes: &dioxus_native_core::node_ref::AttributeMask,
  191. ) {
  192. println!("attributes_changed");
  193. println!("{:?}", attributes);
  194. println!("{:?}: {:#?}", node.id(), &*node.node_type());
  195. }
  196. }
  197. struct CustomElementWithNoSlot {
  198. root: NodeId,
  199. }
  200. impl CustomElement for CustomElementWithNoSlot {
  201. const NAME: &'static str = "customelementnoslot";
  202. fn create(mut node: NodeMut<()>) -> Self {
  203. let dom = node.real_dom_mut();
  204. let root = dom.create_node(ElementNode {
  205. tag: "div".into(),
  206. namespace: None,
  207. attributes: Default::default(),
  208. listeners: Default::default(),
  209. });
  210. Self { root: root.id() }
  211. }
  212. fn roots(&self) -> Vec<NodeId> {
  213. vec![self.root]
  214. }
  215. fn attributes_changed(
  216. &mut self,
  217. node: NodeMut<()>,
  218. attributes: &dioxus_native_core::node_ref::AttributeMask,
  219. ) {
  220. println!("attributes_changed");
  221. println!("{:?}", attributes);
  222. println!("{:?}: {:#?}", node.id(), &*node.node_type());
  223. }
  224. }
  225. #[test]
  226. fn custom_elements_work() {
  227. fn app(cx: Scope) -> Element {
  228. let count = use_state(cx, || 0);
  229. use_future!(cx, |count| async move {
  230. count.with_mut(|count| *count += 1);
  231. });
  232. cx.render(rsx! {
  233. customelementslot {
  234. size: "{count}",
  235. color: "1",
  236. customelementslot {
  237. testing132 {}
  238. }
  239. }
  240. })
  241. }
  242. let rt = tokio::runtime::Builder::new_current_thread()
  243. .enable_time()
  244. .build()
  245. .unwrap();
  246. rt.block_on(async {
  247. let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
  248. rdom.register_custom_element::<CustomElementWithSlot>();
  249. let mut dioxus_state = DioxusState::create(&mut rdom);
  250. let mut dom = VirtualDom::new(app);
  251. let mutations = dom.rebuild();
  252. dioxus_state.apply_mutations(&mut rdom, mutations);
  253. let ctx = SendAnyMap::new();
  254. rdom.update_state(ctx);
  255. for i in 0..10usize {
  256. dom.wait_for_work().await;
  257. let mutations = dom.render_immediate();
  258. dioxus_state.apply_mutations(&mut rdom, mutations);
  259. let ctx = SendAnyMap::new();
  260. rdom.update_state(ctx);
  261. // render...
  262. rdom.traverse_depth_first_advanced(true, |node| {
  263. let node_type = &*node.node_type();
  264. let height = node.height() as usize;
  265. let indent = " ".repeat(height);
  266. let color = *node.get::<ColorState>().unwrap();
  267. let size = *node.get::<LayoutState>().unwrap();
  268. let id = node.id();
  269. println!("{indent}{id:?} {color:?} {size:?} {node_type:?}");
  270. if let NodeType::Element(el) = node_type {
  271. match el.tag.as_str() {
  272. // the color should bubble up from customelementslot
  273. "testing132" | "customelementslot" => {
  274. assert_eq!(color.color, 1);
  275. }
  276. // the color of the light dom should not effect the color of the shadow dom, so the color of divs in the shadow dom should be 0
  277. "div" => {
  278. assert_eq!(color.color, 0);
  279. }
  280. _ => {}
  281. }
  282. if el.tag != "Root" {
  283. assert_eq!(size.size, (i + 2).saturating_sub(height));
  284. }
  285. }
  286. });
  287. }
  288. });
  289. }
  290. #[test]
  291. #[should_panic]
  292. fn slotless_custom_element_cant_have_children() {
  293. fn app(cx: Scope) -> Element {
  294. cx.render(rsx! {
  295. customelementnoslot {
  296. testing132 {}
  297. }
  298. })
  299. }
  300. let rt = tokio::runtime::Builder::new_current_thread()
  301. .enable_time()
  302. .build()
  303. .unwrap();
  304. rt.block_on(async {
  305. let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
  306. rdom.register_custom_element::<CustomElementWithNoSlot>();
  307. let mut dioxus_state = DioxusState::create(&mut rdom);
  308. let mut dom = VirtualDom::new(app);
  309. let mutations = dom.rebuild();
  310. dioxus_state.apply_mutations(&mut rdom, mutations);
  311. let ctx = SendAnyMap::new();
  312. rdom.update_state(ctx);
  313. });
  314. }
  315. #[test]
  316. fn slotless_custom_element() {
  317. fn app(cx: Scope) -> Element {
  318. cx.render(rsx! {
  319. customelementnoslot {
  320. }
  321. })
  322. }
  323. let rt = tokio::runtime::Builder::new_current_thread()
  324. .enable_time()
  325. .build()
  326. .unwrap();
  327. rt.block_on(async {
  328. let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
  329. rdom.register_custom_element::<CustomElementWithNoSlot>();
  330. let mut dioxus_state = DioxusState::create(&mut rdom);
  331. let mut dom = VirtualDom::new(app);
  332. let mutations = dom.rebuild();
  333. dioxus_state.apply_mutations(&mut rdom, mutations);
  334. let ctx = SendAnyMap::new();
  335. rdom.update_state(ctx);
  336. });
  337. }