virtual_dom.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. runtime::{Runtime, RuntimeGuard},
  12. scopes::{ScopeId, ScopeState},
  13. AttributeValue, Element, Event, Scope,
  14. };
  15. use futures_util::{pin_mut, StreamExt};
  16. use rustc_hash::{FxHashMap, FxHashSet};
  17. use slab::Slab;
  18. use std::{any::Any, 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. pub(crate) scopes: Slab<Box<ScopeState>>,
  177. pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
  178. // Maps a template path to a map of byteindexes to templates
  179. pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
  180. // Every element is actually a dual reference - one to the template and the other to the dynamic node in that template
  181. pub(crate) elements: Slab<ElementRef>,
  182. pub(crate) mutations: Mutations<'static>,
  183. pub(crate) runtime: Rc<Runtime>,
  184. // Currently suspended scopes
  185. pub(crate) suspended_scopes: FxHashSet<ScopeId>,
  186. pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>,
  187. }
  188. impl VirtualDom {
  189. /// Create a new VirtualDom with a component that does not have special props.
  190. ///
  191. /// # Description
  192. ///
  193. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  194. ///
  195. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  196. /// to toss out the entire tree.
  197. ///
  198. ///
  199. /// # Example
  200. /// ```rust, ignore
  201. /// fn Example(cx: Scope) -> Element {
  202. /// cx.render(rsx!( div { "hello world" } ))
  203. /// }
  204. ///
  205. /// let dom = VirtualDom::new(Example);
  206. /// ```
  207. ///
  208. /// Note: the VirtualDom is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  209. pub fn new(app: fn(Scope) -> Element) -> Self {
  210. Self::new_with_props(app, ())
  211. }
  212. /// Create a new VirtualDom with the given properties for the root component.
  213. ///
  214. /// # Description
  215. ///
  216. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  217. ///
  218. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  219. /// to toss out the entire tree.
  220. ///
  221. ///
  222. /// # Example
  223. /// ```rust, ignore
  224. /// #[derive(PartialEq, Props)]
  225. /// struct SomeProps {
  226. /// name: &'static str
  227. /// }
  228. ///
  229. /// fn Example(cx: Scope<SomeProps>) -> Element {
  230. /// cx.render(rsx!{ div{ "hello {cx.props.name}" } })
  231. /// }
  232. ///
  233. /// let dom = VirtualDom::new(Example);
  234. /// ```
  235. ///
  236. /// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
  237. ///
  238. /// ```rust, ignore
  239. /// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
  240. /// let mutations = dom.rebuild();
  241. /// ```
  242. pub fn new_with_props<P: 'static>(root: fn(Scope<P>) -> Element, root_props: P) -> Self {
  243. let (tx, rx) = futures_channel::mpsc::unbounded();
  244. let scheduler = Scheduler::new(tx);
  245. let mut dom = Self {
  246. rx,
  247. runtime: Runtime::new(scheduler),
  248. scopes: Default::default(),
  249. dirty_scopes: Default::default(),
  250. templates: Default::default(),
  251. elements: Default::default(),
  252. mutations: Mutations::default(),
  253. suspended_scopes: Default::default(),
  254. };
  255. let root = dom.new_scope(
  256. Box::new(VProps::new(root, |_, _| unreachable!(), root_props)),
  257. "app",
  258. );
  259. // Unlike react, we provide a default error boundary that just renders the error as a string
  260. root.provide_context(Rc::new(ErrorBoundary::new(ScopeId::ROOT)));
  261. // the root element is always given element ID 0 since it's the container for the entire tree
  262. dom.elements.insert(ElementRef::none());
  263. dom
  264. }
  265. /// Get the state for any scope given its ID
  266. ///
  267. /// This is useful for inserting or removing contexts from a scope, or rendering out its root node
  268. pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
  269. self.scopes.get(id.0).map(|s| &**s)
  270. }
  271. /// Get the single scope at the top of the VirtualDom tree that will always be around
  272. ///
  273. /// This scope has a ScopeId of 0 and is the root of the tree
  274. pub fn base_scope(&self) -> &ScopeState {
  275. self.get_scope(ScopeId::ROOT).unwrap()
  276. }
  277. /// Build the virtualdom with a global context inserted into the base scope
  278. ///
  279. /// This is useful for what is essentially dependency injection when building the app
  280. pub fn with_root_context<T: Clone + 'static>(self, context: T) -> Self {
  281. self.base_scope().provide_context(context);
  282. self
  283. }
  284. /// Manually mark a scope as requiring a re-render
  285. ///
  286. /// Whenever the Runtime "works", it will re-render this scope
  287. pub fn mark_dirty(&mut self, id: ScopeId) {
  288. if let Some(scope) = self.get_scope(id) {
  289. let height = scope.height();
  290. tracing::trace!("Marking scope {:?} ({}) as dirty", id, scope.context().name);
  291. self.dirty_scopes.insert(DirtyScope { height, id });
  292. }
  293. }
  294. /// Call a listener inside the VirtualDom with data from outside the VirtualDom.
  295. ///
  296. /// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
  297. /// this method does not give any indication as to the success of the listener call. If the listener is not found,
  298. /// nothing will happen.
  299. ///
  300. /// It is up to the listeners themselves to mark nodes as dirty.
  301. ///
  302. /// If you have multiple events, you can call this method multiple times before calling "render_with_deadline"
  303. pub fn handle_event(
  304. &mut self,
  305. name: &str,
  306. data: Rc<dyn Any>,
  307. element: ElementId,
  308. bubbles: bool,
  309. ) {
  310. let _runtime = RuntimeGuard::new(self.runtime.clone());
  311. /*
  312. ------------------------
  313. The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
  314. we find the target path.
  315. With the target path, we try and move up to the parent until there is no parent.
  316. Due to how bubbling works, we call the listeners before walking to the parent.
  317. If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order.
  318. ----------------------
  319. For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the
  320. right.
  321. | <-- yes (is ascendant)
  322. | | | <-- no (is not direct ascendant)
  323. | | <-- yes (is ascendant)
  324. | | | | | <--- target element, break early, don't check other listeners
  325. | | | <-- no, broke early
  326. | <-- no, broke early
  327. */
  328. let mut parent_path = self.elements.get(element.0);
  329. let mut listeners = vec![];
  330. // We will clone this later. The data itself is wrapped in RC to be used in callbacks if required
  331. let uievent = Event {
  332. propagates: Rc::new(Cell::new(bubbles)),
  333. data,
  334. };
  335. // If the event bubbles, we traverse through the tree until we find the target element.
  336. if bubbles {
  337. // Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
  338. while let Some(el_ref) = parent_path {
  339. // safety: we maintain references of all vnodes in the element slab
  340. if let Some(template) = el_ref.template {
  341. let template = unsafe { template.as_ref() };
  342. let node_template = template.template.get();
  343. let target_path = el_ref.path;
  344. for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
  345. let this_path = node_template.attr_paths[idx];
  346. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  347. if attr.name.trim_start_matches("on") == name
  348. && target_path.is_decendant(&this_path)
  349. {
  350. listeners.push(&attr.value);
  351. // Break if this is the exact target element.
  352. // This means we won't call two listeners with the same name on the same element. This should be
  353. // documented, or be rejected from the rsx! macro outright
  354. if target_path == this_path {
  355. break;
  356. }
  357. }
  358. }
  359. // Now that we've accumulated all the parent attributes for the target element, call them in reverse order
  360. // We check the bubble state between each call to see if the event has been stopped from bubbling
  361. for listener in listeners.drain(..).rev() {
  362. if let AttributeValue::Listener(listener) = listener {
  363. let origin = el_ref.scope;
  364. self.runtime.scope_stack.borrow_mut().push(origin);
  365. self.runtime.rendering.set(false);
  366. if let Some(cb) = listener.borrow_mut().as_deref_mut() {
  367. cb(uievent.clone());
  368. }
  369. self.runtime.scope_stack.borrow_mut().pop();
  370. self.runtime.rendering.set(true);
  371. if !uievent.propagates.get() {
  372. return;
  373. }
  374. }
  375. }
  376. parent_path = template.parent.and_then(|id| self.elements.get(id.0));
  377. } else {
  378. break;
  379. }
  380. }
  381. } else {
  382. // Otherwise, we just call the listener on the target element
  383. if let Some(el_ref) = parent_path {
  384. // safety: we maintain references of all vnodes in the element slab
  385. if let Some(template) = el_ref.template {
  386. let template = unsafe { template.as_ref() };
  387. let node_template = template.template.get();
  388. let target_path = el_ref.path;
  389. for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
  390. let this_path = node_template.attr_paths[idx];
  391. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  392. // Only call the listener if this is the exact target element.
  393. if attr.name.trim_start_matches("on") == name && target_path == this_path {
  394. if let AttributeValue::Listener(listener) = &attr.value {
  395. let origin = el_ref.scope;
  396. self.runtime.scope_stack.borrow_mut().push(origin);
  397. self.runtime.rendering.set(false);
  398. if let Some(cb) = listener.borrow_mut().as_deref_mut() {
  399. cb(uievent.clone());
  400. }
  401. self.runtime.scope_stack.borrow_mut().pop();
  402. self.runtime.rendering.set(true);
  403. break;
  404. }
  405. }
  406. }
  407. }
  408. }
  409. }
  410. }
  411. /// Wait for the scheduler to have any work.
  412. ///
  413. /// This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when
  414. /// any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method
  415. /// will exit.
  416. ///
  417. /// This method is cancel-safe, so you're fine to discard the future in a select block.
  418. ///
  419. /// This lets us poll async tasks and suspended trees during idle periods without blocking the main thread.
  420. ///
  421. /// # Example
  422. ///
  423. /// ```rust, ignore
  424. /// let dom = VirtualDom::new(App);
  425. /// let sender = dom.get_scheduler_channel();
  426. /// ```
  427. pub async fn wait_for_work(&mut self) {
  428. let mut some_msg = None;
  429. loop {
  430. match some_msg.take() {
  431. // If a bunch of messages are ready in a sequence, try to pop them off synchronously
  432. Some(msg) => match msg {
  433. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  434. SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
  435. },
  436. // If they're not ready, then we should wait for them to be ready
  437. None => {
  438. match self.rx.try_next() {
  439. Ok(Some(val)) => some_msg = Some(val),
  440. Ok(None) => return,
  441. Err(_) => {
  442. // If we have any dirty scopes, or finished fiber trees then we should exit
  443. if !self.dirty_scopes.is_empty() || !self.suspended_scopes.is_empty() {
  444. return;
  445. }
  446. some_msg = self.rx.next().await
  447. }
  448. }
  449. }
  450. }
  451. }
  452. }
  453. /// Process all events in the queue until there are no more left
  454. pub fn process_events(&mut self) {
  455. while let Ok(Some(msg)) = self.rx.try_next() {
  456. match msg {
  457. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  458. SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
  459. }
  460. }
  461. }
  462. /// Replace a template at runtime. This will re-render all components that use this template.
  463. /// This is the primitive that enables hot-reloading.
  464. ///
  465. /// The caller must ensure that the template refrences the same dynamic attributes and nodes as the original template.
  466. ///
  467. /// This will only replace the the parent template, not any nested templates.
  468. pub fn replace_template(&mut self, template: Template<'static>) {
  469. self.register_template_first_byte_index(template);
  470. // iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
  471. for (_, scope) in self.scopes.iter() {
  472. if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
  473. if sync.template.get().name.rsplit_once(':').unwrap().0
  474. == template.name.rsplit_once(':').unwrap().0
  475. {
  476. let context = scope.context();
  477. let height = context.height;
  478. self.dirty_scopes.insert(DirtyScope {
  479. height,
  480. id: context.id,
  481. });
  482. }
  483. }
  484. }
  485. }
  486. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
  487. ///
  488. /// The mutations item expects the RealDom's stack to be the root of the application.
  489. ///
  490. /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
  491. /// root component will be ran once and then diffed. All updates will flow out as mutations.
  492. ///
  493. /// All state stored in components will be completely wiped away.
  494. ///
  495. /// Any templates previously registered will remain.
  496. ///
  497. /// # Example
  498. /// ```rust, ignore
  499. /// static App: Component = |cx| cx.render(rsx!{ "hello world" });
  500. ///
  501. /// let mut dom = VirtualDom::new();
  502. /// let edits = dom.rebuild();
  503. ///
  504. /// apply_edits(edits);
  505. /// ```
  506. pub fn rebuild(&mut self) -> Mutations {
  507. let _runtime = RuntimeGuard::new(self.runtime.clone());
  508. match unsafe { self.run_scope(ScopeId::ROOT).extend_lifetime_ref() } {
  509. // Rebuilding implies we append the created elements to the root
  510. RenderReturn::Ready(node) => {
  511. let m = self.create_scope(ScopeId::ROOT, node);
  512. self.mutations.edits.push(Mutation::AppendChildren {
  513. id: ElementId(0),
  514. m,
  515. });
  516. }
  517. // If an error occurs, we should try to render the default error component and context where the error occured
  518. RenderReturn::Aborted(placeholder) => {
  519. tracing::debug!("Ran into suspended or aborted scope during rebuild");
  520. let id = self.next_null();
  521. placeholder.id.set(Some(id));
  522. self.mutations.push(Mutation::CreatePlaceholder { id });
  523. }
  524. }
  525. self.finalize()
  526. }
  527. /// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress
  528. /// suspended subtrees.
  529. pub fn render_immediate(&mut self) -> Mutations {
  530. // Build a waker that won't wake up since our deadline is already expired when it's polled
  531. let waker = futures_util::task::noop_waker();
  532. let mut cx = std::task::Context::from_waker(&waker);
  533. // Now run render with deadline but dont even try to poll any async tasks
  534. let fut = self.render_with_deadline(std::future::ready(()));
  535. pin_mut!(fut);
  536. // The root component is not allowed to be async
  537. match fut.poll(&mut cx) {
  538. std::task::Poll::Ready(mutations) => mutations,
  539. std::task::Poll::Pending => panic!("render_immediate should never return pending"),
  540. }
  541. }
  542. /// Render the virtual dom, waiting for all suspense to be finished
  543. ///
  544. /// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
  545. pub async fn wait_for_suspense(&mut self) {
  546. loop {
  547. // println!("waiting for suspense {:?}", self.suspended_scopes);
  548. if self.suspended_scopes.is_empty() {
  549. return;
  550. }
  551. // println!("waiting for suspense");
  552. self.wait_for_work().await;
  553. // println!("Rendered immediately");
  554. _ = self.render_immediate();
  555. }
  556. }
  557. /// Render what you can given the timeline and then move on
  558. ///
  559. /// It's generally a good idea to put some sort of limit on the suspense process in case a future is having issues.
  560. ///
  561. /// If no suspense trees are present
  562. pub async fn render_with_deadline(&mut self, deadline: impl Future<Output = ()>) -> Mutations {
  563. pin_mut!(deadline);
  564. self.process_events();
  565. loop {
  566. // Next, diff any dirty scopes
  567. // We choose not to poll the deadline since we complete pretty quickly anyways
  568. if let Some(dirty) = self.dirty_scopes.iter().next().cloned() {
  569. self.dirty_scopes.remove(&dirty);
  570. // If the scope doesn't exist for whatever reason, then we should skip it
  571. if !self.scopes.contains(dirty.id.0) {
  572. continue;
  573. }
  574. {
  575. let _runtime = RuntimeGuard::new(self.runtime.clone());
  576. // Run the scope and get the mutations
  577. self.run_scope(dirty.id);
  578. self.diff_scope(dirty.id);
  579. }
  580. }
  581. // If there's more work, then just continue, plenty of work to do
  582. if !self.dirty_scopes.is_empty() {
  583. continue;
  584. }
  585. // Poll the suspense leaves in the meantime
  586. let mut work = self.wait_for_work();
  587. // safety: this is okay since we don't touch the original future
  588. let pinned = unsafe { std::pin::Pin::new_unchecked(&mut work) };
  589. // If the deadline is exceded (left) then we should return the mutations we have
  590. use futures_util::future::{select, Either};
  591. if let Either::Left((_, _)) = select(&mut deadline, pinned).await {
  592. // release the borrowed
  593. drop(work);
  594. return self.finalize();
  595. }
  596. }
  597. }
  598. /// Swap the current mutations with a new
  599. fn finalize(&mut self) -> Mutations {
  600. std::mem::take(&mut self.mutations)
  601. }
  602. }
  603. impl Drop for VirtualDom {
  604. fn drop(&mut self) {
  605. // Simply drop this scope which drops all of its children
  606. self.drop_scope(ScopeId::ROOT, true);
  607. }
  608. }