virtual_dom.rs 25 KB

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