nodes.rs 27 KB

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