nodes.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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::{Element, Properties, Scope, ScopeId, ScopeState},
  7. lazynodes::LazyNodes,
  8. AnyEvent, Component,
  9. };
  10. use bumpalo::{boxed::Box as BumpBox, Bump};
  11. use std::{
  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(&'src 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: Scope) -> Element {
  81. /// ...
  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. /// Placeholders are a type of placeholder VNode used when fragments don't contain any children.
  94. ///
  95. /// Placeholders cannot be directly constructed via public APIs.
  96. ///
  97. /// # Example
  98. ///
  99. /// ```rust, ignore
  100. /// let mut vdom = VirtualDom::new();
  101. ///
  102. /// let node = vdom.render_vnode(rsx!( Fragment {} ));
  103. ///
  104. /// if let VNode::Fragment(frag) = node {
  105. /// let root = &frag.children[0];
  106. /// assert_eq!(root, VNode::Anchor);
  107. /// }
  108. /// ```
  109. Placeholder(&'src VPlaceholder),
  110. }
  111. impl<'src> VNode<'src> {
  112. /// Get the VNode's "key" used in the keyed diffing algorithm.
  113. pub fn key(&self) -> Option<&'src str> {
  114. match &self {
  115. VNode::Element(el) => el.key,
  116. VNode::Component(c) => c.key,
  117. VNode::Fragment(f) => f.key,
  118. VNode::Text(_t) => None,
  119. VNode::Placeholder(_f) => None,
  120. }
  121. }
  122. /// Get the ElementID of the mounted VNode.
  123. ///
  124. /// Panics if the mounted ID is None or if the VNode is not represented by a single Element.
  125. pub fn mounted_id(&self) -> ElementId {
  126. self.try_mounted_id().unwrap()
  127. }
  128. /// Try to get the ElementID of the mounted VNode.
  129. ///
  130. /// Returns None if the VNode is not mounted, or if the VNode cannot be presented by a mounted ID (Fragment/Component)
  131. pub fn try_mounted_id(&self) -> Option<ElementId> {
  132. match &self {
  133. VNode::Text(el) => el.id.get(),
  134. VNode::Element(el) => el.id.get(),
  135. VNode::Placeholder(el) => el.id.get(),
  136. VNode::Fragment(_) => None,
  137. VNode::Component(_) => None,
  138. }
  139. }
  140. pub(crate) fn children(&self) -> &[VNode<'src>] {
  141. match &self {
  142. VNode::Fragment(f) => f.children,
  143. _ => &[],
  144. }
  145. }
  146. // Create an "owned" version of the vnode.
  147. pub fn decouple(&self) -> VNode<'src> {
  148. match *self {
  149. VNode::Text(t) => VNode::Text(t),
  150. VNode::Element(e) => VNode::Element(e),
  151. VNode::Component(c) => VNode::Component(c),
  152. VNode::Placeholder(a) => VNode::Placeholder(a),
  153. VNode::Fragment(f) => VNode::Fragment(f),
  154. }
  155. }
  156. }
  157. impl Debug for VNode<'_> {
  158. fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  159. match &self {
  160. VNode::Element(el) => s
  161. .debug_struct("VNode::VElement")
  162. .field("name", &el.tag)
  163. .field("key", &el.key)
  164. .field("attrs", &el.attributes)
  165. .field("children", &el.children)
  166. .finish(),
  167. VNode::Text(t) => write!(s, "VNode::VText {{ text: {} }}", t.text),
  168. VNode::Placeholder(_) => write!(s, "VNode::VPlaceholder"),
  169. VNode::Fragment(frag) => {
  170. write!(s, "VNode::VFragment {{ children: {:?} }}", frag.children)
  171. }
  172. VNode::Component(comp) => write!(s, "VNode::VComponent {{ fc: {:?}}}", comp.user_fc),
  173. }
  174. }
  175. }
  176. /// An Element's unique identifier.
  177. ///
  178. /// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
  179. /// unmounted, then the `ElementId` will be reused for a new component.
  180. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
  181. pub struct ElementId(pub usize);
  182. impl std::fmt::Display for ElementId {
  183. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  184. write!(f, "{}", self.0)
  185. }
  186. }
  187. impl ElementId {
  188. pub fn as_u64(self) -> u64 {
  189. self.0 as u64
  190. }
  191. }
  192. fn empty_cell() -> Cell<Option<ElementId>> {
  193. Cell::new(None)
  194. }
  195. /// A placeholder node only generated when Fragments don't have any children.
  196. pub struct VPlaceholder {
  197. pub id: Cell<Option<ElementId>>,
  198. }
  199. /// A bump-allocated string slice and metadata.
  200. pub struct VText<'src> {
  201. pub text: &'src str,
  202. pub id: Cell<Option<ElementId>>,
  203. pub is_static: bool,
  204. }
  205. /// A list of VNodes with no single root.
  206. pub struct VFragment<'src> {
  207. pub key: Option<&'src str>,
  208. /// Fragments can never have zero children. Enforced by NodeFactory.
  209. ///
  210. /// You *can* make a fragment with no children, but it's not a valid fragment and your VDom will panic.
  211. pub children: &'src [VNode<'src>],
  212. }
  213. /// An element like a "div" with children, listeners, and attributes.
  214. pub struct VElement<'a> {
  215. pub tag: &'static str,
  216. pub namespace: Option<&'static str>,
  217. pub key: Option<&'a str>,
  218. pub id: Cell<Option<ElementId>>,
  219. pub parent: Cell<Option<ElementId>>,
  220. pub listeners: &'a [Listener<'a>],
  221. pub attributes: &'a [Attribute<'a>],
  222. pub children: &'a [VNode<'a>],
  223. }
  224. impl Debug for VElement<'_> {
  225. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  226. f.debug_struct("VElement")
  227. .field("tag_name", &self.tag)
  228. .field("namespace", &self.namespace)
  229. .field("key", &self.key)
  230. .field("id", &self.id)
  231. .field("parent", &self.parent)
  232. .field("listeners", &self.listeners.len())
  233. .field("attributes", &self.attributes)
  234. .field("children", &self.children)
  235. .finish()
  236. }
  237. }
  238. /// A trait for any generic Dioxus Element.
  239. ///
  240. /// This trait provides the ability to use custom elements in the `rsx!` macro.
  241. ///
  242. /// ```rust, ignore
  243. /// struct my_element;
  244. ///
  245. /// impl DioxusElement for my_element {
  246. /// const TAG_NAME: "my_element";
  247. /// const NAME_SPACE: None;
  248. /// }
  249. ///
  250. /// let _ = rsx!{
  251. /// my_element {}
  252. /// };
  253. /// ```
  254. pub trait DioxusElement {
  255. const TAG_NAME: &'static str;
  256. const NAME_SPACE: Option<&'static str>;
  257. #[inline]
  258. fn tag_name(&self) -> &'static str {
  259. Self::TAG_NAME
  260. }
  261. #[inline]
  262. fn namespace(&self) -> Option<&'static str> {
  263. Self::NAME_SPACE
  264. }
  265. }
  266. /// An attribute on a DOM node, such as `id="my-thing"` or
  267. /// `href="https://example.com"`.
  268. #[derive(Clone, Debug)]
  269. pub struct Attribute<'a> {
  270. pub name: &'static str,
  271. pub value: &'a str,
  272. pub is_static: bool,
  273. pub is_volatile: bool,
  274. // Doesn't exist in the html spec.
  275. // Used in Dioxus to denote "style" tags.
  276. pub namespace: Option<&'static str>,
  277. }
  278. /// An event listener.
  279. /// IE onclick, onkeydown, etc
  280. pub struct Listener<'bump> {
  281. /// The ID of the node that this listener is mounted to
  282. /// Used to generate the event listener's ID on the DOM
  283. pub mounted_node: Cell<Option<ElementId>>,
  284. /// The type of event to listen for.
  285. ///
  286. /// IE "click" - whatever the renderer needs to attach the listener by name.
  287. pub event: &'static str,
  288. /// The actual callback that the user specified
  289. pub(crate) callback: EventHandler<'bump>,
  290. }
  291. /// The callback based into element event listeners.
  292. pub struct EventHandler<'bump> {
  293. pub callback: &'bump RefCell<Option<ListenerCallback<'bump>>>,
  294. }
  295. impl EventHandler<'_> {
  296. pub fn call(&self, event: AnyEvent) {
  297. if let Some(callback) = self.callback.borrow_mut().as_mut() {
  298. callback(event);
  299. }
  300. }
  301. pub fn release(&self) {
  302. self.callback.replace(None);
  303. }
  304. }
  305. type ListenerCallback<'bump> = BumpBox<'bump, dyn FnMut(AnyEvent) + 'bump>;
  306. impl Copy for EventHandler<'_> {}
  307. impl Clone for EventHandler<'_> {
  308. fn clone(&self) -> Self {
  309. Self {
  310. callback: self.callback,
  311. }
  312. }
  313. }
  314. /// Virtual Components for custom user-defined components
  315. /// Only supports the functional syntax
  316. pub struct VComponent<'src> {
  317. pub key: Option<&'src str>,
  318. pub originator: ScopeId,
  319. pub scope: Cell<Option<ScopeId>>,
  320. pub can_memoize: bool,
  321. pub user_fc: *const (),
  322. pub props: RefCell<Option<Box<dyn AnyProps + 'src>>>,
  323. }
  324. pub(crate) struct VComponentProps<P> {
  325. pub render_fn: Component<P>,
  326. pub memo: unsafe fn(&P, &P) -> bool,
  327. pub props: P,
  328. }
  329. pub trait AnyProps {
  330. fn as_ptr(&self) -> *const ();
  331. fn render<'a>(&'a self, bump: &'a ScopeState) -> Element<'a>;
  332. unsafe fn memoize(&self, other: &dyn AnyProps) -> bool;
  333. }
  334. impl<P> AnyProps for VComponentProps<P> {
  335. fn as_ptr(&self) -> *const () {
  336. &self.props as *const _ as *const ()
  337. }
  338. // Safety:
  339. // this will downcat the other ptr as our swallowed type!
  340. // you *must* make this check *before* calling this method
  341. // if your functions are not the same, then you will downcast a pointer into a different type (UB)
  342. unsafe fn memoize(&self, other: &dyn AnyProps) -> bool {
  343. let real_other: &P = &*(other.as_ptr() as *const _ as *const P);
  344. let real_us: &P = &*(self.as_ptr() as *const _ as *const P);
  345. (self.memo)(real_us, real_other)
  346. }
  347. fn render<'a>(&'a self, scope: &'a ScopeState) -> Element<'a> {
  348. let props = unsafe { std::mem::transmute::<&P, &P>(&self.props) };
  349. (self.render_fn)(Scope { scope, props })
  350. }
  351. }
  352. /// This struct provides an ergonomic API to quickly build VNodes.
  353. ///
  354. /// NodeFactory is used to build VNodes in the component's memory space.
  355. /// This struct adds metadata to the final VNode about listeners, attributes, and children
  356. #[derive(Copy, Clone)]
  357. pub struct NodeFactory<'a> {
  358. pub(crate) scope: &'a ScopeState,
  359. pub(crate) bump: &'a Bump,
  360. }
  361. impl<'a> NodeFactory<'a> {
  362. pub fn new(scope: &'a ScopeState) -> NodeFactory<'a> {
  363. NodeFactory {
  364. scope,
  365. bump: &scope.wip_frame().bump,
  366. }
  367. }
  368. #[inline]
  369. pub fn bump(&self) -> &'a bumpalo::Bump {
  370. self.bump
  371. }
  372. /// Directly pass in text blocks without the need to use the format_args macro.
  373. pub fn static_text(&self, text: &'static str) -> VNode<'a> {
  374. VNode::Text(self.bump.alloc(VText {
  375. id: empty_cell(),
  376. text,
  377. is_static: true,
  378. }))
  379. }
  380. /// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
  381. ///
  382. /// Text that's static may be pointer compared, making it cheaper to diff
  383. pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
  384. match args.as_str() {
  385. Some(static_str) => (static_str, true),
  386. None => {
  387. use bumpalo::core_alloc::fmt::Write;
  388. let mut str_buf = bumpalo::collections::String::new_in(self.bump);
  389. str_buf.write_fmt(args).unwrap();
  390. (str_buf.into_bump_str(), false)
  391. }
  392. }
  393. }
  394. /// Create some text that's allocated along with the other vnodes
  395. ///
  396. pub fn text(&self, args: Arguments) -> VNode<'a> {
  397. let (text, is_static) = self.raw_text(args);
  398. VNode::Text(self.bump.alloc(VText {
  399. text,
  400. is_static,
  401. id: empty_cell(),
  402. }))
  403. }
  404. pub fn element(
  405. &self,
  406. el: impl DioxusElement,
  407. listeners: &'a [Listener<'a>],
  408. attributes: &'a [Attribute<'a>],
  409. children: &'a [VNode<'a>],
  410. key: Option<Arguments>,
  411. ) -> VNode<'a> {
  412. self.raw_element(
  413. el.tag_name(),
  414. el.namespace(),
  415. listeners,
  416. attributes,
  417. children,
  418. key,
  419. )
  420. }
  421. pub fn raw_element(
  422. &self,
  423. tag_name: &'static str,
  424. namespace: Option<&'static str>,
  425. listeners: &'a [Listener<'a>],
  426. attributes: &'a [Attribute<'a>],
  427. children: &'a [VNode<'a>],
  428. key: Option<Arguments>,
  429. ) -> VNode<'a> {
  430. let key = key.map(|f| self.raw_text(f).0);
  431. let mut items = self.scope.items.borrow_mut();
  432. for listener in listeners {
  433. let long_listener = unsafe { std::mem::transmute(listener) };
  434. items.listeners.push(long_listener);
  435. }
  436. VNode::Element(self.bump.alloc(VElement {
  437. tag: tag_name,
  438. key,
  439. namespace,
  440. listeners,
  441. attributes,
  442. children,
  443. id: empty_cell(),
  444. parent: empty_cell(),
  445. }))
  446. }
  447. pub fn attr(
  448. &self,
  449. name: &'static str,
  450. val: Arguments,
  451. namespace: Option<&'static str>,
  452. is_volatile: bool,
  453. ) -> Attribute<'a> {
  454. let (value, is_static) = self.raw_text(val);
  455. Attribute {
  456. name,
  457. value,
  458. is_static,
  459. namespace,
  460. is_volatile,
  461. }
  462. }
  463. pub fn component<P>(
  464. &self,
  465. component: fn(Scope<'a, P>) -> Element,
  466. props: P,
  467. key: Option<Arguments>,
  468. ) -> VNode<'a>
  469. where
  470. P: Properties + 'a,
  471. {
  472. let vcomp = self.bump.alloc(VComponent {
  473. key: key.map(|f| self.raw_text(f).0),
  474. scope: Default::default(),
  475. can_memoize: P::IS_STATIC,
  476. user_fc: component as *const (),
  477. originator: self.scope.scope_id(),
  478. props: RefCell::new(Some(Box::new(VComponentProps {
  479. // local_props: RefCell::new(Some(props)),
  480. // heap_props: RefCell::new(None),
  481. props,
  482. memo: P::memoize, // smuggle the memoization function across borders
  483. // i'm sorry but I just need to bludgeon the lifetimes into place here
  484. // this is safe because we're managing all lifetimes to originate from previous calls
  485. // the intricacies of Rust's lifetime system make it difficult to properly express
  486. // the transformation from this specific lifetime to the for<'a> lifetime
  487. render_fn: unsafe { std::mem::transmute(component) },
  488. }))),
  489. });
  490. if !P::IS_STATIC {
  491. let vcomp = &*vcomp;
  492. let vcomp = unsafe { std::mem::transmute(vcomp) };
  493. self.scope.items.borrow_mut().borrowed_props.push(vcomp);
  494. }
  495. VNode::Component(vcomp)
  496. }
  497. pub fn listener(self, event: &'static str, callback: EventHandler<'a>) -> Listener<'a> {
  498. Listener {
  499. event,
  500. mounted_node: Cell::new(None),
  501. callback,
  502. }
  503. }
  504. pub fn fragment_root<'b, 'c>(
  505. self,
  506. node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
  507. ) -> VNode<'a> {
  508. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  509. for node in node_iter {
  510. nodes.push(node.into_vnode(self));
  511. }
  512. if nodes.is_empty() {
  513. VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
  514. } else {
  515. VNode::Fragment(self.bump.alloc(VFragment {
  516. children: nodes.into_bump_slice(),
  517. key: None,
  518. }))
  519. }
  520. }
  521. pub fn fragment_from_iter<'b, 'c>(
  522. self,
  523. node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
  524. ) -> VNode<'a> {
  525. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  526. for node in node_iter {
  527. nodes.push(node.into_vnode(self));
  528. }
  529. if nodes.is_empty() {
  530. VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
  531. } else {
  532. let children = nodes.into_bump_slice();
  533. if cfg!(debug_assertions)
  534. && children.len() > 1
  535. && children.last().unwrap().key().is_none()
  536. {
  537. // todo: make the backtrace prettier or remove it altogether
  538. log::error!(
  539. r#"
  540. Warning: Each child in an array or iterator should have a unique "key" prop.
  541. Not providing a key will lead to poor performance with lists.
  542. See docs.rs/dioxus for more information.
  543. -------------
  544. {:?}
  545. "#,
  546. backtrace::Backtrace::new()
  547. );
  548. }
  549. VNode::Fragment(self.bump.alloc(VFragment {
  550. children,
  551. key: None,
  552. }))
  553. }
  554. }
  555. // this isn't quite feasible yet
  556. // I think we need some form of interior mutability or state on nodefactory that stores which subtree was created
  557. pub fn create_children(
  558. self,
  559. node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
  560. ) -> Element<'a> {
  561. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  562. for node in node_iter {
  563. nodes.push(node.into_vnode(self));
  564. }
  565. if nodes.is_empty() {
  566. Some(VNode::Placeholder(
  567. self.bump.alloc(VPlaceholder { id: empty_cell() }),
  568. ))
  569. } else {
  570. let children = nodes.into_bump_slice();
  571. Some(VNode::Fragment(self.bump.alloc(VFragment {
  572. children,
  573. key: None,
  574. })))
  575. }
  576. }
  577. }
  578. impl Debug for NodeFactory<'_> {
  579. fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  580. Ok(())
  581. }
  582. }
  583. /// Trait implementations for use in the rsx! and html! macros.
  584. ///
  585. /// ## Details
  586. ///
  587. /// This section provides convenience methods and trait implementations for converting common structs into a format accepted
  588. /// by the macros.
  589. ///
  590. /// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
  591. /// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
  592. /// ```rust, ignore
  593. /// impl IntoIterator<Item = impl IntoVNode<'a>>
  594. /// ```
  595. ///
  596. /// As such, all node creation must go through the factory, which is only available in the component context.
  597. /// These strict requirements make it possible to manage lifetimes and state.
  598. pub trait IntoVNode<'a> {
  599. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
  600. }
  601. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  602. impl<'a> IntoIterator for VNode<'a> {
  603. type Item = VNode<'a>;
  604. type IntoIter = std::iter::Once<Self::Item>;
  605. fn into_iter(self) -> Self::IntoIter {
  606. std::iter::once(self)
  607. }
  608. }
  609. // TODO: do we even need this? It almost seems better not to
  610. // // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  611. impl<'a> IntoVNode<'a> for VNode<'a> {
  612. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  613. self
  614. }
  615. }
  616. // Conveniently, we also support "null" (nothing) passed in
  617. impl IntoVNode<'_> for () {
  618. fn into_vnode(self, cx: NodeFactory) -> VNode {
  619. cx.fragment_from_iter(None as Option<VNode>)
  620. }
  621. }
  622. // Conveniently, we also support "None"
  623. impl IntoVNode<'_> for Option<()> {
  624. fn into_vnode(self, cx: NodeFactory) -> VNode {
  625. cx.fragment_from_iter(None as Option<VNode>)
  626. }
  627. }
  628. impl<'a> IntoVNode<'a> for Option<VNode<'a>> {
  629. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  630. self.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  631. }
  632. }
  633. impl<'a> IntoVNode<'a> for Option<LazyNodes<'a, '_>> {
  634. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  635. match self {
  636. Some(lazy) => lazy.call(cx),
  637. None => VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() })),
  638. }
  639. }
  640. }
  641. impl<'a, 'b> IntoIterator for LazyNodes<'a, 'b> {
  642. type Item = LazyNodes<'a, 'b>;
  643. type IntoIter = std::iter::Once<Self::Item>;
  644. fn into_iter(self) -> Self::IntoIter {
  645. std::iter::once(self)
  646. }
  647. }
  648. impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, 'b> {
  649. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  650. self.call(cx)
  651. }
  652. }
  653. impl<'b> IntoVNode<'_> for &'b str {
  654. fn into_vnode(self, cx: NodeFactory) -> VNode {
  655. cx.text(format_args!("{}", self))
  656. }
  657. }
  658. impl IntoVNode<'_> for String {
  659. fn into_vnode(self, cx: NodeFactory) -> VNode {
  660. cx.text(format_args!("{}", self))
  661. }
  662. }
  663. impl IntoVNode<'_> for Arguments<'_> {
  664. fn into_vnode(self, cx: NodeFactory) -> VNode {
  665. cx.text(self)
  666. }
  667. }
  668. impl<'a> IntoVNode<'a> for &Option<VNode<'a>> {
  669. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  670. self.as_ref()
  671. .map(|f| f.into_vnode(cx))
  672. .unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  673. }
  674. }
  675. impl<'a> IntoVNode<'a> for &VNode<'a> {
  676. fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
  677. // borrowed nodes are strange
  678. self.decouple()
  679. }
  680. }