virtual_dom.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //! # VirtualDOM Implementation for Rust
  2. //! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
  3. //!
  4. //! In this file, multiple items are defined. This file is big, but should be documented well to
  5. //! navigate the innerworkings of the Dom. We try to keep these main mechanics in this file to limit
  6. //! the possible exposed API surface (keep fields private). This particular implementation of VDOM
  7. //! is extremely efficient, but relies on some unsafety under the hood to do things like manage
  8. //! micro-heaps for components. We are currently working on refactoring the safety out into safe(r)
  9. //! abstractions, but current tests (MIRI and otherwise) show no issues with the current implementation.
  10. //!
  11. //! Included is:
  12. //! - The [`VirtualDom`] itself
  13. //! - The [`Scope`] object for mangning component lifecycle
  14. //! - The [`ActiveFrame`] object for managing the Scope`s microheap
  15. //! - The [`Context`] object for exposing VirtualDOM API to components
  16. //! - The [`NodeFactory`] object for lazyily exposing the `Context` API to the nodebuilder API
  17. //! - The [`Hook`] object for exposing state management in components.
  18. //!
  19. //! This module includes just the barebones for a complete VirtualDOM API.
  20. //! Additional functionality is defined in the respective files.
  21. use crate::tasks::TaskQueue;
  22. use crate::{arena::ScopeArena, innerlude::*};
  23. use slotmap::DefaultKey;
  24. use slotmap::SlotMap;
  25. use std::{any::TypeId, fmt::Debug, rc::Rc};
  26. pub type ScopeIdx = DefaultKey;
  27. /// An integrated virtual node system that progresses events and diffs UI trees.
  28. /// Differences are converted into patches which a renderer can use to draw the UI.
  29. pub struct VirtualDom {
  30. /// All mounted components are arena allocated to make additions, removals, and references easy to work with
  31. /// A generational arena is used to re-use slots of deleted scopes without having to resize the underlying arena.
  32. ///
  33. /// This is wrapped in an UnsafeCell because we will need to get mutable access to unique values in unique bump arenas
  34. /// and rusts's guartnees cannot prove that this is safe. We will need to maintain the safety guarantees manually.
  35. pub components: ScopeArena,
  36. /// The index of the root component
  37. /// Should always be the first (gen=0, id=0)
  38. pub base_scope: ScopeIdx,
  39. /// All components dump their updates into a queue to be processed
  40. pub(crate) event_queue: EventQueue,
  41. pub(crate) tasks: TaskQueue,
  42. /// a strong allocation to the "caller" for the original component and its props
  43. #[doc(hidden)]
  44. _root_caller: Rc<OpaqueComponent>,
  45. /// Type of the original cx. This is stored as TypeId so VirtualDom does not need to be generic.
  46. ///
  47. /// Whenver props need to be updated, an Error will be thrown if the new props do not
  48. /// match the props used to create the VirtualDom.
  49. #[doc(hidden)]
  50. _root_prop_type: std::any::TypeId,
  51. }
  52. /// The `RealDomNode` is an ID handle that corresponds to a foreign DOM node.
  53. ///
  54. /// "u64" was chosen for two reasons
  55. /// - 0 cost hashing
  56. /// - use with slotmap and other versioned slot arenas
  57. #[derive(Clone, Copy, Debug, PartialEq)]
  58. pub struct RealDomNode(pub u64);
  59. impl RealDomNode {
  60. pub fn new(id: u64) -> Self {
  61. Self(id)
  62. }
  63. pub fn empty() -> Self {
  64. Self(u64::MIN)
  65. }
  66. }
  67. // ======================================
  68. // Public Methods for the VirtualDom
  69. // ======================================
  70. impl VirtualDom {
  71. /// Create a new instance of the Dioxus Virtual Dom with no properties for the root component.
  72. ///
  73. /// This means that the root component must either consumes its own context, or statics are used to generate the page.
  74. /// The root component can access things like routing in its context.
  75. ///
  76. /// As an end-user, you'll want to use the Renderer's "new" method instead of this method.
  77. /// Directly creating the VirtualDOM is only useful when implementing a new renderer.
  78. ///
  79. ///
  80. /// ```ignore
  81. /// // Directly from a closure
  82. ///
  83. /// let dom = VirtualDom::new(|cx| cx.render(rsx!{ div {"hello world"} }));
  84. ///
  85. /// // or pass in...
  86. ///
  87. /// let root = |cx| {
  88. /// cx.render(rsx!{
  89. /// div {"hello world"}
  90. /// })
  91. /// }
  92. /// let dom = VirtualDom::new(root);
  93. ///
  94. /// // or directly from a fn
  95. ///
  96. /// fn Example(cx: Context<()>) -> VNode {
  97. /// cx.render(rsx!{ div{"hello world"} })
  98. /// }
  99. ///
  100. /// let dom = VirtualDom::new(Example);
  101. /// ```
  102. pub fn new(root: FC<()>) -> Self {
  103. Self::new_with_props(root, ())
  104. }
  105. /// Start a new VirtualDom instance with a dependent cx.
  106. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  107. ///
  108. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  109. /// to toss out the entire tree.
  110. ///
  111. /// ```ignore
  112. /// // Directly from a closure
  113. ///
  114. /// let dom = VirtualDom::new(|cx| cx.render(rsx!{ div {"hello world"} }));
  115. ///
  116. /// // or pass in...
  117. ///
  118. /// let root = |cx| {
  119. /// cx.render(rsx!{
  120. /// div {"hello world"}
  121. /// })
  122. /// }
  123. /// let dom = VirtualDom::new(root);
  124. ///
  125. /// // or directly from a fn
  126. ///
  127. /// fn Example(cx: Context, props: &SomeProps) -> VNode {
  128. /// cx.render(rsx!{ div{"hello world"} })
  129. /// }
  130. ///
  131. /// let dom = VirtualDom::new(Example);
  132. /// ```
  133. pub fn new_with_props<P: Properties + 'static>(root: FC<P>, root_props: P) -> Self {
  134. let components = ScopeArena::new(SlotMap::new());
  135. // Normally, a component would be passed as a child in the RSX macro which automatically produces OpaqueComponents
  136. // Here, we need to make it manually, using an RC to force the Weak reference to stick around for the main scope.
  137. let _root_caller: Rc<OpaqueComponent> = Rc::new(move |scope| {
  138. // let _root_caller: Rc<OpaqueComponent<'static>> = Rc::new(move |scope| {
  139. // the lifetime of this closure is just as long as the lifetime on the scope reference
  140. // this closure moves root props (which is static) into this closure
  141. let props = unsafe { &*(&root_props as *const _) };
  142. root(Context {
  143. props,
  144. scope,
  145. tasks: todo!(),
  146. })
  147. });
  148. // Create a weak reference to the OpaqueComponent for the root scope to use as its render function
  149. let caller_ref = Rc::downgrade(&_root_caller);
  150. // Build a funnel for hooks to send their updates into. The `use_hook` method will call into the update funnel.
  151. let event_queue = EventQueue::default();
  152. let _event_queue = event_queue.clone();
  153. // Make the first scope
  154. // We don't run the component though, so renderers will need to call "rebuild" when they initialize their DOM
  155. let link = components.clone();
  156. let base_scope = components
  157. .with(|arena| {
  158. arena.insert_with_key(move |myidx| {
  159. let event_channel = _event_queue.new_channel(0, myidx);
  160. Scope::new(caller_ref, myidx, None, 0, event_channel, link, &[])
  161. })
  162. })
  163. .unwrap();
  164. Self {
  165. _root_caller,
  166. base_scope,
  167. event_queue,
  168. components,
  169. tasks: TaskQueue::new(),
  170. _root_prop_type: TypeId::of::<P>(),
  171. }
  172. }
  173. }
  174. // ======================================
  175. // Private Methods for the VirtualDom
  176. // ======================================
  177. impl VirtualDom {
  178. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom rom scratch
  179. /// Currently this doesn't do what we want it to do
  180. pub fn rebuild<'s, Dom: RealDom<'s>>(&'s mut self, realdom: &mut Dom) -> Result<()> {
  181. let mut diff_machine = DiffMachine::new(
  182. realdom,
  183. &self.components,
  184. self.base_scope,
  185. self.event_queue.clone(),
  186. );
  187. // Schedule an update and then immediately call it on the root component
  188. // This is akin to a hook being called from a listener and requring a re-render
  189. // Instead, this is done on top-level component
  190. let base = self.components.try_get(self.base_scope)?;
  191. let update = &base.event_channel;
  192. update();
  193. self.progress_completely(&mut diff_machine)?;
  194. Ok(())
  195. }
  196. /// This method is the most sophisticated way of updating the virtual dom after an external event has been triggered.
  197. ///
  198. /// Given a synthetic event, the component that triggered the event, and the index of the callback, this runs the virtual
  199. /// dom to completion, tagging components that need updates, compressing events together, and finally emitting a single
  200. /// change list.
  201. ///
  202. /// If implementing an external renderer, this is the perfect method to combine with an async event loop that waits on
  203. /// listeners, something like this:
  204. ///
  205. /// ```ignore
  206. /// while let Ok(event) = receiver.recv().await {
  207. /// let edits = self.internal_dom.progress_with_event(event)?;
  208. /// for edit in &edits {
  209. /// patch_machine.handle_edit(edit);
  210. /// }
  211. /// }
  212. /// ```
  213. ///
  214. /// Note: this method is not async and does not provide suspense-like functionality. It is up to the renderer to provide the
  215. /// executor and handlers for suspense as show in the example.
  216. ///
  217. /// ```ignore
  218. /// let (sender, receiver) = channel::new();
  219. /// sender.send(EventTrigger::start());
  220. ///
  221. /// let mut dom = VirtualDom::new();
  222. /// dom.suspense_handler(|event| sender.send(event));
  223. ///
  224. /// while let Ok(diffs) = dom.progress_with_event(receiver.recv().await) {
  225. /// render(diffs);
  226. /// }
  227. ///
  228. /// ```
  229. //
  230. // Developer notes:
  231. // ----
  232. // This method has some pretty complex safety guarantees to uphold.
  233. // We interact with bump arenas, raw pointers, and use UnsafeCell to get a partial borrow of the arena.
  234. // The final EditList has edits that pull directly from the Bump Arenas which add significant complexity
  235. // in crafting a 100% safe solution with traditional lifetimes. Consider this method to be internally unsafe
  236. // but the guarantees provide a safe, fast, and efficient abstraction for the VirtualDOM updating framework.
  237. //
  238. // A good project would be to remove all unsafe from this crate and move the unsafety into safer abstractions.
  239. pub fn progress_with_event<'s, Dom: RealDom<'s>>(
  240. &'s mut self,
  241. realdom: &'_ mut Dom,
  242. trigger: EventTrigger,
  243. ) -> Result<()> {
  244. let id = trigger.originator.clone();
  245. self.components.try_get_mut(id)?.call_listener(trigger)?;
  246. let mut diff_machine =
  247. DiffMachine::new(realdom, &self.components, id, self.event_queue.clone());
  248. self.progress_completely(&mut diff_machine)?;
  249. Ok(())
  250. }
  251. /// Consume the event queue, descending depth-first.
  252. /// Only ever run each component once.
  253. ///
  254. /// The DiffMachine logs its progress as it goes which might be useful for certain types of renderers.
  255. pub(crate) fn progress_completely<'a, 'bump, Dom: RealDom<'bump>>(
  256. &'bump self,
  257. diff_machine: &'_ mut DiffMachine<'a, 'bump, Dom>,
  258. ) -> Result<()> {
  259. // Add this component to the list of components that need to be difed
  260. // #[allow(unused_assignments)]
  261. // let mut cur_height: u32 = 0;
  262. // Now, there are events in the queue
  263. let mut updates = self.event_queue.0.as_ref().borrow_mut();
  264. // Order the nodes by their height, we want the nodes with the smallest depth on top
  265. // This prevents us from running the same component multiple times
  266. updates.sort_unstable();
  267. log::debug!("There are: {:#?} updates to be processed", updates.len());
  268. // Iterate through the triggered nodes (sorted by height) and begin to diff them
  269. for update in updates.drain(..) {
  270. log::debug!("Running updates for: {:#?}", update);
  271. // Make sure this isn't a node we've already seen, we don't want to double-render anything
  272. // If we double-renderer something, this would cause memory safety issues
  273. if diff_machine.seen_nodes.contains(&update.idx) {
  274. continue;
  275. }
  276. // Now, all the "seen nodes" are nodes that got notified by running this listener
  277. diff_machine.seen_nodes.insert(update.idx.clone());
  278. // Start a new mutable borrow to components
  279. // We are guaranteeed that this scope is unique because we are tracking which nodes have modified
  280. let cur_component = self.components.try_get_mut(update.idx).unwrap();
  281. // let inner: &'s mut _ = unsafe { &mut *self.components.0.borrow().arena.get() };
  282. // let cur_component = inner.get_mut(update.idx).unwrap();
  283. cur_component.run_scope()?;
  284. // diff_machine.change_list.load_known_root(1);
  285. let (old, new) = (cur_component.old_frame(), cur_component.next_frame());
  286. // let (old, new) = cur_component.get_frames_mut();
  287. diff_machine.diff_node(old, new);
  288. // cur_height = cur_component.height;
  289. // log::debug!(
  290. // "Processing update: {:#?} with height {}",
  291. // &update.idx,
  292. // cur_height
  293. // );
  294. }
  295. Ok(())
  296. }
  297. pub fn base_scope(&self) -> &Scope {
  298. let idx = self.base_scope;
  299. self.components.try_get(idx).unwrap()
  300. }
  301. }
  302. // TODO!
  303. // These impls are actually wrong. The DOM needs to have a mutex implemented.
  304. unsafe impl Sync for VirtualDom {}
  305. unsafe impl Send for VirtualDom {}