nodes.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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::{
  6. innerlude::{empty_cell, Context, Element, ElementId, Properties, Scope, ScopeId, ScopeInner},
  7. lazynodes::LazyNodes,
  8. };
  9. use bumpalo::{boxed::Box as BumpBox, Bump};
  10. use std::{
  11. any::Any,
  12. cell::{Cell, RefCell},
  13. fmt::{Arguments, Debug, Formatter},
  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 allocator. 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(&'src 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(&'src 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. pub fn children(&self) -> &[VNode<'src>] {
  147. match &self {
  148. VNode::Fragment(f) => &f.children,
  149. VNode::Component(c) => todo!("children are not accessible through this"),
  150. _ => &[],
  151. }
  152. }
  153. // Create an "owned" version of the vnode.
  154. pub fn decouple(&self) -> VNode<'src> {
  155. match self {
  156. VNode::Text(t) => VNode::Text(*t),
  157. VNode::Element(e) => VNode::Element(*e),
  158. VNode::Component(c) => VNode::Component(*c),
  159. VNode::Suspended(s) => VNode::Suspended(*s),
  160. VNode::Anchor(a) => VNode::Anchor(*a),
  161. VNode::Fragment(f) => VNode::Fragment(VFragment {
  162. children: f.children,
  163. key: f.key,
  164. }),
  165. }
  166. }
  167. }
  168. impl Debug for VNode<'_> {
  169. fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  170. match &self {
  171. VNode::Element(el) => s
  172. .debug_struct("VElement")
  173. .field("name", &el.tag_name)
  174. .field("key", &el.key)
  175. .finish(),
  176. VNode::Text(t) => write!(s, "VText {{ text: {} }}", t.text),
  177. VNode::Anchor(_) => write!(s, "VAnchor"),
  178. VNode::Fragment(frag) => write!(s, "VFragment {{ children: {:?} }}", frag.children),
  179. VNode::Suspended { .. } => write!(s, "VSuspended"),
  180. VNode::Component(comp) => write!(s, "VComponent {{ fc: {:?}}}", comp.user_fc),
  181. }
  182. }
  183. }
  184. /// A placeholder node only generated when Fragments don't have any children.
  185. pub struct VAnchor {
  186. pub dom_id: Cell<Option<ElementId>>,
  187. }
  188. /// A bump-allocated string slice and metadata.
  189. pub struct VText<'src> {
  190. pub text: &'src str,
  191. pub dom_id: Cell<Option<ElementId>>,
  192. pub is_static: bool,
  193. }
  194. /// A list of VNodes with no single root.
  195. pub struct VFragment<'src> {
  196. pub key: Option<&'src str>,
  197. pub children: &'src [VNode<'src>],
  198. }
  199. /// An element like a "div" with children, listeners, and attributes.
  200. pub struct VElement<'a> {
  201. pub tag_name: &'static str,
  202. pub namespace: Option<&'static str>,
  203. pub key: Option<&'a str>,
  204. pub dom_id: Cell<Option<ElementId>>,
  205. pub parent_id: Cell<Option<ElementId>>,
  206. pub listeners: &'a [Listener<'a>],
  207. pub attributes: &'a [Attribute<'a>],
  208. pub children: &'a [VNode<'a>],
  209. }
  210. impl Debug for VElement<'_> {
  211. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  212. f.debug_struct("VElement")
  213. .field("tag_name", &self.tag_name)
  214. .field("namespace", &self.namespace)
  215. .field("key", &self.key)
  216. .field("dom_id", &self.dom_id)
  217. .field("parent_id", &self.parent_id)
  218. .field("listeners", &self.listeners.len())
  219. .field("attributes", &self.attributes)
  220. .field("children", &self.children)
  221. .finish()
  222. }
  223. }
  224. /// A trait for any generic Dioxus Element.
  225. ///
  226. /// This trait provides the ability to use custom elements in the `rsx!` macro.
  227. ///
  228. /// ```rust
  229. /// struct my_element;
  230. ///
  231. /// impl DioxusElement for my_element {
  232. /// const TAG_NAME: "my_element";
  233. /// const NAME_SPACE: None;
  234. /// }
  235. ///
  236. /// let _ = rsx!{
  237. /// my_element {}
  238. /// };
  239. /// ```
  240. pub trait DioxusElement {
  241. const TAG_NAME: &'static str;
  242. const NAME_SPACE: Option<&'static str>;
  243. #[inline]
  244. fn tag_name(&self) -> &'static str {
  245. Self::TAG_NAME
  246. }
  247. #[inline]
  248. fn namespace(&self) -> Option<&'static str> {
  249. Self::NAME_SPACE
  250. }
  251. }
  252. /// An attribute on a DOM node, such as `id="my-thing"` or
  253. /// `href="https://example.com"`.
  254. #[derive(Clone, Debug)]
  255. pub struct Attribute<'a> {
  256. pub name: &'static str,
  257. pub value: &'a str,
  258. pub is_static: bool,
  259. pub is_volatile: bool,
  260. // Doesn't exist in the html spec.
  261. // Used in Dioxus to denote "style" tags.
  262. pub namespace: Option<&'static str>,
  263. }
  264. /// An event listener.
  265. /// IE onclick, onkeydown, etc
  266. pub struct Listener<'bump> {
  267. /// The ID of the node that this listener is mounted to
  268. /// Used to generate the event listener's ID on the DOM
  269. pub mounted_node: Cell<Option<ElementId>>,
  270. /// The type of event to listen for.
  271. ///
  272. /// IE "click" - whatever the renderer needs to attach the listener by name.
  273. pub event: &'static str,
  274. /// The actual callback that the user specified
  275. pub(crate) callback: RefCell<Option<BumpBox<'bump, dyn FnMut(Box<dyn Any + Send>) + 'bump>>>,
  276. }
  277. /// Virtual Components for custom user-defined components
  278. /// Only supports the functional syntax
  279. pub struct VComponent<'src> {
  280. pub key: Option<&'src str>,
  281. pub associated_scope: Cell<Option<*mut ScopeInner>>,
  282. // Function pointer to the FC that was used to generate this component
  283. pub user_fc: *const (),
  284. pub(crate) can_memoize: bool,
  285. // Raw pointer into the bump arena for the props of the component
  286. pub(crate) raw_props: *const (),
  287. // during the "teardown" process we'll take the caller out so it can be dropped properly
  288. pub(crate) caller: Option<VCompCaller<'src>>,
  289. pub(crate) comparator: Option<BumpBox<'src, dyn Fn(&VComponent) -> bool + 'src>>,
  290. }
  291. pub enum VCompCaller<'src> {
  292. Borrowed(BumpBox<'src, dyn for<'b> Fn(&'b ScopeInner) -> Element<'b> + 'src>),
  293. Owned(Box<dyn for<'b> Fn(&'b ScopeInner) -> Element<'b>>),
  294. }
  295. pub struct VSuspended<'a> {
  296. pub task_id: u64,
  297. pub dom_id: Cell<Option<ElementId>>,
  298. #[allow(clippy::type_complexity)]
  299. pub callback: RefCell<Option<BumpBox<'a, dyn FnMut() -> Element<'a> + 'a>>>,
  300. }
  301. /// This struct provides an ergonomic API to quickly build VNodes.
  302. ///
  303. /// NodeFactory is used to build VNodes in the component's memory space.
  304. /// This struct adds metadata to the final VNode about listeners, attributes, and children
  305. #[derive(Copy, Clone)]
  306. pub struct NodeFactory<'a> {
  307. pub(crate) bump: &'a Bump,
  308. }
  309. impl<'a> NodeFactory<'a> {
  310. pub fn new(bump: &'a Bump) -> NodeFactory<'a> {
  311. NodeFactory { bump }
  312. }
  313. #[inline]
  314. pub fn bump(&self) -> &'a bumpalo::Bump {
  315. self.bump
  316. }
  317. /// Directly pass in text blocks without the need to use the format_args macro.
  318. pub fn static_text(&self, text: &'static str) -> VNode<'a> {
  319. VNode::Text(self.bump.alloc(VText {
  320. dom_id: empty_cell(),
  321. text,
  322. is_static: true,
  323. }))
  324. }
  325. /// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
  326. ///
  327. /// Text that's static may be pointer compared, making it cheaper to diff
  328. pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
  329. match args.as_str() {
  330. Some(static_str) => (static_str, true),
  331. None => {
  332. use bumpalo::core_alloc::fmt::Write;
  333. let mut str_buf = bumpalo::collections::String::new_in(self.bump());
  334. str_buf.write_fmt(args).unwrap();
  335. (str_buf.into_bump_str(), false)
  336. }
  337. }
  338. }
  339. /// Create some text that's allocated along with the other vnodes
  340. ///
  341. pub fn text(&self, args: Arguments) -> VNode<'a> {
  342. let (text, is_static) = self.raw_text(args);
  343. VNode::Text(self.bump.alloc(VText {
  344. text,
  345. is_static,
  346. dom_id: empty_cell(),
  347. }))
  348. }
  349. pub fn element<L, A, V>(
  350. &self,
  351. el: impl DioxusElement,
  352. listeners: L,
  353. attributes: A,
  354. children: V,
  355. key: Option<Arguments>,
  356. ) -> VNode<'a>
  357. where
  358. L: 'a + AsRef<[Listener<'a>]>,
  359. A: 'a + AsRef<[Attribute<'a>]>,
  360. V: 'a + AsRef<[VNode<'a>]>,
  361. {
  362. self.raw_element(
  363. el.tag_name(),
  364. el.namespace(),
  365. listeners,
  366. attributes,
  367. children,
  368. key,
  369. )
  370. }
  371. pub fn raw_element<L, A, V>(
  372. &self,
  373. tag_name: &'static str,
  374. namespace: Option<&'static str>,
  375. listeners: L,
  376. attributes: A,
  377. children: V,
  378. key: Option<Arguments>,
  379. ) -> VNode<'a>
  380. where
  381. L: 'a + AsRef<[Listener<'a>]>,
  382. A: 'a + AsRef<[Attribute<'a>]>,
  383. V: 'a + AsRef<[VNode<'a>]>,
  384. {
  385. let listeners: &'a L = self.bump().alloc(listeners);
  386. let listeners = listeners.as_ref();
  387. let attributes: &'a A = self.bump().alloc(attributes);
  388. let attributes = attributes.as_ref();
  389. let children: &'a V = self.bump().alloc(children);
  390. let children = children.as_ref();
  391. let key = key.map(|f| self.raw_text(f).0);
  392. VNode::Element(self.bump().alloc(VElement {
  393. tag_name,
  394. key,
  395. namespace,
  396. listeners,
  397. attributes,
  398. children,
  399. dom_id: empty_cell(),
  400. parent_id: empty_cell(),
  401. }))
  402. }
  403. pub fn attr(
  404. &self,
  405. name: &'static str,
  406. val: Arguments,
  407. namespace: Option<&'static str>,
  408. is_volatile: bool,
  409. ) -> Attribute<'a> {
  410. let (value, is_static) = self.raw_text(val);
  411. Attribute {
  412. name,
  413. value,
  414. is_static,
  415. namespace,
  416. is_volatile,
  417. }
  418. }
  419. pub fn component<P, P1>(
  420. &self,
  421. component: fn(Scope<'a, P>) -> Element<'a>,
  422. props: P,
  423. key: Option<Arguments>,
  424. ) -> VNode<'a>
  425. where
  426. P: Properties + 'a,
  427. {
  428. /*
  429. our strategy:
  430. - unsafe hackery
  431. - lol
  432. - we don't want to hit the global allocator
  433. - allocate into our bump arena
  434. - if the props aren't static, then we convert them into a box which we pass off between renders
  435. */
  436. let bump = self.bump();
  437. // let p = BumpBox::new_in(x, a)
  438. // the best place to allocate the props are the other component's arena
  439. // the second best place is the global allocator
  440. // // if the props are static
  441. // let boxed = if P::IS_STATIC {
  442. // todo!()
  443. // } else {
  444. // todo!()
  445. // }
  446. // let caller = Box::new(|f: &ScopeInner| -> Element {
  447. // //
  448. // component((f, &props))
  449. // });
  450. let user_fc = component as *const ();
  451. // let comparator: &mut dyn Fn(&VComponent) -> bool = bump.alloc_with(|| {
  452. // move |other: &VComponent| {
  453. // if user_fc == other.user_fc {
  454. // // Safety
  455. // // - We guarantee that FC<P> is the same by function pointer
  456. // // - Because FC<P> is the same, then P must be the same (even with generics)
  457. // // - Non-static P are autoderived to memoize as false
  458. // // - This comparator is only called on a corresponding set of bumpframes
  459. // let props_memoized = unsafe {
  460. // let real_other: &P = &*(other.raw_props as *const _ as *const P);
  461. // props.memoize(real_other)
  462. // };
  463. // // It's only okay to memoize if there are no children and the props can be memoized
  464. // // Implementing memoize is unsafe and done automatically with the props trait
  465. // props_memoized
  466. // } else {
  467. // false
  468. // }
  469. // }
  470. // });
  471. // let comparator = Some(unsafe { BumpBox::from_raw(comparator) });
  472. let key = key.map(|f| self.raw_text(f).0);
  473. let caller = match P::IS_STATIC {
  474. true => {
  475. // it just makes sense to box the props
  476. let boxed_props: Box<P> = Box::new(props);
  477. let props_we_know_are_static = todo!();
  478. VCompCaller::Owned(Box::new(|f| {
  479. //
  480. let p = todo!();
  481. todo!()
  482. }))
  483. }
  484. false => VCompCaller::Borrowed({
  485. //
  486. todo!()
  487. // let caller = bump.alloc()
  488. }),
  489. };
  490. todo!()
  491. // let caller: &'a mut dyn for<'b> Fn(&'b ScopeInner) -> Element<'b> =
  492. // bump.alloc(move |scope: &ScopeInner| -> Element {
  493. // log::debug!("calling component renderr {:?}", scope.our_arena_idx);
  494. // let props: &'_ P = unsafe { &*(raw_props as *const P) };
  495. // let scp: &'a ScopeInner = unsafe { std::mem::transmute(scope) };
  496. // let s: Scope<'a, P> = (scp, props);
  497. // let res: Element = component(s);
  498. // unsafe { std::mem::transmute(res) }
  499. // });
  500. // let caller = unsafe { BumpBox::from_raw(caller) };
  501. // VNode::Component(bump.alloc(VComponent {
  502. // user_fc,
  503. // comparator,
  504. // raw_props,
  505. // caller,
  506. // is_static: P::IS_STATIC,
  507. // key,
  508. // can_memoize: P::IS_STATIC,
  509. // drop_props,
  510. // associated_scope: Cell::new(None),
  511. // }))
  512. }
  513. pub fn fragment_from_iter(
  514. self,
  515. node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
  516. ) -> VNode<'a> {
  517. let bump = self.bump();
  518. let mut nodes = bumpalo::collections::Vec::new_in(bump);
  519. for node in node_iter {
  520. nodes.push(node.into_vnode(self));
  521. }
  522. if nodes.is_empty() {
  523. nodes.push(VNode::Anchor(bump.alloc(VAnchor {
  524. dom_id: empty_cell(),
  525. })));
  526. }
  527. let children = nodes.into_bump_slice();
  528. // TODO
  529. // We need a dedicated path in the rsx! macro that will trigger the "you need keys" warning
  530. //
  531. // if cfg!(debug_assertions) {
  532. // if children.len() > 1 {
  533. // if children.last().unwrap().key().is_none() {
  534. // log::error!(
  535. // r#"
  536. // Warning: Each child in an array or iterator should have a unique "key" prop.
  537. // Not providing a key will lead to poor performance with lists.
  538. // See docs.rs/dioxus for more information.
  539. // ---
  540. // To help you identify where this error is coming from, we've generated a backtrace.
  541. // "#,
  542. // );
  543. // }
  544. // }
  545. // }
  546. VNode::Fragment(VFragment {
  547. children,
  548. key: None,
  549. })
  550. }
  551. pub fn annotate_lazy<'z, 'b, F>(f: F) -> Option<LazyNodes<'z, 'b>>
  552. where
  553. F: FnOnce(NodeFactory<'z>) -> VNode<'z> + 'b,
  554. {
  555. Some(LazyNodes::new(f))
  556. }
  557. }
  558. impl Debug for NodeFactory<'_> {
  559. fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  560. Ok(())
  561. }
  562. }
  563. /// Trait implementations for use in the rsx! and html! macros.
  564. ///
  565. /// ## Details
  566. ///
  567. /// This section provides convenience methods and trait implementations for converting common structs into a format accepted
  568. /// by the macros.
  569. ///
  570. /// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
  571. /// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
  572. /// ```
  573. /// impl IntoIterator<Item = impl IntoVNode<'a>>
  574. /// ```
  575. ///
  576. /// As such, all node creation must go through the factory, which is only available in the component context.
  577. /// These strict requirements make it possible to manage lifetimes and state.
  578. pub trait IntoVNode<'a> {
  579. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
  580. }
  581. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  582. impl<'a> IntoIterator for VNode<'a> {
  583. type Item = VNode<'a>;
  584. type IntoIter = std::iter::Once<Self::Item>;
  585. fn into_iter(self) -> Self::IntoIter {
  586. std::iter::once(self)
  587. }
  588. }
  589. // TODO: do we even need this? It almost seems better not to
  590. // // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  591. impl<'a> IntoVNode<'a> for VNode<'a> {
  592. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  593. self
  594. }
  595. }
  596. // Conveniently, we also support "null" (nothing) passed in
  597. impl IntoVNode<'_> for () {
  598. fn into_vnode(self, cx: NodeFactory) -> VNode {
  599. cx.fragment_from_iter(None as Option<VNode>)
  600. }
  601. }
  602. // Conveniently, we also support "None"
  603. impl IntoVNode<'_> for Option<()> {
  604. fn into_vnode(self, cx: NodeFactory) -> VNode {
  605. cx.fragment_from_iter(None as Option<VNode>)
  606. }
  607. }
  608. impl<'a> IntoVNode<'a> for Option<VNode<'a>> {
  609. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  610. self.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  611. }
  612. }
  613. impl<'a> IntoVNode<'a> for Option<LazyNodes<'a, '_>> {
  614. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  615. match self {
  616. Some(lazy) => lazy.call(cx),
  617. None => VNode::Fragment(VFragment {
  618. children: &[],
  619. key: None,
  620. }),
  621. }
  622. }
  623. }
  624. impl<'a> IntoVNode<'a> for LazyNodes<'a, '_> {
  625. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  626. self.call(cx)
  627. }
  628. }
  629. impl IntoVNode<'_> for &'static str {
  630. fn into_vnode(self, cx: NodeFactory) -> VNode {
  631. cx.static_text(self)
  632. }
  633. }
  634. impl IntoVNode<'_> for Arguments<'_> {
  635. fn into_vnode(self, cx: NodeFactory) -> VNode {
  636. cx.text(self)
  637. }
  638. }
  639. /// Access the children elements passed into the component
  640. ///
  641. /// This enables patterns where a component is passed children from its parent.
  642. ///
  643. /// ## Details
  644. ///
  645. /// Unlike React, Dioxus allows *only* lists of children to be passed from parent to child - not arbitrary functions
  646. /// or classes. If you want to generate nodes instead of accepting them as a list, consider declaring a closure
  647. /// on the props that takes Context.
  648. ///
  649. /// If a parent passes children into a component, the child will always re-render when the parent re-renders. In other
  650. /// words, a component cannot be automatically memoized if it borrows nodes from its parent, even if the component's
  651. /// props are valid for the static lifetime.
  652. ///
  653. /// ## Example
  654. ///
  655. /// ```rust
  656. /// const App: FC<()> = |(cx, props)|{
  657. /// cx.render(rsx!{
  658. /// CustomCard {
  659. /// h1 {}
  660. /// p {}
  661. /// }
  662. /// })
  663. /// }
  664. ///
  665. /// const CustomCard: FC<()> = |(cx, props)|{
  666. /// cx.render(rsx!{
  667. /// div {
  668. /// h1 {"Title card"}
  669. /// {props.children}
  670. /// }
  671. /// })
  672. /// }
  673. /// ```
  674. ///
  675. /// ## Notes:
  676. ///
  677. /// This method returns a "ScopeChildren" object. This object is copy-able and preserve the correct lifetime.
  678. pub struct ScopeChildren<'a> {
  679. root: Option<VNode<'a>>,
  680. }
  681. impl Default for ScopeChildren<'_> {
  682. fn default() -> Self {
  683. Self { root: None }
  684. }
  685. }
  686. impl<'a> ScopeChildren<'a> {
  687. pub fn new(root: VNode<'a>) -> Self {
  688. Self { root: Some(root) }
  689. }
  690. pub fn new_option(root: Option<VNode<'a>>) -> Self {
  691. Self { root }
  692. }
  693. }
  694. impl IntoIterator for &ScopeChildren<'_> {
  695. type Item = Self;
  696. type IntoIter = std::iter::Once<Self>;
  697. fn into_iter(self) -> Self::IntoIter {
  698. std::iter::once(self)
  699. }
  700. }
  701. impl<'a> IntoVNode<'a> for &ScopeChildren<'a> {
  702. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  703. match &self.root {
  704. Some(n) => n.decouple(),
  705. None => cx.fragment_from_iter(None as Option<VNode>),
  706. }
  707. }
  708. }