virtual_dom.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. //! # Virtual DOM Implementation for Rust
  2. //!
  3. //! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
  4. use crate::{
  5. any_props::VProps,
  6. arena::{ElementId, ElementRef},
  7. innerlude::{DirtyScope, ErrorBoundary, Mutations, Scheduler, SchedulerMsg, ScopeSlab},
  8. mutations::Mutation,
  9. nodes::RenderReturn,
  10. nodes::{Template, TemplateId},
  11. scheduler::SuspenseId,
  12. scopes::{ScopeId, ScopeState},
  13. AttributeValue, Element, Event, Scope, SuspenseContext,
  14. };
  15. use futures_util::{pin_mut, StreamExt};
  16. use rustc_hash::FxHashMap;
  17. use slab::Slab;
  18. use std::{any::Any, borrow::BorrowMut, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
  19. /// A virtual node system that progresses user events and diffs UI trees.
  20. ///
  21. /// ## Guide
  22. ///
  23. /// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
  24. ///
  25. /// ```rust
  26. /// # use dioxus::prelude::*;
  27. ///
  28. /// #[derive(Props, PartialEq)]
  29. /// struct AppProps {
  30. /// title: String
  31. /// }
  32. ///
  33. /// fn App(cx: Scope<AppProps>) -> Element {
  34. /// cx.render(rsx!(
  35. /// div {"hello, {cx.props.title}"}
  36. /// ))
  37. /// }
  38. /// ```
  39. ///
  40. /// Components may be composed to make complex apps.
  41. ///
  42. /// ```rust
  43. /// # #![allow(unused)]
  44. /// # use dioxus::prelude::*;
  45. ///
  46. /// # #[derive(Props, PartialEq)]
  47. /// # struct AppProps {
  48. /// # title: String
  49. /// # }
  50. ///
  51. /// static ROUTES: &str = "";
  52. ///
  53. /// fn App(cx: Scope<AppProps>) -> Element {
  54. /// cx.render(rsx!(
  55. /// NavBar { routes: ROUTES }
  56. /// Title { "{cx.props.title}" }
  57. /// Footer {}
  58. /// ))
  59. /// }
  60. ///
  61. /// #[inline_props]
  62. /// fn NavBar(cx: Scope, routes: &'static str) -> Element {
  63. /// cx.render(rsx! {
  64. /// div { "Routes: {routes}" }
  65. /// })
  66. /// }
  67. ///
  68. /// fn Footer(cx: Scope) -> Element {
  69. /// cx.render(rsx! { div { "Footer" } })
  70. /// }
  71. ///
  72. /// #[inline_props]
  73. /// fn Title<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
  74. /// cx.render(rsx! {
  75. /// div { id: "title", children }
  76. /// })
  77. /// }
  78. /// ```
  79. ///
  80. /// To start an app, create a [`VirtualDom`] and call [`VirtualDom::rebuild`] to get the list of edits required to
  81. /// draw the UI.
  82. ///
  83. /// ```rust
  84. /// # use dioxus::prelude::*;
  85. /// # fn App(cx: Scope) -> Element { cx.render(rsx! { div {} }) }
  86. ///
  87. /// let mut vdom = VirtualDom::new(App);
  88. /// let edits = vdom.rebuild();
  89. /// ```
  90. ///
  91. /// To call listeners inside the VirtualDom, call [`VirtualDom::handle_event`] with the appropriate event data.
  92. ///
  93. /// ```rust, ignore
  94. /// vdom.handle_event(event);
  95. /// ```
  96. ///
  97. /// While no events are ready, call [`VirtualDom::wait_for_work`] to poll any futures inside the VirtualDom.
  98. ///
  99. /// ```rust, ignore
  100. /// vdom.wait_for_work().await;
  101. /// ```
  102. ///
  103. /// Once work is ready, call [`VirtualDom::render_with_deadline`] to compute the differences between the previous and
  104. /// current UI trees. This will return a [`Mutations`] object that contains Edits, Effects, and NodeRefs that need to be
  105. /// handled by the renderer.
  106. ///
  107. /// ```rust, ignore
  108. /// let mutations = vdom.work_with_deadline(tokio::time::sleep(Duration::from_millis(100)));
  109. ///
  110. /// for edit in mutations.edits {
  111. /// real_dom.apply(edit);
  112. /// }
  113. /// ```
  114. ///
  115. /// To not wait for suspense while diffing the VirtualDom, call [`VirtualDom::render_immediate`] or pass an immediately
  116. /// ready future to [`VirtualDom::render_with_deadline`].
  117. ///
  118. ///
  119. /// ## Building an event loop around Dioxus:
  120. ///
  121. /// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.
  122. /// ```rust, ignore
  123. /// fn app(cx: Scope) -> Element {
  124. /// cx.render(rsx! {
  125. /// div { "Hello World" }
  126. /// })
  127. /// }
  128. ///
  129. /// let dom = VirtualDom::new(app);
  130. ///
  131. /// real_dom.apply(dom.rebuild());
  132. ///
  133. /// loop {
  134. /// select! {
  135. /// _ = dom.wait_for_work() => {}
  136. /// evt = real_dom.wait_for_event() => dom.handle_event(evt),
  137. /// }
  138. ///
  139. /// real_dom.apply(dom.render_immediate());
  140. /// }
  141. /// ```
  142. ///
  143. /// ## Waiting for suspense
  144. ///
  145. /// Because Dioxus supports suspense, you can use it for server-side rendering, static site generation, and other usecases
  146. /// where waiting on portions of the UI to finish rendering is important. To wait for suspense, use the
  147. /// [`VirtualDom::render_with_deadline`] method:
  148. ///
  149. /// ```rust, ignore
  150. /// let dom = VirtualDom::new(app);
  151. ///
  152. /// let deadline = tokio::time::sleep(Duration::from_millis(100));
  153. /// let edits = dom.render_with_deadline(deadline).await;
  154. /// ```
  155. ///
  156. /// ## Use with streaming
  157. ///
  158. /// If not all rendering is done by the deadline, it might be worthwhile to stream the rest later. To do this, we
  159. /// suggest rendering with a deadline, and then looping between [`VirtualDom::wait_for_work`] and render_immediate until
  160. /// no suspended work is left.
  161. ///
  162. /// ```rust, ignore
  163. /// let dom = VirtualDom::new(app);
  164. ///
  165. /// let deadline = tokio::time::sleep(Duration::from_millis(20));
  166. /// let edits = dom.render_with_deadline(deadline).await;
  167. ///
  168. /// real_dom.apply(edits);
  169. ///
  170. /// while dom.has_suspended_work() {
  171. /// dom.wait_for_work().await;
  172. /// real_dom.apply(dom.render_immediate());
  173. /// }
  174. /// ```
  175. pub struct VirtualDom {
  176. // Maps a template path to a map of byteindexes to templates
  177. pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
  178. pub(crate) scopes: ScopeSlab,
  179. pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
  180. pub(crate) scheduler: Rc<Scheduler>,
  181. // Every element is actually a dual reference - one to the template and the other to the dynamic node in that template
  182. pub(crate) elements: Slab<ElementRef>,
  183. // While diffing we need some sort of way of breaking off a stream of suspended mutations.
  184. pub(crate) scope_stack: Vec<ScopeId>,
  185. pub(crate) collected_leaves: Vec<SuspenseId>,
  186. // Whenever a suspense tree is finished, we push its boundary onto this stack.
  187. // When "render_with_deadline" is called, we pop the stack and return the mutations
  188. pub(crate) finished_fibers: Vec<ScopeId>,
  189. pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>,
  190. pub(crate) mutations: Mutations<'static>,
  191. }
  192. impl VirtualDom {
  193. /// Create a new VirtualDom with a component that does not have special props.
  194. ///
  195. /// # Description
  196. ///
  197. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  198. ///
  199. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  200. /// to toss out the entire tree.
  201. ///
  202. ///
  203. /// # Example
  204. /// ```rust, ignore
  205. /// fn Example(cx: Scope) -> Element {
  206. /// cx.render(rsx!( div { "hello world" } ))
  207. /// }
  208. ///
  209. /// let dom = VirtualDom::new(Example);
  210. /// ```
  211. ///
  212. /// Note: the VirtualDom is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  213. pub fn new(app: fn(Scope) -> Element) -> Self {
  214. Self::new_with_props(app, ())
  215. }
  216. /// Create a new VirtualDom with the given properties for the root component.
  217. ///
  218. /// # Description
  219. ///
  220. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  221. ///
  222. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  223. /// to toss out the entire tree.
  224. ///
  225. ///
  226. /// # Example
  227. /// ```rust, ignore
  228. /// #[derive(PartialEq, Props)]
  229. /// struct SomeProps {
  230. /// name: &'static str
  231. /// }
  232. ///
  233. /// fn Example(cx: Scope<SomeProps>) -> Element {
  234. /// cx.render(rsx!{ div{ "hello {cx.props.name}" } })
  235. /// }
  236. ///
  237. /// let dom = VirtualDom::new(Example);
  238. /// ```
  239. ///
  240. /// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
  241. ///
  242. /// ```rust, ignore
  243. /// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
  244. /// let mutations = dom.rebuild();
  245. /// ```
  246. pub fn new_with_props<P: 'static>(root: fn(Scope<P>) -> Element, root_props: P) -> Self {
  247. let (tx, rx) = futures_channel::mpsc::unbounded();
  248. let mut dom = Self {
  249. rx,
  250. scheduler: Scheduler::new(tx),
  251. templates: Default::default(),
  252. scopes: Default::default(),
  253. elements: Default::default(),
  254. scope_stack: Vec::new(),
  255. dirty_scopes: BTreeSet::new(),
  256. collected_leaves: Vec::new(),
  257. finished_fibers: Vec::new(),
  258. mutations: Mutations::default(),
  259. };
  260. let root = dom.new_scope(
  261. Box::new(VProps::new(root, |_, _| unreachable!(), root_props)),
  262. "app",
  263. );
  264. // The root component is always a suspense boundary for any async children
  265. // This could be unexpected, so we might rethink this behavior later
  266. //
  267. // We *could* just panic if the suspense boundary is not found
  268. root.provide_context(Rc::new(SuspenseContext::new(ScopeId(0))));
  269. // Unlike react, we provide a default error boundary that just renders the error as a string
  270. root.provide_context(Rc::new(ErrorBoundary::new(ScopeId(0))));
  271. // the root element is always given element ID 0 since it's the container for the entire tree
  272. dom.elements.insert(ElementRef::none());
  273. dom
  274. }
  275. /// Get the state for any scope given its ID
  276. ///
  277. /// This is useful for inserting or removing contexts from a scope, or rendering out its root node
  278. pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
  279. self.scopes.get(id)
  280. }
  281. /// Get the single scope at the top of the VirtualDom tree that will always be around
  282. ///
  283. /// This scope has a ScopeId of 0 and is the root of the tree
  284. pub fn base_scope(&self) -> &ScopeState {
  285. self.scopes.get(ScopeId(0)).unwrap()
  286. }
  287. /// Build the virtualdom with a global context inserted into the base scope
  288. ///
  289. /// This is useful for what is essentially dependency injection when building the app
  290. pub fn with_root_context<T: Clone + 'static>(self, context: T) -> Self {
  291. self.base_scope().provide_context(context);
  292. self
  293. }
  294. /// Manually mark a scope as requiring a re-render
  295. ///
  296. /// Whenever the VirtualDom "works", it will re-render this scope
  297. pub fn mark_dirty(&mut self, id: ScopeId) {
  298. if let Some(scope) = self.scopes.get(id) {
  299. let height = scope.height;
  300. self.dirty_scopes.insert(DirtyScope { height, id });
  301. }
  302. }
  303. /// Determine whether or not a scope is currently in a suspended state
  304. ///
  305. /// This does not mean the scope is waiting on its own futures, just that the tree that the scope exists in is
  306. /// currently suspended.
  307. pub fn is_scope_suspended(&self, id: ScopeId) -> bool {
  308. !self.scopes[id]
  309. .consume_context::<Rc<SuspenseContext>>()
  310. .unwrap()
  311. .waiting_on
  312. .borrow()
  313. .is_empty()
  314. }
  315. /// Determine if the tree is at all suspended. Used by SSR and other outside mechanisms to determine if the tree is
  316. /// ready to be rendered.
  317. pub fn has_suspended_work(&self) -> bool {
  318. !self.scheduler.leaves.borrow().is_empty()
  319. }
  320. /// Call a listener inside the VirtualDom with data from outside the VirtualDom.
  321. ///
  322. /// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
  323. /// this method does not give any indication as to the success of the listener call. If the listener is not found,
  324. /// nothing will happen.
  325. ///
  326. /// It is up to the listeners themselves to mark nodes as dirty.
  327. ///
  328. /// If you have multiple events, you can call this method multiple times before calling "render_with_deadline"
  329. pub fn handle_event(
  330. &mut self,
  331. name: &str,
  332. data: Rc<dyn Any>,
  333. element: ElementId,
  334. bubbles: bool,
  335. ) {
  336. /*
  337. ------------------------
  338. The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
  339. we find the target path.
  340. With the target path, we try and move up to the parent until there is no parent.
  341. Due to how bubbling works, we call the listeners before walking to the parent.
  342. If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order.
  343. ----------------------
  344. For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the
  345. right.
  346. | <-- yes (is ascendant)
  347. | | | <-- no (is not direct ascendant)
  348. | | <-- yes (is ascendant)
  349. | | | | | <--- target element, break early, don't check other listeners
  350. | | | <-- no, broke early
  351. | <-- no, broke early
  352. */
  353. let mut parent_path = self.elements.get(element.0);
  354. let mut listeners = vec![];
  355. // We will clone this later. The data itself is wrapped in RC to be used in callbacks if required
  356. let uievent = Event {
  357. propagates: Rc::new(Cell::new(bubbles)),
  358. data,
  359. };
  360. // Loop through each dynamic attribute in this template before moving up to the template's parent.
  361. while let Some(el_ref) = parent_path {
  362. // safety: we maintain references of all vnodes in the element slab
  363. let template = unsafe { el_ref.template.unwrap().as_ref() };
  364. let node_template = template.template.get();
  365. let target_path = el_ref.path;
  366. for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
  367. let this_path = node_template.attr_paths[idx];
  368. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  369. if attr.name.trim_start_matches("on") == name
  370. && target_path.is_decendant(&this_path)
  371. {
  372. listeners.push(&attr.value);
  373. // Break if the event doesn't bubble anyways
  374. if !bubbles {
  375. break;
  376. }
  377. // Break if this is the exact target element.
  378. // This means we won't call two listeners with the same name on the same element. This should be
  379. // documented, or be rejected from the rsx! macro outright
  380. if target_path == this_path {
  381. break;
  382. }
  383. }
  384. }
  385. // Now that we've accumulated all the parent attributes for the target element, call them in reverse order
  386. // We check the bubble state between each call to see if the event has been stopped from bubbling
  387. for listener in listeners.drain(..).rev() {
  388. if let AttributeValue::Listener(listener) = listener {
  389. if let Some(cb) = listener.borrow_mut().as_deref_mut() {
  390. cb(uievent.clone());
  391. }
  392. if !uievent.propagates.get() {
  393. return;
  394. }
  395. }
  396. }
  397. parent_path = template.parent.and_then(|id| self.elements.get(id.0));
  398. }
  399. }
  400. /// Wait for the scheduler to have any work.
  401. ///
  402. /// This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when
  403. /// any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method
  404. /// will exit.
  405. ///
  406. /// This method is cancel-safe, so you're fine to discard the future in a select block.
  407. ///
  408. /// This lets us poll async tasks and suspended trees during idle periods without blocking the main thread.
  409. ///
  410. /// # Example
  411. ///
  412. /// ```rust, ignore
  413. /// let dom = VirtualDom::new(App);
  414. /// let sender = dom.get_scheduler_channel();
  415. /// ```
  416. pub async fn wait_for_work(&mut self) {
  417. let mut some_msg = None;
  418. loop {
  419. match some_msg.take() {
  420. // If a bunch of messages are ready in a sequence, try to pop them off synchronously
  421. Some(msg) => match msg {
  422. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  423. SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
  424. SchedulerMsg::SuspenseNotified(id) => self.handle_suspense_wakeup(id),
  425. },
  426. // If they're not ready, then we should wait for them to be ready
  427. None => {
  428. match self.rx.try_next() {
  429. Ok(Some(val)) => some_msg = Some(val),
  430. Ok(None) => return,
  431. Err(_) => {
  432. // If we have any dirty scopes, or finished fiber trees then we should exit
  433. if !self.dirty_scopes.is_empty() || !self.finished_fibers.is_empty() {
  434. return;
  435. }
  436. some_msg = self.rx.next().await
  437. }
  438. }
  439. }
  440. }
  441. }
  442. }
  443. /// Process all events in the queue until there are no more left
  444. pub fn process_events(&mut self) {
  445. while let Ok(Some(msg)) = self.rx.try_next() {
  446. match msg {
  447. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  448. SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
  449. SchedulerMsg::SuspenseNotified(id) => self.handle_suspense_wakeup(id),
  450. }
  451. }
  452. }
  453. /// Replace a template at runtime. This will re-render all components that use this template.
  454. /// This is the primitive that enables hot-reloading.
  455. ///
  456. /// The caller must ensure that the template refrences the same dynamic attributes and nodes as the original template.
  457. ///
  458. /// This will only replace the the parent template, not any nested templates.
  459. pub fn replace_template(&mut self, template: Template<'static>) {
  460. self.register_template_first_byte_index(template);
  461. // iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
  462. for scope in self.scopes.iter() {
  463. if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
  464. if sync.template.get().name.rsplit_once(':').unwrap().0
  465. == template.name.rsplit_once(':').unwrap().0
  466. {
  467. let height = scope.height;
  468. self.dirty_scopes.insert(DirtyScope {
  469. height,
  470. id: scope.id,
  471. });
  472. }
  473. }
  474. }
  475. }
  476. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
  477. ///
  478. /// The mutations item expects the RealDom's stack to be the root of the application.
  479. ///
  480. /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
  481. /// root component will be ran once and then diffed. All updates will flow out as mutations.
  482. ///
  483. /// All state stored in components will be completely wiped away.
  484. ///
  485. /// Any templates previously registered will remain.
  486. ///
  487. /// # Example
  488. /// ```rust, ignore
  489. /// static App: Component = |cx| cx.render(rsx!{ "hello world" });
  490. ///
  491. /// let mut dom = VirtualDom::new();
  492. /// let edits = dom.rebuild();
  493. ///
  494. /// apply_edits(edits);
  495. /// ```
  496. pub fn rebuild(&mut self) -> Mutations {
  497. match unsafe { self.run_scope(ScopeId(0)).extend_lifetime_ref() } {
  498. // Rebuilding implies we append the created elements to the root
  499. RenderReturn::Ready(node) => {
  500. let m = self.create_scope(ScopeId(0), node);
  501. self.mutations.edits.push(Mutation::AppendChildren {
  502. id: ElementId(0),
  503. m,
  504. });
  505. }
  506. // If an error occurs, we should try to render the default error component and context where the error occured
  507. RenderReturn::Aborted(_placeholder) => panic!("Cannot catch errors during rebuild"),
  508. RenderReturn::Pending(_) => unreachable!("Root scope cannot be an async component"),
  509. }
  510. self.finalize()
  511. }
  512. /// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress
  513. /// suspended subtrees.
  514. pub fn render_immediate(&mut self) -> Mutations {
  515. // Build a waker that won't wake up since our deadline is already expired when it's polled
  516. let waker = futures_util::task::noop_waker();
  517. let mut cx = std::task::Context::from_waker(&waker);
  518. // Now run render with deadline but dont even try to poll any async tasks
  519. let fut = self.render_with_deadline(std::future::ready(()));
  520. pin_mut!(fut);
  521. // The root component is not allowed to be async
  522. match fut.poll(&mut cx) {
  523. std::task::Poll::Ready(mutations) => mutations,
  524. std::task::Poll::Pending => panic!("render_immediate should never return pending"),
  525. }
  526. }
  527. /// Render what you can given the timeline and then move on
  528. ///
  529. /// It's generally a good idea to put some sort of limit on the suspense process in case a future is having issues.
  530. ///
  531. /// If no suspense trees are present
  532. pub async fn render_with_deadline(&mut self, deadline: impl Future<Output = ()>) -> Mutations {
  533. pin_mut!(deadline);
  534. self.process_events();
  535. loop {
  536. // first, unload any complete suspense trees
  537. for finished_fiber in self.finished_fibers.drain(..) {
  538. let scope = &self.scopes[finished_fiber];
  539. let context = scope.has_context::<Rc<SuspenseContext>>().unwrap();
  540. self.mutations
  541. .templates
  542. .append(&mut context.mutations.borrow_mut().templates);
  543. self.mutations
  544. .edits
  545. .append(&mut context.mutations.borrow_mut().edits);
  546. // TODO: count how many nodes are on the stack?
  547. self.mutations.push(Mutation::ReplaceWith {
  548. id: context.placeholder.get().unwrap(),
  549. m: 1,
  550. })
  551. }
  552. // Next, diff any dirty scopes
  553. // We choose not to poll the deadline since we complete pretty quickly anyways
  554. if let Some(dirty) = self.dirty_scopes.iter().next().cloned() {
  555. self.dirty_scopes.remove(&dirty);
  556. // If the scope doesn't exist for whatever reason, then we should skip it
  557. if !self.scopes.contains(dirty.id) {
  558. continue;
  559. }
  560. // if the scope is currently suspended, then we should skip it, ignoring any tasks calling for an update
  561. if self.is_scope_suspended(dirty.id) {
  562. continue;
  563. }
  564. // Save the current mutations length so we can split them into boundary
  565. let mutations_to_this_point = self.mutations.edits.len();
  566. // Run the scope and get the mutations
  567. self.run_scope(dirty.id);
  568. self.diff_scope(dirty.id);
  569. // If suspended leaves are present, then we should find the boundary for this scope and attach things
  570. // No placeholder necessary since this is a diff
  571. if !self.collected_leaves.is_empty() {
  572. let mut boundary = self.scopes[dirty.id]
  573. .consume_context::<Rc<SuspenseContext>>()
  574. .unwrap();
  575. let boundary_mut = boundary.borrow_mut();
  576. // Attach mutations
  577. boundary_mut
  578. .mutations
  579. .borrow_mut()
  580. .edits
  581. .extend(self.mutations.edits.split_off(mutations_to_this_point));
  582. // Attach suspended leaves
  583. boundary
  584. .waiting_on
  585. .borrow_mut()
  586. .extend(self.collected_leaves.drain(..));
  587. }
  588. }
  589. // If there's more work, then just continue, plenty of work to do
  590. if !self.dirty_scopes.is_empty() {
  591. continue;
  592. }
  593. // If there's no pending suspense, then we have no reason to wait for anything
  594. if self.scheduler.leaves.borrow().is_empty() {
  595. return self.finalize();
  596. }
  597. // Poll the suspense leaves in the meantime
  598. let mut work = self.wait_for_work();
  599. // safety: this is okay since we don't touch the original future
  600. let pinned = unsafe { std::pin::Pin::new_unchecked(&mut work) };
  601. // If the deadline is exceded (left) then we should return the mutations we have
  602. use futures_util::future::{select, Either};
  603. if let Either::Left((_, _)) = select(&mut deadline, pinned).await {
  604. // release the borrowed
  605. drop(work);
  606. return self.finalize();
  607. }
  608. }
  609. }
  610. /// Swap the current mutations with a new
  611. fn finalize(&mut self) -> Mutations {
  612. std::mem::take(&mut self.mutations)
  613. }
  614. }
  615. impl Drop for VirtualDom {
  616. fn drop(&mut self) {
  617. // Simply drop this scope which drops all of its children
  618. self.drop_scope(ScopeId(0), true);
  619. }
  620. }