virtual_dom.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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::innerlude::*;
  22. use futures_util::Future;
  23. use std::{
  24. any::{Any, TypeId},
  25. pin::Pin,
  26. };
  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. ///
  30. ///
  31. ///
  32. ///
  33. ///
  34. ///
  35. ///
  36. pub struct VirtualDom {
  37. /// All mounted components are arena allocated to make additions, removals, and references easy to work with
  38. /// A generational arena is used to re-use slots of deleted scopes without having to resize the underlying arena.
  39. ///
  40. /// This is wrapped in an UnsafeCell because we will need to get mutable access to unique values in unique bump arenas
  41. /// and rusts's guartnees cannot prove that this is safe. We will need to maintain the safety guarantees manually.
  42. shared: SharedResources,
  43. /// The index of the root component
  44. /// Should always be the first (gen=0, id=0)
  45. base_scope: ScopeId,
  46. scheduler: Scheduler,
  47. // for managing the props that were used to create the dom
  48. #[doc(hidden)]
  49. _root_prop_type: std::any::TypeId,
  50. #[doc(hidden)]
  51. _root_props: std::pin::Pin<Box<dyn std::any::Any>>,
  52. }
  53. impl VirtualDom {
  54. /// Create a new VirtualDOM with a component that does not have special props.
  55. ///
  56. /// # Description
  57. ///
  58. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  59. ///
  60. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  61. /// to toss out the entire tree.
  62. ///
  63. ///
  64. /// # Example
  65. /// ```
  66. /// fn Example(cx: Context<SomeProps>) -> VNode {
  67. /// cx.render(rsx!{ div{"hello world"} })
  68. /// }
  69. ///
  70. /// let dom = VirtualDom::new(Example);
  71. /// ```
  72. ///
  73. /// Note: the VirtualDOM is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  74. pub fn new(root: FC<()>) -> Self {
  75. Self::new_with_props(root, ())
  76. }
  77. /// Create a new VirtualDOM with the given properties for the root component.
  78. ///
  79. /// # Description
  80. ///
  81. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  82. ///
  83. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  84. /// to toss out the entire tree.
  85. ///
  86. ///
  87. /// # Example
  88. /// ```
  89. /// fn Example(cx: Context<SomeProps>) -> VNode {
  90. /// cx.render(rsx!{ div{"hello world"} })
  91. /// }
  92. ///
  93. /// let dom = VirtualDom::new(Example);
  94. /// ```
  95. ///
  96. /// Note: the VirtualDOM is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  97. pub fn new_with_props<P: Properties + 'static>(root: FC<P>, root_props: P) -> Self {
  98. let components = SharedResources::new();
  99. let root_props: Pin<Box<dyn Any>> = Box::pin(root_props);
  100. let props_ptr = root_props.as_ref().downcast_ref::<P>().unwrap() as *const P;
  101. let link = components.clone();
  102. let base_scope = components.insert_scope_with_key(move |myidx| {
  103. let caller = NodeFactory::create_component_caller(root, props_ptr as *const _);
  104. Scope::new(caller, myidx, None, 0, ScopeChildren(&[]), link)
  105. });
  106. Self {
  107. base_scope,
  108. _root_props: root_props,
  109. scheduler: Scheduler::new(components.clone()),
  110. shared: components,
  111. _root_prop_type: TypeId::of::<P>(),
  112. }
  113. }
  114. pub fn launch_in_place(root: FC<()>) -> Self {
  115. let mut s = Self::new(root);
  116. s.rebuild().unwrap();
  117. s
  118. }
  119. /// Creates a new virtualdom and immediately rebuilds it in place, not caring about the RealDom to write into.
  120. ///
  121. pub fn launch_with_props_in_place<P: Properties + 'static>(root: FC<P>, root_props: P) -> Self {
  122. let mut s = Self::new_with_props(root, root_props);
  123. s.rebuild().unwrap();
  124. s
  125. }
  126. pub fn base_scope(&self) -> &Scope {
  127. unsafe { self.shared.get_scope(self.base_scope).unwrap() }
  128. }
  129. pub fn get_scope(&self, id: ScopeId) -> Option<&Scope> {
  130. unsafe { self.shared.get_scope(id) }
  131. }
  132. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom rom scratch
  133. ///
  134. /// The diff machine expects the RealDom's stack to be the root of the application
  135. ///
  136. /// Events like garabge collection, application of refs, etc are not handled by this method and can only be progressed
  137. /// through "run"
  138. ///
  139. pub fn rebuild<'s>(&'s mut self) -> Result<Vec<DomEdit<'s>>> {
  140. let mut edits = Vec::new();
  141. let mut diff_machine = DiffMachine::new(Mutations::new(), self.base_scope, &self.shared);
  142. let cur_component = diff_machine
  143. .get_scope_mut(&self.base_scope)
  144. .expect("The base scope should never be moved");
  145. // We run the component. If it succeeds, then we can diff it and add the changes to the dom.
  146. if cur_component.run_scope().is_ok() {
  147. let meta = diff_machine.create_vnode(cur_component.frames.fin_head());
  148. diff_machine.edit_append_children(meta.added_to_stack);
  149. } else {
  150. // todo: should this be a hard error?
  151. log::warn!(
  152. "Component failed to run succesfully during rebuild.
  153. This does not result in a failed rebuild, but indicates a logic failure within your app."
  154. );
  155. }
  156. Ok(edits)
  157. }
  158. /// Runs the virtualdom immediately, not waiting for any suspended nodes to complete.
  159. ///
  160. /// This method will not wait for any suspended nodes to complete.
  161. pub fn run_immediate<'s>(&'s mut self) -> Result<Mutations<'s>> {
  162. use futures_util::FutureExt;
  163. let mut is_ready = || false;
  164. self.run_with_deadline_and_is_ready(futures_util::future::ready(()), &mut is_ready)
  165. .now_or_never()
  166. .expect("this future will always resolve immediately")
  167. }
  168. /// Runs the virtualdom with no time limit.
  169. ///
  170. /// If there are pending tasks, they will be progressed before returning. This is useful when rendering an application
  171. /// that has suspended nodes or suspended tasks. Be warned - any async tasks running forever will prevent this method
  172. /// from completing. Consider using `run` and specifing a deadline.
  173. pub async fn run_unbounded<'s>(&'s mut self) -> Result<Mutations<'s>> {
  174. self.run_with_deadline(async {}).await
  175. }
  176. /// Run the virtualdom with a deadline.
  177. ///
  178. /// This method will progress async tasks until the deadline is reached. If tasks are completed before the deadline,
  179. /// and no tasks are pending, this method will return immediately. If tasks are still pending, then this method will
  180. /// exhaust the deadline working on them.
  181. ///
  182. /// This method is useful when needing to schedule the virtualdom around other tasks on the main thread to prevent
  183. /// "jank". It will try to finish whatever work it has by the deadline to free up time for other work.
  184. ///
  185. /// Due to platform differences in how time is handled, this method accepts a future that resolves when the deadline
  186. /// is exceeded. However, the deadline won't be met precisely, so you might want to build some wiggle room into the
  187. /// deadline closure manually.
  188. ///
  189. /// The deadline is polled before starting to diff components. This strikes a balance between the overhead of checking
  190. /// the deadline and just completing the work. However, if an individual component takes more than 16ms to render, then
  191. /// the screen will "jank" up. In debug, this will trigger an alert.
  192. ///
  193. /// If there are no in-flight fibers when this method is called, it will await any possible tasks, aborting early if
  194. /// the provided deadline future resolves.
  195. ///
  196. /// For use in the web, it is expected that this method will be called to be executed during "idle times" and the
  197. /// mutations to be applied during the "paint times" IE "animation frames". With this strategy, it is possible to craft
  198. /// entirely jank-free applications that perform a ton of work.
  199. ///
  200. /// # Example
  201. ///
  202. /// ```no_run
  203. /// static App: FC<()> = |cx| rsx!(in cx, div {"hello"} );
  204. /// let mut dom = VirtualDom::new(App);
  205. /// loop {
  206. /// let deadline = TimeoutFuture::from_ms(16);
  207. /// let mutations = dom.run_with_deadline(deadline).await;
  208. /// apply_mutations(mutations);
  209. /// }
  210. /// ```
  211. ///
  212. /// ## Mutations
  213. ///
  214. /// This method returns "mutations" - IE the necessary changes to get the RealDOM to match the VirtualDOM. It also
  215. /// includes a list of NodeRefs that need to be applied and effects that need to be triggered after the RealDOM has
  216. /// applied the edits.
  217. ///
  218. /// Mutations are the only link between the RealDOM and the VirtualDOM.
  219. pub async fn run_with_deadline<'s>(
  220. &'s mut self,
  221. deadline: impl Future<Output = ()>,
  222. ) -> Result<Mutations<'s>> {
  223. use futures_util::FutureExt;
  224. let deadline_future = deadline.shared();
  225. let mut is_ready_deadline = deadline_future.clone();
  226. let mut is_ready = || -> bool { (&mut is_ready_deadline).now_or_never().is_some() };
  227. self.run_with_deadline_and_is_ready(deadline_future, &mut is_ready)
  228. .await
  229. }
  230. /// Runs the virtualdom with a deadline and a custom "check" function.
  231. ///
  232. /// Designed this way so "run_immediate" can re-use all the same rendering logic as "run_with_deadline" but the work
  233. /// queue is completely drained;
  234. async fn run_with_deadline_and_is_ready<'s>(
  235. &'s mut self,
  236. mut deadline: impl Future<Output = ()>,
  237. is_ready: &mut impl FnMut() -> bool,
  238. ) -> Result<Mutations<'s>> {
  239. let mutations = Mutations::new();
  240. loop {
  241. self.scheduler.manually_poll_channels();
  242. // essentially, is idle
  243. if self.scheduler.is_idle() {
  244. let deadline_expired = self.scheduler.wait_for_any_trigger(&mut deadline).await;
  245. if deadline_expired {
  246. return Ok(mutations);
  247. }
  248. }
  249. self.scheduler.consume_pending_events();
  250. match self.scheduler.work_with_deadline(&mut deadline, is_ready) {
  251. FiberResult::Done(mutations) => {
  252. // commit these mutations
  253. }
  254. FiberResult::Interrupted => {
  255. //
  256. return Ok(mutations);
  257. }
  258. }
  259. }
  260. }
  261. pub fn get_event_sender(&self) -> futures_channel::mpsc::UnboundedSender<EventTrigger> {
  262. self.shared.ui_event_sender.clone()
  263. }
  264. }
  265. // TODO!
  266. // These impls are actually wrong. The DOM needs to have a mutex implemented.
  267. unsafe impl Sync for VirtualDom {}
  268. unsafe impl Send for VirtualDom {}