virtual_dom.rs 25 KB

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