custom_element.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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(dom: &mut RealDom<()>) -> Self {
  161. let child = dom.create_node(ElementNode {
  162. tag: "div".into(),
  163. namespace: None,
  164. attributes: Default::default(),
  165. listeners: Default::default(),
  166. });
  167. let slot_id = child.id();
  168. let mut root = dom.create_node(ElementNode {
  169. tag: "div".into(),
  170. namespace: None,
  171. attributes: Default::default(),
  172. listeners: Default::default(),
  173. });
  174. root.add_child(slot_id);
  175. Self {
  176. root: root.id(),
  177. slot: slot_id,
  178. }
  179. }
  180. fn slot(&self) -> Option<NodeId> {
  181. Some(self.slot)
  182. }
  183. fn roots(&self) -> Vec<NodeId> {
  184. vec![self.root]
  185. }
  186. fn attributes_changed(
  187. &mut self,
  188. node: NodeMut<()>,
  189. attributes: &dioxus_native_core::node_ref::AttributeMask,
  190. ) {
  191. println!("attributes_changed");
  192. println!("{:?}", attributes);
  193. println!("{:?}: {:#?}", node.id(), &*node.node_type());
  194. }
  195. }
  196. struct CustomElementWithNoSlot {
  197. root: NodeId,
  198. }
  199. impl CustomElement for CustomElementWithNoSlot {
  200. const NAME: &'static str = "customelementnoslot";
  201. fn create(dom: &mut RealDom<()>) -> Self {
  202. let root = dom.create_node(ElementNode {
  203. tag: "div".into(),
  204. namespace: None,
  205. attributes: Default::default(),
  206. listeners: Default::default(),
  207. });
  208. Self { root: root.id() }
  209. }
  210. fn roots(&self) -> Vec<NodeId> {
  211. vec![self.root]
  212. }
  213. fn attributes_changed(
  214. &mut self,
  215. node: NodeMut<()>,
  216. attributes: &dioxus_native_core::node_ref::AttributeMask,
  217. ) {
  218. println!("attributes_changed");
  219. println!("{:?}", attributes);
  220. println!("{:?}: {:#?}", node.id(), &*node.node_type());
  221. }
  222. }
  223. #[test]
  224. fn custom_elements_work() {
  225. fn app(cx: Scope) -> Element {
  226. let count = use_state(cx, || 0);
  227. use_future!(cx, |count| async move {
  228. count.with_mut(|count| *count += 1);
  229. });
  230. cx.render(rsx! {
  231. customelementslot {
  232. size: "{count}",
  233. color: "1",
  234. customelementslot {
  235. testing132 {}
  236. }
  237. }
  238. })
  239. }
  240. let rt = tokio::runtime::Builder::new_current_thread()
  241. .enable_time()
  242. .build()
  243. .unwrap();
  244. rt.block_on(async {
  245. let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
  246. rdom.register_custom_element::<CustomElementWithSlot>();
  247. let mut dioxus_state = DioxusState::create(&mut rdom);
  248. let mut dom = VirtualDom::new(app);
  249. let mutations = dom.rebuild();
  250. dioxus_state.apply_mutations(&mut rdom, mutations);
  251. let ctx = SendAnyMap::new();
  252. rdom.update_state(ctx);
  253. for i in 0..10usize {
  254. dom.wait_for_work().await;
  255. let mutations = dom.render_immediate();
  256. dioxus_state.apply_mutations(&mut rdom, mutations);
  257. let ctx = SendAnyMap::new();
  258. rdom.update_state(ctx);
  259. // render...
  260. rdom.traverse_depth_first(true, |node| {
  261. let node_type = &*node.node_type();
  262. let height = node.height() as usize;
  263. let indent = " ".repeat(height);
  264. let color = *node.get::<ColorState>().unwrap();
  265. let size = *node.get::<LayoutState>().unwrap();
  266. let id = node.id();
  267. println!("{indent}{id:?} {color:?} {size:?} {node_type:?}");
  268. match node_type {
  269. NodeType::Element(el) => {
  270. match el.tag.as_str() {
  271. // the color should bubble up from customelementslot
  272. "testing132" | "customelementslot" => {
  273. assert_eq!(color.color, 1);
  274. }
  275. // 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
  276. "div" => {
  277. assert_eq!(color.color, 0);
  278. }
  279. _ => {}
  280. }
  281. if el.tag != "Root" {
  282. assert_eq!(size.size, (i + 2).saturating_sub(height));
  283. }
  284. }
  285. _ => {}
  286. }
  287. });
  288. }
  289. });
  290. }
  291. #[test]
  292. #[should_panic]
  293. fn slotless_custom_element_cant_have_children() {
  294. fn app(cx: Scope) -> Element {
  295. cx.render(rsx! {
  296. customelementnoslot {
  297. testing132 {}
  298. }
  299. })
  300. }
  301. let rt = tokio::runtime::Builder::new_current_thread()
  302. .enable_time()
  303. .build()
  304. .unwrap();
  305. rt.block_on(async {
  306. let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
  307. rdom.register_custom_element::<CustomElementWithNoSlot>();
  308. let mut dioxus_state = DioxusState::create(&mut rdom);
  309. let mut dom = VirtualDom::new(app);
  310. let mutations = dom.rebuild();
  311. dioxus_state.apply_mutations(&mut rdom, mutations);
  312. let ctx = SendAnyMap::new();
  313. rdom.update_state(ctx);
  314. });
  315. }
  316. #[test]
  317. fn slotless_custom_element() {
  318. fn app(cx: Scope) -> Element {
  319. cx.render(rsx! {
  320. customelementnoslot {
  321. }
  322. })
  323. }
  324. let rt = tokio::runtime::Builder::new_current_thread()
  325. .enable_time()
  326. .build()
  327. .unwrap();
  328. rt.block_on(async {
  329. let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
  330. rdom.register_custom_element::<CustomElementWithNoSlot>();
  331. let mut dioxus_state = DioxusState::create(&mut rdom);
  332. let mut dom = VirtualDom::new(app);
  333. let mutations = dom.rebuild();
  334. dioxus_state.apply_mutations(&mut rdom, mutations);
  335. let ctx = SendAnyMap::new();
  336. rdom.update_state(ctx);
  337. });
  338. }