nodes.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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::{ComponentPtr, 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 are 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. // Create an "owned" version of the vnode.
  141. pub(crate) fn decouple(&self) -> VNode<'src> {
  142. match *self {
  143. VNode::Text(t) => VNode::Text(t),
  144. VNode::Element(e) => VNode::Element(e),
  145. VNode::Component(c) => VNode::Component(c),
  146. VNode::Placeholder(a) => VNode::Placeholder(a),
  147. VNode::Fragment(f) => VNode::Fragment(f),
  148. }
  149. }
  150. }
  151. impl Debug for VNode<'_> {
  152. fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  153. match &self {
  154. VNode::Element(el) => s
  155. .debug_struct("VNode::Element")
  156. .field("name", &el.tag)
  157. .field("key", &el.key)
  158. .field("attrs", &el.attributes)
  159. .field("children", &el.children)
  160. .field("id", &el.id)
  161. .finish(),
  162. VNode::Text(t) => s
  163. .debug_struct("VNode::Text")
  164. .field("text", &t.text)
  165. .field("id", &t.id)
  166. .finish(),
  167. VNode::Placeholder(t) => s
  168. .debug_struct("VNode::Placholder")
  169. .field("id", &t.id)
  170. .finish(),
  171. VNode::Fragment(frag) => s
  172. .debug_struct("VNode::Fragment")
  173. .field("children", &frag.children)
  174. .finish(),
  175. VNode::Component(comp) => s
  176. .debug_struct("VNode::Component")
  177. .field("name", &comp.fn_name)
  178. .field("fnptr", &comp.user_fc)
  179. .field("key", &comp.key)
  180. .field("scope", &comp.scope)
  181. .finish(),
  182. }
  183. }
  184. }
  185. /// An Element's unique identifier.
  186. ///
  187. /// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
  188. /// unmounted, then the `ElementId` will be reused for a new component.
  189. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
  190. pub struct ElementId(pub usize);
  191. impl std::fmt::Display for ElementId {
  192. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  193. write!(f, "{}", self.0)
  194. }
  195. }
  196. impl ElementId {
  197. /// Convertt the ElementId to a `u64`.
  198. pub fn as_u64(self) -> u64 {
  199. self.0 as u64
  200. }
  201. }
  202. fn empty_cell() -> Cell<Option<ElementId>> {
  203. Cell::new(None)
  204. }
  205. /// A placeholder node only generated when Fragments don't have any children.
  206. pub struct VPlaceholder {
  207. /// The [`ElementId`] of the placeholder.
  208. pub id: Cell<Option<ElementId>>,
  209. }
  210. /// A bump-allocated string slice and metadata.
  211. pub struct VText<'src> {
  212. /// The [`ElementId`] of the VText.
  213. pub id: Cell<Option<ElementId>>,
  214. /// The text of the VText.
  215. pub text: &'src str,
  216. /// An indiciation if this VText can be ignored during diffing
  217. /// Is usually only when there are no strings to be formatted (so the text is &'static str)
  218. pub is_static: bool,
  219. }
  220. /// A list of VNodes with no single root.
  221. pub struct VFragment<'src> {
  222. /// The key of the fragment to be used during keyed diffing.
  223. pub key: Option<&'src str>,
  224. /// Fragments can never have zero children. Enforced by NodeFactory.
  225. ///
  226. /// You *can* make a fragment with no children, but it's not a valid fragment and your VDom will panic.
  227. pub children: &'src [VNode<'src>],
  228. }
  229. /// An element like a "div" with children, listeners, and attributes.
  230. pub struct VElement<'a> {
  231. /// The [`ElementId`] of the VText.
  232. pub id: Cell<Option<ElementId>>,
  233. /// The key of the element to be used during keyed diffing.
  234. pub key: Option<&'a str>,
  235. /// The tag name of the element.
  236. ///
  237. /// IE "div"
  238. pub tag: &'static str,
  239. /// The namespace of the VElement
  240. ///
  241. /// IE "svg"
  242. pub namespace: Option<&'static str>,
  243. /// The parent of the Element (if any).
  244. ///
  245. /// Used when bubbling events
  246. pub parent: Cell<Option<ElementId>>,
  247. /// The Listeners of the VElement.
  248. pub listeners: &'a [Listener<'a>],
  249. /// The attributes of the VElement.
  250. pub attributes: &'a [Attribute<'a>],
  251. /// The children of the VElement.
  252. pub children: &'a [VNode<'a>],
  253. }
  254. impl Debug for VElement<'_> {
  255. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  256. f.debug_struct("VElement")
  257. .field("tag_name", &self.tag)
  258. .field("namespace", &self.namespace)
  259. .field("key", &self.key)
  260. .field("id", &self.id)
  261. .field("parent", &self.parent)
  262. .field("listeners", &self.listeners.len())
  263. .field("attributes", &self.attributes)
  264. .field("children", &self.children)
  265. .finish()
  266. }
  267. }
  268. /// A trait for any generic Dioxus Element.
  269. ///
  270. /// This trait provides the ability to use custom elements in the `rsx!` macro.
  271. ///
  272. /// ```rust, ignore
  273. /// struct my_element;
  274. ///
  275. /// impl DioxusElement for my_element {
  276. /// const TAG_NAME: "my_element";
  277. /// const NAME_SPACE: None;
  278. /// }
  279. ///
  280. /// let _ = rsx!{
  281. /// my_element {}
  282. /// };
  283. /// ```
  284. pub trait DioxusElement {
  285. /// The tag name of the element.
  286. const TAG_NAME: &'static str;
  287. /// The namespace of the element.
  288. const NAME_SPACE: Option<&'static str>;
  289. /// The tag name of the element.
  290. #[inline]
  291. fn tag_name(&self) -> &'static str {
  292. Self::TAG_NAME
  293. }
  294. /// The namespace of the element.
  295. #[inline]
  296. fn namespace(&self) -> Option<&'static str> {
  297. Self::NAME_SPACE
  298. }
  299. }
  300. /// An attribute on a DOM node, such as `id="my-thing"` or
  301. /// `href="https://example.com"`.
  302. #[derive(Clone, Debug)]
  303. pub struct Attribute<'a> {
  304. /// The name of the attribute.
  305. pub name: &'static str,
  306. /// The value of the attribute.
  307. pub value: &'a str,
  308. /// An indication if this attribute can be ignored during diffing
  309. ///
  310. /// Usually only when there are no strings to be formatted (so the value is &'static str)
  311. pub is_static: bool,
  312. /// An indication of we should always try and set the attribute.
  313. /// Used in controlled components to ensure changes are propagated.
  314. pub is_volatile: bool,
  315. /// The namespace of the attribute.
  316. ///
  317. /// Doesn't exist in the html spec.
  318. /// Used in Dioxus to denote "style" tags and other attribute groups.
  319. pub namespace: Option<&'static str>,
  320. }
  321. /// An event listener.
  322. /// IE onclick, onkeydown, etc
  323. pub struct Listener<'bump> {
  324. /// The ID of the node that this listener is mounted to
  325. /// Used to generate the event listener's ID on the DOM
  326. pub mounted_node: Cell<Option<ElementId>>,
  327. /// The type of event to listen for.
  328. ///
  329. /// IE "click" - whatever the renderer needs to attach the listener by name.
  330. pub event: &'static str,
  331. /// The actual callback that the user specified
  332. pub(crate) callback: InternalHandler<'bump>,
  333. }
  334. pub type InternalHandler<'bump> = &'bump RefCell<Option<InternalListenerCallback<'bump>>>;
  335. type InternalListenerCallback<'bump> = BumpBox<'bump, dyn FnMut(AnyEvent) + 'bump>;
  336. type ExternalListenerCallback<'bump, T> = BumpBox<'bump, dyn FnMut(T) + 'bump>;
  337. /// The callback type generated by the `rsx!` macro when an `on` field is specified for components.
  338. ///
  339. /// This makes it possible to pass `move |evt| {}` style closures into components as property fields.
  340. ///
  341. ///
  342. /// # Example
  343. ///
  344. /// ```rust, ignore
  345. ///
  346. /// rsx!{
  347. /// MyComponent { onclick: move |evt| log::info!("clicked"), }
  348. /// }
  349. ///
  350. /// #[derive(Props)]
  351. /// struct MyProps<'a> {
  352. /// onclick: EventHandler<'a, MouseEvent>,
  353. /// }
  354. ///
  355. /// fn MyComponent(cx: Scope<'a, MyProps<'a>>) -> Element {
  356. /// cx.render(rsx!{
  357. /// button {
  358. /// onclick: move |evt| cx.props.onclick.call(evt),
  359. /// }
  360. /// })
  361. /// }
  362. ///
  363. /// ```
  364. pub struct EventHandler<'bump, T = ()> {
  365. /// The (optional) callback that the user specified
  366. /// Uses a `RefCell` to allow for interior mutability, and FnMut closures.
  367. pub callback: RefCell<Option<ExternalListenerCallback<'bump, T>>>,
  368. }
  369. impl<'a, T> Default for EventHandler<'a, T> {
  370. fn default() -> Self {
  371. Self {
  372. callback: RefCell::new(None),
  373. }
  374. }
  375. }
  376. impl<T> EventHandler<'_, T> {
  377. /// Call this event handler with the appropriate event type
  378. pub fn call(&self, event: T) {
  379. if let Some(callback) = self.callback.borrow_mut().as_mut() {
  380. callback(event);
  381. }
  382. }
  383. /// Forcibly drop the internal handler callback, releasing memory
  384. pub fn release(&self) {
  385. self.callback.replace(None);
  386. }
  387. }
  388. /// Virtual Components for custom user-defined components
  389. /// Only supports the functional syntax
  390. pub struct VComponent<'src> {
  391. /// The key of the component to be used during keyed diffing.
  392. pub key: Option<&'src str>,
  393. /// The ID of the component.
  394. /// Will not be assigned until after the component has been initialized.
  395. pub scope: Cell<Option<ScopeId>>,
  396. /// An indication if the component is static (can be memozied)
  397. pub can_memoize: bool,
  398. /// The function pointer to the component's render function.
  399. pub user_fc: ComponentPtr,
  400. /// The actual name of the component.
  401. pub fn_name: &'static str,
  402. /// The props of the component.
  403. pub props: RefCell<Option<Box<dyn AnyProps + 'src>>>,
  404. }
  405. pub(crate) struct VComponentProps<P> {
  406. pub render_fn: Component<P>,
  407. pub memo: unsafe fn(&P, &P) -> bool,
  408. pub props: P,
  409. }
  410. pub trait AnyProps {
  411. fn as_ptr(&self) -> *const ();
  412. fn render<'a>(&'a self, bump: &'a ScopeState) -> Element<'a>;
  413. unsafe fn memoize(&self, other: &dyn AnyProps) -> bool;
  414. }
  415. impl<P> AnyProps for VComponentProps<P> {
  416. fn as_ptr(&self) -> *const () {
  417. &self.props as *const _ as *const ()
  418. }
  419. // Safety:
  420. // this will downcast the other ptr as our swallowed type!
  421. // you *must* make this check *before* calling this method
  422. // if your functions are not the same, then you will downcast a pointer into a different type (UB)
  423. unsafe fn memoize(&self, other: &dyn AnyProps) -> bool {
  424. let real_other: &P = &*(other.as_ptr() as *const _ as *const P);
  425. let real_us: &P = &*(self.as_ptr() as *const _ as *const P);
  426. (self.memo)(real_us, real_other)
  427. }
  428. fn render<'a>(&'a self, scope: &'a ScopeState) -> Element<'a> {
  429. let props = unsafe { std::mem::transmute::<&P, &P>(&self.props) };
  430. (self.render_fn)(Scope { scope, props })
  431. }
  432. }
  433. /// This struct provides an ergonomic API to quickly build VNodes.
  434. ///
  435. /// NodeFactory is used to build VNodes in the component's memory space.
  436. /// This struct adds metadata to the final VNode about listeners, attributes, and children
  437. #[derive(Copy, Clone)]
  438. pub struct NodeFactory<'a> {
  439. pub(crate) scope: &'a ScopeState,
  440. pub(crate) bump: &'a Bump,
  441. }
  442. impl<'a> NodeFactory<'a> {
  443. /// Create a new [`NodeFactory`] from a [`Scope`] or [`ScopeState`]
  444. pub fn new(scope: &'a ScopeState) -> NodeFactory<'a> {
  445. NodeFactory {
  446. scope,
  447. bump: &scope.wip_frame().bump,
  448. }
  449. }
  450. /// Get the custom alloactor for this component
  451. #[inline]
  452. pub fn bump(&self) -> &'a bumpalo::Bump {
  453. self.bump
  454. }
  455. /// Directly pass in text blocks without the need to use the format_args macro.
  456. pub fn static_text(&self, text: &'static str) -> VNode<'a> {
  457. VNode::Text(self.bump.alloc(VText {
  458. id: empty_cell(),
  459. text,
  460. is_static: true,
  461. }))
  462. }
  463. /// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
  464. ///
  465. /// Text that's static may be pointer compared, making it cheaper to diff
  466. pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
  467. match args.as_str() {
  468. Some(static_str) => (static_str, true),
  469. None => {
  470. use bumpalo::core_alloc::fmt::Write;
  471. let mut str_buf = bumpalo::collections::String::new_in(self.bump);
  472. str_buf.write_fmt(args).unwrap();
  473. (str_buf.into_bump_str(), false)
  474. }
  475. }
  476. }
  477. /// Create some text that's allocated along with the other vnodes
  478. ///
  479. pub fn text(&self, args: Arguments) -> VNode<'a> {
  480. let (text, is_static) = self.raw_text(args);
  481. VNode::Text(self.bump.alloc(VText {
  482. text,
  483. is_static,
  484. id: empty_cell(),
  485. }))
  486. }
  487. /// Create a new [`VNode::VElement`]
  488. pub fn element(
  489. &self,
  490. el: impl DioxusElement,
  491. listeners: &'a [Listener<'a>],
  492. attributes: &'a [Attribute<'a>],
  493. children: &'a [VNode<'a>],
  494. key: Option<Arguments>,
  495. ) -> VNode<'a> {
  496. self.raw_element(
  497. el.tag_name(),
  498. el.namespace(),
  499. listeners,
  500. attributes,
  501. children,
  502. key,
  503. )
  504. }
  505. /// Create a new [`VNode::VElement`] without the trait bound
  506. ///
  507. /// IE pass in "div" instead of `div`
  508. pub fn raw_element(
  509. &self,
  510. tag_name: &'static str,
  511. namespace: Option<&'static str>,
  512. listeners: &'a [Listener<'a>],
  513. attributes: &'a [Attribute<'a>],
  514. children: &'a [VNode<'a>],
  515. key: Option<Arguments>,
  516. ) -> VNode<'a> {
  517. let key = key.map(|f| self.raw_text(f).0);
  518. let mut items = self.scope.items.borrow_mut();
  519. for listener in listeners {
  520. let long_listener = unsafe { std::mem::transmute(listener) };
  521. items.listeners.push(long_listener);
  522. }
  523. VNode::Element(self.bump.alloc(VElement {
  524. tag: tag_name,
  525. key,
  526. namespace,
  527. listeners,
  528. attributes,
  529. children,
  530. id: empty_cell(),
  531. parent: empty_cell(),
  532. }))
  533. }
  534. /// Create a new [`Attribute`]
  535. pub fn attr(
  536. &self,
  537. name: &'static str,
  538. val: Arguments,
  539. namespace: Option<&'static str>,
  540. is_volatile: bool,
  541. ) -> Attribute<'a> {
  542. let (value, is_static) = self.raw_text(val);
  543. Attribute {
  544. name,
  545. value,
  546. is_static,
  547. namespace,
  548. is_volatile,
  549. }
  550. }
  551. /// Create a new [`VNode::VComponent`]
  552. pub fn component<P>(
  553. &self,
  554. component: fn(Scope<'a, P>) -> Element,
  555. props: P,
  556. key: Option<Arguments>,
  557. fn_name: &'static str,
  558. ) -> VNode<'a>
  559. where
  560. P: Properties + 'a,
  561. {
  562. let vcomp = self.bump.alloc(VComponent {
  563. key: key.map(|f| self.raw_text(f).0),
  564. scope: Default::default(),
  565. can_memoize: P::IS_STATIC,
  566. user_fc: component as ComponentPtr,
  567. fn_name,
  568. props: RefCell::new(Some(Box::new(VComponentProps {
  569. props,
  570. memo: P::memoize, // smuggle the memoization function across borders
  571. // i'm sorry but I just need to bludgeon the lifetimes into place here
  572. // this is safe because we're managing all lifetimes to originate from previous calls
  573. // the intricacies of Rust's lifetime system make it difficult to properly express
  574. // the transformation from this specific lifetime to the for<'a> lifetime
  575. render_fn: unsafe { std::mem::transmute(component) },
  576. }))),
  577. });
  578. if !P::IS_STATIC {
  579. let vcomp = &*vcomp;
  580. let vcomp = unsafe { std::mem::transmute(vcomp) };
  581. self.scope.items.borrow_mut().borrowed_props.push(vcomp);
  582. }
  583. VNode::Component(vcomp)
  584. }
  585. /// Create a new [`Listener`]
  586. pub fn listener(self, event: &'static str, callback: InternalHandler<'a>) -> Listener<'a> {
  587. Listener {
  588. event,
  589. mounted_node: Cell::new(None),
  590. callback,
  591. }
  592. }
  593. /// Create a new [`VNode::VFragment`] from a root of the rsx! call
  594. pub fn fragment_root<'b, 'c>(
  595. self,
  596. node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
  597. ) -> VNode<'a> {
  598. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  599. for node in node_iter {
  600. nodes.push(node.into_vnode(self));
  601. }
  602. if nodes.is_empty() {
  603. VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
  604. } else {
  605. VNode::Fragment(self.bump.alloc(VFragment {
  606. children: nodes.into_bump_slice(),
  607. key: None,
  608. }))
  609. }
  610. }
  611. /// Create a new [`VNode::VFragment`] from any iterator
  612. pub fn fragment_from_iter<'b, 'c>(
  613. self,
  614. node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
  615. ) -> VNode<'a> {
  616. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  617. for node in node_iter {
  618. nodes.push(node.into_vnode(self));
  619. }
  620. if nodes.is_empty() {
  621. VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
  622. } else {
  623. let children = nodes.into_bump_slice();
  624. if cfg!(debug_assertions)
  625. && children.len() > 1
  626. && children.last().unwrap().key().is_none()
  627. {
  628. // todo: make the backtrace prettier or remove it altogether
  629. log::error!(
  630. r#"
  631. Warning: Each child in an array or iterator should have a unique "key" prop.
  632. Not providing a key will lead to poor performance with lists.
  633. See docs.rs/dioxus for more information.
  634. -------------
  635. {:?}
  636. "#,
  637. backtrace::Backtrace::new()
  638. );
  639. }
  640. VNode::Fragment(self.bump.alloc(VFragment {
  641. children,
  642. key: None,
  643. }))
  644. }
  645. }
  646. /// Create a new [`VNode`] from any iterator of children
  647. pub fn create_children(
  648. self,
  649. node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
  650. ) -> Element<'a> {
  651. let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
  652. for node in node_iter {
  653. nodes.push(node.into_vnode(self));
  654. }
  655. if nodes.is_empty() {
  656. Some(VNode::Placeholder(
  657. self.bump.alloc(VPlaceholder { id: empty_cell() }),
  658. ))
  659. } else {
  660. let children = nodes.into_bump_slice();
  661. Some(VNode::Fragment(self.bump.alloc(VFragment {
  662. children,
  663. key: None,
  664. })))
  665. }
  666. }
  667. /// Create a new [`EventHandler`] from an [`FnMut`]
  668. pub fn event_handler<T>(self, f: impl FnMut(T) + 'a) -> EventHandler<'a, T> {
  669. let handler: &mut dyn FnMut(T) = self.bump.alloc(f);
  670. let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
  671. let callback = RefCell::new(Some(caller));
  672. EventHandler { callback }
  673. }
  674. }
  675. impl Debug for NodeFactory<'_> {
  676. fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  677. Ok(())
  678. }
  679. }
  680. /// Trait implementations for use in the rsx! and html! macros.
  681. ///
  682. /// ## Details
  683. ///
  684. /// This section provides convenience methods and trait implementations for converting common structs into a format accepted
  685. /// by the macros.
  686. ///
  687. /// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
  688. /// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
  689. /// ```rust, ignore
  690. /// impl IntoIterator<Item = impl IntoVNode<'a>>
  691. /// ```
  692. ///
  693. /// As such, all node creation must go through the factory, which is only available in the component context.
  694. /// These strict requirements make it possible to manage lifetimes and state.
  695. pub trait IntoVNode<'a> {
  696. /// Convert this into a [`VNode`], using the [`NodeFactory`] as a source of allocation
  697. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
  698. }
  699. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  700. impl<'a> IntoIterator for VNode<'a> {
  701. type Item = VNode<'a>;
  702. type IntoIter = std::iter::Once<Self::Item>;
  703. fn into_iter(self) -> Self::IntoIter {
  704. std::iter::once(self)
  705. }
  706. }
  707. // TODO: do we even need this? It almost seems better not to
  708. // // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  709. impl<'a> IntoVNode<'a> for VNode<'a> {
  710. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  711. self
  712. }
  713. }
  714. // Conveniently, we also support "null" (nothing) passed in
  715. impl IntoVNode<'_> for () {
  716. fn into_vnode(self, cx: NodeFactory) -> VNode {
  717. cx.fragment_from_iter(None as Option<VNode>)
  718. }
  719. }
  720. // Conveniently, we also support "None"
  721. impl IntoVNode<'_> for Option<()> {
  722. fn into_vnode(self, cx: NodeFactory) -> VNode {
  723. cx.fragment_from_iter(None as Option<VNode>)
  724. }
  725. }
  726. impl<'a> IntoVNode<'a> for Option<VNode<'a>> {
  727. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  728. self.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  729. }
  730. }
  731. impl<'a> IntoVNode<'a> for Option<LazyNodes<'a, '_>> {
  732. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  733. match self {
  734. Some(lazy) => lazy.call(cx),
  735. None => VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() })),
  736. }
  737. }
  738. }
  739. impl<'a, 'b> IntoIterator for LazyNodes<'a, 'b> {
  740. type Item = LazyNodes<'a, 'b>;
  741. type IntoIter = std::iter::Once<Self::Item>;
  742. fn into_iter(self) -> Self::IntoIter {
  743. std::iter::once(self)
  744. }
  745. }
  746. impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, 'b> {
  747. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  748. self.call(cx)
  749. }
  750. }
  751. impl<'b> IntoVNode<'_> for &'b str {
  752. fn into_vnode(self, cx: NodeFactory) -> VNode {
  753. cx.text(format_args!("{}", self))
  754. }
  755. }
  756. impl IntoVNode<'_> for String {
  757. fn into_vnode(self, cx: NodeFactory) -> VNode {
  758. cx.text(format_args!("{}", self))
  759. }
  760. }
  761. impl IntoVNode<'_> for Arguments<'_> {
  762. fn into_vnode(self, cx: NodeFactory) -> VNode {
  763. cx.text(self)
  764. }
  765. }
  766. impl<'a> IntoVNode<'a> for &Option<VNode<'a>> {
  767. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  768. self.as_ref()
  769. .map(|f| f.into_vnode(cx))
  770. .unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
  771. }
  772. }
  773. impl<'a> IntoVNode<'a> for &VNode<'a> {
  774. fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
  775. // borrowed nodes are strange
  776. self.decouple()
  777. }
  778. }