nodes.rs 26 KB

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