nodes.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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: InternalHandler<'bump>,
  290. }
  291. pub type InternalHandler<'bump> = &'bump RefCell<Option<InternalListenerCallback<'bump>>>;
  292. type InternalListenerCallback<'bump> = BumpBox<'bump, dyn FnMut(AnyEvent) + 'bump>;
  293. type ExternalListenerCallback<'bump, T> = BumpBox<'bump, dyn FnMut(T) + 'bump>;
  294. /// The callback type generated by the `rsx!` macro when an `on` field is specified for components.
  295. ///
  296. /// This makes it possible to pass `move |evt| {}` style closures into components as property fields.
  297. ///
  298. ///
  299. /// # Example
  300. ///
  301. /// ```rust, ignore
  302. ///
  303. /// rsx!{
  304. /// MyComponent { onclick: move |evt| log::info!("clicked"), }
  305. /// }
  306. ///
  307. /// #[derive(Props)]
  308. /// struct MyProps<'a> {
  309. /// onclick: EventHandler<'a, MouseEvent>,
  310. /// }
  311. ///
  312. /// fn MyComponent(cx: Scope<'a, MyProps<'a>>) -> Element {
  313. /// cx.render(rsx!{
  314. /// button {
  315. /// onclick: move |evt| cx.props.onclick.call(evt),
  316. /// }
  317. /// })
  318. /// }
  319. ///
  320. /// ```
  321. #[derive(Default)]
  322. pub struct EventHandler<'bump, T = ()> {
  323. pub callback: RefCell<Option<ExternalListenerCallback<'bump, T>>>,
  324. }
  325. impl<T> EventHandler<'_, T> {
  326. /// Call this event handler with the appropriate event type
  327. pub fn call(&self, event: T) {
  328. if let Some(callback) = self.callback.borrow_mut().as_mut() {
  329. callback(event);
  330. }
  331. }
  332. /// Forcibly drop the internal handler callback, releasing memory
  333. pub fn release(&self) {
  334. self.callback.replace(None);
  335. }
  336. }
  337. /// Virtual Components for custom user-defined components
  338. /// Only supports the functional syntax
  339. pub struct VComponent<'src> {
  340. pub key: Option<&'src str>,
  341. pub originator: ScopeId,
  342. pub scope: Cell<Option<ScopeId>>,
  343. pub can_memoize: bool,
  344. pub user_fc: *const (),
  345. pub props: RefCell<Option<Box<dyn AnyProps + 'src>>>,
  346. }
  347. pub(crate) struct VComponentProps<P> {
  348. pub render_fn: Component<P>,
  349. pub memo: unsafe fn(&P, &P) -> bool,
  350. pub props: P,
  351. }
  352. pub trait AnyProps {
  353. fn as_ptr(&self) -> *const ();
  354. fn render<'a>(&'a self, bump: &'a ScopeState) -> Element<'a>;
  355. unsafe fn memoize(&self, other: &dyn AnyProps) -> bool;
  356. }
  357. impl<P> AnyProps for VComponentProps<P> {
  358. fn as_ptr(&self) -> *const () {
  359. &self.props as *const _ as *const ()
  360. }
  361. // Safety:
  362. // this will downcat the other ptr as our swallowed type!
  363. // you *must* make this check *before* calling this method
  364. // if your functions are not the same, then you will downcast a pointer into a different type (UB)
  365. unsafe fn memoize(&self, other: &dyn AnyProps) -> bool {
  366. let real_other: &P = &*(other.as_ptr() as *const _ as *const P);
  367. let real_us: &P = &*(self.as_ptr() as *const _ as *const P);
  368. (self.memo)(real_us, real_other)
  369. }
  370. fn render<'a>(&'a self, scope: &'a ScopeState) -> Element<'a> {
  371. let props = unsafe { std::mem::transmute::<&P, &P>(&self.props) };
  372. (self.render_fn)(Scope { scope, props })
  373. }
  374. }
  375. /// This struct provides an ergonomic API to quickly build VNodes.
  376. ///
  377. /// NodeFactory is used to build VNodes in the component's memory space.
  378. /// This struct adds metadata to the final VNode about listeners, attributes, and children
  379. #[derive(Copy, Clone)]
  380. pub struct NodeFactory<'a> {
  381. pub(crate) scope: &'a ScopeState,
  382. pub(crate) bump: &'a Bump,
  383. }
  384. impl<'a> NodeFactory<'a> {
  385. pub fn new(scope: &'a ScopeState) -> NodeFactory<'a> {
  386. NodeFactory {
  387. scope,
  388. bump: &scope.wip_frame().bump,
  389. }
  390. }
  391. #[inline]
  392. pub fn bump(&self) -> &'a bumpalo::Bump {
  393. self.bump
  394. }
  395. /// Directly pass in text blocks without the need to use the format_args macro.
  396. pub fn static_text(&self, text: &'static str) -> VNode<'a> {
  397. VNode::Text(self.bump.alloc(VText {
  398. id: empty_cell(),
  399. text,
  400. is_static: true,
  401. }))
  402. }
  403. /// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
  404. ///
  405. /// Text that's static may be pointer compared, making it cheaper to diff
  406. pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
  407. match args.as_str() {
  408. Some(static_str) => (static_str, true),
  409. None => {
  410. use bumpalo::core_alloc::fmt::Write;
  411. let mut str_buf = bumpalo::collections::String::new_in(self.bump);
  412. str_buf.write_fmt(args).unwrap();
  413. (str_buf.into_bump_str(), false)
  414. }
  415. }
  416. }
  417. /// Create some text that's allocated along with the other vnodes
  418. ///
  419. pub fn text(&self, args: Arguments) -> VNode<'a> {
  420. let (text, is_static) = self.raw_text(args);
  421. VNode::Text(self.bump.alloc(VText {
  422. text,
  423. is_static,
  424. id: empty_cell(),
  425. }))
  426. }
  427. pub fn element(
  428. &self,
  429. el: impl DioxusElement,
  430. listeners: &'a [Listener<'a>],
  431. attributes: &'a [Attribute<'a>],
  432. children: &'a [VNode<'a>],
  433. key: Option<Arguments>,
  434. ) -> VNode<'a> {
  435. self.raw_element(
  436. el.tag_name(),
  437. el.namespace(),
  438. listeners,
  439. attributes,
  440. children,
  441. key,
  442. )
  443. }
  444. pub fn raw_element(
  445. &self,
  446. tag_name: &'static str,
  447. namespace: Option<&'static str>,
  448. listeners: &'a [Listener<'a>],
  449. attributes: &'a [Attribute<'a>],
  450. children: &'a [VNode<'a>],
  451. key: Option<Arguments>,
  452. ) -> VNode<'a> {
  453. let key = key.map(|f| self.raw_text(f).0);
  454. let mut items = self.scope.items.borrow_mut();
  455. for listener in listeners {
  456. let long_listener = unsafe { std::mem::transmute(listener) };
  457. items.listeners.push(long_listener);
  458. }
  459. VNode::Element(self.bump.alloc(VElement {
  460. tag: tag_name,
  461. key,
  462. namespace,
  463. listeners,
  464. attributes,
  465. children,
  466. id: empty_cell(),
  467. parent: empty_cell(),
  468. }))
  469. }
  470. pub fn attr(
  471. &self,
  472. name: &'static str,
  473. val: Arguments,
  474. namespace: Option<&'static str>,
  475. is_volatile: bool,
  476. ) -> Attribute<'a> {
  477. let (value, is_static) = self.raw_text(val);
  478. Attribute {
  479. name,
  480. value,
  481. is_static,
  482. namespace,
  483. is_volatile,
  484. }
  485. }
  486. pub fn component<P>(
  487. &self,
  488. component: fn(Scope<'a, P>) -> Element,
  489. props: P,
  490. key: Option<Arguments>,
  491. ) -> VNode<'a>
  492. where
  493. P: Properties + 'a,
  494. {
  495. let vcomp = self.bump.alloc(VComponent {
  496. key: key.map(|f| self.raw_text(f).0),
  497. scope: Default::default(),
  498. can_memoize: P::IS_STATIC,
  499. user_fc: component as *const (),
  500. originator: self.scope.scope_id(),
  501. props: RefCell::new(Some(Box::new(VComponentProps {
  502. // local_props: RefCell::new(Some(props)),
  503. // heap_props: RefCell::new(None),
  504. props,
  505. memo: P::memoize, // smuggle the memoization function across borders
  506. // i'm sorry but I just need to bludgeon the lifetimes into place here
  507. // this is safe because we're managing all lifetimes to originate from previous calls
  508. // the intricacies of Rust's lifetime system make it difficult to properly express
  509. // the transformation from this specific lifetime to the for<'a> lifetime
  510. render_fn: unsafe { std::mem::transmute(component) },
  511. }))),
  512. });
  513. if !P::IS_STATIC {
  514. let vcomp = &*vcomp;
  515. let vcomp = unsafe { std::mem::transmute(vcomp) };
  516. self.scope.items.borrow_mut().borrowed_props.push(vcomp);
  517. }
  518. VNode::Component(vcomp)
  519. }
  520. pub fn listener(self, event: &'static str, callback: InternalHandler<'a>) -> Listener<'a> {
  521. Listener {
  522. event,
  523. mounted_node: Cell::new(None),
  524. callback,
  525. }
  526. }
  527. pub fn fragment_root<'b, 'c>(
  528. self,
  529. node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
  530. ) -> VNode<'a> {
  531. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  532. for node in node_iter {
  533. nodes.push(node.into_vnode(self));
  534. }
  535. if nodes.is_empty() {
  536. VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
  537. } else {
  538. VNode::Fragment(self.bump.alloc(VFragment {
  539. children: nodes.into_bump_slice(),
  540. key: None,
  541. }))
  542. }
  543. }
  544. pub fn fragment_from_iter<'b, 'c>(
  545. self,
  546. node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
  547. ) -> VNode<'a> {
  548. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  549. for node in node_iter {
  550. nodes.push(node.into_vnode(self));
  551. }
  552. if nodes.is_empty() {
  553. VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
  554. } else {
  555. let children = nodes.into_bump_slice();
  556. if cfg!(debug_assertions)
  557. && children.len() > 1
  558. && children.last().unwrap().key().is_none()
  559. {
  560. // todo: make the backtrace prettier or remove it altogether
  561. log::error!(
  562. r#"
  563. Warning: Each child in an array or iterator should have a unique "key" prop.
  564. Not providing a key will lead to poor performance with lists.
  565. See docs.rs/dioxus for more information.
  566. -------------
  567. {:?}
  568. "#,
  569. backtrace::Backtrace::new()
  570. );
  571. }
  572. VNode::Fragment(self.bump.alloc(VFragment {
  573. children,
  574. key: None,
  575. }))
  576. }
  577. }
  578. // this isn't quite feasible yet
  579. // I think we need some form of interior mutability or state on nodefactory that stores which subtree was created
  580. pub fn create_children(
  581. self,
  582. node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
  583. ) -> Element<'a> {
  584. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  585. for node in node_iter {
  586. nodes.push(node.into_vnode(self));
  587. }
  588. if nodes.is_empty() {
  589. Some(VNode::Placeholder(
  590. self.bump.alloc(VPlaceholder { id: empty_cell() }),
  591. ))
  592. } else {
  593. let children = nodes.into_bump_slice();
  594. Some(VNode::Fragment(self.bump.alloc(VFragment {
  595. children,
  596. key: None,
  597. })))
  598. }
  599. }
  600. pub fn event_handler<T>(self, f: impl FnMut(T) + 'a) -> EventHandler<'a, T> {
  601. let handler: &mut dyn FnMut(T) = self.bump.alloc(f);
  602. let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
  603. let callback = RefCell::new(Some(caller));
  604. EventHandler { callback }
  605. }
  606. }
  607. impl Debug for NodeFactory<'_> {
  608. fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  609. Ok(())
  610. }
  611. }
  612. /// Trait implementations for use in the rsx! and html! macros.
  613. ///
  614. /// ## Details
  615. ///
  616. /// This section provides convenience methods and trait implementations for converting common structs into a format accepted
  617. /// by the macros.
  618. ///
  619. /// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
  620. /// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
  621. /// ```rust, ignore
  622. /// impl IntoIterator<Item = impl IntoVNode<'a>>
  623. /// ```
  624. ///
  625. /// As such, all node creation must go through the factory, which is only available in the component context.
  626. /// These strict requirements make it possible to manage lifetimes and state.
  627. pub trait IntoVNode<'a> {
  628. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
  629. }
  630. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  631. impl<'a> IntoIterator for VNode<'a> {
  632. type Item = VNode<'a>;
  633. type IntoIter = std::iter::Once<Self::Item>;
  634. fn into_iter(self) -> Self::IntoIter {
  635. std::iter::once(self)
  636. }
  637. }
  638. // TODO: do we even need this? It almost seems better not to
  639. // // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  640. impl<'a> IntoVNode<'a> for VNode<'a> {
  641. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  642. self
  643. }
  644. }
  645. // Conveniently, we also support "null" (nothing) passed in
  646. impl IntoVNode<'_> for () {
  647. fn into_vnode(self, cx: NodeFactory) -> VNode {
  648. cx.fragment_from_iter(None as Option<VNode>)
  649. }
  650. }
  651. // Conveniently, we also support "None"
  652. impl IntoVNode<'_> for Option<()> {
  653. fn into_vnode(self, cx: NodeFactory) -> VNode {
  654. cx.fragment_from_iter(None as Option<VNode>)
  655. }
  656. }
  657. impl<'a> IntoVNode<'a> for Option<VNode<'a>> {
  658. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  659. self.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  660. }
  661. }
  662. impl<'a> IntoVNode<'a> for Option<LazyNodes<'a, '_>> {
  663. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  664. match self {
  665. Some(lazy) => lazy.call(cx),
  666. None => VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() })),
  667. }
  668. }
  669. }
  670. impl<'a, 'b> IntoIterator for LazyNodes<'a, 'b> {
  671. type Item = LazyNodes<'a, 'b>;
  672. type IntoIter = std::iter::Once<Self::Item>;
  673. fn into_iter(self) -> Self::IntoIter {
  674. std::iter::once(self)
  675. }
  676. }
  677. impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, 'b> {
  678. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  679. self.call(cx)
  680. }
  681. }
  682. impl<'b> IntoVNode<'_> for &'b str {
  683. fn into_vnode(self, cx: NodeFactory) -> VNode {
  684. cx.text(format_args!("{}", self))
  685. }
  686. }
  687. impl IntoVNode<'_> for String {
  688. fn into_vnode(self, cx: NodeFactory) -> VNode {
  689. cx.text(format_args!("{}", self))
  690. }
  691. }
  692. impl IntoVNode<'_> for Arguments<'_> {
  693. fn into_vnode(self, cx: NodeFactory) -> VNode {
  694. cx.text(self)
  695. }
  696. }
  697. impl<'a> IntoVNode<'a> for &Option<VNode<'a>> {
  698. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  699. self.as_ref()
  700. .map(|f| f.into_vnode(cx))
  701. .unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  702. }
  703. }
  704. impl<'a> IntoVNode<'a> for &VNode<'a> {
  705. fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
  706. // borrowed nodes are strange
  707. self.decouple()
  708. }
  709. }