2
0
Fork 0
mirror of https://github.com/DioxusLabs/dioxus synced 2024-12-23 19:13:08 +00:00
dioxus/packages/core/src/virtual_dom.rs

646 lines
24 KiB
Rust
Raw Normal View History

//! # Virtual DOM Implementation for Rust
//!
//! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
2022-11-02 01:42:29 +00:00
use crate::{
2022-11-20 23:58:05 +00:00
any_props::VProps,
2022-11-23 02:38:27 +00:00
arena::{ElementId, ElementRef},
2023-01-22 23:16:34 +00:00
innerlude::{DirtyScope, ErrorBoundary, Mutations, Scheduler, SchedulerMsg, ScopeSlab},
2022-11-12 02:29:27 +00:00
mutations::Mutation,
2022-12-03 00:24:49 +00:00
nodes::RenderReturn,
2022-11-12 02:29:27 +00:00
nodes::{Template, TemplateId},
2022-11-02 01:42:29 +00:00
scopes::{ScopeId, ScopeState},
2023-07-14 23:56:17 +00:00
AttributeValue, Element, Event, Scope,
2022-11-02 01:42:29 +00:00
};
2022-11-18 06:31:14 +00:00
use futures_util::{pin_mut, StreamExt};
2023-07-14 23:56:17 +00:00
use rustc_hash::{FxHashMap, FxHashSet};
2022-11-02 01:42:29 +00:00
use slab::Slab;
2023-07-14 23:56:17 +00:00
use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
2022-11-02 01:42:29 +00:00
2022-11-09 18:58:11 +00:00
/// A virtual node system that progresses user events and diffs UI trees.
///
/// ## Guide
///
/// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
///
2023-01-12 01:12:09 +00:00
/// ```rust
/// # use dioxus::prelude::*;
///
2022-11-09 18:58:11 +00:00
/// #[derive(Props, PartialEq)]
/// struct AppProps {
/// title: String
/// }
///
/// fn App(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!(
/// div {"hello, {cx.props.title}"}
/// ))
/// }
/// ```
///
/// Components may be composed to make complex apps.
///
2023-01-12 01:12:09 +00:00
/// ```rust
/// # #![allow(unused)]
/// # use dioxus::prelude::*;
///
/// # #[derive(Props, PartialEq)]
/// # struct AppProps {
/// # title: String
/// # }
///
/// static ROUTES: &str = "";
///
2022-11-09 18:58:11 +00:00
/// fn App(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!(
/// NavBar { routes: ROUTES }
/// Title { "{cx.props.title}" }
/// Footer {}
/// ))
/// }
2023-01-12 01:12:09 +00:00
///
/// #[inline_props]
/// fn NavBar(cx: Scope, routes: &'static str) -> Element {
/// cx.render(rsx! {
/// div { "Routes: {routes}" }
/// })
/// }
///
/// fn Footer(cx: Scope) -> Element {
/// cx.render(rsx! { div { "Footer" } })
/// }
///
/// #[inline_props]
/// fn Title<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
/// cx.render(rsx! {
/// div { id: "title", children }
/// })
/// }
2022-11-09 18:58:11 +00:00
/// ```
///
/// To start an app, create a [`VirtualDom`] and call [`VirtualDom::rebuild`] to get the list of edits required to
/// draw the UI.
///
2023-01-12 01:12:09 +00:00
/// ```rust
/// # use dioxus::prelude::*;
/// # fn App(cx: Scope) -> Element { cx.render(rsx! { div {} }) }
///
2022-11-09 18:58:11 +00:00
/// let mut vdom = VirtualDom::new(App);
/// let edits = vdom.rebuild();
/// ```
///
2022-11-12 02:29:27 +00:00
/// To call listeners inside the VirtualDom, call [`VirtualDom::handle_event`] with the appropriate event data.
2022-11-09 18:58:11 +00:00
///
/// ```rust, ignore
2022-11-12 02:29:27 +00:00
/// vdom.handle_event(event);
2022-11-09 18:58:11 +00:00
/// ```
///
2022-11-12 02:29:27 +00:00
/// While no events are ready, call [`VirtualDom::wait_for_work`] to poll any futures inside the VirtualDom.
2022-11-09 18:58:11 +00:00
///
/// ```rust, ignore
/// vdom.wait_for_work().await;
/// ```
///
2022-11-12 02:29:27 +00:00
/// Once work is ready, call [`VirtualDom::render_with_deadline`] to compute the differences between the previous and
2022-11-09 18:58:11 +00:00
/// current UI trees. This will return a [`Mutations`] object that contains Edits, Effects, and NodeRefs that need to be
/// handled by the renderer.
///
/// ```rust, ignore
2022-11-12 02:29:27 +00:00
/// let mutations = vdom.work_with_deadline(tokio::time::sleep(Duration::from_millis(100)));
///
/// for edit in mutations.edits {
/// real_dom.apply(edit);
2022-11-09 18:58:11 +00:00
/// }
/// ```
///
2022-11-12 02:29:27 +00:00
/// To not wait for suspense while diffing the VirtualDom, call [`VirtualDom::render_immediate`] or pass an immediately
/// ready future to [`VirtualDom::render_with_deadline`].
///
///
2022-11-09 18:58:11 +00:00
/// ## Building an event loop around Dioxus:
///
/// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.
2022-11-30 15:31:44 +00:00
/// ```rust, ignore
2022-11-12 02:29:27 +00:00
/// fn app(cx: Scope) -> Element {
2022-11-30 15:31:44 +00:00
/// cx.render(rsx! {
2022-11-09 18:58:11 +00:00
/// div { "Hello World" }
/// })
/// }
///
2022-11-12 02:29:27 +00:00
/// let dom = VirtualDom::new(app);
2022-11-09 18:58:11 +00:00
///
2022-11-12 02:29:27 +00:00
/// real_dom.apply(dom.rebuild());
2022-11-09 18:58:11 +00:00
///
2022-11-12 02:29:27 +00:00
/// loop {
/// select! {
/// _ = dom.wait_for_work() => {}
/// evt = real_dom.wait_for_event() => dom.handle_event(evt),
2022-11-09 18:58:11 +00:00
/// }
2022-11-12 02:29:27 +00:00
///
/// real_dom.apply(dom.render_immediate());
/// }
/// ```
///
/// ## Waiting for suspense
///
/// Because Dioxus supports suspense, you can use it for server-side rendering, static site generation, and other usecases
/// where waiting on portions of the UI to finish rendering is important. To wait for suspense, use the
/// [`VirtualDom::render_with_deadline`] method:
///
2022-11-30 15:31:44 +00:00
/// ```rust, ignore
2022-11-12 02:29:27 +00:00
/// let dom = VirtualDom::new(app);
///
/// let deadline = tokio::time::sleep(Duration::from_millis(100));
/// let edits = dom.render_with_deadline(deadline).await;
/// ```
///
/// ## Use with streaming
///
/// If not all rendering is done by the deadline, it might be worthwhile to stream the rest later. To do this, we
/// suggest rendering with a deadline, and then looping between [`VirtualDom::wait_for_work`] and render_immediate until
/// no suspended work is left.
///
2022-11-30 15:31:44 +00:00
/// ```rust, ignore
2022-11-12 02:29:27 +00:00
/// let dom = VirtualDom::new(app);
///
/// let deadline = tokio::time::sleep(Duration::from_millis(20));
/// let edits = dom.render_with_deadline(deadline).await;
///
/// real_dom.apply(edits);
///
/// while dom.has_suspended_work() {
/// dom.wait_for_work().await;
/// real_dom.apply(dom.render_immediate());
2022-11-09 18:58:11 +00:00
/// }
/// ```
2022-11-02 01:42:29 +00:00
pub struct VirtualDom {
// Maps a template path to a map of byteindexes to templates
pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
2023-01-22 23:16:34 +00:00
pub(crate) scopes: ScopeSlab,
2022-11-02 01:42:29 +00:00
pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
2022-11-09 19:02:52 +00:00
pub(crate) scheduler: Rc<Scheduler>,
2022-11-09 03:39:37 +00:00
2022-11-18 04:00:39 +00:00
// Every element is actually a dual reference - one to the template and the other to the dynamic node in that template
pub(crate) elements: Slab<ElementRef>,
2022-11-09 03:39:37 +00:00
// While diffing we need some sort of way of breaking off a stream of suspended mutations.
pub(crate) scope_stack: Vec<ScopeId>,
2022-11-09 18:58:11 +00:00
2023-07-14 23:56:17 +00:00
// Currently suspended scopes
pub(crate) suspended_scopes: FxHashSet<ScopeId>,
2022-11-09 18:58:11 +00:00
pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>,
2022-11-23 03:59:56 +00:00
pub(crate) mutations: Mutations<'static>,
2022-11-02 01:42:29 +00:00
}
impl VirtualDom {
2022-11-09 18:58:11 +00:00
/// Create a new VirtualDom with a component that does not have special props.
///
/// # Description
///
/// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
///
/// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
/// to toss out the entire tree.
///
///
/// # Example
/// ```rust, ignore
/// fn Example(cx: Scope) -> Element {
/// cx.render(rsx!( div { "hello world" } ))
/// }
///
/// let dom = VirtualDom::new(Example);
/// ```
///
/// Note: the VirtualDom is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
2022-11-04 00:34:42 +00:00
pub fn new(app: fn(Scope) -> Element) -> Self {
2022-11-09 18:58:11 +00:00
Self::new_with_props(app, ())
}
/// Create a new VirtualDom with the given properties for the root component.
///
/// # Description
///
/// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
///
/// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
/// to toss out the entire tree.
///
///
/// # Example
/// ```rust, ignore
/// #[derive(PartialEq, Props)]
/// struct SomeProps {
/// name: &'static str
/// }
///
/// fn Example(cx: Scope<SomeProps>) -> Element {
/// cx.render(rsx!{ div{ "hello {cx.props.name}" } })
/// }
///
/// let dom = VirtualDom::new(Example);
/// ```
///
/// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
///
/// ```rust, ignore
/// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
/// let mutations = dom.rebuild();
/// ```
2022-11-29 21:31:04 +00:00
pub fn new_with_props<P: 'static>(root: fn(Scope<P>) -> Element, root_props: P) -> Self {
2022-11-12 02:29:27 +00:00
let (tx, rx) = futures_channel::mpsc::unbounded();
2022-11-09 18:58:11 +00:00
let mut dom = Self {
rx,
scheduler: Scheduler::new(tx),
2022-11-02 01:42:29 +00:00
templates: Default::default(),
2023-01-22 23:16:34 +00:00
scopes: Default::default(),
2022-11-02 01:42:29 +00:00
elements: Default::default(),
scope_stack: Vec::new(),
dirty_scopes: BTreeSet::new(),
2023-07-14 23:56:17 +00:00
suspended_scopes: FxHashSet::default(),
2022-11-29 21:46:25 +00:00
mutations: Mutations::default(),
2022-11-02 01:42:29 +00:00
};
2022-12-07 01:41:47 +00:00
let root = dom.new_scope(
Box::new(VProps::new(root, |_, _| unreachable!(), root_props)),
"app",
);
2022-11-12 02:29:27 +00:00
2022-11-29 21:31:04 +00:00
// Unlike react, we provide a default error boundary that just renders the error as a string
2022-12-05 23:30:49 +00:00
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId(0))));
2022-11-29 21:31:04 +00:00
// the root element is always given element ID 0 since it's the container for the entire tree
dom.elements.insert(ElementRef::none());
2022-11-02 01:42:29 +00:00
2022-11-09 18:58:11 +00:00
dom
2022-11-02 01:42:29 +00:00
}
2022-11-18 06:31:14 +00:00
/// Get the state for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
2022-11-12 02:29:27 +00:00
pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
2023-01-22 23:16:34 +00:00
self.scopes.get(id)
2022-11-12 02:29:27 +00:00
}
2022-11-18 06:31:14 +00:00
/// Get the single scope at the top of the VirtualDom tree that will always be around
///
/// This scope has a ScopeId of 0 and is the root of the tree
2022-11-12 02:29:27 +00:00
pub fn base_scope(&self) -> &ScopeState {
2023-01-22 23:16:34 +00:00
self.scopes.get(ScopeId(0)).unwrap()
2022-11-12 02:29:27 +00:00
}
2022-11-18 04:00:39 +00:00
/// Build the virtualdom with a global context inserted into the base scope
2022-11-18 06:31:14 +00:00
///
/// This is useful for what is essentially dependency injection when building the app
2022-11-18 04:00:39 +00:00
pub fn with_root_context<T: Clone + 'static>(self, context: T) -> Self {
self.base_scope().provide_context(context);
self
}
2022-11-18 06:31:14 +00:00
/// Manually mark a scope as requiring a re-render
///
/// Whenever the VirtualDom "works", it will re-render this scope
2022-11-29 21:31:04 +00:00
pub fn mark_dirty(&mut self, id: ScopeId) {
2023-01-22 23:16:34 +00:00
if let Some(scope) = self.scopes.get(id) {
let height = scope.height;
self.dirty_scopes.insert(DirtyScope { height, id });
}
2022-11-12 02:29:27 +00:00
}
2022-11-16 00:05:22 +00:00
/// Call a listener inside the VirtualDom with data from outside the VirtualDom.
///
2022-11-18 06:31:14 +00:00
/// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
/// this method does not give any indication as to the success of the listener call. If the listener is not found,
/// nothing will happen.
2022-11-16 00:05:22 +00:00
///
2022-11-18 06:31:14 +00:00
/// It is up to the listeners themselves to mark nodes as dirty.
2022-11-16 00:05:22 +00:00
///
2022-11-18 06:31:14 +00:00
/// If you have multiple events, you can call this method multiple times before calling "render_with_deadline"
2022-11-18 04:00:39 +00:00
pub fn handle_event(
2022-11-16 00:05:22 +00:00
&mut self,
2023-01-14 19:57:03 +00:00
name: &str,
2022-11-18 04:00:39 +00:00
data: Rc<dyn Any>,
2022-11-16 00:05:22 +00:00
element: ElementId,
bubbles: bool,
2022-11-18 04:00:39 +00:00
) {
2022-11-16 00:05:22 +00:00
/*
2022-11-18 04:00:39 +00:00
------------------------
The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
we find the target path.
With the target path, we try and move up to the parent until there is no parent.
Due to how bubbling works, we call the listeners before walking to the parent.
If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order.
----------------------
For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the
right.
2022-11-18 04:00:39 +00:00
| <-- yes (is ascendant)
2022-11-18 06:31:14 +00:00
| | | <-- no (is not direct ascendant)
2022-11-18 04:00:39 +00:00
| | <-- yes (is ascendant)
2022-11-18 06:31:14 +00:00
| | | | | <--- target element, break early, don't check other listeners
2022-11-18 04:00:39 +00:00
| | | <-- no, broke early
| <-- no, broke early
2022-11-16 00:05:22 +00:00
*/
2022-11-18 04:00:39 +00:00
let mut parent_path = self.elements.get(element.0);
let mut listeners = vec![];
2022-11-12 02:29:27 +00:00
2022-11-18 06:31:14 +00:00
// We will clone this later. The data itself is wrapped in RC to be used in callbacks if required
2022-12-01 04:54:30 +00:00
let uievent = Event {
2023-01-01 20:41:18 +00:00
propagates: Rc::new(Cell::new(bubbles)),
2022-11-18 06:31:14 +00:00
data,
};
2023-04-10 14:45:16 +00:00
// If the event bubbles, we traverse through the tree until we find the target element.
if bubbles {
// Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
while let Some(el_ref) = parent_path {
// safety: we maintain references of all vnodes in the element slab
if let Some(template) = el_ref.template {
let template = unsafe { template.as_ref() };
let node_template = template.template.get();
let target_path = el_ref.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
if attr.name.trim_start_matches("on") == name
&& target_path.is_decendant(&this_path)
{
listeners.push(&attr.value);
// Break if this is the exact target element.
// This means we won't call two listeners with the same name on the same element. This should be
// documented, or be rejected from the rsx! macro outright
if target_path == this_path {
break;
}
2023-04-10 14:45:16 +00:00
}
2022-11-18 04:00:39 +00:00
}
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.drain(..).rev() {
if let AttributeValue::Listener(listener) = listener {
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
2023-04-10 14:45:16 +00:00
if !uievent.propagates.get() {
return;
}
2023-04-10 14:45:16 +00:00
}
2022-11-29 21:31:04 +00:00
}
parent_path = template.parent.and_then(|id| self.elements.get(id.0));
} else {
break;
}
2023-04-10 14:45:16 +00:00
}
} else {
// Otherwise, we just call the listener on the target element
if let Some(el_ref) = parent_path {
// safety: we maintain references of all vnodes in the element slab
if let Some(template) = el_ref.template {
let template = unsafe { template.as_ref() };
let node_template = template.template.get();
let target_path = el_ref.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
// Only call the listener if this is the exact target element.
if attr.name.trim_start_matches("on") == name && target_path == this_path {
if let AttributeValue::Listener(listener) = &attr.value {
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
break;
2023-04-10 14:45:16 +00:00
}
}
2022-11-18 04:00:39 +00:00
}
}
2022-11-12 02:29:27 +00:00
}
2022-11-18 04:00:39 +00:00
}
2022-11-12 02:29:27 +00:00
}
/// Wait for the scheduler to have any work.
///
/// This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when
/// any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method
/// will exit.
///
/// This method is cancel-safe, so you're fine to discard the future in a select block.
///
/// This lets us poll async tasks and suspended trees during idle periods without blocking the main thread.
2022-11-12 02:29:27 +00:00
///
/// # Example
///
/// ```rust, ignore
/// let dom = VirtualDom::new(App);
/// let sender = dom.get_scheduler_channel();
/// ```
pub async fn wait_for_work(&mut self) {
let mut some_msg = None;
loop {
match some_msg.take() {
// If a bunch of messages are ready in a sequence, try to pop them off synchronously
Some(msg) => match msg {
2022-11-29 21:31:04 +00:00
SchedulerMsg::Immediate(id) => self.mark_dirty(id),
2022-11-12 02:29:27 +00:00
SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
},
// If they're not ready, then we should wait for them to be ready
None => {
match self.rx.try_next() {
Ok(Some(val)) => some_msg = Some(val),
Ok(None) => return,
Err(_) => {
// If we have any dirty scopes, or finished fiber trees then we should exit
2023-07-14 23:56:17 +00:00
if !self.dirty_scopes.is_empty() || !self.suspended_scopes.is_empty() {
2022-11-12 02:29:27 +00:00
return;
}
some_msg = self.rx.next().await
}
}
}
}
}
}
2022-11-30 22:21:10 +00:00
/// Process all events in the queue until there are no more left
pub fn process_events(&mut self) {
while let Ok(Some(msg)) = self.rx.try_next() {
match msg {
SchedulerMsg::Immediate(id) => self.mark_dirty(id),
SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
}
}
2022-11-23 03:59:56 +00:00
}
2022-12-10 18:29:15 +00:00
/// Replace a template at runtime. This will re-render all components that use this template.
/// This is the primitive that enables hot-reloading.
///
/// The caller must ensure that the template refrences the same dynamic attributes and nodes as the original template.
///
/// This will only replace the the parent template, not any nested templates.
2022-12-10 18:29:15 +00:00
pub fn replace_template(&mut self, template: Template<'static>) {
self.register_template_first_byte_index(template);
2022-12-10 18:29:15 +00:00
// iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
2023-01-22 23:16:34 +00:00
for scope in self.scopes.iter() {
2022-12-26 03:11:45 +00:00
if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
if sync.template.get().name.rsplit_once(':').unwrap().0
== template.name.rsplit_once(':').unwrap().0
{
2022-12-10 18:29:15 +00:00
let height = scope.height;
self.dirty_scopes.insert(DirtyScope {
height,
id: scope.id,
});
}
}
}
}
2022-11-09 18:58:11 +00:00
/// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
2022-11-09 03:39:37 +00:00
///
/// The mutations item expects the RealDom's stack to be the root of the application.
2022-11-09 18:58:11 +00:00
///
/// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
/// root component will be ran once and then diffed. All updates will flow out as mutations.
///
/// All state stored in components will be completely wiped away.
///
/// Any templates previously registered will remain.
///
/// # Example
/// ```rust, ignore
/// static App: Component = |cx| cx.render(rsx!{ "hello world" });
///
/// let mut dom = VirtualDom::new();
/// let edits = dom.rebuild();
///
/// apply_edits(edits);
/// ```
2022-11-29 21:46:25 +00:00
pub fn rebuild(&mut self) -> Mutations {
2022-11-23 02:38:27 +00:00
match unsafe { self.run_scope(ScopeId(0)).extend_lifetime_ref() } {
2022-11-18 06:31:14 +00:00
// Rebuilding implies we append the created elements to the root
2022-12-20 19:13:06 +00:00
RenderReturn::Ready(node) => {
2022-12-03 00:24:49 +00:00
let m = self.create_scope(ScopeId(0), node);
self.mutations.edits.push(Mutation::AppendChildren {
id: ElementId(0),
m,
});
2022-11-06 08:48:34 +00:00
}
2022-11-23 02:38:27 +00:00
// If an error occurs, we should try to render the default error component and context where the error occured
2022-12-25 06:37:00 +00:00
RenderReturn::Aborted(_placeholder) => panic!("Cannot catch errors during rebuild"),
2022-11-04 03:56:31 +00:00
}
2022-11-09 03:39:37 +00:00
2022-11-23 03:59:56 +00:00
self.finalize()
2022-11-02 01:42:29 +00:00
}
2022-11-12 02:29:27 +00:00
/// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress
/// suspended subtrees.
pub fn render_immediate(&mut self) -> Mutations {
// Build a waker that won't wake up since our deadline is already expired when it's polled
let waker = futures_util::task::noop_waker();
let mut cx = std::task::Context::from_waker(&waker);
// Now run render with deadline but dont even try to poll any async tasks
let fut = self.render_with_deadline(std::future::ready(()));
pin_mut!(fut);
2022-11-18 06:31:14 +00:00
// The root component is not allowed to be async
match fut.poll(&mut cx) {
2022-11-12 02:29:27 +00:00
std::task::Poll::Ready(mutations) => mutations,
std::task::Poll::Pending => panic!("render_immediate should never return pending"),
}
}
2023-07-14 23:56:17 +00:00
/// Render the virtual dom, waiting for all suspense to be finished
///
/// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
pub async fn wait_for_suspense(&mut self) {
loop {
// println!("waiting for suspense {:?}", self.suspended_scopes);
2023-07-14 23:56:17 +00:00
if self.suspended_scopes.is_empty() {
return;
2023-07-14 23:56:17 +00:00
}
// println!("waiting for suspense");
2023-07-14 23:56:17 +00:00
self.wait_for_work().await;
// println!("Rendered immediately");
_ = self.render_immediate();
2023-07-14 23:56:17 +00:00
}
}
2022-11-02 01:42:29 +00:00
/// Render what you can given the timeline and then move on
2022-11-09 03:39:37 +00:00
///
/// It's generally a good idea to put some sort of limit on the suspense process in case a future is having issues.
2022-11-12 02:29:27 +00:00
///
/// If no suspense trees are present
2022-11-29 21:46:25 +00:00
pub async fn render_with_deadline(&mut self, deadline: impl Future<Output = ()>) -> Mutations {
2022-11-18 06:31:14 +00:00
pin_mut!(deadline);
2022-11-02 01:42:29 +00:00
2022-12-13 02:31:30 +00:00
self.process_events();
2022-11-12 02:29:27 +00:00
loop {
// Next, diff any dirty scopes
// We choose not to poll the deadline since we complete pretty quickly anyways
if let Some(dirty) = self.dirty_scopes.iter().next().cloned() {
self.dirty_scopes.remove(&dirty);
// If the scope doesn't exist for whatever reason, then we should skip it
2023-01-22 23:16:34 +00:00
if !self.scopes.contains(dirty.id) {
continue;
}
2022-11-23 04:16:14 +00:00
// Run the scope and get the mutations
self.run_scope(dirty.id);
2022-11-23 03:59:56 +00:00
self.diff_scope(dirty.id);
2022-11-12 02:29:27 +00:00
}
2022-11-23 03:59:56 +00:00
// If there's more work, then just continue, plenty of work to do
if !self.dirty_scopes.is_empty() {
continue;
}
2022-11-12 02:29:27 +00:00
2022-11-23 03:59:56 +00:00
// Poll the suspense leaves in the meantime
let mut work = self.wait_for_work();
// safety: this is okay since we don't touch the original future
let pinned = unsafe { std::pin::Pin::new_unchecked(&mut work) };
// If the deadline is exceded (left) then we should return the mutations we have
use futures_util::future::{select, Either};
if let Either::Left((_, _)) = select(&mut deadline, pinned).await {
// release the borrowed
drop(work);
return self.finalize();
2022-11-12 02:29:27 +00:00
}
}
2022-11-02 08:00:37 +00:00
}
2022-11-30 22:21:10 +00:00
/// Swap the current mutations with a new
fn finalize(&mut self) -> Mutations {
2023-01-03 03:26:12 +00:00
std::mem::take(&mut self.mutations)
2022-11-30 22:21:10 +00:00
}
2022-11-02 01:42:29 +00:00
}
impl Drop for VirtualDom {
fn drop(&mut self) {
2022-11-30 15:31:44 +00:00
// Simply drop this scope which drops all of its children
2023-01-16 03:23:49 +00:00
self.drop_scope(ScopeId(0), true);
2022-11-02 01:42:29 +00:00
}
}