nodes.old.rs 26 KB

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