nodes.rs 23 KB

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