virtual_dom.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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::{AttributeType, DirtyScope, ErrorBoundary, Mutations, Scheduler, SchedulerMsg},
  8. mutations::Mutation,
  9. nodes::RenderReturn,
  10. nodes::{Template, TemplateId},
  11. runtime::{Runtime, RuntimeGuard},
  12. scopes::{ScopeId, ScopeState},
  13. Attribute, 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(0))));
  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(0)).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. self.dirty_scopes.insert(DirtyScope { height, id });
  291. }
  292. }
  293. /// Call a listener inside the VirtualDom with data from outside the VirtualDom.
  294. ///
  295. /// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
  296. /// this method does not give any indication as to the success of the listener call. If the listener is not found,
  297. /// nothing will happen.
  298. ///
  299. /// It is up to the listeners themselves to mark nodes as dirty.
  300. ///
  301. /// If you have multiple events, you can call this method multiple times before calling "render_with_deadline"
  302. pub fn handle_event(
  303. &mut self,
  304. name: &str,
  305. data: Rc<dyn Any>,
  306. element: ElementId,
  307. bubbles: bool,
  308. ) {
  309. let _runtime = RuntimeGuard::new(self.runtime.clone());
  310. /*
  311. ------------------------
  312. The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
  313. we find the target path.
  314. With the target path, we try and move up to the parent until there is no parent.
  315. Due to how bubbling works, we call the listeners before walking to the parent.
  316. If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order.
  317. ----------------------
  318. For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the
  319. right.
  320. | <-- yes (is ascendant)
  321. | | | <-- no (is not direct ascendant)
  322. | | <-- yes (is ascendant)
  323. | | | | | <--- target element, break early, don't check other listeners
  324. | | | <-- no, broke early
  325. | <-- no, broke early
  326. */
  327. let mut parent_path = self.elements.get(element.0);
  328. let mut listeners = vec![];
  329. // We will clone this later. The data itself is wrapped in RC to be used in callbacks if required
  330. let uievent = Event {
  331. propagates: Rc::new(Cell::new(bubbles)),
  332. data,
  333. };
  334. // If the event bubbles, we traverse through the tree until we find the target element.
  335. if bubbles {
  336. // Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
  337. while let Some(el_ref) = parent_path {
  338. // safety: we maintain references of all vnodes in the element slab
  339. if let Some(template) = el_ref.template {
  340. let template = unsafe { template.as_ref() };
  341. let node_template = template.template.get();
  342. let target_path = el_ref.path;
  343. for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
  344. let this_path = node_template.attr_paths[idx];
  345. fn add_listener<'a>(
  346. attribute: &'a Attribute<'a>,
  347. event_name: &str,
  348. listeners: &mut Vec<&'a AttributeValue<'a>>,
  349. ) {
  350. if attribute.name.trim_start_matches("on") == event_name {
  351. listeners.push(&attribute.value);
  352. }
  353. listeners.push(&attribute.value);
  354. }
  355. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  356. if target_path.is_decendant(&this_path) {
  357. match &attr.ty {
  358. AttributeType::Single(attribute) => {
  359. add_listener(attribute, name, &mut listeners);
  360. }
  361. AttributeType::Many(attributes) => {
  362. for attribute in *attributes {
  363. add_listener(attribute, name, &mut listeners);
  364. }
  365. }
  366. }
  367. // Break if this is the exact target element.
  368. // This means we won't call two listeners with the same name on the same element. This should be
  369. // documented, or be rejected from the rsx! macro outright
  370. if target_path == this_path {
  371. break;
  372. }
  373. }
  374. }
  375. // Now that we've accumulated all the parent attributes for the target element, call them in reverse order
  376. // We check the bubble state between each call to see if the event has been stopped from bubbling
  377. for listener in listeners.drain(..).rev() {
  378. if let AttributeValue::Listener(listener) = listener {
  379. let origin = el_ref.scope;
  380. self.runtime.scope_stack.borrow_mut().push(origin);
  381. self.runtime.rendering.set(false);
  382. if let Some(cb) = listener.borrow_mut().as_deref_mut() {
  383. cb(uievent.clone());
  384. }
  385. self.runtime.scope_stack.borrow_mut().pop();
  386. self.runtime.rendering.set(true);
  387. if !uievent.propagates.get() {
  388. return;
  389. }
  390. }
  391. }
  392. parent_path = template.parent.and_then(|id| self.elements.get(id.0));
  393. } else {
  394. break;
  395. }
  396. }
  397. } else {
  398. // Otherwise, we just call the listener on the target element
  399. if let Some(el_ref) = parent_path {
  400. // safety: we maintain references of all vnodes in the element slab
  401. if let Some(template) = el_ref.template {
  402. let template = unsafe { template.as_ref() };
  403. let node_template = template.template.get();
  404. let target_path = el_ref.path;
  405. for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
  406. let this_path = node_template.attr_paths[idx];
  407. fn call_listener(
  408. attribute: &Attribute,
  409. event_name: &str,
  410. uievent: &Event<dyn Any>,
  411. runtime: &Runtime,
  412. origin: ScopeId,
  413. ) -> bool {
  414. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  415. // Only call the listener if this is the exact target element.
  416. if attribute.name.trim_start_matches("on") == event_name {
  417. if let AttributeValue::Listener(listener) = &attribute.value {
  418. runtime.scope_stack.borrow_mut().push(origin);
  419. runtime.rendering.set(false);
  420. if let Some(cb) = listener.borrow_mut().as_deref_mut() {
  421. cb(uievent.clone());
  422. }
  423. runtime.scope_stack.borrow_mut().pop();
  424. runtime.rendering.set(true);
  425. return true;
  426. }
  427. }
  428. false
  429. }
  430. if target_path == this_path {
  431. match &attr.ty {
  432. AttributeType::Single(attribute) => {
  433. if call_listener(
  434. attribute,
  435. name,
  436. &uievent,
  437. &self.runtime,
  438. el_ref.scope,
  439. ) {
  440. return;
  441. }
  442. }
  443. AttributeType::Many(attributes) => {
  444. for attribute in *attributes {
  445. if call_listener(
  446. attribute,
  447. name,
  448. &uievent,
  449. &self.runtime,
  450. el_ref.scope,
  451. ) {
  452. return;
  453. }
  454. }
  455. }
  456. }
  457. }
  458. }
  459. }
  460. }
  461. }
  462. }
  463. /// Wait for the scheduler to have any work.
  464. ///
  465. /// This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when
  466. /// any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method
  467. /// will exit.
  468. ///
  469. /// This method is cancel-safe, so you're fine to discard the future in a select block.
  470. ///
  471. /// This lets us poll async tasks and suspended trees during idle periods without blocking the main thread.
  472. ///
  473. /// # Example
  474. ///
  475. /// ```rust, ignore
  476. /// let dom = VirtualDom::new(App);
  477. /// let sender = dom.get_scheduler_channel();
  478. /// ```
  479. pub async fn wait_for_work(&mut self) {
  480. let mut some_msg = None;
  481. loop {
  482. match some_msg.take() {
  483. // If a bunch of messages are ready in a sequence, try to pop them off synchronously
  484. Some(msg) => match msg {
  485. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  486. SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
  487. },
  488. // If they're not ready, then we should wait for them to be ready
  489. None => {
  490. match self.rx.try_next() {
  491. Ok(Some(val)) => some_msg = Some(val),
  492. Ok(None) => return,
  493. Err(_) => {
  494. // If we have any dirty scopes, or finished fiber trees then we should exit
  495. if !self.dirty_scopes.is_empty() || !self.suspended_scopes.is_empty() {
  496. return;
  497. }
  498. some_msg = self.rx.next().await
  499. }
  500. }
  501. }
  502. }
  503. }
  504. }
  505. /// Process all events in the queue until there are no more left
  506. pub fn process_events(&mut self) {
  507. while let Ok(Some(msg)) = self.rx.try_next() {
  508. match msg {
  509. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  510. SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
  511. }
  512. }
  513. }
  514. /// Replace a template at runtime. This will re-render all components that use this template.
  515. /// This is the primitive that enables hot-reloading.
  516. ///
  517. /// The caller must ensure that the template refrences the same dynamic attributes and nodes as the original template.
  518. ///
  519. /// This will only replace the the parent template, not any nested templates.
  520. pub fn replace_template(&mut self, template: Template<'static>) {
  521. self.register_template_first_byte_index(template);
  522. // iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
  523. for (_, scope) in self.scopes.iter() {
  524. if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
  525. if sync.template.get().name.rsplit_once(':').unwrap().0
  526. == template.name.rsplit_once(':').unwrap().0
  527. {
  528. let context = scope.context();
  529. let height = context.height;
  530. self.dirty_scopes.insert(DirtyScope {
  531. height,
  532. id: context.id,
  533. });
  534. }
  535. }
  536. }
  537. }
  538. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
  539. ///
  540. /// The mutations item expects the RealDom's stack to be the root of the application.
  541. ///
  542. /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
  543. /// root component will be ran once and then diffed. All updates will flow out as mutations.
  544. ///
  545. /// All state stored in components will be completely wiped away.
  546. ///
  547. /// Any templates previously registered will remain.
  548. ///
  549. /// # Example
  550. /// ```rust, ignore
  551. /// static App: Component = |cx| cx.render(rsx!{ "hello world" });
  552. ///
  553. /// let mut dom = VirtualDom::new();
  554. /// let edits = dom.rebuild();
  555. ///
  556. /// apply_edits(edits);
  557. /// ```
  558. pub fn rebuild(&mut self) -> Mutations {
  559. let _runtime = RuntimeGuard::new(self.runtime.clone());
  560. match unsafe { self.run_scope(ScopeId(0)).extend_lifetime_ref() } {
  561. // Rebuilding implies we append the created elements to the root
  562. RenderReturn::Ready(node) => {
  563. let m = self.create_scope(ScopeId(0), node);
  564. self.mutations.edits.push(Mutation::AppendChildren {
  565. id: ElementId(0),
  566. m,
  567. });
  568. }
  569. // If an error occurs, we should try to render the default error component and context where the error occured
  570. RenderReturn::Aborted(placeholder) => {
  571. log::info!("Ran into suspended or aborted scope during rebuild");
  572. let id = self.next_null();
  573. placeholder.id.set(Some(id));
  574. self.mutations.push(Mutation::CreatePlaceholder { id });
  575. }
  576. }
  577. self.finalize()
  578. }
  579. /// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress
  580. /// suspended subtrees.
  581. pub fn render_immediate(&mut self) -> Mutations {
  582. // Build a waker that won't wake up since our deadline is already expired when it's polled
  583. let waker = futures_util::task::noop_waker();
  584. let mut cx = std::task::Context::from_waker(&waker);
  585. // Now run render with deadline but dont even try to poll any async tasks
  586. let fut = self.render_with_deadline(std::future::ready(()));
  587. pin_mut!(fut);
  588. // The root component is not allowed to be async
  589. match fut.poll(&mut cx) {
  590. std::task::Poll::Ready(mutations) => mutations,
  591. std::task::Poll::Pending => panic!("render_immediate should never return pending"),
  592. }
  593. }
  594. /// Render the virtual dom, waiting for all suspense to be finished
  595. ///
  596. /// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
  597. pub async fn wait_for_suspense(&mut self) {
  598. loop {
  599. // println!("waiting for suspense {:?}", self.suspended_scopes);
  600. if self.suspended_scopes.is_empty() {
  601. return;
  602. }
  603. // println!("waiting for suspense");
  604. self.wait_for_work().await;
  605. // println!("Rendered immediately");
  606. _ = self.render_immediate();
  607. }
  608. }
  609. /// Render what you can given the timeline and then move on
  610. ///
  611. /// It's generally a good idea to put some sort of limit on the suspense process in case a future is having issues.
  612. ///
  613. /// If no suspense trees are present
  614. pub async fn render_with_deadline(&mut self, deadline: impl Future<Output = ()>) -> Mutations {
  615. pin_mut!(deadline);
  616. self.process_events();
  617. loop {
  618. // Next, diff any dirty scopes
  619. // We choose not to poll the deadline since we complete pretty quickly anyways
  620. if let Some(dirty) = self.dirty_scopes.iter().next().cloned() {
  621. self.dirty_scopes.remove(&dirty);
  622. // If the scope doesn't exist for whatever reason, then we should skip it
  623. if !self.scopes.contains(dirty.id.0) {
  624. continue;
  625. }
  626. {
  627. let _runtime = RuntimeGuard::new(self.runtime.clone());
  628. // Run the scope and get the mutations
  629. self.run_scope(dirty.id);
  630. self.diff_scope(dirty.id);
  631. }
  632. }
  633. // If there's more work, then just continue, plenty of work to do
  634. if !self.dirty_scopes.is_empty() {
  635. continue;
  636. }
  637. // Poll the suspense leaves in the meantime
  638. let mut work = self.wait_for_work();
  639. // safety: this is okay since we don't touch the original future
  640. let pinned = unsafe { std::pin::Pin::new_unchecked(&mut work) };
  641. // If the deadline is exceded (left) then we should return the mutations we have
  642. use futures_util::future::{select, Either};
  643. if let Either::Left((_, _)) = select(&mut deadline, pinned).await {
  644. // release the borrowed
  645. drop(work);
  646. return self.finalize();
  647. }
  648. }
  649. }
  650. /// Swap the current mutations with a new
  651. fn finalize(&mut self) -> Mutations {
  652. std::mem::take(&mut self.mutations)
  653. }
  654. }
  655. impl Drop for VirtualDom {
  656. fn drop(&mut self) {
  657. // Simply drop this scope which drops all of its children
  658. self.drop_scope(ScopeId(0), true);
  659. }
  660. }