nodes.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. //! Virtual Node Support
  2. //! --------------------
  3. //! VNodes represent lazily-constructed VDom trees that support diffing and event handlers.
  4. //!
  5. //! These VNodes should be *very* cheap and *very* fast to construct - building a full tree should be insanely quick.
  6. use crate::{
  7. events::VirtualEvent,
  8. innerlude::{Context, DomTree, Properties, RealDomNode, Scope, ScopeId, FC},
  9. };
  10. use std::{
  11. cell::Cell,
  12. fmt::{Arguments, Debug, Formatter},
  13. marker::PhantomData,
  14. rc::Rc,
  15. };
  16. pub struct VNode<'src> {
  17. pub kind: VNodeKind<'src>,
  18. pub(crate) dom_id: Cell<RealDomNode>,
  19. pub(crate) key: Option<&'src str>,
  20. }
  21. impl VNode<'_> {
  22. fn key(&self) -> Option<&str> {
  23. self.key
  24. }
  25. }
  26. /// Tools for the base unit of the virtual dom - the VNode
  27. /// VNodes are intended to be quickly-allocated, lightweight enum values.
  28. ///
  29. /// Components will be generating a lot of these very quickly, so we want to
  30. /// limit the amount of heap allocations / overly large enum sizes.
  31. pub enum VNodeKind<'src> {
  32. Text(VText<'src>),
  33. Element(&'src VElement<'src>),
  34. Fragment(VFragment<'src>),
  35. Component(&'src VComponent<'src>),
  36. Suspended { node: Rc<Cell<RealDomNode>> },
  37. }
  38. pub struct VText<'src> {
  39. pub text: &'src str,
  40. pub is_static: bool,
  41. }
  42. pub struct VFragment<'src> {
  43. pub children: &'src [VNode<'src>],
  44. pub is_static: bool,
  45. pub is_error: bool,
  46. }
  47. pub trait DioxusElement {
  48. const TAG_NAME: &'static str;
  49. const NAME_SPACE: Option<&'static str>;
  50. #[inline]
  51. fn tag_name(&self) -> &'static str {
  52. Self::TAG_NAME
  53. }
  54. #[inline]
  55. fn namespace(&self) -> Option<&'static str> {
  56. Self::NAME_SPACE
  57. }
  58. }
  59. pub struct VElement<'a> {
  60. // tag is always static
  61. pub tag_name: &'static str,
  62. pub namespace: Option<&'static str>,
  63. pub static_listeners: bool,
  64. pub listeners: &'a [Listener<'a>],
  65. pub static_attrs: bool,
  66. pub attributes: &'a [Attribute<'a>],
  67. pub static_children: bool,
  68. pub children: &'a [VNode<'a>],
  69. }
  70. /// An attribute on a DOM node, such as `id="my-thing"` or
  71. /// `href="https://example.com"`.
  72. #[derive(Clone, Debug)]
  73. pub struct Attribute<'a> {
  74. pub name: &'static str,
  75. pub value: &'a str,
  76. pub is_static: bool,
  77. pub is_volatile: bool,
  78. // Doesn't exist in the html spec, mostly used to denote "style" tags - could be for any type of group
  79. pub namespace: Option<&'static str>,
  80. }
  81. /// An event listener.
  82. /// IE onclick, onkeydown, etc
  83. pub struct Listener<'bump> {
  84. /// The type of event to listen for.
  85. pub(crate) event: &'static str,
  86. pub scope: ScopeId,
  87. pub mounted_node: &'bump mut Cell<RealDomNode>,
  88. pub(crate) callback: &'bump dyn FnMut(VirtualEvent),
  89. }
  90. /// Virtual Components for custom user-defined components
  91. /// Only supports the functional syntax
  92. pub struct VComponent<'src> {
  93. pub ass_scope: Cell<Option<ScopeId>>,
  94. pub(crate) caller: Rc<dyn Fn(&Scope) -> DomTree>,
  95. pub(crate) children: &'src [VNode<'src>],
  96. pub(crate) comparator: Option<&'src dyn Fn(&VComponent) -> bool>,
  97. pub is_static: bool,
  98. // a pointer into the bump arena (given by the 'src lifetime)
  99. pub(crate) raw_props: *const (),
  100. // a pointer to the raw fn typ
  101. pub(crate) user_fc: *const (),
  102. }
  103. /// This struct provides an ergonomic API to quickly build VNodes.
  104. ///
  105. /// NodeFactory is used to build VNodes in the component's memory space.
  106. /// This struct adds metadata to the final VNode about listeners, attributes, and children
  107. #[derive(Copy, Clone)]
  108. pub struct NodeFactory<'a> {
  109. pub scope_ref: &'a Scope,
  110. pub listener_id: &'a Cell<usize>,
  111. }
  112. impl<'a> NodeFactory<'a> {
  113. #[inline]
  114. pub fn bump(&self) -> &'a bumpalo::Bump {
  115. &self.scope_ref.cur_frame().bump
  116. }
  117. /// Used in a place or two to make it easier to build vnodes from dummy text
  118. pub fn static_text(text: &'static str) -> VNode {
  119. VNode {
  120. dom_id: RealDomNode::empty_cell(),
  121. key: None,
  122. kind: VNodeKind::Text(VText {
  123. text,
  124. is_static: true,
  125. }),
  126. }
  127. }
  128. /// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
  129. ///
  130. /// Text that's static may be pointer compared, making it cheaper to diff
  131. pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
  132. match args.as_str() {
  133. Some(static_str) => (static_str, true),
  134. None => {
  135. use bumpalo::core_alloc::fmt::Write;
  136. let mut s = bumpalo::collections::String::new_in(self.bump());
  137. s.write_fmt(args).unwrap();
  138. (s.into_bump_str(), false)
  139. }
  140. }
  141. }
  142. /// Create some text that's allocated along with the other vnodes
  143. ///
  144. pub fn text(&self, args: Arguments) -> VNode<'a> {
  145. let (text, is_static) = self.raw_text(args);
  146. VNode {
  147. dom_id: RealDomNode::empty_cell(),
  148. key: None,
  149. kind: VNodeKind::Text(VText { text, is_static }),
  150. }
  151. }
  152. pub fn element(
  153. &self,
  154. el: impl DioxusElement,
  155. listeners: &'a mut [Listener<'a>],
  156. attributes: &'a [Attribute<'a>],
  157. children: &'a [VNode<'a>],
  158. key: Option<&'a str>,
  159. ) -> VNode<'a> {
  160. self.raw_element(
  161. el.tag_name(),
  162. el.namespace(),
  163. listeners,
  164. attributes,
  165. children,
  166. key,
  167. )
  168. }
  169. pub fn raw_element(
  170. &self,
  171. tag: &'static str,
  172. namespace: Option<&'static str>,
  173. listeners: &'a mut [Listener],
  174. attributes: &'a [Attribute],
  175. children: &'a [VNode<'a>],
  176. key: Option<&'a str>,
  177. ) -> VNode<'a> {
  178. // We take the references directly from the bump arena
  179. // TODO: this code shouldn't necessarily be here of all places
  180. // It would make more sense to do this in diffing
  181. let mut queue = self.scope_ref.listeners.borrow_mut();
  182. for listener in listeners.iter_mut() {
  183. let mounted = listener.mounted_node as *mut _;
  184. let callback = listener.callback as *const _ as *mut _;
  185. queue.push((mounted, callback))
  186. }
  187. VNode {
  188. dom_id: RealDomNode::empty_cell(),
  189. key,
  190. kind: VNodeKind::Element(self.bump().alloc(VElement {
  191. tag_name: tag,
  192. namespace,
  193. listeners,
  194. attributes,
  195. children,
  196. // todo: wire up more constization
  197. static_listeners: false,
  198. static_attrs: false,
  199. static_children: false,
  200. })),
  201. }
  202. }
  203. pub fn suspended() -> VNode<'static> {
  204. VNode {
  205. dom_id: RealDomNode::empty_cell(),
  206. key: None,
  207. kind: VNodeKind::Suspended {
  208. node: Rc::new(RealDomNode::empty_cell()),
  209. },
  210. }
  211. }
  212. pub fn attr(
  213. &self,
  214. name: &'static str,
  215. val: Arguments,
  216. namespace: Option<&'static str>,
  217. is_volatile: bool,
  218. ) -> Attribute<'a> {
  219. let (value, is_static) = self.raw_text(val);
  220. Attribute {
  221. name,
  222. value,
  223. is_static,
  224. namespace,
  225. is_volatile,
  226. }
  227. }
  228. pub fn component<P>(
  229. &self,
  230. component: FC<P>,
  231. props: P,
  232. key: Option<&'a str>,
  233. children: &'a [VNode<'a>],
  234. ) -> VNode<'a>
  235. where
  236. P: Properties + 'a,
  237. {
  238. // TODO
  239. // It's somewhat wrong to go about props like this
  240. // We don't want the fat part of the fat pointer
  241. // This function does static dispatch so we don't need any VTable stuff
  242. let props = self.bump().alloc(props);
  243. let raw_props = props as *const P as *const ();
  244. let user_fc = component as *const ();
  245. let comparator: Option<&dyn Fn(&VComponent) -> bool> = Some(self.bump().alloc_with(|| {
  246. move |other: &VComponent| {
  247. if user_fc == other.user_fc {
  248. let real_other = unsafe { &*(other.raw_props as *const _ as *const P) };
  249. let props_memoized = unsafe { props.memoize(&real_other) };
  250. match (props_memoized, children.len() == 0) {
  251. (true, true) => true,
  252. _ => false,
  253. }
  254. } else {
  255. false
  256. }
  257. }
  258. }));
  259. let is_static = children.len() == 0 && P::IS_STATIC && key.is_none();
  260. VNode {
  261. key,
  262. dom_id: Cell::new(RealDomNode::empty()),
  263. kind: VNodeKind::Component(self.bump().alloc_with(|| VComponent {
  264. user_fc,
  265. comparator,
  266. raw_props,
  267. children,
  268. caller: NodeFactory::create_component_caller(component, raw_props),
  269. is_static,
  270. ass_scope: Cell::new(None),
  271. })),
  272. }
  273. }
  274. pub fn create_component_caller<'g, P: 'g>(
  275. component: FC<P>,
  276. raw_props: *const (),
  277. ) -> Rc<dyn for<'r> Fn(&'r Scope) -> DomTree<'r>> {
  278. type Captured<'a> = Rc<dyn for<'r> Fn(&'r Scope) -> DomTree<'r> + 'a>;
  279. let caller: Captured = Rc::new(move |scp: &Scope| -> DomTree {
  280. // cast back into the right lifetime
  281. let safe_props: &'_ P = unsafe { &*(raw_props as *const P) };
  282. let cx: Context<P> = Context {
  283. props: safe_props,
  284. scope: scp,
  285. };
  286. let res = component(cx);
  287. let g2 = unsafe { std::mem::transmute(res) };
  288. g2
  289. });
  290. unsafe { std::mem::transmute::<_, Captured<'static>>(caller) }
  291. }
  292. pub fn fragment_from_iter(
  293. self,
  294. node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
  295. ) -> VNode<'a> {
  296. let mut nodes = bumpalo::collections::Vec::new_in(self.bump());
  297. for node in node_iter.into_iter() {
  298. nodes.push(node.into_vnode(self));
  299. }
  300. if cfg!(debug_assertions) {
  301. if nodes.len() > 1 {
  302. if nodes.last().unwrap().key().is_none() {
  303. log::error!(
  304. r#"
  305. Warning: Each child in an array or iterator should have a unique "key" prop.
  306. Not providing a key will lead to poor performance with lists.
  307. See docs.rs/dioxus for more information.
  308. ---
  309. To help you identify where this error is coming from, we've generated a backtrace.
  310. "#,
  311. );
  312. }
  313. }
  314. }
  315. VNode {
  316. dom_id: RealDomNode::empty_cell(),
  317. key: None,
  318. kind: VNodeKind::Fragment(VFragment {
  319. children: nodes.into_bump_slice(),
  320. is_static: false,
  321. is_error: false,
  322. }),
  323. }
  324. }
  325. }
  326. /// Trait implementations for use in the rsx! and html! macros.
  327. ///
  328. /// ## Details
  329. ///
  330. /// This section provides convenience methods and trait implementations for converting common structs into a format accepted
  331. /// by the macros.
  332. ///
  333. /// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
  334. /// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
  335. /// ```
  336. /// impl IntoIterator<Item = impl IntoVNode<'a>>
  337. /// ```
  338. ///
  339. /// As such, all node creation must go through the factory, which is only availble in the component context.
  340. /// These strict requirements make it possible to manage lifetimes and state.
  341. pub trait IntoVNode<'a> {
  342. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
  343. }
  344. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  345. impl<'a> IntoIterator for VNode<'a> {
  346. type Item = VNode<'a>;
  347. type IntoIter = std::iter::Once<Self::Item>;
  348. fn into_iter(self) -> Self::IntoIter {
  349. std::iter::once(self)
  350. }
  351. }
  352. // For the case where a rendered VNode is passed into the rsx! macro through curly braces
  353. impl<'a> IntoVNode<'a> for VNode<'a> {
  354. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  355. self
  356. }
  357. }
  358. // For the case where a rendered VNode is by reference passed into the rsx! macro through curly braces
  359. // This behavior is designed for the cx.children method where child nodes are passed by reference.
  360. //
  361. // Designed to support indexing
  362. impl<'a> IntoVNode<'a> for &VNode<'a> {
  363. fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
  364. let kind = match &self.kind {
  365. VNodeKind::Element(element) => VNodeKind::Element(element),
  366. VNodeKind::Text(old) => VNodeKind::Text(VText {
  367. text: old.text,
  368. is_static: old.is_static,
  369. }),
  370. VNodeKind::Fragment(fragment) => VNodeKind::Fragment(VFragment {
  371. children: fragment.children,
  372. is_static: fragment.is_static,
  373. is_error: false,
  374. }),
  375. VNodeKind::Component(component) => VNodeKind::Component(component),
  376. // todo: it doesn't make much sense to pass in suspended nodes
  377. // I think this is right but I'm not too sure.
  378. VNodeKind::Suspended { node } => VNodeKind::Suspended { node: node.clone() },
  379. };
  380. VNode {
  381. kind,
  382. dom_id: self.dom_id.clone(),
  383. key: self.key.clone(),
  384. }
  385. }
  386. }
  387. /// A concrete type provider for closures that build VNode structures.
  388. ///
  389. /// This struct wraps lazy structs that build VNode trees Normally, we cannot perform a blanket implementation over
  390. /// closures, but if we wrap the closure in a concrete type, we can maintain separate implementations of IntoVNode.
  391. ///
  392. ///
  393. /// ```rust
  394. /// LazyNodes::new(|f| f.element("div", [], [], [] None))
  395. /// ```
  396. pub struct LazyNodes<'a, G>
  397. where
  398. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  399. {
  400. inner: G,
  401. _p: PhantomData<&'a ()>,
  402. }
  403. impl<'a, G> LazyNodes<'a, G>
  404. where
  405. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  406. {
  407. pub fn new(f: G) -> Self {
  408. Self {
  409. inner: f,
  410. _p: PhantomData {},
  411. }
  412. }
  413. }
  414. // Our blanket impl
  415. impl<'a, G> IntoVNode<'a> for LazyNodes<'a, G>
  416. where
  417. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  418. {
  419. fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
  420. (self.inner)(cx)
  421. }
  422. }
  423. // Our blanket impl
  424. impl<'a, G> IntoIterator for LazyNodes<'a, G>
  425. where
  426. G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
  427. {
  428. type Item = Self;
  429. type IntoIter = std::iter::Once<Self::Item>;
  430. fn into_iter(self) -> Self::IntoIter {
  431. std::iter::once(self)
  432. }
  433. }
  434. // Conveniently, we also support "null" (nothing) passed in
  435. impl IntoVNode<'_> for () {
  436. fn into_vnode<'a>(self, cx: NodeFactory<'a>) -> VNode<'a> {
  437. cx.fragment_from_iter(None as Option<VNode>)
  438. }
  439. }
  440. // Conveniently, we also support "None"
  441. impl IntoVNode<'_> for Option<()> {
  442. fn into_vnode<'a>(self, cx: NodeFactory<'a>) -> VNode<'a> {
  443. cx.fragment_from_iter(None as Option<VNode>)
  444. }
  445. }
  446. impl Debug for NodeFactory<'_> {
  447. fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  448. Ok(())
  449. }
  450. }
  451. impl Debug for VNode<'_> {
  452. fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
  453. match &self.kind {
  454. VNodeKind::Element(el) => write!(s, "element, {}", el.tag_name),
  455. VNodeKind::Text(t) => write!(s, "text, {}", t.text),
  456. VNodeKind::Fragment(_) => write!(s, "fragment"),
  457. VNodeKind::Suspended { .. } => write!(s, "suspended"),
  458. VNodeKind::Component(_) => write!(s, "component"),
  459. }
  460. }
  461. }