nodes.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. //! Virtual Node Support
  2. //!
  3. //! VNodes represent lazily-constructed VDom trees that support diffing and event handlers. These VNodes should be *very*
  4. //! cheap and *very* fast to construct - building a full tree should be quick.
  5. use crate::innerlude::{
  6. empty_cell, Context, DomTree, ElementId, Properties, Scope, ScopeId, SuspendedContext,
  7. SyntheticEvent, FC,
  8. };
  9. use bumpalo::{boxed::Box as BumpBox, Bump};
  10. use std::{
  11. cell::{Cell, RefCell},
  12. fmt::{Arguments, Debug, Formatter},
  13. marker::PhantomData,
  14. };
  15. /// A composable "VirtualNode" to declare a User Interface in the Dioxus VirtualDOM.
  16. ///
  17. /// VNodes are designed to be lightweight and used with with a bump alloactor. To create a VNode, you can use either of:
  18. /// - the [`rsx`] macro
  19. /// - the [`html`] macro
  20. /// - the [`NodeFactory`] API
  21. pub enum VNode<'src> {
  22. /// Text VNodes simply bump-allocated (or static) string slices
  23. ///
  24. /// # Example
  25. ///
  26. /// ```
  27. /// let node = cx.render(rsx!{ "hello" }).unwrap();
  28. ///
  29. /// if let VNode::Text(vtext) = node {
  30. /// assert_eq!(vtext.text, "hello");
  31. /// assert_eq!(vtext.dom_id.get(), None);
  32. /// assert_eq!(vtext.is_static, true);
  33. /// }
  34. /// ```
  35. Text(VText<'src>),
  36. /// Element VNodes are VNodes that may contain attributes, listeners, a key, a tag, and children.
  37. ///
  38. /// # Example
  39. ///
  40. /// ```rust
  41. /// let node = cx.render(rsx!{
  42. /// div {
  43. /// key: "a",
  44. /// onclick: |e| log::info!("clicked"),
  45. /// hidden: "true",
  46. /// style: { background_color: "red" }
  47. /// "hello"
  48. /// }
  49. /// }).unwrap();
  50. /// if let VNode::Element(velement) = node {
  51. /// assert_eq!(velement.tag_name, "div");
  52. /// assert_eq!(velement.namespace, None);
  53. /// assert_eq!(velement.key, Some("a));
  54. /// }
  55. /// ```
  56. Element(&'src VElement<'src>),
  57. /// Fragment nodes may contain many VNodes without a single root.
  58. ///
  59. /// # Example
  60. ///
  61. /// ```rust
  62. /// rsx!{
  63. /// a {}
  64. /// link {}
  65. /// style {}
  66. /// "asd"
  67. /// Example {}
  68. /// }
  69. /// ```
  70. Fragment(VFragment<'src>),
  71. /// Component nodes represent a mounted component with props, children, and a key.
  72. ///
  73. /// # Example
  74. ///
  75. /// ```rust
  76. /// fn Example(cx: Context<()>) -> DomTree {
  77. /// todo!()
  78. /// }
  79. ///
  80. /// let node = cx.render(rsx!{
  81. /// Example {}
  82. /// }).unwrap();
  83. ///
  84. /// if let VNode::Component(vcomp) = node {
  85. /// assert_eq!(vcomp.user_fc, Example as *const ());
  86. /// }
  87. /// ```
  88. Component(&'src VComponent<'src>),
  89. /// Suspended VNodes represent chunks of the UI tree that are not yet ready to be displayed.
  90. ///
  91. /// These nodes currently can only be constructed via the [`use_suspense`] hook.
  92. ///
  93. /// # Example
  94. ///
  95. /// ```rust
  96. /// rsx!{
  97. /// }
  98. /// ```
  99. Suspended(&'src VSuspended<'src>),
  100. /// Anchors are a type of placeholder VNode used when fragments don't contain any children.
  101. ///
  102. /// Anchors cannot be directly constructed via public APIs.
  103. ///
  104. /// # Example
  105. ///
  106. /// ```rust
  107. /// let node = cx.render(rsx! ( Fragment {} )).unwrap();
  108. /// if let VNode::Fragment(frag) = node {
  109. /// let root = &frag.children[0];
  110. /// assert_eq!(root, VNode::Anchor);
  111. /// }
  112. /// ```
  113. Anchor(VAnchor),
  114. }
  115. impl<'src> VNode<'src> {
  116. /// Get the VNode's "key" used in the keyed diffing algorithm.
  117. pub fn key(&self) -> Option<&'src str> {
  118. match &self {
  119. VNode::Element(el) => el.key,
  120. VNode::Component(c) => c.key,
  121. VNode::Fragment(f) => f.key,
  122. VNode::Text(_t) => None,
  123. VNode::Suspended(_s) => None,
  124. VNode::Anchor(_f) => None,
  125. }
  126. }
  127. /// Get the ElementID of the mounted VNode.
  128. ///
  129. /// Panics if the mounted ID is None or if the VNode is not represented by a single Element.
  130. pub fn mounted_id(&self) -> ElementId {
  131. self.try_mounted_id().unwrap()
  132. }
  133. /// Try to get the ElementID of the mounted VNode.
  134. ///
  135. /// Returns None if the VNode is not mounted, or if the VNode cannot be presented by a mounted ID (Fragment/Component)
  136. pub fn try_mounted_id(&self) -> Option<ElementId> {
  137. match &self {
  138. VNode::Text(el) => el.dom_id.get(),
  139. VNode::Element(el) => el.dom_id.get(),
  140. VNode::Anchor(el) => el.dom_id.get(),
  141. VNode::Suspended(el) => el.dom_id.get(),
  142. VNode::Fragment(_) => None,
  143. VNode::Component(_) => None,
  144. }
  145. }
  146. }
  147. /// A placeholder node only generated when Fragments don't have any children.
  148. pub struct VAnchor {
  149. pub dom_id: Cell<Option<ElementId>>,
  150. }
  151. /// A bump-alloacted string slice and metadata.
  152. pub struct VText<'src> {
  153. pub text: &'src str,
  154. pub dom_id: Cell<Option<ElementId>>,
  155. pub is_static: bool,
  156. }
  157. /// A list of VNodes with no single root.
  158. pub struct VFragment<'src> {
  159. pub key: Option<&'src str>,
  160. pub children: &'src [VNode<'src>],
  161. pub is_static: bool,
  162. }
  163. /// An element like a "div" with children, listeners, and attributes.
  164. pub struct VElement<'a> {
  165. pub tag_name: &'static str,
  166. pub namespace: Option<&'static str>,
  167. pub key: Option<&'a str>,
  168. pub dom_id: Cell<Option<ElementId>>,
  169. pub parent_id: Cell<Option<ElementId>>,
  170. pub listeners: &'a [Listener<'a>],
  171. pub attributes: &'a [Attribute<'a>],
  172. pub children: &'a [VNode<'a>],
  173. }
  174. impl Debug for VElement<'_> {
  175. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  176. f.debug_struct("VElement")
  177. .field("tag_name", &self.tag_name)
  178. .field("namespace", &self.namespace)
  179. .field("key", &self.key)
  180. .field("dom_id", &self.dom_id)
  181. .field("parent_id", &self.parent_id)
  182. .field("listeners", &self.listeners.len())
  183. .field("attributes", &self.attributes)
  184. .field("children", &self.children)
  185. .finish()
  186. }
  187. }
  188. /// A trait for any generic Dioxus Element.
  189. ///
  190. /// This trait provides the ability to use custom elements in the `rsx!` macro.
  191. ///
  192. /// ```rust
  193. /// struct my_element;
  194. ///
  195. /// impl DioxusElement for my_element {
  196. /// const TAG_NAME: "my_element";
  197. /// const NAME_SPACE: None;
  198. /// }
  199. ///
  200. /// let _ = rsx!{
  201. /// my_element {}
  202. /// };
  203. /// ```
  204. pub trait DioxusElement {
  205. const TAG_NAME: &'static str;
  206. const NAME_SPACE: Option<&'static str>;
  207. #[inline]
  208. fn tag_name(&self) -> &'static str {
  209. Self::TAG_NAME
  210. }
  211. #[inline]
  212. fn namespace(&self) -> Option<&'static str> {
  213. Self::NAME_SPACE
  214. }
  215. }
  216. /// An attribute on a DOM node, such as `id="my-thing"` or
  217. /// `href="https://example.com"`.
  218. #[derive(Clone, Debug)]
  219. pub struct Attribute<'a> {
  220. pub name: &'static str,
  221. pub value: &'a str,
  222. pub is_static: bool,
  223. pub is_volatile: bool,
  224. // Doesn't exist in the html spec.
  225. // Used in Dioxus to denote "style" tags.
  226. pub namespace: Option<&'static str>,
  227. }
  228. /// An event listener.
  229. /// IE onclick, onkeydown, etc
  230. pub struct Listener<'bump> {
  231. /// The ID of the node that this listener is mounted to
  232. /// Used to generate the event listener's ID on the DOM
  233. pub mounted_node: Cell<Option<ElementId>>,
  234. /// The type of event to listen for.
  235. ///
  236. /// IE "click" - whatever the renderer needs to attach the listener by name.
  237. pub event: &'static str,
  238. /// The actual callback that the user specified
  239. pub(crate) callback: RefCell<Option<BumpBox<'bump, dyn FnMut(SyntheticEvent) + 'bump>>>,
  240. }
  241. /// Virtual Components for custom user-defined components
  242. /// Only supports the functional syntax
  243. pub struct VComponent<'src> {
  244. pub key: Option<&'src str>,
  245. pub associated_scope: Cell<Option<ScopeId>>,
  246. pub is_static: bool,
  247. // Function pointer to the FC that was used to generate this component
  248. pub user_fc: *const (),
  249. pub(crate) caller: &'src dyn for<'b> Fn(&'b Scope) -> DomTree<'b>,
  250. pub(crate) children: &'src [VNode<'src>],
  251. pub(crate) comparator: Option<&'src dyn Fn(&VComponent) -> bool>,
  252. pub(crate) drop_props: RefCell<Option<BumpBox<'src, dyn FnMut()>>>,
  253. pub(crate) can_memoize: bool,
  254. // Raw pointer into the bump arena for the props of the component
  255. pub(crate) raw_props: *const (),
  256. }
  257. pub struct VSuspended<'a> {
  258. pub task_id: u64,
  259. pub dom_id: Cell<Option<ElementId>>,
  260. pub callback: RefCell<Option<BumpBox<'a, dyn FnMut(SuspendedContext<'a>) -> DomTree<'a>>>>,
  261. }
  262. /// This struct provides an ergonomic API to quickly build VNodes.
  263. ///
  264. /// NodeFactory is used to build VNodes in the component's memory space.
  265. /// This struct adds metadata to the final VNode about listeners, attributes, and children
  266. #[derive(Copy, Clone)]
  267. pub struct NodeFactory<'a> {
  268. pub(crate) bump: &'a Bump,
  269. }
  270. impl<'a> NodeFactory<'a> {
  271. pub fn new(bump: &'a Bump) -> NodeFactory<'a> {
  272. NodeFactory { bump }
  273. }
  274. #[inline]
  275. pub fn bump(&self) -> &'a bumpalo::Bump {
  276. self.bump
  277. }
  278. pub fn render_directly<F>(&self, lazy_nodes: LazyNodes<'a, F>) -> DomTree<'a>
  279. where
  280. F: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  281. {
  282. Some(lazy_nodes.into_vnode(NodeFactory { bump: self.bump }))
  283. }
  284. pub fn unstable_place_holder() -> VNode<'static> {
  285. VNode::Text(VText {
  286. text: "",
  287. dom_id: empty_cell(),
  288. is_static: true,
  289. })
  290. }
  291. /// Directly pass in text blocks without the need to use the format_args macro.
  292. pub fn static_text(&self, text: &'static str) -> VNode<'a> {
  293. VNode::Text(VText {
  294. dom_id: empty_cell(),
  295. text,
  296. is_static: true,
  297. })
  298. }
  299. /// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
  300. ///
  301. /// Text that's static may be pointer compared, making it cheaper to diff
  302. pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
  303. match args.as_str() {
  304. Some(static_str) => (static_str, true),
  305. None => {
  306. use bumpalo::core_alloc::fmt::Write;
  307. let mut str_buf = bumpalo::collections::String::new_in(self.bump());
  308. str_buf.write_fmt(args).unwrap();
  309. (str_buf.into_bump_str(), false)
  310. }
  311. }
  312. }
  313. /// Create some text that's allocated along with the other vnodes
  314. ///
  315. pub fn text(&self, args: Arguments) -> VNode<'a> {
  316. let (text, is_static) = self.raw_text(args);
  317. VNode::Text(VText {
  318. text,
  319. is_static,
  320. dom_id: empty_cell(),
  321. })
  322. }
  323. pub fn element<L, A, V>(
  324. &self,
  325. el: impl DioxusElement,
  326. listeners: L,
  327. attributes: A,
  328. children: V,
  329. key: Option<Arguments>,
  330. ) -> VNode<'a>
  331. where
  332. L: 'a + AsRef<[Listener<'a>]>,
  333. A: 'a + AsRef<[Attribute<'a>]>,
  334. V: 'a + AsRef<[VNode<'a>]>,
  335. {
  336. self.raw_element(
  337. el.tag_name(),
  338. el.namespace(),
  339. listeners,
  340. attributes,
  341. children,
  342. key,
  343. )
  344. }
  345. pub fn raw_element<L, A, V>(
  346. &self,
  347. tag_name: &'static str,
  348. namespace: Option<&'static str>,
  349. listeners: L,
  350. attributes: A,
  351. children: V,
  352. key: Option<Arguments>,
  353. ) -> VNode<'a>
  354. where
  355. L: 'a + AsRef<[Listener<'a>]>,
  356. A: 'a + AsRef<[Attribute<'a>]>,
  357. V: 'a + AsRef<[VNode<'a>]>,
  358. {
  359. let listeners: &'a L = self.bump().alloc(listeners);
  360. let listeners = listeners.as_ref();
  361. let attributes: &'a A = self.bump().alloc(attributes);
  362. let attributes = attributes.as_ref();
  363. let children: &'a V = self.bump().alloc(children);
  364. let children = children.as_ref();
  365. let key = key.map(|f| self.raw_text(f).0);
  366. VNode::Element(self.bump().alloc(VElement {
  367. tag_name,
  368. key,
  369. namespace,
  370. listeners,
  371. attributes,
  372. children,
  373. dom_id: empty_cell(),
  374. parent_id: empty_cell(),
  375. }))
  376. }
  377. pub fn attr(
  378. &self,
  379. name: &'static str,
  380. val: Arguments,
  381. namespace: Option<&'static str>,
  382. is_volatile: bool,
  383. ) -> Attribute<'a> {
  384. let (value, is_static) = self.raw_text(val);
  385. Attribute {
  386. name,
  387. value,
  388. is_static,
  389. namespace,
  390. is_volatile,
  391. }
  392. }
  393. pub fn component<P, V>(
  394. &self,
  395. component: FC<P>,
  396. props: P,
  397. key: Option<Arguments>,
  398. children: V,
  399. ) -> VNode<'a>
  400. where
  401. P: Properties + 'a,
  402. V: 'a + AsRef<[VNode<'a>]>,
  403. {
  404. let bump = self.bump();
  405. let children: &'a V = bump.alloc(children);
  406. let children = children.as_ref();
  407. let props = bump.alloc(props);
  408. let raw_props = props as *mut P as *mut ();
  409. let user_fc = component as *const ();
  410. let comparator: Option<&dyn Fn(&VComponent) -> bool> = Some(bump.alloc_with(|| {
  411. move |other: &VComponent| {
  412. if user_fc == other.user_fc {
  413. // Safety
  414. // - We guarantee that FC<P> is the same by function pointer
  415. // - Because FC<P> is the same, then P must be the same (even with generics)
  416. // - Non-static P are autoderived to memoize as false
  417. // - This comparator is only called on a corresponding set of bumpframes
  418. let props_memoized = unsafe {
  419. let real_other: &P = &*(other.raw_props as *const _ as *const P);
  420. props.memoize(real_other)
  421. };
  422. // It's only okay to memoize if there are no children and the props can be memoized
  423. // Implementing memoize is unsafe and done automatically with the props trait
  424. match (props_memoized, children.is_empty()) {
  425. (true, true) => true,
  426. _ => false,
  427. }
  428. } else {
  429. false
  430. }
  431. }
  432. }));
  433. let drop_props = {
  434. // create a closure to drop the props
  435. let mut has_dropped = false;
  436. let drop_props: &mut dyn FnMut() = bump.alloc_with(|| {
  437. move || unsafe {
  438. if !has_dropped {
  439. let real_other = raw_props as *mut _ as *mut P;
  440. let b = BumpBox::from_raw(real_other);
  441. std::mem::drop(b);
  442. has_dropped = true;
  443. } else {
  444. panic!("Drop props called twice - this is an internal failure of Dioxus");
  445. }
  446. }
  447. });
  448. let drop_props = unsafe { BumpBox::from_raw(drop_props) };
  449. RefCell::new(Some(drop_props))
  450. };
  451. let is_static = children.is_empty() && P::IS_STATIC && key.is_none();
  452. let key = key.map(|f| self.raw_text(f).0);
  453. let caller: &'a mut dyn for<'b> Fn(&'b Scope) -> DomTree<'b> =
  454. bump.alloc(move |scope: &Scope| -> DomTree {
  455. let props: &'_ P = unsafe { &*(raw_props as *const P) };
  456. let res = component(Context { scope }, props);
  457. unsafe { std::mem::transmute(res) }
  458. });
  459. let can_memoize = children.is_empty() && P::IS_STATIC;
  460. VNode::Component(bump.alloc(VComponent {
  461. user_fc,
  462. comparator,
  463. raw_props,
  464. children,
  465. caller,
  466. is_static,
  467. key,
  468. can_memoize,
  469. drop_props,
  470. associated_scope: Cell::new(None),
  471. }))
  472. }
  473. pub fn fragment_from_iter(self, node_iter: impl IntoVNodeList<'a>) -> VNode<'a> {
  474. let children = node_iter.into_vnode_list(self);
  475. // TODO
  476. // We need a dedicated path in the rsx! macro that will trigger the "you need keys" warning
  477. //
  478. // if cfg!(debug_assertions) {
  479. // if children.len() > 1 {
  480. // if children.last().unwrap().key().is_none() {
  481. // log::error!(
  482. // r#"
  483. // Warning: Each child in an array or iterator should have a unique "key" prop.
  484. // Not providing a key will lead to poor performance with lists.
  485. // See docs.rs/dioxus for more information.
  486. // ---
  487. // To help you identify where this error is coming from, we've generated a backtrace.
  488. // "#,
  489. // );
  490. // }
  491. // }
  492. // }
  493. VNode::Fragment(VFragment {
  494. children,
  495. key: None,
  496. is_static: false,
  497. })
  498. }
  499. }
  500. /// Trait implementations for use in the rsx! and html! macros.
  501. ///
  502. /// ## Details
  503. ///
  504. /// This section provides convenience methods and trait implementations for converting common structs into a format accepted
  505. /// by the macros.
  506. ///
  507. /// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
  508. /// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
  509. /// ```
  510. /// impl IntoIterator<Item = impl IntoVNode<'a>>
  511. /// ```
  512. ///
  513. /// As such, all node creation must go through the factory, which is only availble in the component context.
  514. /// These strict requirements make it possible to manage lifetimes and state.
  515. pub trait IntoVNode<'a> {
  516. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
  517. }
  518. pub trait IntoVNodeList<'a> {
  519. fn into_vnode_list(self, cx: NodeFactory<'a>) -> &'a [VNode<'a>];
  520. }
  521. impl<'a, T, V> IntoVNodeList<'a> for T
  522. where
  523. T: IntoIterator<Item = V>,
  524. V: IntoVNode<'a>,
  525. {
  526. fn into_vnode_list(self, cx: NodeFactory<'a>) -> &'a [VNode<'a>] {
  527. let mut nodes = bumpalo::collections::Vec::new_in(cx.bump());
  528. for node in self.into_iter() {
  529. nodes.push(node.into_vnode(cx));
  530. }
  531. if nodes.is_empty() {
  532. nodes.push(VNode::Anchor(VAnchor {
  533. dom_id: empty_cell(),
  534. }));
  535. }
  536. nodes.into_bump_slice()
  537. }
  538. }
  539. /// Child nodes of the parent component.
  540. ///
  541. /// # Example
  542. ///
  543. /// ```rust
  544. /// let children = cx.children();
  545. /// let first_node = &children[0];
  546. /// rsx!{
  547. /// h1 { {first_node} }
  548. /// p { {&children[1..]} }
  549. /// }
  550. /// ```
  551. ///
  552. pub struct ScopeChildren<'a>(pub &'a [VNode<'a>]);
  553. impl Copy for ScopeChildren<'_> {}
  554. impl<'a> Clone for ScopeChildren<'a> {
  555. fn clone(&self) -> Self {
  556. ScopeChildren(self.0)
  557. }
  558. }
  559. impl ScopeChildren<'_> {
  560. // dangerous method - used to fix the associated lifetime
  561. pub(crate) unsafe fn extend_lifetime(self) -> ScopeChildren<'static> {
  562. std::mem::transmute(self)
  563. }
  564. // dangerous method - used to fix the associated lifetime
  565. pub(crate) unsafe fn shorten_lifetime<'a>(self) -> ScopeChildren<'a> {
  566. std::mem::transmute(self)
  567. }
  568. }
  569. impl<'a> IntoVNodeList<'a> for ScopeChildren<'a> {
  570. fn into_vnode_list(self, _: NodeFactory<'a>) -> &'a [VNode<'a>] {
  571. self.0
  572. }
  573. }
  574. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  575. impl<'a> IntoIterator for VNode<'a> {
  576. type Item = VNode<'a>;
  577. type IntoIter = std::iter::Once<Self::Item>;
  578. fn into_iter(self) -> Self::IntoIter {
  579. std::iter::once(self)
  580. }
  581. }
  582. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  583. impl<'a> IntoVNode<'a> for VNode<'a> {
  584. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  585. self
  586. }
  587. }
  588. /// A concrete type provider for closures that build VNode structures.
  589. ///
  590. /// This struct wraps lazy structs that build VNode trees Normally, we cannot perform a blanket implementation over
  591. /// closures, but if we wrap the closure in a concrete type, we can maintain separate implementations of IntoVNode.
  592. ///
  593. ///
  594. /// ```rust
  595. /// LazyNodes::new(|f| f.element("div", [], [], [] None))
  596. /// ```
  597. pub struct LazyNodes<'a, G>
  598. where
  599. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  600. {
  601. inner: G,
  602. _p: PhantomData<&'a ()>,
  603. }
  604. impl<'a, G> LazyNodes<'a, G>
  605. where
  606. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  607. {
  608. pub fn new(f: G) -> Self {
  609. Self {
  610. inner: f,
  611. _p: PhantomData {},
  612. }
  613. }
  614. }
  615. // Our blanket impl
  616. impl<'a, G> IntoVNode<'a> for LazyNodes<'a, G>
  617. where
  618. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  619. {
  620. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  621. (self.inner)(cx)
  622. }
  623. }
  624. // Our blanket impl
  625. impl<'a, G> IntoIterator for LazyNodes<'a, G>
  626. where
  627. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  628. {
  629. type Item = Self;
  630. type IntoIter = std::iter::Once<Self::Item>;
  631. fn into_iter(self) -> Self::IntoIter {
  632. std::iter::once(self)
  633. }
  634. }
  635. // Conveniently, we also support "null" (nothing) passed in
  636. impl IntoVNode<'_> for () {
  637. fn into_vnode(self, cx: NodeFactory) -> VNode {
  638. cx.fragment_from_iter(None as Option<VNode>)
  639. }
  640. }
  641. // Conveniently, we also support "None"
  642. impl IntoVNode<'_> for Option<()> {
  643. fn into_vnode(self, cx: NodeFactory) -> VNode {
  644. cx.fragment_from_iter(None as Option<VNode>)
  645. }
  646. }
  647. impl<'a> IntoVNode<'a> for Option<VNode<'a>> {
  648. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  649. match self {
  650. Some(n) => n,
  651. None => cx.fragment_from_iter(None as Option<VNode>),
  652. }
  653. }
  654. }
  655. impl IntoVNode<'_> for &'static str {
  656. fn into_vnode(self, cx: NodeFactory) -> VNode {
  657. cx.static_text(self)
  658. }
  659. }
  660. impl IntoVNode<'_> for Arguments<'_> {
  661. fn into_vnode(self, cx: NodeFactory) -> VNode {
  662. cx.text(self)
  663. }
  664. }
  665. impl Debug for NodeFactory<'_> {
  666. fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  667. Ok(())
  668. }
  669. }
  670. impl Debug for VNode<'_> {
  671. fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  672. match &self {
  673. VNode::Element(el) => s
  674. .debug_struct("VElement")
  675. .field("name", &el.tag_name)
  676. .field("key", &el.key)
  677. .finish(),
  678. VNode::Text(t) => write!(s, "VText {{ text: {} }}", t.text),
  679. VNode::Anchor(_) => write!(s, "VAnchor"),
  680. VNode::Fragment(frag) => write!(s, "VFragment {{ children: {:?} }}", frag.children),
  681. VNode::Suspended { .. } => write!(s, "VSuspended"),
  682. VNode::Component(comp) => write!(
  683. s,
  684. "VComponent {{ fc: {:?}, children: {:?} }}",
  685. comp.user_fc, comp.children
  686. ),
  687. }
  688. }
  689. }