Suspense boundaries/out of order streaming/anyhow like error handling (#2365)
* create static site generation helpers in the router crate * work on integrating static site generation into fullstack * move ssg into a separate crate * integrate ssg with the launch builder * simplify ssg example * fix static_routes for child routes * move CLI hot reloading websocket code into dioxus-hot-reload * fix some unused imports * use the same hot reloading websocket code for fullstack * fix fullstack hot reloading * move cli hot reloading logic into the hot reload crate * ssg example working with dx serve * add more examples * fix clippy * switch to a result for Element * fix formatting * fix hot reload doctest imports * fix axum imports * add show method to error context * implement retaining nodes during suspense * fix unterminated if statements * communicate between tasks and suspense boundaries * make suspense placeholders easier to use * implement IntoDynNode and IntoVNode for more wrappers * fix clippy examples * fix rsx tests * add streaming html utilities to the ssr package * unify hydration and non-hydration ssr cache * fix router with Result Element * don't run server doc tests * Fix hot reload websocket doc examples * simple apps working with fullstack streaming * fix preloading wasm * Report errors encountered while streaming * remove async from incremental renderer * document new VirtualDom suspense methods * make streaming work with incremental rendering * fix static site generation * document suspense structs * create closure type; allow async event handlers in props; allow shorthand event handlers * test forwarding event handlers with the shorthand syntax * fix clippy * fix imports in spawn async doctest * fix empty rsx * fix async result event handlers * fix mounting router in multiple places * Fix task dead cancel race condition * simplify diffing before adding suspense * fix binary size increase * fix attribute diffing * more diffing fixes * create minimal fullstack feature * smaller fullstack bundles * allow mounting nodes that are already created and creating nodes without mounting them * fix hot reload feature * fix replacing components * don't reclaim virtual nodes * client side suspense working! * fix CLI * slightly smaller fullstack builds * fix multiple suspended scopes * fix merge errors * yield back to tokio every few polls to fix suspending on many tasks at once * remove logs * document suspense boundary and update suspense example * fix ssg * make streaming optional * fix some router and core tests * fix suspense example * fix serialization with out of order server futures * add incremental streaming hackernews demo * fix hackernews demo * fix root hackernews redirect * fix formatting * add tests for suspense cases * slightly smaller binaries * slightly smaller * improve error handling docs * fix errors example link * fix doc tests * remove log file * fix ssr cache type inference * remove index.html * fix ssg render template * fix assigning ids on elements with dynamic attributes * add desktop feature to the workspace examples * remove router static generation example; ssg lives in the dioxus-static-generation package * add a test for effects during suspense * only run effects on mounted nodes * fix multiple suspense roots * fix node iterator * fix closures without arguments * fix dioxus-core readme doctest * remove suspense logs * fix scope stack * fix clippy * remove unused suspense boundary from hackernews * assert that launch never returns for better compiler errors * fix static generation launch function * fix web renderer * pass context providers into server functions * add an example for FromContext * clean up DioxusRouterExt * fix server function context * fix fullstack desktop example * forward CLI serve settings to fullstack * re-export serve config at the root of fullstack * forward env directly instead of using a guard * just set the port in the CLI for fullstack playwright tests * fix fullstack dioxus-cli-config feature * fix launch server merge conflicts * fix fullstack launch context * Merge branch 'main' into suspense-2.0 * fix fullstack html data * remove drop virtual dom feature * add a comment about only_write_templates binary size workaround * remove explicit dependencies from use_server_future * make ErrorContext and SuspenseContext more similar * Tweak: small tweaks to tomls to make diff smaller * only rerun components under suspense after the initial placeholders are sent to the client * add module docs for suspense * keep track of when suspense boundaries are resolved * start implementing JS out of order streaming * fix core tests * implement the server side of suspense with js * fix streaming ssr with nested suspense * move streaming ssr code into fullstack * revert minification changes * serialize server future data as the html streams * start loading scripts wasm immediately instead of defering the script * very basic nested suspense example working with minimal html updates * clean up some suspense/error docs * fix hydrating nested pending server futures * sort resolved boundaries by height * Fix disconnecting clients while streaming * fix static generation crate * don't insert extra divs when hydrating streamed chunks * wait to swap in the elements until they are hydrated * remove inline streaming script * hackernews partially working * fix spa mode * banish the open shadow dom * fix removing placeholder * set up streaming playwright test * run web playwright tests on 9999 to avoid port conflicts with other local servers * remove suspense nodes if the suspense boundary is replaced before the suspense resolves on the server * ignore hydration of removed suspense boundaries * use path based indexing to fix hydrating suspense after parent suspense with child is removed * re-export dioxus error * remove resolved suspense divs if the suspense boundary has been removed * Fix client side initialized server futures * ignore comment nodes while traversing nodes in core to avoid lists getting swapped out with suspense * Pass initial hydration data to the client * hide pre nodes * don't panic if reclaiming an element fails * fix scope stack when polling tasks * improve deserialization out of length message * Ok(VNode::placeholder()) -> VNode::empty() * fix typo in rsx usage * restore testing changes from suspense example * clean up some logs and comments * fix playwright tests * clean up more changes in core * clean up core tests * remove anymap dependency * clean up changes to hooks * clean up changes in the router, rsx, and web * revert changes to axum-hello-world * fix use_server_future * fix clippy in dioxus-core * check that the next or previous node exist before checking if we should ignore them * fix formatting * fix suspense playwright test * remove unused suspense code * add more suspense playwright tests * add more docs for error boundaries * fix suspense core tests * fix ErrorBoundary example * remove a bunch of debug logging in js * fix router failure_external_navigation * use absolute paths in the interpreter build.rs * strip '\r' while hashing ts files * add a wrapper with a default error boundary and suspense boundary * restore hot reloading * ignore non-ts files when hashing * sort ts files before hashing them * fix rsx tests * fix fullstack doc tests * fix core tests * fix axum auth example * update suspense hydration diagram * longer playwright build limit * tiny fixes - spelling, formatting * update diagram link * remove comment and template nodes for suspense placeholders * remove comment nodes as we hydrate text * simplify hackernews example * clean up hydrating text nodes * switch to a separate environment variable for the base path for smaller binaries * clean up file system html trait * fix form data * move streaming code into fullstack * implement serialize and deserialize for CapturedError * remove waits in the nested suspense playwright spec * force sequential fullstack builds for CI * longer nested suspense delay for CI * fix --force-sequential flag * wait to launch server until client build is done --------- Co-authored-by: Jonathan Kelley <jkelleyrtp@gmail.com>
This commit is contained in:
1 parent
ffa36a67c3
commit
022e4ad203
175 files changed
+7872
-4010
No files matched your search
@@ -1,8 +1,4 @@
|
||||
use crate::{
|
||||
innerlude::{throw_error, CapturedPanic},
|
||||
nodes::RenderReturn,
|
||||
ComponentFunction,
|
||||
};
|
||||
use crate::{innerlude::CapturedPanic, nodes::RenderReturn, ComponentFunction};
|
||||
use std::{any::Any, panic::AssertUnwindSafe};
|
||||
|
||||
pub(crate) type BoxedAnyProps = Box<dyn AnyProps>;
|
||||
@@ -15,6 +11,8 @@ pub(crate) trait AnyProps: 'static {
|
||||
fn memoize(&mut self, other: &dyn Any) -> bool;
|
||||
/// Get the props as a type erased `dyn Any`.
|
||||
fn props(&self) -> &dyn Any;
|
||||
/// Get the props as a type erased `dyn Any`.
|
||||
fn props_mut(&mut self) -> &mut dyn Any;
|
||||
/// Duplicate this component into a new boxed component.
|
||||
fn duplicate(&self) -> BoxedAnyProps;
|
||||
}
|
||||
@@ -72,19 +70,24 @@ impl<F: ComponentFunction<P, M> + Clone, P: Clone + 'static, M: 'static> AnyProp
|
||||
&self.props
|
||||
}
|
||||
|
||||
fn props_mut(&mut self) -> &mut dyn Any {
|
||||
&mut self.props
|
||||
}
|
||||
|
||||
fn render(&self) -> RenderReturn {
|
||||
let res = std::panic::catch_unwind(AssertUnwindSafe(move || {
|
||||
self.render_fn.rebuild(self.props.clone())
|
||||
}));
|
||||
|
||||
match res {
|
||||
Ok(Some(e)) => RenderReturn::Ready(e),
|
||||
Ok(None) => RenderReturn::default(),
|
||||
Ok(node) => RenderReturn { node },
|
||||
Err(err) => {
|
||||
let component_name = self.name;
|
||||
tracing::error!("Error while rendering component `{component_name}`: {err:?}");
|
||||
throw_error::<()>(CapturedPanic { error: err });
|
||||
RenderReturn::default()
|
||||
let panic = CapturedPanic { error: err };
|
||||
RenderReturn {
|
||||
node: Err(panic.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,18 +19,25 @@ pub(crate) struct MountId(pub(crate) usize);
|
||||
|
||||
impl Default for MountId {
|
||||
fn default() -> Self {
|
||||
Self(usize::MAX)
|
||||
Self::PLACEHOLDER
|
||||
}
|
||||
}
|
||||
|
||||
impl MountId {
|
||||
pub(crate) const PLACEHOLDER: Self = Self(usize::MAX);
|
||||
|
||||
pub(crate) fn as_usize(self) -> Option<usize> {
|
||||
if self.0 == usize::MAX {
|
||||
if self == Self::PLACEHOLDER {
|
||||
None
|
||||
} else {
|
||||
Some(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub(crate) fn mounted(self) -> bool {
|
||||
self != Self::PLACEHOLDER
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -53,16 +60,18 @@ impl VirtualDom {
|
||||
}
|
||||
|
||||
pub(crate) fn reclaim(&mut self, el: ElementId) {
|
||||
self.try_reclaim(el)
|
||||
.unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
|
||||
if !self.try_reclaim(el) {
|
||||
tracing::error!("cannot reclaim {:?}", el);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<()> {
|
||||
if el.0 == 0 {
|
||||
panic!("Cannot reclaim the root element",);
|
||||
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> bool {
|
||||
// We never reclaim the unmounted elements or the root element
|
||||
if el.0 == 0 || el.0 == usize::MAX {
|
||||
return true;
|
||||
}
|
||||
|
||||
self.elements.try_remove(el.0).map(|_| ())
|
||||
self.elements.try_remove(el.0).is_some()
|
||||
}
|
||||
|
||||
// Drop a scope without dropping its children
|
||||
|
||||
@@ -1,56 +1,125 @@
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::{
|
||||
any::TypeId,
|
||||
ops::{Deref, DerefMut},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
any_props::AnyProps,
|
||||
innerlude::{ElementRef, MountId, ScopeOrder, VComponent, WriteMutations},
|
||||
nodes::RenderReturn,
|
||||
innerlude::{
|
||||
ElementRef, MountId, ScopeOrder, SuspenseBoundaryProps, SuspenseBoundaryPropsWithOwner,
|
||||
VComponent, WriteMutations,
|
||||
},
|
||||
nodes::VNode,
|
||||
scopes::ScopeId,
|
||||
virtual_dom::VirtualDom,
|
||||
RenderReturn,
|
||||
};
|
||||
|
||||
impl VirtualDom {
|
||||
pub(crate) fn diff_scope(
|
||||
pub(crate) fn run_and_diff_scope<M: WriteMutations>(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
to: Option<&mut M>,
|
||||
scope_id: ScopeId,
|
||||
) {
|
||||
let scope = &mut self.scopes[scope_id.0];
|
||||
if SuspenseBoundaryProps::downcast_mut_from_props(&mut *scope.props).is_some() {
|
||||
SuspenseBoundaryProps::diff(scope_id, self, to)
|
||||
} else {
|
||||
let new_nodes = self.run_scope(scope_id);
|
||||
self.diff_scope(to, scope_id, new_nodes);
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self, to), level = "trace", name = "VirtualDom::diff_scope")]
|
||||
fn diff_scope<M: WriteMutations>(
|
||||
&mut self,
|
||||
to: Option<&mut M>,
|
||||
scope: ScopeId,
|
||||
new_nodes: RenderReturn,
|
||||
) {
|
||||
self.runtime.scope_stack.borrow_mut().push(scope);
|
||||
// We don't diff the nodes if the scope is suspended or has an error
|
||||
let Ok(new_real_nodes) = &new_nodes.node else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.runtime.push_scope(scope);
|
||||
let scope_state = &mut self.scopes[scope.0];
|
||||
// Load the old and new bump arenas
|
||||
let new = &new_nodes;
|
||||
// Load the old and new rendered nodes
|
||||
let old = scope_state.last_rendered_node.take().unwrap();
|
||||
|
||||
old.diff_node(new, self, to);
|
||||
// If there are suspended scopes, we need to check if the scope is suspended before we diff it
|
||||
// If it is suspended, we need to diff it but write the mutations nothing
|
||||
// Note: It is important that we still diff the scope even if it is suspended, because the scope may render other child components which may change between renders
|
||||
let mut render_to = to.filter(|_| self.runtime.scope_should_render(scope));
|
||||
old.diff_node(new_real_nodes, self, render_to.as_deref_mut());
|
||||
|
||||
let scope_state = &mut self.scopes[scope.0];
|
||||
scope_state.last_rendered_node = Some(new_nodes);
|
||||
self.scopes[scope.0].last_rendered_node = Some(new_nodes);
|
||||
|
||||
self.runtime.scope_stack.borrow_mut().pop();
|
||||
if render_to.is_some() {
|
||||
self.runtime.get_state(scope).unwrap().mount(&self.runtime);
|
||||
}
|
||||
|
||||
self.runtime.pop_scope();
|
||||
}
|
||||
|
||||
/// Create a new template [`VNode`] and write it to the [`Mutations`] buffer.
|
||||
/// Create a new [`ScopeState`] for a component that has been created with [`VirtualDom::create_scope`]
|
||||
///
|
||||
/// This method pushes the ScopeID to the internal scopestack and returns the number of nodes created.
|
||||
pub(crate) fn create_scope(
|
||||
/// Returns the number of nodes created on the stack
|
||||
#[tracing::instrument(skip(self, to), level = "trace", name = "VirtualDom::create_scope")]
|
||||
pub(crate) fn create_scope<M: WriteMutations>(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
to: Option<&mut M>,
|
||||
scope: ScopeId,
|
||||
new_node: RenderReturn,
|
||||
new_nodes: RenderReturn,
|
||||
parent: Option<ElementRef>,
|
||||
) -> usize {
|
||||
self.runtime.scope_stack.borrow_mut().push(scope);
|
||||
self.runtime.push_scope(scope);
|
||||
|
||||
// If there are suspended scopes, we need to check if the scope is suspended before we diff it
|
||||
// If it is suspended, we need to diff it but write the mutations nothing
|
||||
// Note: It is important that we still diff the scope even if it is suspended, because the scope may render other child components which may change between renders
|
||||
let mut render_to = to.filter(|_| self.runtime.scope_should_render(scope));
|
||||
|
||||
// Create the node
|
||||
let nodes = new_node.create(self, to, parent);
|
||||
let nodes = new_nodes.create(self, parent, render_to.as_deref_mut());
|
||||
|
||||
// Then set the new node as the last rendered node
|
||||
self.scopes[scope.0].last_rendered_node = Some(new_node);
|
||||
self.scopes[scope.0].last_rendered_node = Some(new_nodes);
|
||||
|
||||
self.runtime.scope_stack.borrow_mut().pop();
|
||||
if render_to.is_some() {
|
||||
self.runtime.get_state(scope).unwrap().mount(&self.runtime);
|
||||
}
|
||||
|
||||
self.runtime.pop_scope();
|
||||
nodes
|
||||
}
|
||||
|
||||
pub(crate) fn remove_component_node<M: WriteMutations>(
|
||||
&mut self,
|
||||
to: Option<&mut M>,
|
||||
destroy_component_state: bool,
|
||||
scope_id: ScopeId,
|
||||
replace_with: Option<usize>,
|
||||
) {
|
||||
// If this is a suspense boundary, remove the suspended nodes as well
|
||||
if let Some(mut suspense) =
|
||||
SuspenseBoundaryProps::downcast_mut_from_props(&mut *self.scopes[scope_id.0].props)
|
||||
.cloned()
|
||||
{
|
||||
suspense.remove_suspended_nodes::<M>(self, destroy_component_state);
|
||||
}
|
||||
|
||||
// Remove the component from the dom
|
||||
if let Some(node) = self.scopes[scope_id.0].last_rendered_node.as_ref() {
|
||||
node.clone_mounted()
|
||||
.remove_node_inner(self, to, destroy_component_state, replace_with)
|
||||
};
|
||||
|
||||
if destroy_component_state {
|
||||
// Now drop all the resources
|
||||
self.drop_scope(scope_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VNode {
|
||||
@@ -63,7 +132,7 @@ impl VNode {
|
||||
scope_id: ScopeId,
|
||||
parent: Option<ElementRef>,
|
||||
dom: &mut VirtualDom,
|
||||
to: &mut impl WriteMutations,
|
||||
to: Option<&mut impl WriteMutations>,
|
||||
) {
|
||||
// Replace components that have different render fns
|
||||
if old.render_fn != new.render_fn {
|
||||
@@ -83,9 +152,8 @@ impl VNode {
|
||||
return;
|
||||
}
|
||||
|
||||
// Now run the component and diff it
|
||||
let new = dom.run_scope(scope_id);
|
||||
dom.diff_scope(to, scope_id, new);
|
||||
// Now diff the scope
|
||||
dom.run_and_diff_scope(to, scope_id);
|
||||
|
||||
let height = dom.runtime.get_state(scope_id).unwrap().height;
|
||||
dom.dirty_scopes.remove(&ScopeOrder::new(height, scope_id));
|
||||
@@ -98,16 +166,21 @@ impl VNode {
|
||||
new: &VComponent,
|
||||
parent: Option<ElementRef>,
|
||||
dom: &mut VirtualDom,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
) {
|
||||
let scope = ScopeId(dom.mounts[mount.0].mounted_dynamic_nodes[idx]);
|
||||
|
||||
let m = self.create_component_node(mount, idx, new, parent, dom, to);
|
||||
// Remove the scope id from the mount
|
||||
dom.mounts[mount.0].mounted_dynamic_nodes[idx] = ScopeId::PLACEHOLDER.0;
|
||||
let m = self.create_component_node(mount, idx, new, parent, dom, to.as_deref_mut());
|
||||
|
||||
// Instead of *just* removing it, we can use the replace mutation
|
||||
dom.remove_component_node(to, scope, Some(m), true);
|
||||
dom.remove_component_node(to, true, scope, Some(m));
|
||||
}
|
||||
|
||||
/// Create a new component (if it doesn't already exist) node and then mount the [`ScopeState`] for a component
|
||||
///
|
||||
/// Returns the number of nodes created on the stack
|
||||
pub(super) fn create_component_node(
|
||||
&self,
|
||||
mount: MountId,
|
||||
@@ -115,19 +188,40 @@ impl VNode {
|
||||
component: &VComponent,
|
||||
parent: Option<ElementRef>,
|
||||
dom: &mut VirtualDom,
|
||||
to: &mut impl WriteMutations,
|
||||
to: Option<&mut impl WriteMutations>,
|
||||
) -> usize {
|
||||
// Load up a ScopeId for this vcomponent. If it's already mounted, then we can just use that
|
||||
let scope = dom
|
||||
.new_scope(component.props.duplicate(), component.name)
|
||||
.state()
|
||||
.id;
|
||||
// If this is a suspense boundary, run our suspense creation logic instead of running the component
|
||||
if component.props.props().type_id() == TypeId::of::<SuspenseBoundaryPropsWithOwner>() {
|
||||
return SuspenseBoundaryProps::create(mount, idx, component, parent, dom, to);
|
||||
}
|
||||
|
||||
// Store the scope id for the next render
|
||||
dom.mounts[mount.0].mounted_dynamic_nodes[idx] = scope.0;
|
||||
let mut scope_id = ScopeId(dom.mounts[mount.0].mounted_dynamic_nodes[idx]);
|
||||
|
||||
let new = dom.run_scope(scope);
|
||||
// If the scopeid is a placeholder, we need to load up a new scope for this vcomponent. If it's already mounted, then we can just use that
|
||||
if scope_id.is_placeholder() {
|
||||
scope_id = dom
|
||||
.new_scope(component.props.duplicate(), component.name)
|
||||
.state()
|
||||
.id;
|
||||
|
||||
dom.create_scope(to, scope, new, parent)
|
||||
// Store the scope id for the next render
|
||||
dom.mounts[mount.0].mounted_dynamic_nodes[idx] = scope_id.0;
|
||||
|
||||
// If this is a new scope, we also need to run it once to get the initial state
|
||||
let new = dom.run_scope(scope_id);
|
||||
|
||||
// Then set the new node as the last rendered node
|
||||
dom.scopes[scope_id.0].last_rendered_node = Some(new);
|
||||
}
|
||||
|
||||
let scope = ScopeId(dom.mounts[mount.0].mounted_dynamic_nodes[idx]);
|
||||
|
||||
let new_node = dom.scopes[scope.0]
|
||||
.last_rendered_node
|
||||
.as_ref()
|
||||
.expect("Component to be mounted")
|
||||
.clone();
|
||||
|
||||
dom.create_scope(to, scope, new_node, parent)
|
||||
}
|
||||
}
|
||||
+157
-125
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
innerlude::{ElementRef, WriteMutations},
|
||||
nodes::VNode,
|
||||
DynamicNode, ScopeId, TemplateNode, VirtualDom,
|
||||
DynamicNode, ScopeId, VirtualDom,
|
||||
};
|
||||
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
@@ -9,7 +9,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
|
||||
impl VirtualDom {
|
||||
pub(crate) fn diff_non_empty_fragment(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
to: Option<&mut impl WriteMutations>,
|
||||
old: &[VNode],
|
||||
new: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
@@ -42,7 +42,7 @@ impl VirtualDom {
|
||||
// the change list stack is in the same state when this function returns.
|
||||
fn diff_non_keyed_children(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
old: &[VNode],
|
||||
new: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
@@ -54,15 +54,18 @@ impl VirtualDom {
|
||||
debug_assert!(!old.is_empty());
|
||||
|
||||
match old.len().cmp(&new.len()) {
|
||||
Ordering::Greater => self.remove_nodes(to, &old[new.len()..], None),
|
||||
Ordering::Less => {
|
||||
self.create_and_insert_after(to, &new[old.len()..], old.last().unwrap(), parent)
|
||||
}
|
||||
Ordering::Greater => self.remove_nodes(to.as_deref_mut(), &old[new.len()..], None),
|
||||
Ordering::Less => self.create_and_insert_after(
|
||||
to.as_deref_mut(),
|
||||
&new[old.len()..],
|
||||
old.last().unwrap(),
|
||||
parent,
|
||||
),
|
||||
Ordering::Equal => {}
|
||||
}
|
||||
|
||||
for (new, old) in new.iter().zip(old.iter()) {
|
||||
old.diff_node(new, self, to);
|
||||
old.diff_node(new, self, to.as_deref_mut());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +87,7 @@ impl VirtualDom {
|
||||
// The stack is empty upon entry.
|
||||
fn diff_keyed_children(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
old: &[VNode],
|
||||
new: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
@@ -116,10 +119,11 @@ impl VirtualDom {
|
||||
//
|
||||
// `shared_prefix_count` is the count of how many nodes at the start of
|
||||
// `new` and `old` share the same keys.
|
||||
let (left_offset, right_offset) = match self.diff_keyed_ends(to, old, new, parent) {
|
||||
Some(count) => count,
|
||||
None => return,
|
||||
};
|
||||
let (left_offset, right_offset) =
|
||||
match self.diff_keyed_ends(to.as_deref_mut(), old, new, parent) {
|
||||
Some(count) => count,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Ok, we now hopefully have a smaller range of children in the middle
|
||||
// within which to re-order nodes with the same keys, remove old nodes with
|
||||
@@ -164,7 +168,7 @@ impl VirtualDom {
|
||||
/// If there is no offset, then this function returns None and the diffing is complete.
|
||||
fn diff_keyed_ends(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
old: &[VNode],
|
||||
new: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
@@ -176,7 +180,7 @@ impl VirtualDom {
|
||||
if old.key != new.key {
|
||||
break;
|
||||
}
|
||||
old.diff_node(new, self, to);
|
||||
old.diff_node(new, self, to.as_deref_mut());
|
||||
left_offset += 1;
|
||||
}
|
||||
|
||||
@@ -201,7 +205,7 @@ impl VirtualDom {
|
||||
if old.key != new.key {
|
||||
break;
|
||||
}
|
||||
old.diff_node(new, self, to);
|
||||
old.diff_node(new, self, to.as_deref_mut());
|
||||
right_offset += 1;
|
||||
}
|
||||
|
||||
@@ -224,7 +228,7 @@ impl VirtualDom {
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn diff_keyed_middle(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
old: &[VNode],
|
||||
new: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
@@ -236,7 +240,7 @@ impl VirtualDom {
|
||||
- IE if we have ABCD becomes BACD, our sequence would be 1,0,2,3
|
||||
- if we have ABCD to ABDE, our sequence would be 0,1,3,MAX because E doesn't exist
|
||||
|
||||
now, we should have a list of integers that indicates where in the old list the new items mapto.
|
||||
now, we should have a list of integers that indicates where in the old list the new items map to.
|
||||
|
||||
4. Compute the LIS of this list
|
||||
- this indicates the longest list of new children that won't need to be moved.
|
||||
@@ -257,11 +261,11 @@ impl VirtualDom {
|
||||
|
||||
// 1. Map the old keys into a numerical ordering based on indices.
|
||||
// 2. Create a map of old key to its index
|
||||
// IE if the keys were A B C, then we would have (A, 1) (B, 2) (C, 3).
|
||||
// IE if the keys were A B C, then we would have (A, 0) (B, 1) (C, 2).
|
||||
let old_key_to_old_index = old
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, o)| (o.key.as_ref().unwrap(), i))
|
||||
.map(|(i, o)| (o.key.as_ref().unwrap().as_str(), i))
|
||||
.collect::<FxHashMap<_, _>>();
|
||||
|
||||
let mut shared_keys = FxHashSet::default();
|
||||
@@ -271,163 +275,194 @@ impl VirtualDom {
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let key = node.key.as_ref().unwrap();
|
||||
if let Some(&index) = old_key_to_old_index.get(&key) {
|
||||
if let Some(&index) = old_key_to_old_index.get(key.as_str()) {
|
||||
shared_keys.insert(key);
|
||||
index
|
||||
} else {
|
||||
u32::MAX as usize
|
||||
usize::MAX
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
.collect::<Box<[_]>>();
|
||||
|
||||
// If none of the old keys are reused by the new children, then we remove all the remaining old children and
|
||||
// create the new children afresh.
|
||||
if shared_keys.is_empty() {
|
||||
if !old.is_empty() {
|
||||
let m = self.create_children(to, new, parent);
|
||||
self.remove_nodes(to, old, Some(m));
|
||||
} else {
|
||||
// I think this is wrong - why are we appending?
|
||||
// only valid of the if there are no trailing elements
|
||||
// self.create_and_append_children(new);
|
||||
debug_assert!(
|
||||
!old.is_empty(),
|
||||
"we should never be appending - just creating N"
|
||||
);
|
||||
|
||||
let m = self.create_children(to.as_deref_mut(), new, parent);
|
||||
self.remove_nodes(to, old, Some(m));
|
||||
|
||||
todo!("we should never be appending - just creating N");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// remove any old children that are not shared
|
||||
// todo: make this an iterator
|
||||
for child in old {
|
||||
let key = child.key.as_ref().unwrap();
|
||||
if !shared_keys.contains(&key) {
|
||||
child.remove_node(self, to, None, true);
|
||||
}
|
||||
for child_to_remove in old
|
||||
.iter()
|
||||
.filter(|child| !shared_keys.contains(child.key.as_ref().unwrap()))
|
||||
{
|
||||
child_to_remove.remove_node(self, to.as_deref_mut(), None);
|
||||
}
|
||||
|
||||
// 4. Compute the LIS of this list
|
||||
let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len());
|
||||
|
||||
let mut predecessors = vec![0; new_index_to_old_index.len()];
|
||||
let mut starts = vec![0; new_index_to_old_index.len()];
|
||||
let mut allocation = vec![0; new_index_to_old_index.len() * 2];
|
||||
let (predecessors, starts) = allocation.split_at_mut(new_index_to_old_index.len());
|
||||
|
||||
longest_increasing_subsequence::lis_with(
|
||||
&new_index_to_old_index,
|
||||
&mut lis_sequence,
|
||||
|a, b| a < b,
|
||||
&mut predecessors,
|
||||
&mut starts,
|
||||
predecessors,
|
||||
starts,
|
||||
);
|
||||
|
||||
// the lis comes out backwards, I think. can't quite tell.
|
||||
lis_sequence.sort_unstable();
|
||||
|
||||
// if a new node gets u32 max and is at the end, then it might be part of our LIS (because u32 max is a valid LIS)
|
||||
if lis_sequence.last().map(|f| new_index_to_old_index[*f]) == Some(u32::MAX as usize) {
|
||||
lis_sequence.pop();
|
||||
if lis_sequence.first().map(|f| new_index_to_old_index[*f]) == Some(usize::MAX) {
|
||||
lis_sequence.remove(0);
|
||||
}
|
||||
|
||||
// Diff each nod in the LIS
|
||||
for idx in &lis_sequence {
|
||||
old[new_index_to_old_index[*idx]].diff_node(&new[*idx], self, to);
|
||||
old[new_index_to_old_index[*idx]].diff_node(&new[*idx], self, to.as_deref_mut());
|
||||
}
|
||||
|
||||
let mut nodes_created = 0;
|
||||
/// Create or diff each node in a range depending on whether it is in the LIS or not
|
||||
/// Returns the number of nodes created on the stack
|
||||
fn create_or_diff(
|
||||
vdom: &mut VirtualDom,
|
||||
new: &[VNode],
|
||||
old: &[VNode],
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
parent: Option<ElementRef>,
|
||||
new_index_to_old_index: &[usize],
|
||||
range: std::ops::Range<usize>,
|
||||
) -> usize {
|
||||
let range_start = range.start;
|
||||
new[range]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, new_node)| {
|
||||
let new_idx = range_start + idx;
|
||||
let old_index = new_index_to_old_index[new_idx];
|
||||
// If the node existed in the old list, diff it
|
||||
if let Some(old_node) = old.get(old_index) {
|
||||
old_node.diff_node(new_node, vdom, to.as_deref_mut());
|
||||
if let Some(to) = to.as_deref_mut() {
|
||||
new_node.push_all_root_nodes(vdom, to)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
// Otherwise, just add it to the stack
|
||||
new_node.create(vdom, parent, to.as_deref_mut())
|
||||
}
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
// add mount instruction for the first items not covered by the lis
|
||||
let last = *lis_sequence.last().unwrap();
|
||||
// add mount instruction for the items before the LIS
|
||||
let last = *lis_sequence.first().unwrap();
|
||||
if last < (new.len() - 1) {
|
||||
for (idx, new_node) in new[(last + 1)..].iter().enumerate() {
|
||||
let new_idx = idx + last + 1;
|
||||
let old_index = new_index_to_old_index[new_idx];
|
||||
if old_index == u32::MAX as usize {
|
||||
nodes_created += new_node.create(self, to, parent);
|
||||
} else {
|
||||
old[old_index].diff_node(new_node, self, to);
|
||||
nodes_created += new_node.push_all_real_nodes(self, to);
|
||||
}
|
||||
}
|
||||
let nodes_created = create_or_diff(
|
||||
self,
|
||||
new,
|
||||
old,
|
||||
to.as_deref_mut(),
|
||||
parent,
|
||||
&new_index_to_old_index,
|
||||
(last + 1)..new.len(),
|
||||
);
|
||||
|
||||
let id = new[last].find_last_element(self);
|
||||
if nodes_created > 0 {
|
||||
to.insert_nodes_after(id, nodes_created)
|
||||
}
|
||||
nodes_created = 0;
|
||||
// Insert all the nodes that we just created after the last node in the LIS
|
||||
self.insert_after(to.as_deref_mut(), nodes_created, &new[last]);
|
||||
}
|
||||
|
||||
// for each spacing, generate a mount instruction
|
||||
let mut lis_iter = lis_sequence.iter().rev();
|
||||
// For each node inside of the LIS, but not included in the LIS, generate a mount instruction
|
||||
// We loop over the LIS in reverse order and insert any nodes we find in the gaps between indexes
|
||||
let mut lis_iter = lis_sequence.iter();
|
||||
let mut last = *lis_iter.next().unwrap();
|
||||
for next in lis_iter {
|
||||
if last - next > 1 {
|
||||
for (idx, new_node) in new[(next + 1)..last].iter().enumerate() {
|
||||
let new_idx = idx + next + 1;
|
||||
let old_index = new_index_to_old_index[new_idx];
|
||||
if old_index == u32::MAX as usize {
|
||||
nodes_created += new_node.create(self, to, parent);
|
||||
} else {
|
||||
old[old_index].diff_node(new_node, self, to);
|
||||
nodes_created += new_node.push_all_real_nodes(self, to);
|
||||
}
|
||||
}
|
||||
let nodes_created = create_or_diff(
|
||||
self,
|
||||
new,
|
||||
old,
|
||||
to.as_deref_mut(),
|
||||
parent,
|
||||
&new_index_to_old_index,
|
||||
(next + 1)..last,
|
||||
);
|
||||
|
||||
let id = new[last].find_first_element(self);
|
||||
if nodes_created > 0 {
|
||||
to.insert_nodes_before(id, nodes_created);
|
||||
}
|
||||
|
||||
nodes_created = 0;
|
||||
self.insert_before(to.as_deref_mut(), nodes_created, &new[last]);
|
||||
}
|
||||
last = *next;
|
||||
}
|
||||
|
||||
// add mount instruction for the last items not covered by the lis
|
||||
let first_lis = *lis_sequence.first().unwrap();
|
||||
// add mount instruction for the items after the LIS
|
||||
let first_lis = *lis_sequence.last().unwrap();
|
||||
if first_lis > 0 {
|
||||
for (idx, new_node) in new[..first_lis].iter().enumerate() {
|
||||
let old_index = new_index_to_old_index[idx];
|
||||
if old_index == u32::MAX as usize {
|
||||
nodes_created += new_node.create(self, to, parent);
|
||||
} else {
|
||||
old[old_index].diff_node(new_node, self, to);
|
||||
nodes_created += new_node.push_all_real_nodes(self, to);
|
||||
}
|
||||
}
|
||||
let nodes_created = create_or_diff(
|
||||
self,
|
||||
new,
|
||||
old,
|
||||
to.as_deref_mut(),
|
||||
parent,
|
||||
&new_index_to_old_index,
|
||||
0..first_lis,
|
||||
);
|
||||
|
||||
let id = new[first_lis].find_first_element(self);
|
||||
if nodes_created > 0 {
|
||||
to.insert_nodes_before(id, nodes_created);
|
||||
}
|
||||
self.insert_before(to, nodes_created, &new[first_lis]);
|
||||
}
|
||||
}
|
||||
|
||||
fn create_and_insert_before(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
new: &[VNode],
|
||||
before: &VNode,
|
||||
parent: Option<ElementRef>,
|
||||
) {
|
||||
let m = self.create_children(to, new, parent);
|
||||
let id = before.find_first_element(self);
|
||||
to.insert_nodes_before(id, m);
|
||||
let m = self.create_children(to.as_deref_mut(), new, parent);
|
||||
self.insert_before(to, m, before);
|
||||
}
|
||||
|
||||
fn insert_before(&mut self, to: Option<&mut impl WriteMutations>, new: usize, before: &VNode) {
|
||||
if let Some(to) = to {
|
||||
if new > 0 {
|
||||
let id = before.find_first_element(self);
|
||||
to.insert_nodes_before(id, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_and_insert_after(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
new: &[VNode],
|
||||
after: &VNode,
|
||||
parent: Option<ElementRef>,
|
||||
) {
|
||||
let m = self.create_children(to, new, parent);
|
||||
let id = after.find_last_element(self);
|
||||
to.insert_nodes_after(id, m);
|
||||
let m = self.create_children(to.as_deref_mut(), new, parent);
|
||||
self.insert_after(to, m, after);
|
||||
}
|
||||
|
||||
fn insert_after(&mut self, to: Option<&mut impl WriteMutations>, new: usize, after: &VNode) {
|
||||
if let Some(to) = to {
|
||||
if new > 0 {
|
||||
let id = after.find_last_element(self);
|
||||
to.insert_nodes_after(id, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VNode {
|
||||
/// Push all the real nodes on the stack
|
||||
pub(crate) fn push_all_real_nodes(
|
||||
/// Push all the root nodes on the stack
|
||||
pub(crate) fn push_all_root_nodes(
|
||||
&self,
|
||||
dom: &VirtualDom,
|
||||
to: &mut impl WriteMutations,
|
||||
@@ -440,30 +475,27 @@ impl VNode {
|
||||
.roots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(root_idx, _)| match &self.template.get().roots[root_idx] {
|
||||
TemplateNode::Dynamic { id: idx } => match &self.dynamic_nodes[*idx] {
|
||||
DynamicNode::Placeholder(_) | DynamicNode::Text(_) => {
|
||||
to.push_root(mount.root_ids[root_idx]);
|
||||
1
|
||||
}
|
||||
DynamicNode::Fragment(nodes) => {
|
||||
.map(
|
||||
|(root_idx, _)| match self.get_dynamic_root_node_and_id(root_idx) {
|
||||
Some((_, DynamicNode::Fragment(nodes))) => {
|
||||
let mut accumulated = 0;
|
||||
for node in nodes {
|
||||
accumulated += node.push_all_real_nodes(dom, to);
|
||||
accumulated += node.push_all_root_nodes(dom, to);
|
||||
}
|
||||
accumulated
|
||||
}
|
||||
DynamicNode::Component(_) => {
|
||||
let scope = ScopeId(mount.mounted_dynamic_nodes[*idx]);
|
||||
Some((idx, DynamicNode::Component(_))) => {
|
||||
let scope = ScopeId(mount.mounted_dynamic_nodes[idx]);
|
||||
let node = dom.get_scope(scope).unwrap().root_node();
|
||||
node.push_all_real_nodes(dom, to)
|
||||
node.push_all_root_nodes(dom, to)
|
||||
}
|
||||
// This is a static root node or a single dynamic node, just push it
|
||||
None | Some((_, DynamicNode::Placeholder(_) | DynamicNode::Text(_))) => {
|
||||
to.push_root(mount.root_ids[root_idx]);
|
||||
1
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
to.push_root(mount.root_ids[root_idx]);
|
||||
1
|
||||
}
|
||||
})
|
||||
)
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
//! This module contains all the code for creating and diffing nodes.
|
||||
//!
|
||||
//! For suspense there are three different cases we need to handle:
|
||||
//! - Creating nodes/scopes without mounting them
|
||||
//! - Diffing nodes that are not mounted
|
||||
//! - Mounted nodes that have already been created
|
||||
//!
|
||||
//! To support those cases, we lazily create components and only optionally write to the real dom while diffing with Option<&mut impl WriteMutations>
|
||||
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use crate::{
|
||||
arena::ElementId,
|
||||
innerlude::{ElementRef, MountId, WriteMutations},
|
||||
nodes::VNode,
|
||||
scopes::ScopeId,
|
||||
virtual_dom::VirtualDom,
|
||||
Template, TemplateNode,
|
||||
};
|
||||
@@ -14,34 +22,36 @@ mod iterator;
|
||||
mod node;
|
||||
|
||||
impl VirtualDom {
|
||||
pub(crate) fn create_children<'a>(
|
||||
pub(crate) fn create_children(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
nodes: impl IntoIterator<Item = &'a VNode>,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
nodes: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
) -> usize {
|
||||
nodes
|
||||
.into_iter()
|
||||
.map(|child| child.create(self, to, parent))
|
||||
.iter()
|
||||
.map(|child| child.create(self, parent, to.as_deref_mut()))
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Simply replace a placeholder with a list of nodes
|
||||
fn replace_placeholder<'a>(
|
||||
fn replace_placeholder(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
placeholder_id: ElementId,
|
||||
r: impl IntoIterator<Item = &'a VNode>,
|
||||
r: &[VNode],
|
||||
parent: Option<ElementRef>,
|
||||
) {
|
||||
let m = self.create_children(to, r, parent);
|
||||
to.replace_node_with(placeholder_id, m);
|
||||
self.reclaim(placeholder_id);
|
||||
let m = self.create_children(to.as_deref_mut(), r, parent);
|
||||
if let Some(to) = to {
|
||||
to.replace_node_with(placeholder_id, m);
|
||||
self.reclaim(placeholder_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn nodes_to_placeholder(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
mount: MountId,
|
||||
dyn_node_idx: usize,
|
||||
old_nodes: &[VNode],
|
||||
@@ -52,13 +62,15 @@ impl VirtualDom {
|
||||
// Set the id of the placeholder
|
||||
self.mounts[mount.0].mounted_dynamic_nodes[dyn_node_idx] = placeholder.0;
|
||||
|
||||
to.create_placeholder(placeholder);
|
||||
if let Some(to) = to.as_deref_mut() {
|
||||
to.create_placeholder(placeholder);
|
||||
}
|
||||
|
||||
self.replace_nodes(to, old_nodes, 1);
|
||||
}
|
||||
|
||||
/// Replace many nodes with a number of nodes on the stack
|
||||
fn replace_nodes(&mut self, to: &mut impl WriteMutations, nodes: &[VNode], m: usize) {
|
||||
fn replace_nodes(&mut self, to: Option<&mut impl WriteMutations>, nodes: &[VNode], m: usize) {
|
||||
debug_assert!(
|
||||
!nodes.is_empty(),
|
||||
"replace_nodes must have at least one node"
|
||||
@@ -73,32 +85,16 @@ impl VirtualDom {
|
||||
/// Wont generate mutations for the inner nodes
|
||||
fn remove_nodes(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
mut to: Option<&mut impl WriteMutations>,
|
||||
nodes: &[VNode],
|
||||
replace_with: Option<usize>,
|
||||
) {
|
||||
for (i, node) in nodes.iter().rev().enumerate() {
|
||||
let last_node = i == nodes.len() - 1;
|
||||
node.remove_node(self, to, replace_with.filter(|_| last_node), true);
|
||||
node.remove_node(self, to.as_deref_mut(), replace_with.filter(|_| last_node));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove_component_node(
|
||||
&mut self,
|
||||
to: &mut impl WriteMutations,
|
||||
scope: ScopeId,
|
||||
replace_with: Option<usize>,
|
||||
gen_muts: bool,
|
||||
) {
|
||||
// Remove the component from the dom
|
||||
if let Some(node) = self.scopes[scope.0].last_rendered_node.take() {
|
||||
node.remove_node(self, to, replace_with, gen_muts)
|
||||
};
|
||||
|
||||
// Now drop all the resources
|
||||
self.drop_scope(scope);
|
||||
}
|
||||
|
||||
/// Insert a new template into the VirtualDom's template registry
|
||||
// used in conditional compilation
|
||||
#[allow(unused_mut)]
|
||||
@@ -107,40 +103,37 @@ impl VirtualDom {
|
||||
to: &mut impl WriteMutations,
|
||||
mut template: Template,
|
||||
) {
|
||||
let (path, byte_index) = template.name.rsplit_once(':').unwrap();
|
||||
|
||||
let byte_index = byte_index.parse::<usize>().unwrap();
|
||||
// First, check if we've already seen this template
|
||||
if self
|
||||
.templates
|
||||
.get(&path)
|
||||
.filter(|set| set.contains_key(&byte_index))
|
||||
.is_none()
|
||||
// In debug mode, we check the more complete hashmap by byte index
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
// if hot reloading is enabled, then we need to check for a template that has overriten this one
|
||||
#[cfg(debug_assertions)]
|
||||
if let Some(mut new_template) = self
|
||||
.templates
|
||||
.get_mut(path)
|
||||
.and_then(|map| map.remove(&usize::MAX))
|
||||
{
|
||||
// the byte index of the hot reloaded template could be different
|
||||
new_template.name = template.name;
|
||||
template = new_template;
|
||||
let (path, byte_index) = template.name.rsplit_once(':').unwrap();
|
||||
|
||||
let byte_index = byte_index.parse::<usize>().unwrap();
|
||||
let mut entry = self.templates.entry(path);
|
||||
// If we've already seen this template, just return
|
||||
if let std::collections::hash_map::Entry::Occupied(occupied) = &entry {
|
||||
if occupied.get().contains_key(&byte_index) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self.templates
|
||||
.entry(path)
|
||||
.or_default()
|
||||
.insert(byte_index, template);
|
||||
// Otherwise, insert it and register it
|
||||
entry.or_default().insert(byte_index, template);
|
||||
}
|
||||
|
||||
// If it's all dynamic nodes, then we don't need to register it
|
||||
if !template.is_completely_dynamic() {
|
||||
to.register_template(template)
|
||||
}
|
||||
// In release mode, everything is built into the &'static str
|
||||
#[cfg(not(debug_assertions))]
|
||||
if !self.templates.insert(template.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If it's all dynamic nodes, then we don't need to register it
|
||||
if !template.is_completely_dynamic() {
|
||||
to.register_template(template)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
/// Insert a new template into the VirtualDom's template registry
|
||||
pub(crate) fn register_template_first_byte_index(&mut self, mut template: Template) {
|
||||
// First, make sure we mark the template as seen, regardless if we process it
|
||||
|
||||
+369
-371
File diff suppressed because it is too large.
Load diff
@@ -16,9 +16,9 @@ pub(crate) struct Effect {
|
||||
}
|
||||
|
||||
impl Effect {
|
||||
pub(crate) fn new(order: ScopeOrder, f: impl FnOnce() + 'static) -> Self {
|
||||
pub(crate) fn new(order: ScopeOrder, f: Box<dyn FnOnce() + 'static>) -> Self {
|
||||
let mut effect = VecDeque::new();
|
||||
effect.push_back(Box::new(f) as Box<dyn FnOnce() + 'static>);
|
||||
effect.push_back(f);
|
||||
Self {
|
||||
order,
|
||||
effect: RefCell::new(effect),
|
||||
|
||||
+520
-244
@@ -1,21 +1,24 @@
|
||||
use crate::{
|
||||
global_context::{current_scope_id, try_consume_context},
|
||||
innerlude::provide_context,
|
||||
use_hook, Element, IntoDynNode, Properties, ScopeId, Template, TemplateAttribute, TemplateNode,
|
||||
VNode,
|
||||
global_context::current_scope_id, innerlude::provide_context, use_hook, Element, IntoDynNode,
|
||||
Properties, ScopeId, Template, TemplateAttribute, TemplateNode, VNode,
|
||||
};
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
backtrace::Backtrace,
|
||||
cell::RefCell,
|
||||
cell::{Ref, RefCell},
|
||||
error::Error,
|
||||
fmt::{Debug, Display},
|
||||
rc::Rc,
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
/// A panic in a component that was caught by an error boundary.
|
||||
///
|
||||
/// NOTE: WASM currently does not support caching unwinds, so this struct will not be created in WASM.
|
||||
/// <div class="warning">
|
||||
///
|
||||
/// WASM currently does not support caching unwinds, so this struct will not be created in WASM.
|
||||
///
|
||||
/// </div>
|
||||
pub struct CapturedPanic {
|
||||
#[allow(dead_code)]
|
||||
/// The error that was caught
|
||||
@@ -28,66 +31,465 @@ impl Debug for CapturedPanic {
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide an error boundary to catch errors from child components
|
||||
pub fn use_error_boundary() -> ErrorBoundary {
|
||||
use_hook(|| provide_context(ErrorBoundary::new()))
|
||||
}
|
||||
|
||||
/// A boundary that will capture any errors from child components
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ErrorBoundary {
|
||||
inner: Rc<ErrorBoundaryInner>,
|
||||
}
|
||||
|
||||
/// A boundary that will capture any errors from child components
|
||||
pub struct ErrorBoundaryInner {
|
||||
error: RefCell<Option<CapturedError>>,
|
||||
_id: ScopeId,
|
||||
}
|
||||
|
||||
impl Debug for ErrorBoundaryInner {
|
||||
impl Display for CapturedPanic {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ErrorBoundaryInner")
|
||||
.field("error", &self.error)
|
||||
.finish()
|
||||
f.write_fmt(format_args!("Encountered panic: {:?}", self.error))
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for any type that can be downcast to a concrete type and implements Debug. This is automatically implemented for all types that implement Any + Debug.
|
||||
pub trait AnyDebug: Any + Debug {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
impl Error for CapturedPanic {}
|
||||
|
||||
/// Provide an error boundary to catch errors from child components
|
||||
pub fn use_error_boundary() -> ErrorContext {
|
||||
use_hook(|| provide_context(ErrorContext::new(Vec::new(), current_scope_id().unwrap())))
|
||||
}
|
||||
|
||||
impl<T: Any + Debug> AnyDebug for T {
|
||||
/// A trait for any type that can be downcast to a concrete type and implements Debug. This is automatically implemented for all types that implement Any + Debug.
|
||||
pub trait AnyError {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn as_error(&self) -> &dyn Error;
|
||||
}
|
||||
|
||||
/// An wrapper error type for types that only implement Display. We use a inner type here to avoid overlapping implementations for DisplayError and impl Error
|
||||
struct DisplayError(DisplayErrorInner);
|
||||
|
||||
impl<E: Display + 'static> From<E> for DisplayError {
|
||||
fn from(e: E) -> Self {
|
||||
Self(DisplayErrorInner(Box::new(e)))
|
||||
}
|
||||
}
|
||||
|
||||
struct DisplayErrorInner(Box<dyn Display>);
|
||||
impl Display for DisplayErrorInner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for DisplayErrorInner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for DisplayErrorInner {}
|
||||
|
||||
impl AnyError for DisplayError {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
&self.0 .0
|
||||
}
|
||||
|
||||
fn as_error(&self) -> &dyn Error {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides context methods to [`Result`] and [`Option`] types that are compatible with [`CapturedError`]
|
||||
///
|
||||
/// This trait is sealed and cannot be implemented outside of dioxus-core
|
||||
pub trait Context<T, E>: private::Sealed {
|
||||
/// Add a visual representation of the error that the [`ErrorBoundary`] may render
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// # use dioxus::prelude::*;
|
||||
/// fn Component() -> Element {
|
||||
/// // You can bubble up errors with `?` inside components, and event handlers
|
||||
/// // Along with the error itself, you can provide a way to display the error by calling `show`
|
||||
/// let number = "1234".parse::<usize>().show(|error| rsx! {
|
||||
/// div {
|
||||
/// background_color: "red",
|
||||
/// color: "white",
|
||||
/// "Error parsing number: {error}"
|
||||
/// }
|
||||
/// })?;
|
||||
/// todo!()
|
||||
/// }
|
||||
/// ```
|
||||
fn show(self, display_error: impl FnOnce(&E) -> Element) -> Result<T>;
|
||||
|
||||
/// Wrap the result additional context about the error that occurred.
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// # use dioxus::prelude::*;
|
||||
/// fn NumberParser() -> Element {
|
||||
/// // You can bubble up errors with `?` inside components, and event handlers
|
||||
/// // Along with the error itself, you can provide a way to display the error by calling `context`
|
||||
/// let number = "-1234".parse::<usize>().context("Parsing number inside of the NumberParser")?;
|
||||
/// todo!()
|
||||
/// }
|
||||
/// ```
|
||||
fn context<C: Display + 'static>(self, context: C) -> Result<T>;
|
||||
|
||||
/// Wrap the result with additional context about the error that occurred. The closure will only be run if the Result is an error.
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// # use dioxus::prelude::*;
|
||||
/// fn NumberParser() -> Element {
|
||||
/// // You can bubble up errors with `?` inside components, and event handlers
|
||||
/// // Along with the error itself, you can provide a way to display the error by calling `context`
|
||||
/// let number = "-1234".parse::<usize>().with_context(|| format!("Timestamp: {:?}", std::time::Instant::now()))?;
|
||||
/// todo!()
|
||||
/// }
|
||||
/// ```
|
||||
fn with_context<C: Display + 'static>(self, context: impl FnOnce() -> C) -> Result<T>;
|
||||
}
|
||||
|
||||
impl<T, E> Context<T, E> for std::result::Result<T, E>
|
||||
where
|
||||
E: Error + 'static,
|
||||
{
|
||||
fn show(self, display_error: impl FnOnce(&E) -> Element) -> Result<T> {
|
||||
// We don't use result mapping to avoid extra frames
|
||||
match self {
|
||||
std::result::Result::Ok(value) => Ok(value),
|
||||
Err(error) => {
|
||||
let render = display_error(&error).unwrap_or_default();
|
||||
let mut error: CapturedError = error.into();
|
||||
error.render = render;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn context<C: Display + 'static>(self, context: C) -> Result<T> {
|
||||
self.with_context(|| context)
|
||||
}
|
||||
|
||||
fn with_context<C: Display + 'static>(self, context: impl FnOnce() -> C) -> Result<T> {
|
||||
// We don't use result mapping to avoid extra frames
|
||||
match self {
|
||||
std::result::Result::Ok(value) => Ok(value),
|
||||
Err(error) => {
|
||||
let mut error: CapturedError = error.into();
|
||||
error.context.push(Rc::new(AdditionalErrorContext {
|
||||
backtrace: Backtrace::capture(),
|
||||
context: Box::new(context()),
|
||||
scope: current_scope_id(),
|
||||
}));
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Context<T, CapturedError> for Option<T> {
|
||||
fn show(self, display_error: impl FnOnce(&CapturedError) -> Element) -> Result<T> {
|
||||
// We don't use result mapping to avoid extra frames
|
||||
match self {
|
||||
Some(value) => Ok(value),
|
||||
None => {
|
||||
let mut error = CapturedError::from_display("Value was none");
|
||||
let render = display_error(&error).unwrap_or_default();
|
||||
error.render = render;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn context<C: Display + 'static>(self, context: C) -> Result<T> {
|
||||
self.with_context(|| context)
|
||||
}
|
||||
|
||||
fn with_context<C: Display + 'static>(self, context: impl FnOnce() -> C) -> Result<T> {
|
||||
// We don't use result mapping to avoid extra frames
|
||||
match self {
|
||||
Some(value) => Ok(value),
|
||||
None => {
|
||||
let error = CapturedError::from_display(context());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod private {
|
||||
use super::*;
|
||||
|
||||
pub trait Sealed {}
|
||||
|
||||
impl<T, E> Sealed for std::result::Result<T, E> where E: Error {}
|
||||
impl<T> Sealed for Option<T> {}
|
||||
}
|
||||
|
||||
impl<T: Any + Error> AnyError for T {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_error(&self) -> &dyn Error {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// A context with information about suspended components
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ErrorContext {
|
||||
errors: Rc<RefCell<Vec<CapturedError>>>,
|
||||
id: ScopeId,
|
||||
}
|
||||
|
||||
impl PartialEq for ErrorContext {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Rc::ptr_eq(&self.errors, &other.errors)
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorContext {
|
||||
/// Create a new suspense boundary in a specific scope
|
||||
pub(crate) fn new(errors: Vec<CapturedError>, id: ScopeId) -> Self {
|
||||
Self {
|
||||
errors: Rc::new(RefCell::new(errors)),
|
||||
id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all errors thrown from child components
|
||||
pub fn errors(&self) -> Ref<[CapturedError]> {
|
||||
Ref::map(self.errors.borrow(), |errors| errors.as_slice())
|
||||
}
|
||||
|
||||
/// Get the Element from the first error that can be shown
|
||||
pub fn show(&self) -> Option<Element> {
|
||||
self.errors.borrow().iter().find_map(|task| task.show())
|
||||
}
|
||||
|
||||
/// Push an error into this Error Boundary
|
||||
pub fn insert_error(&self, error: CapturedError) {
|
||||
self.errors.borrow_mut().push(error);
|
||||
self.id.needs_update();
|
||||
}
|
||||
|
||||
/// Clear all errors from this Error Boundary
|
||||
pub fn clear_errors(&self) {
|
||||
self.errors.borrow_mut().clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors can have additional context added as they bubble up the render tree
|
||||
/// This context can be used to provide additional information to the user
|
||||
struct AdditionalErrorContext {
|
||||
backtrace: Backtrace,
|
||||
context: Box<dyn Display>,
|
||||
scope: Option<ScopeId>,
|
||||
}
|
||||
|
||||
impl Debug for AdditionalErrorContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ErrorContext")
|
||||
.field("backtrace", &self.backtrace)
|
||||
.field("context", &self.context.to_string())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for AdditionalErrorContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let AdditionalErrorContext {
|
||||
backtrace,
|
||||
context,
|
||||
scope,
|
||||
} = self;
|
||||
|
||||
write!(f, "{context} (from ")?;
|
||||
|
||||
if let Some(scope) = scope {
|
||||
write!(f, "scope {scope:?} ")?;
|
||||
}
|
||||
|
||||
write!(f, "at {backtrace:?})")
|
||||
}
|
||||
}
|
||||
|
||||
/// A type alias for a result that can be either a boxed error or a value
|
||||
/// This is useful to avoid having to use `Result<T, CapturedError>` everywhere
|
||||
pub type Result<T = ()> = std::result::Result<T, CapturedError>;
|
||||
|
||||
/// A helper function for an Ok result that can be either a boxed error or a value
|
||||
/// This is useful to avoid having to use `Ok<T, CapturedError>` everywhere
|
||||
#[allow(non_snake_case)]
|
||||
pub fn Ok<T>(value: T) -> Result<T> {
|
||||
Result::Ok(value)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
/// An instance of an error captured by a descendant component.
|
||||
pub struct CapturedError {
|
||||
/// The error captured by the error boundary
|
||||
pub error: Box<dyn AnyDebug + 'static>,
|
||||
error: Rc<dyn AnyError + 'static>,
|
||||
|
||||
/// The backtrace of the error
|
||||
pub backtrace: Backtrace,
|
||||
backtrace: Rc<Backtrace>,
|
||||
|
||||
/// The scope that threw the error
|
||||
pub scope: ScopeId,
|
||||
scope: ScopeId,
|
||||
|
||||
/// An error message that can be displayed to the user
|
||||
pub(crate) render: VNode,
|
||||
|
||||
/// Additional context that was added to the error
|
||||
context: Vec<Rc<AdditionalErrorContext>>,
|
||||
}
|
||||
|
||||
impl FromStr for CapturedError {
|
||||
type Err = std::convert::Infallible;
|
||||
|
||||
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
||||
std::result::Result::Ok(Self::from_display(s.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct SerializedCapturedError {
|
||||
error: String,
|
||||
context: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl serde::Serialize for CapturedError {
|
||||
fn serialize<S: serde::Serializer>(
|
||||
&self,
|
||||
serializer: S,
|
||||
) -> std::result::Result<S::Ok, S::Error> {
|
||||
let serialized = SerializedCapturedError {
|
||||
error: self.error.as_error().to_string(),
|
||||
context: self
|
||||
.context
|
||||
.iter()
|
||||
.map(|context| context.to_string())
|
||||
.collect(),
|
||||
};
|
||||
serialized.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'de> serde::Deserialize<'de> for CapturedError {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<Self, D::Error> {
|
||||
let serialized = SerializedCapturedError::deserialize(deserializer)?;
|
||||
|
||||
let error = DisplayError::from(serialized.error);
|
||||
let context = serialized
|
||||
.context
|
||||
.into_iter()
|
||||
.map(|context| {
|
||||
Rc::new(AdditionalErrorContext {
|
||||
scope: None,
|
||||
backtrace: Backtrace::disabled(),
|
||||
context: Box::new(context),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
std::result::Result::Ok(Self {
|
||||
error: Rc::new(error),
|
||||
context,
|
||||
backtrace: Rc::new(Backtrace::disabled()),
|
||||
scope: ScopeId::ROOT,
|
||||
render: VNode::placeholder(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for CapturedError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("CapturedError")
|
||||
.field("error", &self.error.as_error())
|
||||
.field("backtrace", &self.backtrace)
|
||||
.field("scope", &self.scope)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: AnyError + 'static> From<E> for CapturedError {
|
||||
fn from(error: E) -> Self {
|
||||
Self {
|
||||
error: Rc::new(error),
|
||||
backtrace: Rc::new(Backtrace::capture()),
|
||||
scope: current_scope_id()
|
||||
.expect("Cannot create an error boundary outside of a component's scope."),
|
||||
render: Default::default(),
|
||||
context: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CapturedError {
|
||||
/// Create a new captured error
|
||||
pub fn new(error: impl AnyError + 'static) -> Self {
|
||||
Self {
|
||||
error: Rc::new(error),
|
||||
backtrace: Rc::new(Backtrace::capture()),
|
||||
scope: current_scope_id().unwrap_or(ScopeId::ROOT),
|
||||
render: Default::default(),
|
||||
context: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new error from a type that only implements [`Display`]. If your type implements [`Error`], you can use [`CapturedError::from`] instead.
|
||||
pub fn from_display(error: impl Display + 'static) -> Self {
|
||||
Self {
|
||||
error: Rc::new(DisplayError::from(error)),
|
||||
backtrace: Rc::new(Backtrace::capture()),
|
||||
scope: current_scope_id().unwrap_or(ScopeId::ROOT),
|
||||
render: Default::default(),
|
||||
context: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark the error as being thrown from a specific scope
|
||||
pub fn with_origin(mut self, scope: ScopeId) -> Self {
|
||||
self.scope = scope;
|
||||
self
|
||||
}
|
||||
|
||||
/// Clone the error while retaining the mounted information of the error
|
||||
pub(crate) fn clone_mounted(&self) -> Self {
|
||||
Self {
|
||||
error: self.error.clone(),
|
||||
backtrace: self.backtrace.clone(),
|
||||
scope: self.scope,
|
||||
render: self.render.clone_mounted(),
|
||||
context: self.context.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a VNode representation of the error if the error provides one
|
||||
pub fn show(&self) -> Option<Element> {
|
||||
if self.render == VNode::placeholder() {
|
||||
None
|
||||
} else {
|
||||
Some(std::result::Result::Ok(self.render.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CapturedError {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
format!("{:?}", self) == format!("{:?}", other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for CapturedError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"Encountered error: {:?}\nIn scope: {:?}\nBacktrace: {}",
|
||||
self.error, self.scope, self.backtrace
|
||||
))
|
||||
"Encountered error: {:?}\nIn scope: {:?}\nBacktrace: {}\nContext: ",
|
||||
self.error.as_error(),
|
||||
self.scope,
|
||||
self.backtrace
|
||||
))?;
|
||||
for context in &*self.context {
|
||||
f.write_fmt(format_args!("{}\n", context))?;
|
||||
}
|
||||
std::result::Result::Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CapturedError {}
|
||||
|
||||
impl CapturedError {
|
||||
/// Downcast the error type into a concrete error type
|
||||
pub fn downcast<T: 'static>(&self) -> Option<&T> {
|
||||
@@ -99,217 +501,69 @@ impl CapturedError {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ErrorBoundaryInner {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
error: RefCell::new(None),
|
||||
_id: current_scope_id()
|
||||
.expect("Cannot create an error boundary outside of a component's scope."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorBoundary {
|
||||
/// Create a new error boundary
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Create a new error boundary in the current scope
|
||||
pub(crate) fn new_in_scope(scope: ScopeId) -> Self {
|
||||
Self {
|
||||
inner: Rc::new(ErrorBoundaryInner {
|
||||
error: RefCell::new(None),
|
||||
_id: scope,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Push an error into this Error Boundary
|
||||
pub fn insert_error(&self, scope: ScopeId, error: impl Debug + 'static, backtrace: Backtrace) {
|
||||
self.inner.error.replace(Some(CapturedError {
|
||||
error: Box::new(error),
|
||||
scope,
|
||||
backtrace,
|
||||
}));
|
||||
if self.inner._id != ScopeId::ROOT {
|
||||
self.inner._id.needs_update();
|
||||
}
|
||||
}
|
||||
|
||||
/// Take any error that has been captured by this error boundary
|
||||
pub fn take_error(&self) -> Option<CapturedError> {
|
||||
self.inner.error.take()
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait to allow results to be thrown upwards to the nearest Error Boundary
|
||||
///
|
||||
/// The canonical way of using this trait is to throw results from hooks, aborting rendering
|
||||
/// through question mark syntax. The throw method returns an option that evaluates to None
|
||||
/// if there is an error, injecting the error to the nearest error boundary.
|
||||
///
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
|
||||
///
|
||||
/// The call stack is saved for this component and provided to the error boundary
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
///
|
||||
/// #[component]
|
||||
/// fn app(count: String) -> Element {
|
||||
/// let count: i32 = count.parse().throw()?;
|
||||
///
|
||||
/// rsx! {
|
||||
/// div { "Count {count}" }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait Throw<S = ()>: Sized {
|
||||
/// The value that will be returned in if the given value is `Ok`.
|
||||
type Out;
|
||||
|
||||
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
|
||||
///
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
|
||||
///
|
||||
/// The call stack is saved for this component and provided to the error boundary
|
||||
///
|
||||
///
|
||||
/// Note that you can also manually throw errors using the throw method on `ScopeState` directly,
|
||||
/// which is what this trait shells out to.
|
||||
///
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
///
|
||||
/// #[component]
|
||||
/// fn app( count: String) -> Element {
|
||||
/// let count: i32 = count.parse().throw()?;
|
||||
///
|
||||
/// rsx! {
|
||||
/// div { "Count {count}" }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn throw(self) -> Option<Self::Out>;
|
||||
|
||||
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
|
||||
///
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
|
||||
///
|
||||
/// The call stack is saved for this component and provided to the error boundary
|
||||
///
|
||||
///
|
||||
/// Note that you can also manually throw errors using the throw method on `ScopeState` directly,
|
||||
/// which is what this trait shells out to.
|
||||
///
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
///
|
||||
/// #[component]
|
||||
/// fn app( count: String) -> Element {
|
||||
/// let count: i32 = count.parse().throw()?;
|
||||
///
|
||||
/// rsx! {
|
||||
/// div { "Count {count}" }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn throw_with<D: Debug + 'static>(self, e: impl FnOnce() -> D) -> Option<Self::Out> {
|
||||
self.throw().or_else(|| throw_error(e()))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn throw_error<T>(e: impl Debug + 'static) -> Option<T> {
|
||||
if let Some(cx) = try_consume_context::<ErrorBoundary>() {
|
||||
match current_scope_id() {
|
||||
Some(id) => cx.insert_error(id, Box::new(e), Backtrace::capture()),
|
||||
None => {
|
||||
tracing::error!("Cannot throw error outside of a component's scope.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// We call clone on any errors that can be owned out of a reference
|
||||
impl<'a, T, O: Debug + 'static, E: ToOwned<Owned = O>> Throw for &'a Result<T, E> {
|
||||
type Out = &'a T;
|
||||
|
||||
fn throw(self) -> Option<Self::Out> {
|
||||
match self {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) => throw_error(e.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn throw_with<D: Debug + 'static>(self, err: impl FnOnce() -> D) -> Option<Self::Out> {
|
||||
match self {
|
||||
Ok(t) => Some(t),
|
||||
Err(_e) => throw_error(err()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Or just throw errors we know about
|
||||
impl<T, E: Debug + 'static> Throw for Result<T, E> {
|
||||
type Out = T;
|
||||
|
||||
fn throw(self) -> Option<T> {
|
||||
match self {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) => throw_error(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn throw_with<D: Debug + 'static>(self, error: impl FnOnce() -> D) -> Option<Self::Out> {
|
||||
self.ok().or_else(|| throw_error(error()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Or just throw errors we know about
|
||||
impl<T> Throw for Option<T> {
|
||||
type Out = T;
|
||||
|
||||
fn throw(self) -> Option<T> {
|
||||
self.or_else(|| throw_error("Attempted to unwrap a None value."))
|
||||
}
|
||||
|
||||
fn throw_with<D: Debug + 'static>(self, error: impl FnOnce() -> D) -> Option<Self::Out> {
|
||||
self.or_else(|| throw_error(error()))
|
||||
pub(crate) fn throw_into(error: impl Into<CapturedError>, scope: ScopeId) {
|
||||
let error = error.into();
|
||||
if let Some(cx) = scope.consume_context::<ErrorContext>() {
|
||||
cx.insert_error(error)
|
||||
} else {
|
||||
tracing::error!(
|
||||
"Tried to throw an error into an error boundary, but failed to locate a boundary: {:?}",
|
||||
error
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
#[derive(Clone)]
|
||||
pub struct ErrorHandler(Rc<dyn Fn(CapturedError) -> Element>);
|
||||
impl<F: Fn(CapturedError) -> Element + 'static> From<F> for ErrorHandler {
|
||||
pub struct ErrorHandler(Rc<dyn Fn(ErrorContext) -> Element>);
|
||||
impl<F: Fn(ErrorContext) -> Element + 'static> From<F> for ErrorHandler {
|
||||
fn from(value: F) -> Self {
|
||||
Self(Rc::new(value))
|
||||
}
|
||||
}
|
||||
fn default_handler(error: CapturedError) -> Element {
|
||||
|
||||
fn default_handler(errors: ErrorContext) -> Element {
|
||||
static TEMPLATE: Template = Template {
|
||||
name: "error_handle.rs:42:5:884",
|
||||
roots: &[TemplateNode::Element {
|
||||
tag: "pre",
|
||||
tag: "div",
|
||||
namespace: None,
|
||||
attrs: &[TemplateAttribute::Static {
|
||||
name: "color",
|
||||
namespace: Some("style"),
|
||||
value: "red",
|
||||
}],
|
||||
children: &[TemplateNode::DynamicText { id: 0usize }],
|
||||
children: &[TemplateNode::Dynamic { id: 0usize }],
|
||||
}],
|
||||
node_paths: &[&[0u8, 0u8]],
|
||||
attr_paths: &[],
|
||||
};
|
||||
Some(VNode::new(
|
||||
std::result::Result::Ok(VNode::new(
|
||||
None,
|
||||
TEMPLATE,
|
||||
Box::new([error.to_string().into_dyn_node()]),
|
||||
Box::new([errors
|
||||
.errors()
|
||||
.iter()
|
||||
.map(|e| {
|
||||
static TEMPLATE: Template = Template {
|
||||
name: "error_handle.rs:43:5:884",
|
||||
roots: &[TemplateNode::Element {
|
||||
tag: "pre",
|
||||
namespace: None,
|
||||
attrs: &[],
|
||||
children: &[TemplateNode::Dynamic { id: 0usize }],
|
||||
}],
|
||||
node_paths: &[&[0u8, 0u8]],
|
||||
attr_paths: &[],
|
||||
};
|
||||
VNode::new(
|
||||
None,
|
||||
TEMPLATE,
|
||||
Box::new([e.to_string().into_dyn_node()]),
|
||||
Default::default(),
|
||||
)
|
||||
})
|
||||
.into_dyn_node()]),
|
||||
Default::default(),
|
||||
))
|
||||
}
|
||||
@@ -433,9 +687,7 @@ impl<
|
||||
{
|
||||
pub fn build(self) -> ErrorBoundaryProps {
|
||||
let (children, handle_error) = self.fields;
|
||||
let children = ErrorBoundaryPropsBuilder_Optional::into_value(children, || {
|
||||
::core::default::Default::default()
|
||||
});
|
||||
let children = ErrorBoundaryPropsBuilder_Optional::into_value(children, VNode::empty);
|
||||
let handle_error = ErrorBoundaryPropsBuilder_Optional::into_value(handle_error, || {
|
||||
ErrorHandler(Rc::new(default_handler))
|
||||
});
|
||||
@@ -445,23 +697,45 @@ impl<
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Create a new error boundary component.
|
||||
|
||||
/// Create a new error boundary component that catches any errors thrown from child components
|
||||
///
|
||||
/// ## Details
|
||||
///
|
||||
/// Error boundaries handle errors within a specific part of your application. Any errors passed in a child with [`Throw`] will be caught by the nearest error boundary.
|
||||
/// Error boundaries handle errors within a specific part of your application. Any errors passed up from a child will be caught by the nearest error boundary.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```rust
|
||||
/// ```rust, no_run
|
||||
/// # use dioxus::prelude::*;
|
||||
/// # fn ThrowsError() -> Element { unimplemented!() }
|
||||
/// rsx! {
|
||||
/// ErrorBoundary {
|
||||
/// handle_error: |error| rsx! { "Oops, we encountered an error. Please report {error} to the developer of this application" },
|
||||
/// ThrowsError {}
|
||||
/// fn App() -> Element {
|
||||
/// rsx! {
|
||||
/// ErrorBoundary {
|
||||
/// handle_error: |errors: ErrorContext| rsx! { "Oops, we encountered an error. Please report {errors:?} to the developer of this application" },
|
||||
/// Counter {
|
||||
/// multiplier: "1234"
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// };
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn Counter(multiplier: String) -> Element {
|
||||
/// // You can bubble up errors with `?` inside components
|
||||
/// let multiplier_parsed = multiplier.parse::<usize>()?;
|
||||
/// let mut count = use_signal(|| multiplier_parsed);
|
||||
/// rsx! {
|
||||
/// button {
|
||||
/// // Or inside event handlers
|
||||
/// onclick: move |_| {
|
||||
/// let multiplier_parsed = multiplier.parse::<usize>()?;
|
||||
/// *count.write() *= multiplier_parsed;
|
||||
/// Ok(())
|
||||
/// },
|
||||
/// "{count}x{multiplier}"
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Usage
|
||||
@@ -472,9 +746,9 @@ impl<
|
||||
#[allow(non_upper_case_globals, non_snake_case)]
|
||||
pub fn ErrorBoundary(props: ErrorBoundaryProps) -> Element {
|
||||
let error_boundary = use_error_boundary();
|
||||
match error_boundary.take_error() {
|
||||
Some(error) => (props.handle_error.0)(error),
|
||||
None => Some({
|
||||
let errors = error_boundary.errors();
|
||||
if errors.is_empty() {
|
||||
std::result::Result::Ok({
|
||||
static TEMPLATE: Template = Template {
|
||||
name: "examples/error_handle.rs:81:17:2342",
|
||||
roots: &[TemplateNode::Dynamic { id: 0usize }],
|
||||
@@ -487,6 +761,8 @@ pub fn ErrorBoundary(props: ErrorBoundaryProps) -> Element {
|
||||
Box::new([(props.children).into_dyn_node()]),
|
||||
Default::default(),
|
||||
)
|
||||
}),
|
||||
})
|
||||
} else {
|
||||
(props.handle_error.0)(error_boundary.clone())
|
||||
}
|
||||
}
|
||||
@@ -209,7 +209,7 @@ pub struct Callback<Args = (), Ret = ()> {
|
||||
/// fn Child(onclick: EventHandler<MouseEvent>) -> Element {
|
||||
/// rsx!{
|
||||
/// button {
|
||||
/// // Diffing Child will not rerun this component, it will just update the EventHandler in place so that if this callback is called, it will run the latest version of the callback
|
||||
/// // Diffing Child will not rerun this component, it will just update the callback in place so that if this callback is called, it will run the latest version of the callback
|
||||
/// onclick: move |evt| onclick(evt),
|
||||
/// }
|
||||
/// }
|
||||
@@ -270,10 +270,10 @@ impl<Ret> SpawnIfAsync<(), Ret> for Ret {
|
||||
}
|
||||
}
|
||||
|
||||
// Support for FnMut -> async { anything } for the unit return type
|
||||
// Support for FnMut -> async { unit } for the unit return type
|
||||
#[doc(hidden)]
|
||||
pub struct AsyncMarker<O>(PhantomData<O>);
|
||||
impl<F: std::future::Future<Output = O> + 'static, O> SpawnIfAsync<AsyncMarker<O>, ()> for F {
|
||||
pub struct AsyncMarker;
|
||||
impl<F: std::future::Future<Output = ()> + 'static> SpawnIfAsync<AsyncMarker> for F {
|
||||
fn spawn(self) {
|
||||
crate::prelude::spawn(async move {
|
||||
self.await;
|
||||
@@ -281,6 +281,34 @@ impl<F: std::future::Future<Output = O> + 'static, O> SpawnIfAsync<AsyncMarker<O
|
||||
}
|
||||
}
|
||||
|
||||
// Support for FnMut -> async { Result(()) } for the unit return type
|
||||
#[doc(hidden)]
|
||||
pub struct AsyncResultMarker;
|
||||
|
||||
impl<T> SpawnIfAsync<AsyncResultMarker> for T
|
||||
where
|
||||
T: std::future::Future<Output = crate::Result<()>> + 'static,
|
||||
{
|
||||
#[inline]
|
||||
fn spawn(self) {
|
||||
crate::prelude::spawn(async move {
|
||||
if let Err(err) = self.await {
|
||||
crate::prelude::throw_error(err)
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Support for FnMut -> Result(()) for the unit return type
|
||||
impl SpawnIfAsync<()> for crate::Result<()> {
|
||||
#[inline]
|
||||
fn spawn(self) {
|
||||
if let Err(err) = self {
|
||||
crate::prelude::throw_error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We can't directly forward the marker because it would overlap with a bunch of other impls, so we wrap it in another type instead
|
||||
#[doc(hidden)]
|
||||
pub struct MarkerWrapper<T>(PhantomData<T>);
|
||||
@@ -299,6 +327,22 @@ impl<
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct UnitClosure<Marker>(PhantomData<Marker>);
|
||||
|
||||
// Closure can be created from FnMut -> async { () } or FnMut -> Ret
|
||||
impl<
|
||||
Function: FnMut() -> Spawn + 'static,
|
||||
Spawn: SpawnIfAsync<Marker, Ret> + 'static,
|
||||
Ret: 'static,
|
||||
Marker,
|
||||
> SuperFrom<Function, UnitClosure<Marker>> for Callback<(), Ret>
|
||||
{
|
||||
fn super_from(mut input: Function) -> Self {
|
||||
Callback::new(move |()| input())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closure_types_infer() {
|
||||
#[allow(unused)]
|
||||
@@ -315,6 +359,11 @@ fn closure_types_infer() {
|
||||
let callback: Callback<u32, ()> = Callback::new(|value: u32| async move {
|
||||
println!("{}", value);
|
||||
});
|
||||
|
||||
// Unit closures shouldn't require an argument
|
||||
let callback: Callback<(), ()> = Callback::super_from(|| async move {
|
||||
println!("hello world");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,12 +418,12 @@ impl<Args: 'static, Ret: 'static> Callback<Args, Ret> {
|
||||
/// This borrows the callback using a RefCell. Recursively calling a callback will cause a panic.
|
||||
pub fn call(&self, arguments: Args) -> Ret {
|
||||
if let Some(callback) = self.callback.read().as_ref() {
|
||||
Runtime::with(|rt| rt.scope_stack.borrow_mut().push(self.origin));
|
||||
Runtime::with(|rt| rt.push_scope(self.origin));
|
||||
let value = {
|
||||
let mut callback = callback.borrow_mut();
|
||||
callback(arguments)
|
||||
};
|
||||
Runtime::with(|rt| rt.scope_stack.borrow_mut().pop());
|
||||
Runtime::with(|rt| rt.pop_scope());
|
||||
value
|
||||
} else {
|
||||
panic!("Callback was manually dropped")
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn Fragment(cx: FragmentProps) -> Element {
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct FragmentProps(Element);
|
||||
pub struct FragmentProps(pub(crate) Element);
|
||||
|
||||
pub struct FragmentBuilder<const BUILT: bool>(Element);
|
||||
impl FragmentBuilder<false> {
|
||||
@@ -66,7 +66,7 @@ impl<const A: bool> FragmentBuilder<A> {
|
||||
/// ```rust
|
||||
/// # use dioxus::prelude::*;
|
||||
/// fn app() -> Element {
|
||||
/// rsx!{
|
||||
/// rsx! {
|
||||
/// CustomCard {
|
||||
/// h1 {}
|
||||
/// p {}
|
||||
@@ -87,7 +87,7 @@ impl<const A: bool> FragmentBuilder<A> {
|
||||
impl Properties for FragmentProps {
|
||||
type Builder = FragmentBuilder<false>;
|
||||
fn builder() -> Self::Builder {
|
||||
FragmentBuilder(None)
|
||||
FragmentBuilder(VNode::empty())
|
||||
}
|
||||
fn memoize(&mut self, new: &Self) -> bool {
|
||||
let equal = self == new;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{runtime::Runtime, Element, ScopeId, Task};
|
||||
use futures_util::Future;
|
||||
use crate::{innerlude::SuspendedFuture, runtime::Runtime, CapturedError, Element, ScopeId, Task};
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Get the current scope id
|
||||
@@ -13,6 +13,29 @@ pub fn vdom_is_rendering() -> bool {
|
||||
Runtime::with(|rt| rt.rendering.get()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Throw a [`CapturedError`] into the current scope. The error will bubble up to the nearest [`crate::prelude::ErrorBoundary()`] or the root of the app.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust, no_run
|
||||
/// # use dioxus::prelude::*;
|
||||
/// fn Component() -> Element {
|
||||
/// let request = spawn(async move {
|
||||
/// match reqwest::get("https://api.example.com").await {
|
||||
/// Ok(_) => todo!(),
|
||||
/// // You can explicitly throw an error into a scope with throw_error
|
||||
/// Err(err) => ScopeId::APP.throw_error(err)
|
||||
/// }
|
||||
/// });
|
||||
///
|
||||
/// todo!()
|
||||
/// }
|
||||
/// ```
|
||||
pub fn throw_error(error: impl Into<CapturedError> + 'static) {
|
||||
current_scope_id()
|
||||
.expect("to be in a dioxus runtime")
|
||||
.throw_error(error)
|
||||
}
|
||||
|
||||
/// Consume context from the current scope
|
||||
pub fn try_consume_context<T: 'static + Clone>() -> Option<T> {
|
||||
Runtime::with_current_scope(|cx| cx.consume_context::<T>()).flatten()
|
||||
@@ -52,8 +75,9 @@ pub fn provide_root_context<T: 'static + Clone>(value: T) -> T {
|
||||
|
||||
/// Suspended the current component on a specific task and then return None
|
||||
pub fn suspend(task: Task) -> Element {
|
||||
Runtime::with_current_scope(|cx| cx.suspend(task));
|
||||
None
|
||||
Err(crate::innerlude::RenderError::Suspended(
|
||||
SuspendedFuture::new(task),
|
||||
))
|
||||
}
|
||||
|
||||
/// Start a new future on the same thread as the rest of the VirtualDom.
|
||||
@@ -191,7 +215,7 @@ pub fn remove_future(id: Task) {
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// ```rust, no_run
|
||||
/// use dioxus::prelude::*;
|
||||
///
|
||||
/// // prints a greeting on the initial render
|
||||
@@ -202,7 +226,7 @@ pub fn remove_future(id: Task) {
|
||||
///
|
||||
/// # Custom Hook Example
|
||||
///
|
||||
/// ```rust
|
||||
/// ```rust, no_run
|
||||
/// use dioxus::prelude::*;
|
||||
///
|
||||
/// pub struct InnerCustomState(usize);
|
||||
@@ -377,21 +401,6 @@ pub fn after_render(f: impl FnMut() + 'static) {
|
||||
Runtime::with_current_scope(|cx| cx.push_after_render(f));
|
||||
}
|
||||
|
||||
/// Wait for the next render to complete
|
||||
///
|
||||
/// This is useful if you've just triggered an update and want to wait for it to finish before proceeding with valid
|
||||
/// DOM nodes.
|
||||
///
|
||||
/// Effects rely on this to ensure that they only run effects after the DOM has been updated. Without wait_for_next_render effects
|
||||
/// are run immediately before diffing the DOM, which causes all sorts of out-of-sync weirdness.
|
||||
pub async fn wait_for_next_render() {
|
||||
// Wait for the flush lock to be available
|
||||
// We release it immediately, so it's impossible for the lock to be held longer than this function
|
||||
Runtime::with(|rt| rt.render_signal.subscribe())
|
||||
.unwrap()
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Use a hook with a cleanup function
|
||||
pub fn use_hook_with_cleanup<T: Clone + 'static>(
|
||||
hook: impl FnOnce() -> T,
|
||||
|
||||
+18
-12
@@ -16,12 +16,14 @@ mod mutations;
|
||||
mod nodes;
|
||||
mod properties;
|
||||
mod reactive_context;
|
||||
mod render_signal;
|
||||
mod render_error;
|
||||
mod root_wrapper;
|
||||
mod runtime;
|
||||
mod scheduler;
|
||||
mod scope_arena;
|
||||
mod scope_context;
|
||||
mod scopes;
|
||||
mod suspense;
|
||||
mod tasks;
|
||||
mod virtual_dom;
|
||||
|
||||
@@ -44,16 +46,18 @@ pub(crate) mod innerlude {
|
||||
pub use crate::nodes::*;
|
||||
pub use crate::properties::*;
|
||||
pub use crate::reactive_context::*;
|
||||
pub use crate::render_error::*;
|
||||
pub use crate::runtime::{Runtime, RuntimeGuard};
|
||||
pub use crate::scheduler::*;
|
||||
pub use crate::scopes::*;
|
||||
pub use crate::suspense::*;
|
||||
pub use crate::tasks::*;
|
||||
pub use crate::virtual_dom::*;
|
||||
|
||||
/// An [`Element`] is a possibly-none [`VNode`] created by calling `render` on [`ScopeId`] or [`ScopeState`].
|
||||
///
|
||||
/// An Errored [`Element`] will propagate the error to the nearest error boundary.
|
||||
pub type Element = Option<VNode>;
|
||||
pub type Element = std::result::Result<VNode, RenderError>;
|
||||
|
||||
/// A [`Component`] is a function that takes [`Properties`] and returns an [`Element`].
|
||||
pub type Component<P = ()> = fn(P) -> Element;
|
||||
@@ -63,9 +67,9 @@ pub use crate::innerlude::{
|
||||
fc_to_builder, generation, schedule_update, schedule_update_any, use_hook, vdom_is_rendering,
|
||||
AnyValue, Attribute, AttributeValue, CapturedError, Component, ComponentFunction, DynamicNode,
|
||||
Element, ElementId, Event, Fragment, HasAttributes, IntoDynNode, MarkerWrapper, Mutation,
|
||||
Mutations, NoOpMutations, Properties, RenderReturn, Runtime, ScopeId, ScopeState, SpawnIfAsync,
|
||||
Task, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VNodeInner, VPlaceholder,
|
||||
VText, VirtualDom, WriteMutations,
|
||||
Mutations, NoOpMutations, Ok, Properties, RenderReturn, Result, Runtime, ScopeId, ScopeState,
|
||||
SpawnIfAsync, Task, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VNodeInner,
|
||||
VPlaceholder, VText, VirtualDom, WriteMutations,
|
||||
};
|
||||
|
||||
/// The purpose of this module is to alleviate imports of many common types
|
||||
@@ -76,12 +80,14 @@ pub mod prelude {
|
||||
consume_context, consume_context_from_scope, current_owner, current_scope_id,
|
||||
fc_to_builder, generation, has_context, needs_update, needs_update_any, parent_scope,
|
||||
provide_context, provide_root_context, queue_effect, remove_future, schedule_update,
|
||||
schedule_update_any, spawn, spawn_forever, spawn_isomorphic, suspend, try_consume_context,
|
||||
use_after_render, use_before_render, use_drop, use_error_boundary, use_hook,
|
||||
use_hook_with_cleanup, wait_for_next_render, with_owner, AnyValue, Attribute, Callback,
|
||||
Component, ComponentFunction, Element, ErrorBoundary, Event, EventHandler, Fragment,
|
||||
HasAttributes, IntoAttributeValue, IntoDynNode, OptionStringFromMarker, Properties,
|
||||
ReactiveContext, Runtime, RuntimeGuard, ScopeId, ScopeState, SuperFrom, SuperInto, Task,
|
||||
Template, TemplateAttribute, TemplateNode, Throw, VNode, VNodeInner, VirtualDom,
|
||||
schedule_update_any, spawn, spawn_forever, spawn_isomorphic, suspend, throw_error,
|
||||
try_consume_context, use_after_render, use_before_render, use_drop, use_error_boundary,
|
||||
use_hook, use_hook_with_cleanup, with_owner, AnyValue, Attribute, Callback, CapturedError,
|
||||
Component, ComponentFunction, Context, Element, ErrorBoundary, ErrorContext, Event,
|
||||
EventHandler, Fragment, HasAttributes, IntoAttributeValue, IntoDynNode,
|
||||
OptionStringFromMarker, Properties, ReactiveContext, RenderError, Runtime, RuntimeGuard,
|
||||
ScopeId, ScopeState, SuperFrom, SuperInto, SuspendedFuture, SuspenseBoundary,
|
||||
SuspenseBoundaryProps, SuspenseContext, SuspenseExtension, Task, Template,
|
||||
TemplateAttribute, TemplateNode, VNode, VNodeInner, VirtualDom,
|
||||
};
|
||||
}
|
||||
+162
-71
@@ -1,13 +1,13 @@
|
||||
use crate::innerlude::VProps;
|
||||
use crate::innerlude::{RenderError, VProps};
|
||||
use crate::{any_props::BoxedAnyProps, innerlude::ScopeState};
|
||||
use crate::{arena::ElementId, Element, Event};
|
||||
use crate::{
|
||||
innerlude::{ElementRef, EventHandler, MountId},
|
||||
properties::ComponentFunction,
|
||||
};
|
||||
use crate::{Properties, VirtualDom};
|
||||
use crate::{Properties, ScopeId, VirtualDom};
|
||||
use core::panic;
|
||||
use std::ops::Deref;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::rc::Rc;
|
||||
use std::vec;
|
||||
use std::{
|
||||
@@ -21,28 +21,49 @@ pub type TemplateId = &'static str;
|
||||
/// The actual state of the component's most recent computation
|
||||
///
|
||||
/// If the component returned early (e.g. `return None`), this will be Aborted(None)
|
||||
pub enum RenderReturn {
|
||||
/// A currently-available element
|
||||
Ready(VNode),
|
||||
#[derive(Debug)]
|
||||
pub struct RenderReturn {
|
||||
/// The node that was rendered
|
||||
pub(crate) node: Element,
|
||||
}
|
||||
|
||||
/// The component aborted rendering early. It might've thrown an error.
|
||||
///
|
||||
/// In its place we've produced a placeholder to locate its spot in the dom when it recovers.
|
||||
Aborted(VNode),
|
||||
impl From<RenderReturn> for VNode {
|
||||
fn from(val: RenderReturn) -> Self {
|
||||
match val.node {
|
||||
Ok(node) => node,
|
||||
Err(RenderError::Aborted(e)) => e.render,
|
||||
Err(RenderError::Suspended(fut)) => fut.placeholder,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Element> for RenderReturn {
|
||||
fn from(node: Element) -> Self {
|
||||
RenderReturn { node }
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for RenderReturn {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
RenderReturn::Ready(node) => RenderReturn::Ready(node.clone_mounted()),
|
||||
RenderReturn::Aborted(node) => RenderReturn::Aborted(node.clone_mounted()),
|
||||
match &self.node {
|
||||
Ok(node) => RenderReturn {
|
||||
node: Ok(node.clone_mounted()),
|
||||
},
|
||||
Err(RenderError::Aborted(err)) => RenderReturn {
|
||||
node: Err(RenderError::Aborted(err.clone_mounted())),
|
||||
},
|
||||
Err(RenderError::Suspended(fut)) => RenderReturn {
|
||||
node: Err(RenderError::Suspended(fut.clone_mounted())),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RenderReturn {
|
||||
fn default() -> Self {
|
||||
RenderReturn::Aborted(VNode::placeholder())
|
||||
RenderReturn {
|
||||
node: Ok(VNode::placeholder()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,8 +71,20 @@ impl Deref for RenderReturn {
|
||||
type Target = VNode;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
RenderReturn::Ready(node) | RenderReturn::Aborted(node) => node,
|
||||
match &self.node {
|
||||
Ok(node) => node,
|
||||
Err(RenderError::Aborted(err)) => &err.render,
|
||||
Err(RenderError::Suspended(fut)) => &fut.placeholder,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for RenderReturn {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
match &mut self.node {
|
||||
Ok(node) => node,
|
||||
Err(RenderError::Aborted(err)) => &mut err.render,
|
||||
Err(RenderError::Suspended(fut)) => &mut fut.placeholder,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,6 +182,12 @@ impl Clone for VNode {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VNode {
|
||||
fn default() -> Self {
|
||||
Self::placeholder()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for VNode {
|
||||
fn drop(&mut self) {
|
||||
// FIXME:
|
||||
@@ -197,31 +236,7 @@ impl VNode {
|
||||
|
||||
/// Create a template with no nodes that will be skipped over during diffing
|
||||
pub fn empty() -> Element {
|
||||
use std::cell::OnceCell;
|
||||
// We can reuse all placeholders across the same thread to save memory
|
||||
thread_local! {
|
||||
static EMPTY_VNODE: OnceCell<Rc<VNodeInner>> = const { OnceCell::new() };
|
||||
}
|
||||
let vnode = EMPTY_VNODE.with(|cell| {
|
||||
cell.get_or_init(move || {
|
||||
Rc::new(VNodeInner {
|
||||
key: None,
|
||||
dynamic_nodes: Box::new([]),
|
||||
dynamic_attrs: Box::new([]),
|
||||
template: Cell::new(Template {
|
||||
name: "packages/core/nodes.rs:180:0:0",
|
||||
roots: &[],
|
||||
node_paths: &[],
|
||||
attr_paths: &[],
|
||||
}),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
});
|
||||
Some(Self {
|
||||
vnode,
|
||||
mount: Default::default(),
|
||||
})
|
||||
Ok(Self::default())
|
||||
}
|
||||
|
||||
/// Create a template with a single placeholder node
|
||||
@@ -240,7 +255,7 @@ impl VNode {
|
||||
template: Cell::new(Template {
|
||||
name: "packages/core/nodes.rs:198:0:0",
|
||||
roots: &[TemplateNode::Dynamic { id: 0 }],
|
||||
node_paths: &[&[]],
|
||||
node_paths: &[&[0]],
|
||||
attr_paths: &[],
|
||||
}),
|
||||
})
|
||||
@@ -275,12 +290,9 @@ impl VNode {
|
||||
///
|
||||
/// Returns [`None`] if the root is actually a static node (Element/Text)
|
||||
pub fn dynamic_root(&self, idx: usize) -> Option<&DynamicNode> {
|
||||
match &self.template.get().roots[idx] {
|
||||
TemplateNode::Element { .. } | TemplateNode::Text { text: _ } => None,
|
||||
TemplateNode::Dynamic { id } | TemplateNode::DynamicText { id } => {
|
||||
Some(&self.dynamic_nodes[*id])
|
||||
}
|
||||
}
|
||||
self.template.get().roots[idx]
|
||||
.dynamic_id()
|
||||
.map(|id| &self.dynamic_nodes[id])
|
||||
}
|
||||
|
||||
/// Get the mounted id for a dynamic node index
|
||||
@@ -427,9 +439,14 @@ impl Template {
|
||||
/// There's no point in saving templates that are completely dynamic, since they'll be recreated every time anyway.
|
||||
pub fn is_completely_dynamic(&self) -> bool {
|
||||
use TemplateNode::*;
|
||||
self.roots
|
||||
.iter()
|
||||
.all(|root| matches!(root, Dynamic { .. } | DynamicText { .. }))
|
||||
self.roots.iter().all(|root| matches!(root, Dynamic { .. }))
|
||||
}
|
||||
|
||||
/// Get a unique id for this template. If the id between two templates are different, the contents of the template may be different.
|
||||
pub fn id(&self) -> usize {
|
||||
// We compare the template name by pointer so that the id is different after hot reloading even if the name is the same
|
||||
let ptr: *const str = self.name;
|
||||
ptr as *const () as usize
|
||||
}
|
||||
|
||||
/// Iterate over the attribute paths in order along with the original indexes for each path
|
||||
@@ -447,6 +464,20 @@ impl Template {
|
||||
sort_bfo(self.attr_paths).into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate over the node paths in order along with the original indexes for each path
|
||||
pub(crate) fn breadth_first_node_paths(&self) -> impl Iterator<Item = (usize, &'static [u8])> {
|
||||
// In release mode, hot reloading is disabled and everything is in breadth first order already
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
self.node_paths.iter().copied().enumerate()
|
||||
}
|
||||
// If we are in debug mode, hot reloading may have messed up the order of the paths. We need to sort them
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
sort_bfo(self.node_paths).into_iter()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A statically known node in a layout.
|
||||
@@ -500,14 +531,6 @@ pub enum TemplateNode {
|
||||
/// The index of the dynamic node in the VNode's dynamic_nodes list
|
||||
id: usize,
|
||||
},
|
||||
|
||||
/// This template node is known to be some text, but needs to be created at runtime
|
||||
///
|
||||
/// This is separate from the pure Dynamic variant for various optimizations
|
||||
DynamicText {
|
||||
/// The index of the dynamic node in the VNode's dynamic_nodes list
|
||||
id: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl TemplateNode {
|
||||
@@ -515,7 +538,7 @@ impl TemplateNode {
|
||||
pub fn dynamic_id(&self) -> Option<usize> {
|
||||
use TemplateNode::*;
|
||||
match self {
|
||||
Dynamic { id } | DynamicText { id } => Some(*id),
|
||||
Dynamic { id } => Some(*id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -575,9 +598,20 @@ pub struct VComponent {
|
||||
/// It is possible that components get folded at compile time, so these shouldn't be really used as a key
|
||||
pub(crate) render_fn: TypeId,
|
||||
|
||||
/// The props for this component
|
||||
pub(crate) props: BoxedAnyProps,
|
||||
}
|
||||
|
||||
impl Clone for VComponent {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
name: self.name,
|
||||
render_fn: self.render_fn,
|
||||
props: self.props.duplicate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VComponent {
|
||||
/// Create a new [`VComponent`] variant
|
||||
pub fn new<P, M: 'static>(
|
||||
@@ -603,6 +637,24 @@ impl VComponent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`ScopeId`] this node is mounted to if it's mounted
|
||||
///
|
||||
/// This is useful for rendering nodes outside of the VirtualDom, such as in SSR
|
||||
///
|
||||
/// Returns [`None`] if the node is not mounted
|
||||
pub fn mounted_scope_id(
|
||||
&self,
|
||||
dynamic_node_index: usize,
|
||||
vnode: &VNode,
|
||||
dom: &VirtualDom,
|
||||
) -> Option<ScopeId> {
|
||||
let mount = vnode.mount.get().as_usize()?;
|
||||
|
||||
let scope_id = dom.mounts.get(mount)?.mounted_dynamic_nodes[dynamic_node_index];
|
||||
|
||||
Some(ScopeId(scope_id))
|
||||
}
|
||||
|
||||
/// Get the scope this node is mounted to if it's mounted
|
||||
///
|
||||
/// This is useful for rendering nodes outside of the VirtualDom, such as in SSR
|
||||
@@ -844,9 +896,7 @@ impl<T: Any + PartialEq + 'static> AnyValue for T {
|
||||
|
||||
/// A trait that allows various items to be converted into a dynamic node for the rsx macro
|
||||
pub trait IntoDynNode<A = ()> {
|
||||
/// Consume this item along with a scopestate and produce a DynamicNode
|
||||
///
|
||||
/// You can use the bump alloactor of the scopestate to creat the dynamic node
|
||||
/// Consume this item and produce a DynamicNode
|
||||
fn into_dyn_node(self) -> DynamicNode;
|
||||
}
|
||||
|
||||
@@ -860,13 +910,11 @@ impl IntoDynNode for VNode {
|
||||
DynamicNode::Fragment(vec![self])
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDynNode for DynamicNode {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoDynNode> IntoDynNode for Option<T> {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
match self {
|
||||
@@ -875,8 +923,23 @@ impl<T: IntoDynNode> IntoDynNode for Option<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDynNode for &Element {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
match self.as_ref() {
|
||||
Ok(val) => val.into_dyn_node(),
|
||||
_ => DynamicNode::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoDynNode for Element {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
match self {
|
||||
Ok(val) => val.into_dyn_node(),
|
||||
_ => DynamicNode::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoDynNode for &Option<VNode> {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
match self.as_ref() {
|
||||
Some(val) => val.clone().into_dyn_node(),
|
||||
@@ -884,7 +947,6 @@ impl IntoDynNode for &Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDynNode for &str {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
DynamicNode::Text(VText {
|
||||
@@ -892,13 +954,11 @@ impl IntoDynNode for &str {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDynNode for String {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
DynamicNode::Text(VText { value: self })
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDynNode for Arguments<'_> {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
DynamicNode::Text(VText {
|
||||
@@ -906,7 +966,6 @@ impl IntoDynNode for Arguments<'_> {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDynNode for &VNode {
|
||||
fn into_dyn_node(self) -> DynamicNode {
|
||||
DynamicNode::Fragment(vec![self.clone()])
|
||||
@@ -929,12 +988,20 @@ impl IntoVNode for &VNode {
|
||||
impl IntoVNode for Element {
|
||||
fn into_vnode(self) -> VNode {
|
||||
match self {
|
||||
Some(val) => val.into_vnode(),
|
||||
Ok(val) => val.into_vnode(),
|
||||
_ => VNode::empty().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoVNode for &Element {
|
||||
fn into_vnode(self) -> VNode {
|
||||
match self {
|
||||
Ok(val) => val.into_vnode(),
|
||||
_ => VNode::empty().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoVNode for Option<VNode> {
|
||||
fn into_vnode(self) -> VNode {
|
||||
match self {
|
||||
Some(val) => val.into_vnode(),
|
||||
@@ -942,6 +1009,30 @@ impl IntoVNode for &Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoVNode for &Option<VNode> {
|
||||
fn into_vnode(self) -> VNode {
|
||||
match self.as_ref() {
|
||||
Some(val) => val.clone().into_vnode(),
|
||||
_ => VNode::empty().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoVNode for Option<Element> {
|
||||
fn into_vnode(self) -> VNode {
|
||||
match self {
|
||||
Some(val) => val.into_vnode(),
|
||||
_ => VNode::empty().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoVNode for &Option<Element> {
|
||||
fn into_vnode(self) -> VNode {
|
||||
match self.as_ref() {
|
||||
Some(val) => val.clone().into_vnode(),
|
||||
_ => VNode::empty().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Note that we're using the E as a generic but this is never crafted anyways.
|
||||
pub struct FromNodeIterator;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
use std::fmt::{Debug, Display};
|
||||
|
||||
use crate::innerlude::*;
|
||||
|
||||
/// An error that can occur while rendering a component
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum RenderError {
|
||||
/// The render function returned early
|
||||
Aborted(CapturedError),
|
||||
|
||||
/// The component was suspended
|
||||
Suspended(SuspendedFuture),
|
||||
}
|
||||
|
||||
impl Default for RenderError {
|
||||
fn default() -> Self {
|
||||
struct RenderAbortedEarly;
|
||||
impl Debug for RenderAbortedEarly {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Render aborted early")
|
||||
}
|
||||
}
|
||||
impl Display for RenderAbortedEarly {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Render aborted early")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for RenderAbortedEarly {}
|
||||
Self::Aborted(RenderAbortedEarly.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RenderError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Aborted(e) => write!(f, "Render aborted: {e}"),
|
||||
Self::Suspended(e) => write!(f, "Component suspended: {e:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: std::error::Error + 'static> From<E> for RenderError {
|
||||
fn from(e: E) -> Self {
|
||||
Self::Aborted(CapturedError::from(e))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CapturedError> for RenderError {
|
||||
fn from(e: CapturedError) -> Self {
|
||||
RenderError::Aborted(e)
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
//! TODO: We no longer run effects with async tasks. Effects are now their own type of task. We should remove this next breaking release.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::task::Waker;
|
||||
|
||||
/// A signal is a message that can be sent to all listening tasks at once
|
||||
#[derive(Default)]
|
||||
pub struct RenderSignal {
|
||||
wakers: Rc<RefCell<Vec<Rc<RefCell<RenderSignalFutureInner>>>>>,
|
||||
}
|
||||
|
||||
impl RenderSignal {
|
||||
/// Send the signal to all listening tasks
|
||||
pub fn send(&self) {
|
||||
let mut wakers = self.wakers.borrow_mut();
|
||||
for waker in wakers.drain(..) {
|
||||
let mut inner = waker.borrow_mut();
|
||||
inner.resolved = true;
|
||||
if let Some(waker) = inner.waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a future that resolves when the signal is sent
|
||||
pub fn subscribe(&self) -> RenderSignalFuture {
|
||||
let inner = Rc::new(RefCell::new(RenderSignalFutureInner {
|
||||
resolved: false,
|
||||
waker: None,
|
||||
}));
|
||||
self.wakers.borrow_mut().push(inner.clone());
|
||||
RenderSignalFuture { inner }
|
||||
}
|
||||
}
|
||||
|
||||
struct RenderSignalFutureInner {
|
||||
resolved: bool,
|
||||
waker: Option<Waker>,
|
||||
}
|
||||
|
||||
pub(crate) struct RenderSignalFuture {
|
||||
inner: Rc<RefCell<RenderSignalFutureInner>>,
|
||||
}
|
||||
|
||||
impl Future for RenderSignalFuture {
|
||||
type Output = ();
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
|
||||
let mut inner = self.inner.borrow_mut();
|
||||
if inner.resolved {
|
||||
Poll::Ready(())
|
||||
} else {
|
||||
inner.waker = Some(cx.waker().clone());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use crate::{prelude::*, properties::RootProps, DynamicNode, VComponent};
|
||||
|
||||
// We wrap the root scope in a component that renders it inside a default ErrorBoundary and SuspenseBoundary
|
||||
#[allow(non_snake_case)]
|
||||
#[allow(clippy::let_and_return)]
|
||||
pub(crate) fn RootScopeWrapper(props: RootProps<VComponent>) -> Element {
|
||||
static TEMPLATE: Template = Template {
|
||||
name: "root_wrapper.rs:16:5:561",
|
||||
roots: &[TemplateNode::Dynamic { id: 0usize }],
|
||||
node_paths: &[&[0u8]],
|
||||
attr_paths: &[],
|
||||
};
|
||||
Element::Ok(VNode::new(
|
||||
None,
|
||||
TEMPLATE,
|
||||
Box::new([DynamicNode::Component(
|
||||
fc_to_builder(ErrorBoundary)
|
||||
.children(Element::Ok(VNode::new(
|
||||
None,
|
||||
TEMPLATE,
|
||||
Box::new([DynamicNode::Component({
|
||||
#[allow(unused_imports)]
|
||||
fc_to_builder(SuspenseBoundary)
|
||||
.fallback(|_| Element::Ok(VNode::placeholder()))
|
||||
.children(Ok(VNode::new(
|
||||
None,
|
||||
TEMPLATE,
|
||||
Box::new([DynamicNode::Component(props.0)]),
|
||||
Box::new([]),
|
||||
)))
|
||||
.build()
|
||||
.into_vcomponent(SuspenseBoundary, "SuspenseBoundary")
|
||||
})]),
|
||||
Box::new([]),
|
||||
)))
|
||||
.build()
|
||||
.into_vcomponent(ErrorBoundary, "ErrorBoundary"),
|
||||
)]),
|
||||
Box::new([]),
|
||||
))
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
use slotmap::DefaultKey;
|
||||
|
||||
use crate::innerlude::Effect;
|
||||
use crate::innerlude::{DirtyTasks, Effect};
|
||||
use crate::scope_context::SuspenseLocation;
|
||||
use crate::{
|
||||
innerlude::{LocalTask, SchedulerMsg},
|
||||
render_signal::RenderSignal,
|
||||
scope_context::Scope,
|
||||
scopes::ScopeId,
|
||||
Task,
|
||||
};
|
||||
use slotmap::DefaultKey;
|
||||
use std::collections::BTreeSet;
|
||||
use std::{
|
||||
cell::{Cell, Ref, RefCell},
|
||||
@@ -25,6 +24,9 @@ pub struct Runtime {
|
||||
// We use this to track the current scope
|
||||
pub(crate) scope_stack: RefCell<Vec<ScopeId>>,
|
||||
|
||||
// We use this to track the current suspense location. Generally this lines up with the scope stack, but it may be different for children of a suspense boundary
|
||||
pub(crate) suspense_stack: RefCell<Vec<SuspenseLocation>>,
|
||||
|
||||
// We use this to track the current task
|
||||
pub(crate) current_task: Cell<Option<Task>>,
|
||||
|
||||
@@ -38,25 +40,26 @@ pub struct Runtime {
|
||||
|
||||
pub(crate) sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>,
|
||||
|
||||
// Synchronous tasks need to be run after the next render. The virtual dom stores a list of those tasks to send a signal to them when the next render is done.
|
||||
pub(crate) render_signal: RenderSignal,
|
||||
|
||||
// The effects that need to be run after the next render
|
||||
pub(crate) pending_effects: RefCell<BTreeSet<Effect>>,
|
||||
|
||||
// Tasks that are waiting to be polled
|
||||
pub(crate) dirty_tasks: RefCell<BTreeSet<DirtyTasks>>,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
pub(crate) fn new(sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>) -> Rc<Self> {
|
||||
Rc::new(Self {
|
||||
sender,
|
||||
render_signal: RenderSignal::default(),
|
||||
rendering: Cell::new(true),
|
||||
scope_states: Default::default(),
|
||||
scope_stack: Default::default(),
|
||||
suspense_stack: Default::default(),
|
||||
current_task: Default::default(),
|
||||
tasks: Default::default(),
|
||||
suspended_tasks: Default::default(),
|
||||
pending_effects: Default::default(),
|
||||
dirty_tasks: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -111,15 +114,34 @@ impl Runtime {
|
||||
/// Useful in a limited number of scenarios
|
||||
pub fn on_scope<O>(&self, id: ScopeId, f: impl FnOnce() -> O) -> O {
|
||||
{
|
||||
self.scope_stack.borrow_mut().push(id);
|
||||
self.push_scope(id);
|
||||
}
|
||||
let o = f();
|
||||
{
|
||||
self.scope_stack.borrow_mut().pop();
|
||||
self.pop_scope();
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Push a scope onto the stack
|
||||
pub(crate) fn push_scope(&self, scope: ScopeId) {
|
||||
let suspense_location = self
|
||||
.scope_states
|
||||
.borrow()
|
||||
.get(scope.0)
|
||||
.and_then(|s| s.as_ref())
|
||||
.map(|s| s.suspense_boundary())
|
||||
.unwrap_or_default();
|
||||
self.suspense_stack.borrow_mut().push(suspense_location);
|
||||
self.scope_stack.borrow_mut().push(scope);
|
||||
}
|
||||
|
||||
/// Pop a scope off the stack
|
||||
pub(crate) fn pop_scope(&self) {
|
||||
self.scope_stack.borrow_mut().pop();
|
||||
self.suspense_stack.borrow_mut().pop();
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -167,9 +189,18 @@ impl Runtime {
|
||||
.unbounded_send(SchedulerMsg::EffectQueued)
|
||||
.expect("Scheduler should exist");
|
||||
}
|
||||
}
|
||||
|
||||
// And send the render signal
|
||||
self.render_signal.send();
|
||||
/// Check if we should render a scope
|
||||
pub(crate) fn scope_should_render(&self, scope_id: ScopeId) -> bool {
|
||||
// If there are no suspended futures, we know the scope is not and we can skip context checks
|
||||
if self.suspended_tasks.get() == 0 {
|
||||
return true;
|
||||
}
|
||||
// If this is not a suspended scope, and we are under a frozen context, then we should
|
||||
let scopes = self.scope_states.borrow();
|
||||
let scope = &scopes[scope_id.0].as_ref().unwrap();
|
||||
!matches!(scope.suspense_boundary(), SuspenseLocation::UnderSuspense(suspense) if suspense.suspended())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -124,12 +124,13 @@ impl Hash for ScopeOrder {
|
||||
impl VirtualDom {
|
||||
/// Queue a task to be polled
|
||||
pub(crate) fn queue_task(&mut self, task: Task, order: ScopeOrder) {
|
||||
match self.dirty_tasks.get(&order) {
|
||||
let mut dirty_tasks = self.runtime.dirty_tasks.borrow_mut();
|
||||
match dirty_tasks.get(&order) {
|
||||
Some(scope) => scope.queue_task(task),
|
||||
None => {
|
||||
let scope = DirtyTasks::from(order);
|
||||
scope.queue_task(task);
|
||||
self.dirty_tasks.insert(scope);
|
||||
dirty_tasks.insert(scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,15 +145,23 @@ impl VirtualDom {
|
||||
!self.dirty_scopes.is_empty()
|
||||
}
|
||||
|
||||
/// Take any tasks from the highest scope
|
||||
pub(crate) fn pop_task(&mut self) -> Option<DirtyTasks> {
|
||||
let mut task = self.dirty_tasks.pop_first()?;
|
||||
/// Take the top task from the highest scope
|
||||
pub(crate) fn pop_task(&mut self) -> Option<Task> {
|
||||
let mut dirty_tasks = self.runtime.dirty_tasks.borrow_mut();
|
||||
let mut tasks = dirty_tasks.first()?;
|
||||
|
||||
// If the scope doesn't exist for whatever reason, then we should skip it
|
||||
while !self.scopes.contains(task.order.id.0) {
|
||||
task = self.dirty_tasks.pop_first()?;
|
||||
while !self.scopes.contains(tasks.order.id.0) {
|
||||
dirty_tasks.pop_first();
|
||||
tasks = dirty_tasks.first()?;
|
||||
}
|
||||
|
||||
let mut tasks = tasks.tasks_queued.borrow_mut();
|
||||
let task = tasks.pop_front()?;
|
||||
if tasks.is_empty() {
|
||||
drop(tasks);
|
||||
dirty_tasks.pop_first();
|
||||
}
|
||||
Some(task)
|
||||
}
|
||||
|
||||
@@ -182,16 +191,21 @@ impl VirtualDom {
|
||||
}
|
||||
}
|
||||
|
||||
let mut dirty_task = self.dirty_tasks.first();
|
||||
// Pop any invalid tasks off of each dirty scope;
|
||||
while let Some(task) = dirty_task {
|
||||
if !self.scopes.contains(task.order.id.0) {
|
||||
self.dirty_tasks.pop_first();
|
||||
dirty_task = self.dirty_tasks.first();
|
||||
} else {
|
||||
break;
|
||||
// Find the height of the highest dirty scope
|
||||
let dirty_task = {
|
||||
let mut dirty_tasks = self.runtime.dirty_tasks.borrow_mut();
|
||||
let mut dirty_task = dirty_tasks.first();
|
||||
// Pop any invalid tasks off of each dirty scope;
|
||||
while let Some(task) = dirty_task {
|
||||
if task.tasks_queued.borrow().is_empty() || !self.scopes.contains(task.order.id.0) {
|
||||
dirty_tasks.pop_first();
|
||||
dirty_task = dirty_tasks.first()
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
dirty_task.map(|task| task.order)
|
||||
};
|
||||
|
||||
match (dirty_scope, dirty_task) {
|
||||
(Some(scope), Some(task)) => {
|
||||
@@ -199,57 +213,27 @@ impl VirtualDom {
|
||||
match scope.cmp(tasks_order) {
|
||||
std::cmp::Ordering::Less => {
|
||||
let scope = self.dirty_scopes.pop_first().unwrap();
|
||||
Some(Work {
|
||||
scope,
|
||||
rerun_scope: true,
|
||||
tasks: Default::default(),
|
||||
})
|
||||
Some(Work::RerunScope(scope))
|
||||
}
|
||||
std::cmp::Ordering::Greater => {
|
||||
let task = self.dirty_tasks.pop_first().unwrap();
|
||||
Some(Work {
|
||||
scope: task.order,
|
||||
rerun_scope: false,
|
||||
tasks: task.tasks_queued.into_inner(),
|
||||
})
|
||||
}
|
||||
std::cmp::Ordering::Equal => {
|
||||
let scope = self.dirty_scopes.pop_first().unwrap();
|
||||
let task = self.dirty_tasks.pop_first().unwrap();
|
||||
Some(Work {
|
||||
scope,
|
||||
rerun_scope: true,
|
||||
tasks: task.tasks_queued.into_inner(),
|
||||
})
|
||||
std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => {
|
||||
Some(Work::PollTask(self.pop_task().unwrap()))
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(_), None) => {
|
||||
let scope = self.dirty_scopes.pop_first().unwrap();
|
||||
Some(Work {
|
||||
scope,
|
||||
rerun_scope: true,
|
||||
tasks: Default::default(),
|
||||
})
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
let task = self.dirty_tasks.pop_first().unwrap();
|
||||
Some(Work {
|
||||
scope: task.order,
|
||||
rerun_scope: false,
|
||||
tasks: task.tasks_queued.into_inner(),
|
||||
})
|
||||
Some(Work::RerunScope(scope))
|
||||
}
|
||||
(None, Some(_)) => Some(Work::PollTask(self.pop_task().unwrap())),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Work {
|
||||
pub scope: ScopeOrder,
|
||||
pub rerun_scope: bool,
|
||||
pub tasks: VecDeque<Task>,
|
||||
pub enum Work {
|
||||
RerunScope(ScopeOrder),
|
||||
PollTask(Task),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq)]
|
||||
@@ -269,7 +253,16 @@ impl From<ScopeOrder> for DirtyTasks {
|
||||
|
||||
impl DirtyTasks {
|
||||
pub fn queue_task(&self, task: Task) {
|
||||
self.tasks_queued.borrow_mut().push_back(task);
|
||||
let mut borrow_mut = self.tasks_queued.borrow_mut();
|
||||
// If the task is already queued, we don't need to do anything
|
||||
if borrow_mut.contains(&task) {
|
||||
return;
|
||||
}
|
||||
borrow_mut.push_back(task);
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&self, id: Task) {
|
||||
self.tasks_queued.borrow_mut().retain(|task| *task != id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,38 @@
|
||||
use crate::innerlude::ScopeOrder;
|
||||
use crate::reactive_context::ReactiveContext;
|
||||
use crate::innerlude::{throw_error, RenderError, RenderReturn, ScopeOrder};
|
||||
use crate::prelude::ReactiveContext;
|
||||
use crate::scope_context::SuspenseLocation;
|
||||
use crate::{
|
||||
any_props::{AnyProps, BoxedAnyProps},
|
||||
innerlude::ScopeState,
|
||||
nodes::RenderReturn,
|
||||
scope_context::Scope,
|
||||
scopes::ScopeId,
|
||||
virtual_dom::VirtualDom,
|
||||
};
|
||||
use crate::{Element, VNode};
|
||||
|
||||
impl VirtualDom {
|
||||
pub(super) fn new_scope(&mut self, props: BoxedAnyProps, name: &'static str) -> &ScopeState {
|
||||
pub(super) fn new_scope(
|
||||
&mut self,
|
||||
props: BoxedAnyProps,
|
||||
name: &'static str,
|
||||
) -> &mut ScopeState {
|
||||
let parent_id = self.runtime.current_scope_id();
|
||||
let height = parent_id
|
||||
.and_then(|parent_id| self.runtime.get_state(parent_id).map(|f| f.height + 1))
|
||||
.unwrap_or(0);
|
||||
let height = match parent_id.and_then(|id| self.runtime.get_state(id)) {
|
||||
Some(parent) => parent.height() + 1,
|
||||
None => 0,
|
||||
};
|
||||
let suspense_boundary = self
|
||||
.runtime
|
||||
.suspense_stack
|
||||
.borrow()
|
||||
.last()
|
||||
.cloned()
|
||||
.unwrap_or(SuspenseLocation::NotSuspended);
|
||||
let entry = self.scopes.vacant_entry();
|
||||
let id = ScopeId(entry.key());
|
||||
|
||||
let scope_runtime = Scope::new(name, id, parent_id, height);
|
||||
let scope_runtime = Scope::new(name, id, parent_id, height, suspense_boundary);
|
||||
let reactive_context = ReactiveContext::new_for_scope(&scope_runtime, &self.runtime);
|
||||
self.runtime.create_scope(scope_runtime);
|
||||
|
||||
let scope = entry.insert(ScopeState {
|
||||
runtime: self.runtime.clone(),
|
||||
@@ -30,60 +42,104 @@ impl VirtualDom {
|
||||
reactive_context,
|
||||
});
|
||||
|
||||
self.runtime.create_scope(scope_runtime);
|
||||
tracing::trace!("created scope {id:?} with parent {parent_id:?}");
|
||||
|
||||
scope
|
||||
}
|
||||
|
||||
/// Run a scope and return the rendered nodes. This will not modify the DOM or update the last rendered node of the scope.
|
||||
#[tracing::instrument(skip(self), level = "trace", name = "VirtualDom::run_scope")]
|
||||
pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> RenderReturn {
|
||||
debug_assert!(
|
||||
crate::Runtime::current().is_some(),
|
||||
"Must be in a dioxus runtime"
|
||||
);
|
||||
self.runtime.push_scope(scope_id);
|
||||
|
||||
self.runtime.scope_stack.borrow_mut().push(scope_id);
|
||||
let scope = &self.scopes[scope_id.0];
|
||||
let new_nodes = {
|
||||
let context = scope.state();
|
||||
let output = {
|
||||
let scope_state = scope.state();
|
||||
|
||||
context.hook_index.set(0);
|
||||
scope_state.hook_index.set(0);
|
||||
|
||||
// Run all pre-render hooks
|
||||
for pre_run in context.before_render.borrow_mut().iter_mut() {
|
||||
for pre_run in scope_state.before_render.borrow_mut().iter_mut() {
|
||||
pre_run();
|
||||
}
|
||||
|
||||
// safety: due to how we traverse the tree, we know that the scope is not currently aliased
|
||||
let props: &dyn AnyProps = &*scope.props;
|
||||
|
||||
let span = tracing::trace_span!("render", scope = %scope.state().name);
|
||||
span.in_scope(|| scope.reactive_context.reset_and_run_in(|| props.render()))
|
||||
span.in_scope(|| {
|
||||
scope.reactive_context.reset_and_run_in(|| {
|
||||
let mut render_return = props.render();
|
||||
self.handle_element_return(&mut render_return.node, scope_id, &scope.state());
|
||||
render_return
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
let context = scope.state();
|
||||
let scope_state = scope.state();
|
||||
|
||||
// Run all post-render hooks
|
||||
for post_run in context.after_render.borrow_mut().iter_mut() {
|
||||
for post_run in scope_state.after_render.borrow_mut().iter_mut() {
|
||||
post_run();
|
||||
}
|
||||
|
||||
// And move the render generation forward by one
|
||||
context.render_count.set(context.render_count.get() + 1);
|
||||
|
||||
// remove this scope from dirty scopes
|
||||
self.dirty_scopes
|
||||
.remove(&ScopeOrder::new(context.height, scope_id));
|
||||
.remove(&ScopeOrder::new(scope_state.height, scope_id));
|
||||
|
||||
if let Some(task) = context.last_suspendable_task.take() {
|
||||
if matches!(new_nodes, RenderReturn::Aborted(_)) {
|
||||
tracing::trace!("Suspending {:?} on {:?}", scope_id, task);
|
||||
self.runtime.tasks.borrow().get(task.0).unwrap().suspend();
|
||||
self.runtime
|
||||
.suspended_tasks
|
||||
.set(self.runtime.suspended_tasks.get() + 1);
|
||||
self.runtime.pop_scope();
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Insert any errors, or suspended tasks from an element return into the runtime
|
||||
fn handle_element_return(&self, node: &mut Element, scope_id: ScopeId, scope_state: &Scope) {
|
||||
match node {
|
||||
Err(RenderError::Aborted(e)) => {
|
||||
tracing::error!(
|
||||
"Error while rendering component `{}`: {e:?}",
|
||||
scope_state.name
|
||||
);
|
||||
throw_error(e.clone_mounted());
|
||||
e.render = VNode::placeholder();
|
||||
}
|
||||
Err(RenderError::Suspended(e)) => {
|
||||
let task = e.task();
|
||||
// Insert the task into the nearest suspense boundary if it exists
|
||||
let boundary = self
|
||||
.runtime
|
||||
.get_state(scope_id)
|
||||
.unwrap()
|
||||
.suspense_boundary();
|
||||
let already_suspended = self
|
||||
.runtime
|
||||
.tasks
|
||||
.borrow()
|
||||
.get(task.id)
|
||||
.expect("Suspended on a task that no longer exists")
|
||||
.suspend(boundary.clone());
|
||||
if !already_suspended {
|
||||
tracing::trace!("Suspending {:?} on {:?}", scope_id, task);
|
||||
// Add this task to the suspended tasks list of the boundary
|
||||
if let SuspenseLocation::UnderSuspense(boundary) = &boundary {
|
||||
boundary.add_suspended_task(e.clone());
|
||||
}
|
||||
self.runtime
|
||||
.suspended_tasks
|
||||
.set(self.runtime.suspended_tasks.get() + 1);
|
||||
}
|
||||
e.placeholder = VNode::placeholder();
|
||||
}
|
||||
Ok(_) => {
|
||||
// If the render was successful, we can move the render generation forward by one
|
||||
scope_state
|
||||
.render_count
|
||||
.set(scope_state.render_count.get() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
self.runtime.scope_stack.borrow_mut().pop();
|
||||
|
||||
new_nodes
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
use crate::{innerlude::SchedulerMsg, Element, Runtime, ScopeId, Task};
|
||||
use crate::{innerlude::SchedulerMsg, Runtime, ScopeId, Task};
|
||||
use crate::{
|
||||
innerlude::{throw_into, CapturedError},
|
||||
prelude::SuspenseContext,
|
||||
};
|
||||
use generational_box::{AnyStorage, Owner};
|
||||
use rustc_hash::FxHashSet;
|
||||
use std::{
|
||||
@@ -8,6 +12,32 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub(crate) enum ScopeStatus {
|
||||
Mounted,
|
||||
Unmounted {
|
||||
// Before the component is mounted, we need to keep track of effects that need to be run once the scope is mounted
|
||||
effects_queued: Vec<Box<dyn FnOnce() + 'static>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) enum SuspenseLocation {
|
||||
#[default]
|
||||
NotSuspended,
|
||||
InSuspensePlaceholder(SuspenseContext),
|
||||
UnderSuspense(SuspenseContext),
|
||||
}
|
||||
|
||||
impl SuspenseLocation {
|
||||
pub(crate) fn suspense_context(&self) -> Option<&SuspenseContext> {
|
||||
match self {
|
||||
SuspenseLocation::InSuspensePlaceholder(context) => Some(context),
|
||||
SuspenseLocation::UnderSuspense(context) => Some(context),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A component's state separate from its props.
|
||||
///
|
||||
/// This struct exists to provide a common interface for all scopes without relying on generics.
|
||||
@@ -23,10 +53,13 @@ pub(crate) struct Scope {
|
||||
pub(crate) hook_index: Cell<usize>,
|
||||
pub(crate) shared_contexts: RefCell<Vec<Box<dyn Any>>>,
|
||||
pub(crate) spawned_tasks: RefCell<FxHashSet<Task>>,
|
||||
/// The task that was last spawned that may suspend. We use this task to check what task to suspend in the event of an early None return from a component
|
||||
pub(crate) last_suspendable_task: Cell<Option<Task>>,
|
||||
pub(crate) before_render: RefCell<Vec<Box<dyn FnMut()>>>,
|
||||
pub(crate) after_render: RefCell<Vec<Box<dyn FnMut()>>>,
|
||||
|
||||
/// The suspense boundary that this scope is currently in (if any)
|
||||
suspense_boundary: SuspenseLocation,
|
||||
|
||||
pub(crate) status: RefCell<ScopeStatus>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
@@ -35,6 +68,7 @@ impl Scope {
|
||||
id: ScopeId,
|
||||
parent_id: Option<ScopeId>,
|
||||
height: u32,
|
||||
suspense_boundary: SuspenseLocation,
|
||||
) -> Self {
|
||||
Self {
|
||||
name,
|
||||
@@ -44,11 +78,14 @@ impl Scope {
|
||||
render_count: Cell::new(0),
|
||||
shared_contexts: RefCell::new(vec![]),
|
||||
spawned_tasks: RefCell::new(FxHashSet::default()),
|
||||
last_suspendable_task: Cell::new(None),
|
||||
hooks: RefCell::new(vec![]),
|
||||
hook_index: Cell::new(0),
|
||||
before_render: RefCell::new(vec![]),
|
||||
after_render: RefCell::new(vec![]),
|
||||
status: RefCell::new(ScopeStatus::Unmounted {
|
||||
effects_queued: Vec::new(),
|
||||
}),
|
||||
suspense_boundary,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +97,30 @@ impl Scope {
|
||||
Runtime::with(|rt| rt.sender.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// Mount the scope and queue any pending effects if it is not already mounted
|
||||
pub(crate) fn mount(&self, runtime: &Runtime) {
|
||||
let mut status = self.status.borrow_mut();
|
||||
if let ScopeStatus::Unmounted { effects_queued } = &mut *status {
|
||||
for f in effects_queued.drain(..) {
|
||||
runtime.queue_effect_on_mounted_scope(self.id, f);
|
||||
}
|
||||
*status = ScopeStatus::Mounted;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the suspense boundary this scope is currently in (if any)
|
||||
pub(crate) fn suspense_boundary(&self) -> SuspenseLocation {
|
||||
self.suspense_boundary.clone()
|
||||
}
|
||||
|
||||
/// Check if a node should run during suspense
|
||||
pub(crate) fn should_run_during_suspense(&self) -> bool {
|
||||
matches!(
|
||||
self.suspense_boundary,
|
||||
SuspenseLocation::UnderSuspense(_) | SuspenseLocation::InSuspensePlaceholder(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// Mark this scope as dirty, and schedule a render for it.
|
||||
pub fn needs_update(&self) {
|
||||
self.needs_update_any(self.id)
|
||||
@@ -129,18 +190,18 @@ impl Scope {
|
||||
let mut search_parent = self.parent_id;
|
||||
let cur_runtime = Runtime::with(|runtime| {
|
||||
while let Some(parent_id) = search_parent {
|
||||
let parent = runtime.get_state(parent_id).unwrap();
|
||||
let Some(parent) = runtime.get_state(parent_id) else {
|
||||
tracing::error!("Parent scope {:?} not found", parent_id);
|
||||
return None;
|
||||
};
|
||||
tracing::trace!(
|
||||
"looking for context {} ({:?}) in {}",
|
||||
std::any::type_name::<T>(),
|
||||
std::any::TypeId::of::<T>(),
|
||||
parent.name
|
||||
);
|
||||
if let Some(shared) = parent.shared_contexts.borrow().iter().find_map(|any| {
|
||||
tracing::trace!("found context {:?}", (**any).type_id());
|
||||
any.downcast_ref::<T>()
|
||||
}) {
|
||||
return Some(shared.clone());
|
||||
if let Some(shared) = parent.has_context() {
|
||||
return Some(shared);
|
||||
}
|
||||
search_parent = parent.parent_id;
|
||||
}
|
||||
@@ -286,12 +347,6 @@ impl Scope {
|
||||
Runtime::with(|rt| rt.queue_effect(self.id, f)).expect("Runtime to exist");
|
||||
}
|
||||
|
||||
/// Mark this component as suspended on a specific task and then return None
|
||||
pub fn suspend(&self, task: Task) -> Option<Element> {
|
||||
self.last_suspendable_task.set(Some(task));
|
||||
None
|
||||
}
|
||||
|
||||
/// Store a value between renders. The foundational hook for all other hooks.
|
||||
///
|
||||
/// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render).
|
||||
@@ -413,14 +468,6 @@ impl ScopeId {
|
||||
.expect("to be in a dioxus runtime")
|
||||
}
|
||||
|
||||
/// Suspended a component on a specific task and then return None
|
||||
pub fn suspend(self, task: Task) -> Option<Element> {
|
||||
Runtime::with_scope(self, |cx| {
|
||||
cx.suspend(task);
|
||||
});
|
||||
None
|
||||
}
|
||||
|
||||
/// Pushes the future onto the poll queue to be polled after the component renders.
|
||||
pub fn push_future(self, fut: impl Future<Output = ()> + 'static) -> Option<Task> {
|
||||
Runtime::with_scope(self, |cx| cx.spawn(fut))
|
||||
@@ -466,4 +513,25 @@ impl ScopeId {
|
||||
.expect("to be in a dioxus runtime")
|
||||
.on_scope(self, f)
|
||||
}
|
||||
|
||||
/// Throw a [`CapturedError`] into a scope. The error will bubble up to the nearest [`ErrorBoundary`] or the root of the app.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust, no_run
|
||||
/// # use dioxus::prelude::*;
|
||||
/// fn Component() -> Element {
|
||||
/// let request = spawn(async move {
|
||||
/// match reqwest::get("https://api.example.com").await {
|
||||
/// Ok(_) => todo!(),
|
||||
/// // You can explicitly throw an error into a scope with throw_error
|
||||
/// Err(err) => ScopeId::APP.throw_error(err)
|
||||
/// }
|
||||
/// });
|
||||
///
|
||||
/// todo!()
|
||||
/// }
|
||||
/// ```
|
||||
pub fn throw_error(self, error: impl Into<CapturedError> + 'static) {
|
||||
throw_into(error, self)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
any_props::BoxedAnyProps, nodes::RenderReturn, reactive_context::ReactiveContext,
|
||||
runtime::Runtime, scope_context::Scope,
|
||||
scope_context::Scope, Runtime, VNode,
|
||||
};
|
||||
use std::{cell::Ref, rc::Rc};
|
||||
|
||||
@@ -32,7 +32,7 @@ impl std::fmt::Debug for ScopeId {
|
||||
}
|
||||
|
||||
impl ScopeId {
|
||||
/// The root ScopeId.
|
||||
/// The ScopeId of the main scope passed into [`VirtualDom::new`].
|
||||
///
|
||||
/// This scope will last for the entire duration of your app, making it convenient for long-lived state
|
||||
/// that is created dynamically somewhere down the component tree.
|
||||
@@ -41,9 +41,24 @@ impl ScopeId {
|
||||
///
|
||||
/// ```rust, no_run
|
||||
/// use dioxus::prelude::*;
|
||||
/// let my_persistent_state = Signal::new_in_scope(String::new(), ScopeId::ROOT);
|
||||
/// let my_persistent_state = Signal::new_in_scope(String::new(), ScopeId::APP);
|
||||
/// ```
|
||||
// ScopeId(0) is the root scope wrapper
|
||||
// ScopeId(1) is the default error boundary
|
||||
// ScopeId(2) is the default suspense boundary
|
||||
// ScopeId(3) is the users root scope
|
||||
pub const APP: ScopeId = ScopeId(3);
|
||||
|
||||
/// The ScopeId of the topmost scope in the tree.
|
||||
/// This will be higher up in the tree than [`ScopeId::APP`] because dioxus inserts a default [`SuspenseBoundary`] and [`ErrorBoundary`] at the root of the tree.
|
||||
// ScopeId(0) is the root scope wrapper
|
||||
pub const ROOT: ScopeId = ScopeId(0);
|
||||
|
||||
pub(crate) const PLACEHOLDER: ScopeId = ScopeId(usize::MAX);
|
||||
|
||||
pub(crate) fn is_placeholder(&self) -> bool {
|
||||
*self == Self::PLACEHOLDER
|
||||
}
|
||||
}
|
||||
|
||||
/// A component's rendered state.
|
||||
@@ -52,6 +67,8 @@ impl ScopeId {
|
||||
pub struct ScopeState {
|
||||
pub(crate) runtime: Rc<Runtime>,
|
||||
pub(crate) context_id: ScopeId,
|
||||
/// The last node that has been rendered for this component. This node may not ben mounted
|
||||
/// During suspense, this component can be rendered in the background multiple times
|
||||
pub(crate) last_rendered_node: Option<RenderReturn>,
|
||||
pub(crate) props: BoxedAnyProps,
|
||||
pub(crate) reactive_context: ReactiveContext,
|
||||
@@ -69,7 +86,7 @@ impl ScopeState {
|
||||
/// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.
|
||||
///
|
||||
/// Panics if the tree has not been built yet.
|
||||
pub fn root_node(&self) -> &RenderReturn {
|
||||
pub fn root_node(&self) -> &VNode {
|
||||
self.try_root_node()
|
||||
.expect("The tree has not been built yet. Make sure to call rebuild on the tree before accessing its nodes.")
|
||||
}
|
||||
@@ -79,8 +96,13 @@ impl ScopeState {
|
||||
/// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.
|
||||
///
|
||||
/// Returns [`None`] if the tree has not been built yet.
|
||||
pub fn try_root_node(&self) -> Option<&RenderReturn> {
|
||||
self.last_rendered_node.as_ref()
|
||||
pub fn try_root_node(&self) -> Option<&VNode> {
|
||||
self.last_rendered_node.as_deref()
|
||||
}
|
||||
|
||||
/// Returns the scope id of this [`ScopeState`].
|
||||
pub fn id(&self) -> ScopeId {
|
||||
self.context_id
|
||||
}
|
||||
|
||||
pub(crate) fn state(&self) -> Ref<'_, Scope> {
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
use crate::innerlude::*;
|
||||
|
||||
/// Properties for the [`SuspenseBoundary()`] component.
|
||||
#[allow(non_camel_case_types)]
|
||||
pub struct SuspenseBoundaryProps {
|
||||
fallback: Callback<SuspenseContext, Element>,
|
||||
/// The children of the suspense boundary
|
||||
children: Element,
|
||||
/// THe nodes that are suspended under this boundary
|
||||
pub suspended_nodes: Option<VNode>,
|
||||
}
|
||||
|
||||
impl Clone for SuspenseBoundaryProps {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
fallback: self.fallback,
|
||||
children: self.children.clone(),
|
||||
suspended_nodes: self
|
||||
.suspended_nodes
|
||||
.as_ref()
|
||||
.map(|node| node.clone_mounted()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SuspenseBoundaryProps {
|
||||
/**
|
||||
Create a builder for building `SuspenseBoundaryProps`.
|
||||
On the builder, call `.fallback(...)`, `.children(...)`(optional) to set the values of the fields.
|
||||
Finally, call `.build()` to create the instance of `SuspenseBoundaryProps`.
|
||||
*/
|
||||
#[allow(dead_code, clippy::type_complexity)]
|
||||
fn builder() -> SuspenseBoundaryPropsBuilder<((), ())> {
|
||||
SuspenseBoundaryPropsBuilder {
|
||||
owner: Owner::default(),
|
||||
fields: ((), ()),
|
||||
_phantom: ::core::default::Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, non_snake_case)]
|
||||
pub struct SuspenseBoundaryPropsBuilder<TypedBuilderFields> {
|
||||
owner: Owner,
|
||||
fields: TypedBuilderFields,
|
||||
_phantom: (),
|
||||
}
|
||||
impl Properties for SuspenseBoundaryProps
|
||||
where
|
||||
Self: Clone,
|
||||
{
|
||||
type Builder = SuspenseBoundaryPropsBuilder<((), ())>;
|
||||
fn builder() -> Self::Builder {
|
||||
SuspenseBoundaryProps::builder()
|
||||
}
|
||||
fn memoize(&mut self, new: &Self) -> bool {
|
||||
let equal = self == new;
|
||||
self.fallback.__set(new.fallback.__take());
|
||||
if !equal {
|
||||
let new_clone = new.clone();
|
||||
self.children = new_clone.children;
|
||||
}
|
||||
equal
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, non_snake_case)]
|
||||
pub trait SuspenseBoundaryPropsBuilder_Optional<T> {
|
||||
fn into_value<F: FnOnce() -> T>(self, default: F) -> T;
|
||||
}
|
||||
impl<T> SuspenseBoundaryPropsBuilder_Optional<T> for () {
|
||||
fn into_value<F: FnOnce() -> T>(self, default: F) -> T {
|
||||
default()
|
||||
}
|
||||
}
|
||||
impl<T> SuspenseBoundaryPropsBuilder_Optional<T> for (T,) {
|
||||
fn into_value<F: FnOnce() -> T>(self, _: F) -> T {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
impl<__children> SuspenseBoundaryPropsBuilder<((), __children)> {
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn fallback<__Marker>(
|
||||
self,
|
||||
fallback: impl SuperInto<Callback<SuspenseContext, Element>, __Marker>,
|
||||
) -> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> {
|
||||
let fallback = (with_owner(self.owner.clone(), move || {
|
||||
SuperInto::super_into(fallback)
|
||||
}),);
|
||||
let (_, children) = self.fields;
|
||||
SuspenseBoundaryPropsBuilder {
|
||||
owner: self.owner,
|
||||
fields: (fallback, children),
|
||||
_phantom: self._phantom,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, non_snake_case)]
|
||||
pub enum SuspenseBoundaryPropsBuilder_Error_Repeated_field_fallback {}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
impl<__children> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> {
|
||||
#[deprecated(note = "Repeated field fallback")]
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn fallback(
|
||||
self,
|
||||
_: SuspenseBoundaryPropsBuilder_Error_Repeated_field_fallback,
|
||||
) -> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> {
|
||||
self
|
||||
}
|
||||
}
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
impl<__fallback> SuspenseBoundaryPropsBuilder<(__fallback, ())> {
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn children(
|
||||
self,
|
||||
children: Element,
|
||||
) -> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> {
|
||||
let children = (children,);
|
||||
let (fallback, _) = self.fields;
|
||||
SuspenseBoundaryPropsBuilder {
|
||||
owner: self.owner,
|
||||
fields: (fallback, children),
|
||||
_phantom: self._phantom,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, non_snake_case)]
|
||||
pub enum SuspenseBoundaryPropsBuilder_Error_Repeated_field_children {}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
impl<__fallback> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> {
|
||||
#[deprecated(note = "Repeated field children")]
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn children(
|
||||
self,
|
||||
_: SuspenseBoundaryPropsBuilder_Error_Repeated_field_children,
|
||||
) -> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> {
|
||||
self
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, non_snake_case)]
|
||||
pub enum SuspenseBoundaryPropsBuilder_Error_Missing_required_field_fallback {}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs, clippy::panic)]
|
||||
impl<__children> SuspenseBoundaryPropsBuilder<((), __children)> {
|
||||
#[deprecated(note = "Missing required field fallback")]
|
||||
pub fn build(
|
||||
self,
|
||||
_: SuspenseBoundaryPropsBuilder_Error_Missing_required_field_fallback,
|
||||
) -> SuspenseBoundaryProps {
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
pub struct SuspenseBoundaryPropsWithOwner {
|
||||
inner: SuspenseBoundaryProps,
|
||||
owner: Owner,
|
||||
}
|
||||
#[automatically_derived]
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
impl ::core::clone::Clone for SuspenseBoundaryPropsWithOwner {
|
||||
#[inline]
|
||||
fn clone(&self) -> SuspenseBoundaryPropsWithOwner {
|
||||
SuspenseBoundaryPropsWithOwner {
|
||||
inner: ::core::clone::Clone::clone(&self.inner),
|
||||
owner: ::core::clone::Clone::clone(&self.owner),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PartialEq for SuspenseBoundaryPropsWithOwner {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.inner.eq(&other.inner)
|
||||
}
|
||||
}
|
||||
impl SuspenseBoundaryPropsWithOwner {
|
||||
/// Create a component from the props.
|
||||
pub fn into_vcomponent<M: 'static>(
|
||||
self,
|
||||
render_fn: impl ComponentFunction<SuspenseBoundaryProps, M>,
|
||||
component_name: &'static str,
|
||||
) -> VComponent {
|
||||
VComponent::new(
|
||||
move |wrapper: Self| render_fn.rebuild(wrapper.inner),
|
||||
self,
|
||||
component_name,
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Properties for SuspenseBoundaryPropsWithOwner {
|
||||
type Builder = ();
|
||||
fn builder() -> Self::Builder {
|
||||
unreachable!()
|
||||
}
|
||||
fn memoize(&mut self, new: &Self) -> bool {
|
||||
self.inner.memoize(&new.inner)
|
||||
}
|
||||
}
|
||||
#[allow(dead_code, non_camel_case_types, missing_docs)]
|
||||
impl<__children: SuspenseBoundaryPropsBuilder_Optional<Element>>
|
||||
SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)>
|
||||
{
|
||||
pub fn build(self) -> SuspenseBoundaryPropsWithOwner {
|
||||
let (fallback, children) = self.fields;
|
||||
let fallback = fallback.0;
|
||||
let children = SuspenseBoundaryPropsBuilder_Optional::into_value(children, VNode::empty);
|
||||
SuspenseBoundaryPropsWithOwner {
|
||||
inner: SuspenseBoundaryProps {
|
||||
fallback,
|
||||
children,
|
||||
suspended_nodes: None,
|
||||
},
|
||||
owner: self.owner,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[automatically_derived]
|
||||
#[allow(non_camel_case_types)]
|
||||
impl ::core::cmp::PartialEq for SuspenseBoundaryProps {
|
||||
#[inline]
|
||||
fn eq(&self, other: &SuspenseBoundaryProps) -> bool {
|
||||
self.fallback == other.fallback && self.children == other.children
|
||||
}
|
||||
}
|
||||
|
||||
/// Suspense Boundaries let you render a fallback UI while a child component is suspended.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # use dioxus::prelude::*;
|
||||
/// # fn Article() -> Element { rsx! { "Article" } }
|
||||
/// fn App() -> Element {
|
||||
/// rsx! {
|
||||
/// SuspenseBoundary {
|
||||
/// fallback: |context: SuspenseContext| rsx! {
|
||||
/// if let Some(placeholder) = context.suspense_placeholder() {
|
||||
/// {placeholder}
|
||||
/// } else {
|
||||
/// "Loading..."
|
||||
/// }
|
||||
/// },
|
||||
/// Article {}
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[allow(non_snake_case)]
|
||||
pub fn SuspenseBoundary(mut __props: SuspenseBoundaryProps) -> Element {
|
||||
unreachable!("SuspenseBoundary should not be called directly")
|
||||
}
|
||||
#[allow(non_snake_case)]
|
||||
#[doc(hidden)]
|
||||
mod SuspenseBoundary_completions {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_camel_case_types)]
|
||||
/// This enum is generated to help autocomplete the braces after the component. It does nothing
|
||||
pub enum Component {
|
||||
SuspenseBoundary {},
|
||||
}
|
||||
}
|
||||
use generational_box::Owner;
|
||||
#[allow(unused)]
|
||||
pub use SuspenseBoundary_completions::Component::SuspenseBoundary;
|
||||
|
||||
/// Suspense has a custom diffing algorithm that diffs the suspended nodes in the background without rendering them
|
||||
impl SuspenseBoundaryProps {
|
||||
/// Try to downcast [`AnyProps`] to [`SuspenseBoundaryProps`]
|
||||
pub(crate) fn downcast_mut_from_props(props: &mut dyn AnyProps) -> Option<&mut Self> {
|
||||
let inner: Option<&mut SuspenseBoundaryPropsWithOwner> = props.props_mut().downcast_mut();
|
||||
inner.map(|inner| &mut inner.inner)
|
||||
}
|
||||
|
||||
/// Try to downcast [`AnyProps`] to [`SuspenseBoundaryProps`]
|
||||
pub(crate) fn downcast_ref_from_props(props: &dyn AnyProps) -> Option<&Self> {
|
||||
let inner: Option<&SuspenseBoundaryPropsWithOwner> = props.props().downcast_ref();
|
||||
inner.map(|inner| &inner.inner)
|
||||
}
|
||||
|
||||
/// Try to extract [`SuspenseBoundaryProps`] from [`ScopeState`]
|
||||
pub fn downcast_from_scope(scope_state: &ScopeState) -> Option<&Self> {
|
||||
let inner: Option<&SuspenseBoundaryPropsWithOwner> =
|
||||
scope_state.props.props().downcast_ref();
|
||||
inner.map(|inner| &inner.inner)
|
||||
}
|
||||
|
||||
/// Check if the suspense boundary is currently holding its children in suspense
|
||||
pub fn suspended(&self) -> bool {
|
||||
self.suspended_nodes.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn create<M: WriteMutations>(
|
||||
mount: MountId,
|
||||
idx: usize,
|
||||
component: &VComponent,
|
||||
parent: Option<ElementRef>,
|
||||
dom: &mut VirtualDom,
|
||||
to: Option<&mut M>,
|
||||
) -> usize {
|
||||
let mut scope_id = ScopeId(dom.mounts[mount.0].mounted_dynamic_nodes[idx]);
|
||||
|
||||
// If the ScopeId is a placeholder, we need to load up a new scope for this vcomponent. If it's already mounted, then we can just use that
|
||||
if scope_id.is_placeholder() {
|
||||
{
|
||||
let suspense_context = SuspenseContext::new();
|
||||
|
||||
dom.runtime.suspense_stack.borrow_mut().push(
|
||||
crate::scope_context::SuspenseLocation::UnderSuspense(suspense_context.clone()),
|
||||
);
|
||||
{
|
||||
let scope_state = dom
|
||||
.new_scope(component.props.duplicate(), component.name)
|
||||
.state();
|
||||
suspense_context.mount(scope_state.id);
|
||||
scope_id = scope_state.id;
|
||||
}
|
||||
dom.runtime.suspense_stack.borrow_mut().pop();
|
||||
}
|
||||
|
||||
// Store the scope id for the next render
|
||||
dom.mounts[mount.0].mounted_dynamic_nodes[idx] = scope_id.0;
|
||||
}
|
||||
|
||||
let scope_state = &mut dom.scopes[scope_id.0];
|
||||
let props = Self::downcast_mut_from_props(&mut *scope_state.props).unwrap();
|
||||
|
||||
let children = RenderReturn {
|
||||
node: props
|
||||
.children
|
||||
.as_ref()
|
||||
.map(|node| node.clone_mounted())
|
||||
.map_err(Clone::clone),
|
||||
};
|
||||
|
||||
// First always render the children in the background. Rendering the children may cause this boundary to suspend
|
||||
dom.runtime.push_scope(scope_id);
|
||||
children.create(dom, parent, None::<&mut M>);
|
||||
dom.runtime.pop_scope();
|
||||
|
||||
// Store the (now mounted) children back into the scope state
|
||||
let scope_state = &mut dom.scopes[scope_id.0];
|
||||
let props = Self::downcast_mut_from_props(&mut *scope_state.props).unwrap();
|
||||
props.children = children.clone().node;
|
||||
|
||||
let scope_state = &mut dom.scopes[scope_id.0];
|
||||
let suspense_context = scope_state
|
||||
.state()
|
||||
.suspense_boundary()
|
||||
.suspense_context()
|
||||
.unwrap()
|
||||
.clone();
|
||||
// If there are suspended futures, render the fallback
|
||||
let nodes_created = if !suspense_context.suspended_futures().is_empty() {
|
||||
let props = Self::downcast_mut_from_props(&mut *scope_state.props).unwrap();
|
||||
props.suspended_nodes = Some(children.into());
|
||||
|
||||
dom.runtime.suspense_stack.borrow_mut().push(
|
||||
crate::scope_context::SuspenseLocation::InSuspensePlaceholder(
|
||||
suspense_context.clone(),
|
||||
),
|
||||
);
|
||||
let suspense_placeholder = props.fallback.call(suspense_context);
|
||||
let node = RenderReturn {
|
||||
node: suspense_placeholder,
|
||||
};
|
||||
let nodes_created = node.create(dom, parent, to);
|
||||
dom.runtime.suspense_stack.borrow_mut().pop();
|
||||
|
||||
let scope_state = &mut dom.scopes[scope_id.0];
|
||||
scope_state.last_rendered_node = Some(node);
|
||||
|
||||
nodes_created
|
||||
} else {
|
||||
// Otherwise just render the children in the real dom
|
||||
dom.runtime.push_scope(scope_id);
|
||||
debug_assert!(children.mount.get().mounted());
|
||||
let nodes_created = children.create(dom, parent, to);
|
||||
dom.runtime.pop_scope();
|
||||
let scope_state = &mut dom.scopes[scope_id.0];
|
||||
scope_state.last_rendered_node = Some(children);
|
||||
let props = Self::downcast_mut_from_props(&mut *dom.scopes[scope_id.0].props).unwrap();
|
||||
props.suspended_nodes = None;
|
||||
nodes_created
|
||||
};
|
||||
|
||||
nodes_created
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Manually rerun the children of this suspense boundary without diffing against the old nodes.
|
||||
///
|
||||
/// This should only be called by dioxus-web after the suspense boundary has been streamed in from the server.
|
||||
pub fn resolve_suspense<M: WriteMutations>(
|
||||
scope_id: ScopeId,
|
||||
dom: &mut VirtualDom,
|
||||
to: &mut M,
|
||||
only_write_templates: impl FnOnce(&mut M),
|
||||
replace_with: usize,
|
||||
) {
|
||||
let _runtime = RuntimeGuard::new(dom.runtime.clone());
|
||||
let Some(scope_state) = dom.scopes.get_mut(scope_id.0) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Reset the suspense context
|
||||
let suspense_context = scope_state
|
||||
.state()
|
||||
.suspense_boundary()
|
||||
.suspense_context()
|
||||
.unwrap()
|
||||
.clone();
|
||||
suspense_context.inner.suspended_tasks.borrow_mut().clear();
|
||||
|
||||
// Get the parent of the suspense boundary to later create children with the right parent
|
||||
let currently_rendered = scope_state.last_rendered_node.as_ref().unwrap().clone();
|
||||
let mount = currently_rendered.mount.get();
|
||||
let parent = dom
|
||||
.mounts
|
||||
.get(mount.0)
|
||||
.expect("suspense placeholder is not mounted")
|
||||
.parent;
|
||||
|
||||
let props = Self::downcast_mut_from_props(&mut *scope_state.props).unwrap();
|
||||
|
||||
// Unmount any children to reset any scopes under this suspense boundary
|
||||
let children = props
|
||||
.children
|
||||
.as_ref()
|
||||
.map(|node| node.clone_mounted())
|
||||
.map_err(Clone::clone);
|
||||
let suspended = props
|
||||
.suspended_nodes
|
||||
.as_ref()
|
||||
.map(|node| node.clone_mounted());
|
||||
if let Some(node) = suspended {
|
||||
node.remove_node(&mut *dom, None::<&mut M>, None);
|
||||
}
|
||||
// Replace the rendered nodes with resolved nodes
|
||||
currently_rendered.remove_node(&mut *dom, Some(to), Some(replace_with));
|
||||
|
||||
// Switch to only writing templates
|
||||
only_write_templates(to);
|
||||
|
||||
let children = RenderReturn { node: children };
|
||||
children.mount.take();
|
||||
|
||||
// First always render the children in the background. Rendering the children may cause this boundary to suspend
|
||||
dom.runtime.push_scope(scope_id);
|
||||
children.create(dom, parent, Some(to));
|
||||
dom.runtime.pop_scope();
|
||||
|
||||
// Store the (now mounted) children back into the scope state
|
||||
let scope_state = &mut dom.scopes[scope_id.0];
|
||||
let props = Self::downcast_mut_from_props(&mut *scope_state.props).unwrap();
|
||||
props.children = children.clone().node;
|
||||
scope_state.last_rendered_node = Some(children);
|
||||
props.suspended_nodes = None;
|
||||
}
|
||||
|
||||
pub(crate) fn diff<M: WriteMutations>(
|
||||
scope_id: ScopeId,
|
||||
dom: &mut VirtualDom,
|
||||
to: Option<&mut M>,
|
||||
) {
|
||||
let scope = &mut dom.scopes[scope_id.0];
|
||||
let myself = Self::downcast_mut_from_props(&mut *scope.props)
|
||||
.unwrap()
|
||||
.clone();
|
||||
|
||||
let last_rendered_node = scope.last_rendered_node.as_ref().unwrap().clone_mounted();
|
||||
|
||||
let Self {
|
||||
fallback,
|
||||
children,
|
||||
suspended_nodes,
|
||||
..
|
||||
} = myself;
|
||||
|
||||
let suspense_context = scope
|
||||
.state()
|
||||
.suspense_boundary()
|
||||
.suspense_context()
|
||||
.unwrap()
|
||||
.clone();
|
||||
let suspended = !suspense_context.suspended_futures().is_empty();
|
||||
match (suspended_nodes, suspended) {
|
||||
// We already have suspended nodes that still need to be suspended
|
||||
// Just diff the normal and suspended nodes
|
||||
(Some(suspended_nodes), true) => {
|
||||
let new_suspended_nodes: VNode = RenderReturn { node: children }.into();
|
||||
|
||||
// Diff the placeholder nodes in the dom
|
||||
dom.runtime.suspense_stack.borrow_mut().push(
|
||||
crate::scope_context::SuspenseLocation::InSuspensePlaceholder(
|
||||
suspense_context.clone(),
|
||||
),
|
||||
);
|
||||
let old_placeholder = last_rendered_node;
|
||||
let new_placeholder = RenderReturn {
|
||||
node: fallback.call(suspense_context),
|
||||
};
|
||||
|
||||
old_placeholder.diff_node(&new_placeholder, dom, to);
|
||||
dom.runtime.suspense_stack.borrow_mut().pop();
|
||||
|
||||
// Set the last rendered node to the placeholder
|
||||
dom.scopes[scope_id.0].last_rendered_node = Some(new_placeholder);
|
||||
|
||||
// Diff the suspended nodes in the background
|
||||
dom.runtime.push_scope(scope_id);
|
||||
suspended_nodes.diff_node(&new_suspended_nodes, dom, None::<&mut M>);
|
||||
dom.runtime.pop_scope();
|
||||
|
||||
let props =
|
||||
Self::downcast_mut_from_props(&mut *dom.scopes[scope_id.0].props).unwrap();
|
||||
props.suspended_nodes = Some(new_suspended_nodes);
|
||||
}
|
||||
// We have no suspended nodes, and we are not suspended. Just diff the children like normal
|
||||
(None, false) => {
|
||||
let old_children = last_rendered_node;
|
||||
let new_children = RenderReturn { node: children };
|
||||
|
||||
dom.runtime.push_scope(scope_id);
|
||||
old_children.diff_node(&new_children, dom, to);
|
||||
dom.runtime.pop_scope();
|
||||
|
||||
// Set the last rendered node to the new children
|
||||
dom.scopes[scope_id.0].last_rendered_node = Some(new_children);
|
||||
}
|
||||
// We have no suspended nodes, but we just became suspended. Move the children to the background
|
||||
(None, true) => {
|
||||
let old_children = last_rendered_node;
|
||||
let new_children: VNode = RenderReturn { node: children }.into();
|
||||
|
||||
let new_placeholder = RenderReturn {
|
||||
node: fallback.call(suspense_context.clone()),
|
||||
};
|
||||
|
||||
// Move the children to the background
|
||||
let mount = old_children.mount.get();
|
||||
let mount = dom.mounts.get(mount.0).expect("mount should exist");
|
||||
let parent = mount.parent;
|
||||
dom.runtime.push_scope(scope_id);
|
||||
dom.runtime.suspense_stack.borrow_mut().push(
|
||||
crate::scope_context::SuspenseLocation::InSuspensePlaceholder(suspense_context),
|
||||
);
|
||||
old_children.move_node_to_background(
|
||||
std::slice::from_ref(&*new_placeholder),
|
||||
parent,
|
||||
dom,
|
||||
to,
|
||||
);
|
||||
dom.runtime.suspense_stack.borrow_mut().pop();
|
||||
|
||||
// Then diff the new children in the background
|
||||
old_children.diff_node(&new_children, dom, None::<&mut M>);
|
||||
dom.runtime.pop_scope();
|
||||
|
||||
// Set the last rendered node to the new suspense placeholder
|
||||
dom.scopes[scope_id.0].last_rendered_node = Some(new_placeholder);
|
||||
|
||||
let props =
|
||||
Self::downcast_mut_from_props(&mut *dom.scopes[scope_id.0].props).unwrap();
|
||||
props.suspended_nodes = Some(new_children);
|
||||
} // We have suspended nodes, but we just got out of suspense. Move the suspended nodes to the foreground
|
||||
(Some(old_suspended_nodes), false) => {
|
||||
let old_placeholder = last_rendered_node;
|
||||
let new_children = RenderReturn { node: children };
|
||||
|
||||
// First diff the two children nodes in the background
|
||||
dom.runtime.push_scope(scope_id);
|
||||
old_suspended_nodes.diff_node(&new_children, dom, None::<&mut M>);
|
||||
|
||||
// Then replace the placeholder with the new children
|
||||
let mount = old_placeholder.mount.get();
|
||||
let mount = dom.mounts.get(mount.0).expect("mount should exist");
|
||||
let parent = mount.parent;
|
||||
old_placeholder.replace(std::slice::from_ref(&*new_children), parent, dom, to);
|
||||
dom.runtime.pop_scope();
|
||||
|
||||
// Set the last rendered node to the new children
|
||||
dom.scopes[scope_id.0].last_rendered_node = Some(new_children);
|
||||
|
||||
let props =
|
||||
Self::downcast_mut_from_props(&mut *dom.scopes[scope_id.0].props).unwrap();
|
||||
props.suspended_nodes = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove_suspended_nodes<M: WriteMutations>(
|
||||
&mut self,
|
||||
dom: &mut VirtualDom,
|
||||
destroy_component_state: bool,
|
||||
) {
|
||||
// Remove the suspended nodes
|
||||
if let Some(node) = self.suspended_nodes.take() {
|
||||
node.remove_node_inner(dom, None::<&mut M>, destroy_component_state, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Suspense allows you to render a placeholder while nodes are waiting for data in the background
|
||||
//!
|
||||
//! During suspense on the server:
|
||||
//! - Rebuild once
|
||||
//! - Send page with loading placeholders down to the client
|
||||
//! - loop
|
||||
//! - Poll (only) suspended futures
|
||||
//! - If a scope is marked as dirty and that scope is a suspense boundary, under a suspended boundary, or the suspense placeholder, rerun the scope
|
||||
//! - If it is a different scope, ignore it and warn the user
|
||||
//! - Rerender the scope on the server and send down the nodes under a hidden div with serialized data
|
||||
//!
|
||||
//! During suspense on the web:
|
||||
//! - Rebuild once without running server futures
|
||||
//! - Rehydrate the placeholders that were initially sent down. At this point, no suspense nodes are resolved so the client and server pages should be the same
|
||||
//! - loop
|
||||
//! - Wait for work or suspense data
|
||||
//! - If suspense data comes in
|
||||
//! - replace the suspense placeholder
|
||||
//! - get any data associated with the suspense placeholder and rebuild nodes under the suspense that was resolved
|
||||
//! - rehydrate the suspense placeholders that were at that node
|
||||
//! - If work comes in
|
||||
//! - Just do the work; this may remove suspense placeholders that the server hasn't yet resolved. If we see new data come in from the server about that node, ignore it
|
||||
//!
|
||||
//! Generally suspense placeholders should not be stateful because they are driven from the server. If they are stateful and the client renders something different, hydration will fail.
|
||||
|
||||
mod component;
|
||||
pub use component::*;
|
||||
|
||||
use crate::innerlude::*;
|
||||
use std::{
|
||||
cell::{Cell, Ref, RefCell},
|
||||
fmt::Debug,
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
/// A task that has been suspended which may have an optional loading placeholder
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct SuspendedFuture {
|
||||
origin: ScopeId,
|
||||
task: Task,
|
||||
pub(crate) placeholder: VNode,
|
||||
}
|
||||
|
||||
impl SuspendedFuture {
|
||||
/// Create a new suspended future
|
||||
pub fn new(task: Task) -> Self {
|
||||
Self {
|
||||
task,
|
||||
origin: current_scope_id().expect("to be in a dioxus runtime"),
|
||||
placeholder: VNode::placeholder(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a placeholder to display while the future is suspended
|
||||
pub fn suspense_placeholder(&self) -> Option<VNode> {
|
||||
if self.placeholder == VNode::placeholder() {
|
||||
None
|
||||
} else {
|
||||
Some(self.placeholder.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a new placeholder the SuspenseBoundary may use to display while the future is suspended
|
||||
pub fn with_placeholder(mut self, placeholder: VNode) -> Self {
|
||||
self.placeholder = placeholder;
|
||||
self
|
||||
}
|
||||
|
||||
/// Get the task that was suspended
|
||||
pub fn task(&self) -> Task {
|
||||
self.task
|
||||
}
|
||||
|
||||
/// Clone the future while retaining the mounted information of the future
|
||||
pub(crate) fn clone_mounted(&self) -> Self {
|
||||
Self {
|
||||
task: self.task,
|
||||
origin: self.origin,
|
||||
placeholder: self.placeholder.clone_mounted(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A context with information about suspended components
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SuspenseContext {
|
||||
inner: Rc<SuspenseBoundaryInner>,
|
||||
}
|
||||
|
||||
impl PartialEq for SuspenseContext {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Rc::ptr_eq(&self.inner, &other.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl SuspenseContext {
|
||||
/// Create a new suspense boundary in a specific scope
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
inner: Rc::new(SuspenseBoundaryInner {
|
||||
suspended_tasks: RefCell::new(vec![]),
|
||||
id: Cell::new(ScopeId::ROOT),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mount the context in a specific scope
|
||||
pub(crate) fn mount(&self, scope: ScopeId) {
|
||||
self.inner.id.set(scope);
|
||||
}
|
||||
|
||||
/// Check if there are any suspended tasks
|
||||
pub fn suspended(&self) -> bool {
|
||||
!self.inner.suspended_tasks.borrow().is_empty()
|
||||
}
|
||||
|
||||
/// Add a suspended task
|
||||
pub(crate) fn add_suspended_task(&self, task: SuspendedFuture) {
|
||||
self.inner.suspended_tasks.borrow_mut().push(task);
|
||||
self.inner.id.get().needs_update();
|
||||
}
|
||||
|
||||
/// Remove a suspended task
|
||||
pub(crate) fn remove_suspended_task(&self, task: Task) {
|
||||
self.inner
|
||||
.suspended_tasks
|
||||
.borrow_mut()
|
||||
.retain(|t| t.task != task);
|
||||
self.inner.id.get().needs_update();
|
||||
}
|
||||
|
||||
/// Get all suspended tasks
|
||||
pub fn suspended_futures(&self) -> Ref<[SuspendedFuture]> {
|
||||
Ref::map(self.inner.suspended_tasks.borrow(), |tasks| {
|
||||
tasks.as_slice()
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the first suspended task with a loading placeholder
|
||||
pub fn suspense_placeholder(&self) -> Option<Element> {
|
||||
self.inner
|
||||
.suspended_tasks
|
||||
.borrow()
|
||||
.iter()
|
||||
.find_map(|task| task.suspense_placeholder())
|
||||
.map(std::result::Result::Ok)
|
||||
}
|
||||
}
|
||||
|
||||
/// A boundary that will capture any errors from child components
|
||||
#[derive(Debug)]
|
||||
pub struct SuspenseBoundaryInner {
|
||||
suspended_tasks: RefCell<Vec<SuspendedFuture>>,
|
||||
id: Cell<ScopeId>,
|
||||
}
|
||||
|
||||
/// Provides context methods to [`Result<T, RenderError>`] to show loading indicators for suspended results
|
||||
///
|
||||
/// This trait is sealed and cannot be implemented outside of dioxus-core
|
||||
pub trait SuspenseExtension<T>: private::Sealed {
|
||||
/// Add a loading indicator if the result is suspended
|
||||
fn with_loading_placeholder(
|
||||
self,
|
||||
display_placeholder: impl FnOnce() -> Element,
|
||||
) -> std::result::Result<T, RenderError>;
|
||||
}
|
||||
|
||||
impl<T> SuspenseExtension<T> for std::result::Result<T, RenderError> {
|
||||
fn with_loading_placeholder(
|
||||
self,
|
||||
display_placeholder: impl FnOnce() -> Element,
|
||||
) -> std::result::Result<T, RenderError> {
|
||||
if let Err(RenderError::Suspended(suspense)) = self {
|
||||
Err(RenderError::Suspended(suspense.with_placeholder(
|
||||
display_placeholder().unwrap_or_default(),
|
||||
)))
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod private {
|
||||
use super::*;
|
||||
|
||||
pub trait Sealed {}
|
||||
|
||||
impl<T> Sealed for std::result::Result<T, RenderError> {}
|
||||
}
|
||||
+90
-33
@@ -1,9 +1,12 @@
|
||||
use crate::innerlude::Effect;
|
||||
use crate::innerlude::ScopeOrder;
|
||||
use crate::innerlude::{remove_future, spawn, Runtime};
|
||||
use crate::scope_context::ScopeStatus;
|
||||
use crate::scope_context::SuspenseLocation;
|
||||
use crate::ScopeId;
|
||||
use futures_util::task::ArcWake;
|
||||
use slotmap::DefaultKey;
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::Arc;
|
||||
use std::task::Waker;
|
||||
use std::{cell::Cell, future::Future};
|
||||
@@ -15,9 +18,21 @@ use std::{pin::Pin, task::Poll};
|
||||
/// `Task` is a unique identifier for a task that has been spawned onto the runtime. It can be used to cancel the task
|
||||
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct Task(pub(crate) slotmap::DefaultKey);
|
||||
pub struct Task {
|
||||
pub(crate) id: slotmap::DefaultKey,
|
||||
// We add a raw pointer to make this !Send + !Sync
|
||||
unsend: PhantomData<*const ()>,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
/// Create a task from a raw id
|
||||
pub(crate) const fn from_id(id: slotmap::DefaultKey) -> Self {
|
||||
Self {
|
||||
id,
|
||||
unsend: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a new future on the same thread as the rest of the VirtualDom.
|
||||
///
|
||||
/// This future will not contribute to suspense resolving, so you should primarily use this for reacting to changes
|
||||
@@ -51,7 +66,7 @@ impl Task {
|
||||
/// Check if the task is paused.
|
||||
pub fn paused(&self) -> bool {
|
||||
Runtime::with(|rt| {
|
||||
if let Some(task) = rt.tasks.borrow().get(self.0) {
|
||||
if let Some(task) = rt.tasks.borrow().get(self.id) {
|
||||
!task.active.get()
|
||||
} else {
|
||||
false
|
||||
@@ -62,7 +77,11 @@ impl Task {
|
||||
|
||||
/// Wake the task.
|
||||
pub fn wake(&self) {
|
||||
Runtime::with(|rt| _ = rt.sender.unbounded_send(SchedulerMsg::TaskNotified(*self)));
|
||||
Runtime::with(|rt| {
|
||||
_ = rt
|
||||
.sender
|
||||
.unbounded_send(SchedulerMsg::TaskNotified(self.id))
|
||||
});
|
||||
}
|
||||
|
||||
/// Poll the task immediately.
|
||||
@@ -73,10 +92,12 @@ impl Task {
|
||||
/// Set the task as active or paused.
|
||||
pub fn set_active(&self, active: bool) {
|
||||
Runtime::with(|rt| {
|
||||
if let Some(task) = rt.tasks.borrow().get(self.0) {
|
||||
if let Some(task) = rt.tasks.borrow().get(self.id) {
|
||||
let was_active = task.active.replace(active);
|
||||
if !was_active && active {
|
||||
_ = rt.sender.unbounded_send(SchedulerMsg::TaskNotified(*self));
|
||||
_ = rt
|
||||
.sender
|
||||
.unbounded_send(SchedulerMsg::TaskNotified(self.id));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -140,10 +161,10 @@ impl Runtime {
|
||||
let (task, task_id) = {
|
||||
let mut tasks = self.tasks.borrow_mut();
|
||||
|
||||
let mut task_id = Task(DefaultKey::default());
|
||||
let mut task_id = Task::from_id(DefaultKey::default());
|
||||
let mut local_task = None;
|
||||
tasks.insert_with_key(|key| {
|
||||
task_id = Task(key);
|
||||
task_id = Task::from_id(key);
|
||||
|
||||
let new_task = Rc::new(LocalTask {
|
||||
scope,
|
||||
@@ -151,10 +172,10 @@ impl Runtime {
|
||||
parent: self.current_task(),
|
||||
task: RefCell::new(Box::pin(task)),
|
||||
waker: futures_util::task::waker(Arc::new(LocalTaskHandle {
|
||||
id: task_id,
|
||||
id: task_id.id,
|
||||
tx: self.sender.clone(),
|
||||
})),
|
||||
ty: Cell::new(ty),
|
||||
ty: RefCell::new(ty),
|
||||
});
|
||||
|
||||
local_task = Some(new_task.clone());
|
||||
@@ -170,7 +191,7 @@ impl Runtime {
|
||||
debug_assert!(task.task.try_borrow_mut().is_ok());
|
||||
|
||||
self.sender
|
||||
.unbounded_send(SchedulerMsg::TaskNotified(task_id))
|
||||
.unbounded_send(SchedulerMsg::TaskNotified(task_id.id))
|
||||
.expect("Scheduler should exist");
|
||||
|
||||
task_id
|
||||
@@ -178,11 +199,32 @@ impl Runtime {
|
||||
|
||||
/// Queue an effect to run after the next render
|
||||
pub(crate) fn queue_effect(&self, id: ScopeId, f: impl FnOnce() + 'static) {
|
||||
let effect = Box::new(f) as Box<dyn FnOnce() + 'static>;
|
||||
let Some(scope) = self.get_state(id) else {
|
||||
return;
|
||||
};
|
||||
let mut status = scope.status.borrow_mut();
|
||||
match &mut *status {
|
||||
ScopeStatus::Mounted => {
|
||||
self.queue_effect_on_mounted_scope(id, effect);
|
||||
}
|
||||
ScopeStatus::Unmounted { effects_queued, .. } => {
|
||||
effects_queued.push(effect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue an effect to run after the next render without checking if the scope is mounted
|
||||
pub(crate) fn queue_effect_on_mounted_scope(
|
||||
&self,
|
||||
id: ScopeId,
|
||||
f: Box<dyn FnOnce() + 'static>,
|
||||
) {
|
||||
// Add the effect to the queue of effects to run after the next render for the given scope
|
||||
let mut effects = self.pending_effects.borrow_mut();
|
||||
let scope_order = ScopeOrder::new(id.height(), id);
|
||||
match effects.get(&scope_order) {
|
||||
Some(effects) => effects.push_back(Box::new(f)),
|
||||
Some(effects) => effects.push_back(f),
|
||||
None => {
|
||||
effects.insert(Effect::new(scope_order, f));
|
||||
}
|
||||
@@ -196,17 +238,17 @@ impl Runtime {
|
||||
|
||||
/// Get the parent task of the given task, if it exists
|
||||
pub fn parent_task(&self, task: Task) -> Option<Task> {
|
||||
self.tasks.borrow().get(task.0)?.parent
|
||||
self.tasks.borrow().get(task.id)?.parent
|
||||
}
|
||||
|
||||
pub(crate) fn task_scope(&self, task: Task) -> Option<ScopeId> {
|
||||
self.tasks.borrow().get(task.0).map(|t| t.scope)
|
||||
self.tasks.borrow().get(task.id).map(|t| t.scope)
|
||||
}
|
||||
|
||||
pub(crate) fn handle_task_wakeup(&self, id: Task) -> Poll<()> {
|
||||
debug_assert!(Runtime::current().is_some(), "Must be in a dioxus runtime");
|
||||
|
||||
let task = self.tasks.borrow().get(id.0).cloned();
|
||||
let task = self.tasks.borrow().get(id.id).cloned();
|
||||
|
||||
// The task was removed from the scheduler, so we can just ignore it
|
||||
let Some(task) = task else {
|
||||
@@ -221,7 +263,7 @@ impl Runtime {
|
||||
let mut cx = std::task::Context::from_waker(&task.waker);
|
||||
|
||||
// update the scope stack
|
||||
self.scope_stack.borrow_mut().push(task.scope);
|
||||
self.push_scope(task.scope);
|
||||
self.rendering.set(false);
|
||||
self.current_task.set(Some(id));
|
||||
|
||||
@@ -239,7 +281,7 @@ impl Runtime {
|
||||
}
|
||||
|
||||
// Remove the scope from the stack
|
||||
self.scope_stack.borrow_mut().pop();
|
||||
self.pop_scope();
|
||||
self.rendering.set(true);
|
||||
self.current_task.set(None);
|
||||
|
||||
@@ -250,20 +292,35 @@ impl Runtime {
|
||||
///
|
||||
/// This does not abort the task, so you'll want to wrap it in an abort handle if that's important to you
|
||||
pub(crate) fn remove_task(&self, id: Task) -> Option<Rc<LocalTask>> {
|
||||
let task = self.tasks.borrow_mut().remove(id.0);
|
||||
// Remove the task from the task list
|
||||
let task = self.tasks.borrow_mut().remove(id.id);
|
||||
|
||||
if let Some(task) = &task {
|
||||
if task.suspended() {
|
||||
// Remove the task from suspense
|
||||
if let TaskType::Suspended { boundary } = &*task.ty.borrow() {
|
||||
self.suspended_tasks.set(self.suspended_tasks.get() - 1);
|
||||
if let SuspenseLocation::UnderSuspense(boundary) = boundary {
|
||||
boundary.remove_suspended_task(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the task from pending work. We could reuse the slot before the task is polled and discarded so we need to remove it from pending work instead of filtering out dead tasks when we try to poll them
|
||||
if let Some(scope) = self.get_state(task.scope) {
|
||||
let order = ScopeOrder::new(scope.height(), scope.id);
|
||||
if let Some(dirty_tasks) = self.dirty_tasks.borrow_mut().get(&order) {
|
||||
dirty_tasks.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task
|
||||
}
|
||||
|
||||
/// Check if a task should be run during suspense
|
||||
pub(crate) fn task_runs_during_suspense(&self, task: Task) -> bool {
|
||||
let borrow = self.tasks.borrow();
|
||||
let task: Option<&LocalTask> = borrow.get(task.0).map(|t| &**t);
|
||||
matches!(task, Some(LocalTask { ty, .. }) if ty.get().runs_during_suspense())
|
||||
let task: Option<&LocalTask> = borrow.get(task.id).map(|t| &**t);
|
||||
matches!(task, Some(LocalTask { ty, .. }) if ty.borrow().runs_during_suspense())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,49 +330,49 @@ pub(crate) struct LocalTask {
|
||||
parent: Option<Task>,
|
||||
task: RefCell<Pin<Box<dyn Future<Output = ()> + 'static>>>,
|
||||
waker: Waker,
|
||||
ty: Cell<TaskType>,
|
||||
ty: RefCell<TaskType>,
|
||||
active: Cell<bool>,
|
||||
}
|
||||
|
||||
impl LocalTask {
|
||||
pub(crate) fn suspend(&self) {
|
||||
self.ty.set(TaskType::Suspended);
|
||||
}
|
||||
|
||||
pub(crate) fn suspended(&self) -> bool {
|
||||
matches!(self.ty.get(), TaskType::Suspended)
|
||||
/// Suspend the task, returns true if the task was already suspended
|
||||
pub(crate) fn suspend(&self, boundary: SuspenseLocation) -> bool {
|
||||
// Make this a suspended task so it runs during suspense
|
||||
let old_type = self.ty.replace(TaskType::Suspended { boundary });
|
||||
matches!(old_type, TaskType::Suspended { .. })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone)]
|
||||
enum TaskType {
|
||||
ClientOnly,
|
||||
Suspended,
|
||||
Suspended { boundary: SuspenseLocation },
|
||||
Isomorphic,
|
||||
}
|
||||
|
||||
impl TaskType {
|
||||
fn runs_during_suspense(self) -> bool {
|
||||
matches!(self, TaskType::Isomorphic | TaskType::Suspended)
|
||||
fn runs_during_suspense(&self) -> bool {
|
||||
matches!(self, TaskType::Isomorphic | TaskType::Suspended { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of message that can be sent to the scheduler.
|
||||
///
|
||||
/// These messages control how the scheduler will process updates to the UI.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum SchedulerMsg {
|
||||
/// Immediate updates from Components that mark them as dirty
|
||||
Immediate(ScopeId),
|
||||
|
||||
/// A task has woken and needs to be progressed
|
||||
TaskNotified(Task),
|
||||
TaskNotified(slotmap::DefaultKey),
|
||||
|
||||
/// An effect has been queued to run after the next render
|
||||
EffectQueued,
|
||||
}
|
||||
|
||||
struct LocalTaskHandle {
|
||||
id: Task,
|
||||
id: slotmap::DefaultKey,
|
||||
tx: futures_channel::mpsc::UnboundedSender<SchedulerMsg>,
|
||||
}
|
||||
|
||||
|
||||
+213
-126
@@ -2,22 +2,22 @@
|
||||
//!
|
||||
//! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
|
||||
|
||||
use crate::Task;
|
||||
use crate::innerlude::{SuspenseBoundaryProps, Work};
|
||||
use crate::properties::RootProps;
|
||||
use crate::root_wrapper::RootScopeWrapper;
|
||||
use crate::{
|
||||
any_props::AnyProps,
|
||||
arena::ElementId,
|
||||
innerlude::{
|
||||
DirtyTasks, ElementRef, ErrorBoundary, NoOpMutations, SchedulerMsg, ScopeOrder, ScopeState,
|
||||
VNodeMount, VProps, WriteMutations,
|
||||
ElementRef, NoOpMutations, SchedulerMsg, ScopeOrder, ScopeState, VNodeMount, VProps,
|
||||
WriteMutations,
|
||||
},
|
||||
nodes::RenderReturn,
|
||||
nodes::{Template, TemplateId},
|
||||
runtime::{Runtime, RuntimeGuard},
|
||||
scopes::ScopeId,
|
||||
AttributeValue, ComponentFunction, Element, Event, Mutations, VNode,
|
||||
AttributeValue, ComponentFunction, Element, Event, Mutations,
|
||||
};
|
||||
use crate::{Task, VComponent};
|
||||
use futures_util::StreamExt;
|
||||
use rustc_hash::FxHashMap;
|
||||
use slab::Slab;
|
||||
use std::collections::BTreeSet;
|
||||
use std::{any::Any, rc::Rc};
|
||||
@@ -206,18 +206,25 @@ pub struct VirtualDom {
|
||||
pub(crate) scopes: Slab<ScopeState>,
|
||||
|
||||
pub(crate) dirty_scopes: BTreeSet<ScopeOrder>,
|
||||
pub(crate) dirty_tasks: BTreeSet<DirtyTasks>,
|
||||
|
||||
// Maps a template path to a map of byte indexes to templates
|
||||
pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template>>,
|
||||
// if hot reload is enabled, we need to keep track of template overrides
|
||||
#[cfg(debug_assertions)]
|
||||
pub(crate) templates: rustc_hash::FxHashMap<TemplateId, rustc_hash::FxHashMap<usize, Template>>,
|
||||
// Otherwise, we just need to keep track of what templates we have registered
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub(crate) templates: rustc_hash::FxHashSet<TemplateId>,
|
||||
|
||||
// Templates changes that are queued for the next render
|
||||
pub(crate) queued_templates: Vec<Template>,
|
||||
|
||||
// The element ids that are used in the renderer
|
||||
// These mark a specific place in a whole rsx block
|
||||
pub(crate) elements: Slab<Option<ElementRef>>,
|
||||
|
||||
// Once nodes are mounted, the information about where they are mounted is stored here
|
||||
// We need to store this information on the virtual dom so that we know what nodes are mounted where when we bubble events
|
||||
// Each mount is associated with a whole rsx block. [`VirtualDom::elements`] link to a specific node in the block
|
||||
pub(crate) mounts: Slab<VNodeMount>,
|
||||
|
||||
pub(crate) runtime: Rc<Runtime>,
|
||||
@@ -297,7 +304,13 @@ impl VirtualDom {
|
||||
root: impl ComponentFunction<P, M>,
|
||||
root_props: P,
|
||||
) -> Self {
|
||||
Self::new_with_component(VProps::new(root, |_, _| true, root_props, "root"))
|
||||
let render_fn = root.id();
|
||||
let props = VProps::new(root, |_, _| true, root_props, "Root");
|
||||
Self::new_with_component(VComponent {
|
||||
name: "root",
|
||||
render_fn,
|
||||
props: Box::new(props),
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a new virtualdom and build it immediately
|
||||
@@ -309,7 +322,7 @@ impl VirtualDom {
|
||||
|
||||
/// Create a new VirtualDom from something that implements [`AnyProps`]
|
||||
#[instrument(skip(root), level = "trace", name = "VirtualDom::new")]
|
||||
pub(crate) fn new_with_component(root: impl AnyProps + 'static) -> Self {
|
||||
pub(crate) fn new_with_component(root: VComponent) -> Self {
|
||||
let (tx, rx) = futures_channel::mpsc::unbounded();
|
||||
|
||||
let mut dom = Self {
|
||||
@@ -317,18 +330,19 @@ impl VirtualDom {
|
||||
runtime: Runtime::new(tx),
|
||||
scopes: Default::default(),
|
||||
dirty_scopes: Default::default(),
|
||||
dirty_tasks: Default::default(),
|
||||
templates: Default::default(),
|
||||
queued_templates: Default::default(),
|
||||
elements: Default::default(),
|
||||
mounts: Default::default(),
|
||||
};
|
||||
|
||||
let root = dom.new_scope(Box::new(root), "app");
|
||||
|
||||
// Unlike react, we provide a default error boundary that just renders the error as a string
|
||||
root.state()
|
||||
.provide_context(Rc::new(ErrorBoundary::new_in_scope(ScopeId::ROOT)));
|
||||
let root = VProps::new(
|
||||
RootScopeWrapper,
|
||||
|_, _| true,
|
||||
RootProps(root),
|
||||
"RootWrapper",
|
||||
);
|
||||
dom.new_scope(Box::new(root), "app");
|
||||
|
||||
// the root element is always given element ID 0 since it's the container for the entire tree
|
||||
dom.elements.insert(None);
|
||||
@@ -404,7 +418,7 @@ impl VirtualDom {
|
||||
tracing::Level::TRACE,
|
||||
"Marking task {:?} (spawned in {:?}) as dirty",
|
||||
task,
|
||||
scope.id
|
||||
scope.id,
|
||||
);
|
||||
|
||||
let order = ScopeOrder::new(scope.height(), scope.id);
|
||||
@@ -485,7 +499,7 @@ impl VirtualDom {
|
||||
SchedulerMsg::TaskNotified(id) => {
|
||||
// Instead of running the task immediately, we insert it into the runtime's task queue.
|
||||
// The task may be marked dirty at the same time as the scope that owns the task is dropped.
|
||||
self.mark_task_dirty(id);
|
||||
self.mark_task_dirty(Task::from_id(id));
|
||||
}
|
||||
SchedulerMsg::EffectQueued => {}
|
||||
};
|
||||
@@ -497,7 +511,7 @@ impl VirtualDom {
|
||||
while let Ok(Some(msg)) = self.rx.try_next() {
|
||||
match msg {
|
||||
SchedulerMsg::Immediate(id) => self.mark_dirty(id),
|
||||
SchedulerMsg::TaskNotified(task) => self.mark_task_dirty(task),
|
||||
SchedulerMsg::TaskNotified(task) => self.mark_task_dirty(Task::from_id(task)),
|
||||
SchedulerMsg::EffectQueued => {}
|
||||
}
|
||||
}
|
||||
@@ -524,24 +538,18 @@ impl VirtualDom {
|
||||
|
||||
// Keep polling tasks until there are no more effects or tasks to run
|
||||
// Or until we have no more dirty scopes
|
||||
while !self.dirty_tasks.is_empty() || !self.runtime.pending_effects.borrow().is_empty() {
|
||||
while !self.runtime.dirty_tasks.borrow().is_empty()
|
||||
|| !self.runtime.pending_effects.borrow().is_empty()
|
||||
{
|
||||
// Next, run any queued tasks
|
||||
// We choose not to poll the deadline since we complete pretty quickly anyways
|
||||
while let Some(task) = self.pop_task() {
|
||||
// Then poll any tasks that might be pending
|
||||
let mut tasks = task.tasks_queued.into_inner();
|
||||
while let Some(task) = tasks.pop_front() {
|
||||
let _ = self.runtime.handle_task_wakeup(task);
|
||||
let _ = self.runtime.handle_task_wakeup(task);
|
||||
|
||||
// Running that task, may mark a scope higher up as dirty. If it does, return from the function early
|
||||
self.queue_events();
|
||||
if self.has_dirty_scopes() {
|
||||
// requeue any remaining tasks
|
||||
for task in tasks {
|
||||
self.mark_task_dirty(task);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Running that task, may mark a scope higher up as dirty. If it does, return from the function early
|
||||
self.queue_events();
|
||||
if self.has_dirty_scopes() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -565,41 +573,45 @@ impl VirtualDom {
|
||||
/// This will only replace the parent template, not any nested templates.
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::replace_template")]
|
||||
pub fn replace_template(&mut self, template: Template) {
|
||||
self.register_template_first_byte_index(template);
|
||||
// we only replace templates if hot reloading is enabled
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
self.register_template_first_byte_index(template);
|
||||
|
||||
// iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
|
||||
let mut dirty = Vec::new();
|
||||
for (id, scope) in self.scopes.iter() {
|
||||
// Recurse into the dynamic nodes of the existing mounted node to see if the template is alive in the tree
|
||||
fn check_node_for_templates(node: &VNode, template: Template) -> bool {
|
||||
let this_template_name = node.template.get().name.rsplit_once(':').unwrap().0;
|
||||
// iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
|
||||
let mut dirty = Vec::new();
|
||||
for (id, scope) in self.scopes.iter() {
|
||||
// Recurse into the dynamic nodes of the existing mounted node to see if the template is alive in the tree
|
||||
fn check_node_for_templates(node: &crate::VNode, template: Template) -> bool {
|
||||
let this_template_name = node.template.get().name.rsplit_once(':').unwrap().0;
|
||||
|
||||
if this_template_name == template.name.rsplit_once(':').unwrap().0 {
|
||||
return true;
|
||||
}
|
||||
if this_template_name == template.name.rsplit_once(':').unwrap().0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
for dynamic in node.dynamic_nodes.iter() {
|
||||
if let crate::DynamicNode::Fragment(nodes) = dynamic {
|
||||
for node in nodes {
|
||||
if check_node_for_templates(node, template) {
|
||||
return true;
|
||||
for dynamic in node.dynamic_nodes.iter() {
|
||||
if let crate::DynamicNode::Fragment(nodes) = dynamic {
|
||||
for node in nodes {
|
||||
if check_node_for_templates(node, template) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
|
||||
if check_node_for_templates(sync, template) {
|
||||
dirty.push(ScopeId(id));
|
||||
if let Some(sync) = scope.try_root_node() {
|
||||
if check_node_for_templates(sync, template) {
|
||||
dirty.push(ScopeId(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for dirty in dirty {
|
||||
self.mark_dirty(dirty);
|
||||
for dirty in dirty {
|
||||
self.mark_dirty(dirty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -647,8 +659,10 @@ impl VirtualDom {
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
let new_nodes = self.run_scope(ScopeId::ROOT);
|
||||
|
||||
self.scopes[ScopeId::ROOT.0].last_rendered_node = Some(new_nodes.clone());
|
||||
|
||||
// Rebuilding implies we append the created elements to the root
|
||||
let m = self.create_scope(to, ScopeId::ROOT, new_nodes, None);
|
||||
let m = self.create_scope(Some(to), ScopeId::ROOT, new_nodes, None);
|
||||
|
||||
to.append_children(ElementId(0), m);
|
||||
}
|
||||
@@ -666,22 +680,17 @@ impl VirtualDom {
|
||||
|
||||
// Next, diff any dirty scopes
|
||||
// We choose not to poll the deadline since we complete pretty quickly anyways
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
while let Some(work) = self.pop_work() {
|
||||
{
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
|
||||
// Then, poll any tasks that might be pending in the scope
|
||||
for task in work.tasks {
|
||||
let _ = self.runtime.handle_task_wakeup(task);
|
||||
match work {
|
||||
Work::PollTask(task) => {
|
||||
_ = self.runtime.handle_task_wakeup(task);
|
||||
// Make sure we process any new events
|
||||
self.queue_events();
|
||||
}
|
||||
|
||||
self.queue_events();
|
||||
|
||||
// If the scope is dirty, run the scope and get the mutations
|
||||
if work.rerun_scope {
|
||||
let new_nodes = self.run_scope(work.scope.id);
|
||||
|
||||
self.diff_scope(to, work.scope.id, new_nodes);
|
||||
Work::RerunScope(scope) => {
|
||||
// If the scope is dirty, run the scope and get the mutations
|
||||
self.run_and_diff_scope(Some(to), scope.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -705,70 +714,127 @@ impl VirtualDom {
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::wait_for_suspense")]
|
||||
pub async fn wait_for_suspense(&mut self) {
|
||||
loop {
|
||||
if self.runtime.suspended_tasks.get() == 0 {
|
||||
if !self.suspended_tasks_remaining() {
|
||||
break;
|
||||
}
|
||||
|
||||
// Wait for a work to be ready (IE new suspense leaves to pop up)
|
||||
'wait_for_work: loop {
|
||||
// Process all events - Scopes are marked dirty, etc
|
||||
// Sometimes when wakers fire we get a slew of updates at once, so its important that we drain this completely
|
||||
self.queue_events();
|
||||
self.wait_for_suspense_work().await;
|
||||
|
||||
// Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures
|
||||
if self.has_dirty_scopes() {
|
||||
break;
|
||||
}
|
||||
self.render_suspense_immediate().await;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// Make sure we set the runtime since we're running user code
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
// Next, run any queued tasks
|
||||
// We choose not to poll the deadline since we complete pretty quickly anyways
|
||||
while let Some(task) = self.pop_task() {
|
||||
// Then poll any tasks that might be pending
|
||||
let mut tasks = task.tasks_queued.into_inner();
|
||||
while let Some(task) = tasks.pop_front() {
|
||||
if self.runtime.task_runs_during_suspense(task) {
|
||||
let _ = self.runtime.handle_task_wakeup(task);
|
||||
// Running that task, may mark a scope higher up as dirty. If it does, return from the function early
|
||||
self.queue_events();
|
||||
if self.has_dirty_scopes() {
|
||||
// requeue any remaining tasks
|
||||
for task in tasks {
|
||||
self.mark_task_dirty(task);
|
||||
}
|
||||
break 'wait_for_work;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Check if there are any suspended tasks remaining
|
||||
pub fn suspended_tasks_remaining(&self) -> bool {
|
||||
self.runtime.suspended_tasks.get() > 0
|
||||
}
|
||||
|
||||
self.wait_for_event().await;
|
||||
/// Wait for the scheduler to have any work that should be run during suspense.
|
||||
pub async fn wait_for_suspense_work(&mut self) {
|
||||
// Wait for a work to be ready (IE new suspense leaves to pop up)
|
||||
loop {
|
||||
// Process all events - Scopes are marked dirty, etc
|
||||
// Sometimes when wakers fire we get a slew of updates at once, so its important that we drain this completely
|
||||
self.queue_events();
|
||||
|
||||
// Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures
|
||||
if self.has_dirty_scopes() {
|
||||
break;
|
||||
}
|
||||
|
||||
// Render whatever work needs to be rendered, unlocking new futures and suspense leaves
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
while let Some(work) = self.pop_work() {
|
||||
// Then, poll any tasks that might be pending in the scope
|
||||
for task in work.tasks {
|
||||
{
|
||||
// Make sure we set the runtime since we're running user code
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
// Next, run any queued tasks
|
||||
// We choose not to poll the deadline since we complete pretty quickly anyways
|
||||
let mut tasks_polled = 0;
|
||||
while let Some(task) = self.pop_task() {
|
||||
if self.runtime.task_runs_during_suspense(task) {
|
||||
let _ = self.runtime.handle_task_wakeup(task);
|
||||
// Running that task, may mark a scope higher up as dirty. If it does, return from the function early
|
||||
self.queue_events();
|
||||
if self.has_dirty_scopes() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
tasks_polled += 1;
|
||||
// Once we have polled a few tasks, we manually yield to the scheduler to give it a chance to run other pending work
|
||||
if tasks_polled > 32 {
|
||||
yield_now().await;
|
||||
tasks_polled = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.wait_for_event().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Render any dirty scopes immediately, but don't poll any futures that are client only on that scope
|
||||
/// Returns a list of suspense boundaries that were resolved
|
||||
pub async fn render_suspense_immediate(&mut self) -> Vec<ScopeId> {
|
||||
// Queue any new events before we start working
|
||||
self.queue_events();
|
||||
|
||||
let mut resolved_scopes = Vec::new();
|
||||
|
||||
// Render whatever work needs to be rendered, unlocking new futures and suspense leaves
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
|
||||
let mut work_done = 0;
|
||||
while let Some(work) = self.pop_work() {
|
||||
match work {
|
||||
Work::PollTask(task) => {
|
||||
// During suspense, we only want to run tasks that are suspended
|
||||
if self.runtime.task_runs_during_suspense(task) {
|
||||
let _ = self.runtime.handle_task_wakeup(task);
|
||||
}
|
||||
}
|
||||
Work::RerunScope(scope) => {
|
||||
if self
|
||||
.runtime
|
||||
.get_state(scope.id)
|
||||
.filter(|scope| scope.should_run_during_suspense())
|
||||
.is_some()
|
||||
{
|
||||
let scope_state = self.get_scope(scope.id).unwrap();
|
||||
let was_suspended =
|
||||
SuspenseBoundaryProps::downcast_ref_from_props(&*scope_state.props)
|
||||
.filter(|props| props.suspended())
|
||||
.is_some();
|
||||
// If the scope is dirty, run the scope and get the mutations
|
||||
self.run_and_diff_scope(None::<&mut NoOpMutations>, scope.id);
|
||||
let scope_state = self.get_scope(scope.id).unwrap();
|
||||
let is_now_suspended =
|
||||
SuspenseBoundaryProps::downcast_ref_from_props(&*scope_state.props)
|
||||
.filter(|props| props.suspended())
|
||||
.is_some();
|
||||
|
||||
self.queue_events();
|
||||
|
||||
// If the scope is dirty, run the scope and get the mutations
|
||||
if work.rerun_scope {
|
||||
let new_nodes = self.run_scope(work.scope.id);
|
||||
|
||||
self.diff_scope(&mut NoOpMutations, work.scope.id, new_nodes);
|
||||
if is_now_suspended {
|
||||
resolved_scopes.retain(|&id| id != scope.id);
|
||||
} else if was_suspended {
|
||||
resolved_scopes.push(scope.id);
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"Scope {:?} was marked as dirty, but will not rerun during suspense. Only nodes that are under a suspense boundary rerun during suspense",
|
||||
scope.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Queue any new events
|
||||
self.queue_events();
|
||||
work_done += 1;
|
||||
// Once we have polled a few tasks, we manually yield to the scheduler to give it a chance to run other pending work
|
||||
if work_done > 32 {
|
||||
yield_now().await;
|
||||
work_done = 0;
|
||||
}
|
||||
}
|
||||
|
||||
resolved_scopes.sort_by_key(|&id| self.runtime.get_state(id).unwrap().height);
|
||||
resolved_scopes
|
||||
}
|
||||
|
||||
/// Get the current runtime
|
||||
@@ -817,7 +883,11 @@ impl VirtualDom {
|
||||
while let Some(path) = parent {
|
||||
let mut listeners = vec![];
|
||||
|
||||
let el_ref = &self.mounts[path.mount.0].node;
|
||||
let Some(mount) = self.mounts.get(path.mount.0) else {
|
||||
// If the node is suspended and not mounted, we can just ignore the event
|
||||
return;
|
||||
};
|
||||
let el_ref = &mount.node;
|
||||
let node_template = el_ref.template.get();
|
||||
let target_path = path.path;
|
||||
|
||||
@@ -827,9 +897,7 @@ impl VirtualDom {
|
||||
|
||||
for attr in attrs.iter() {
|
||||
// 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)
|
||||
{
|
||||
if attr.name.get(2..) == Some(name) && target_path.is_decendant(this_path) {
|
||||
listeners.push(&attr.value);
|
||||
|
||||
// Break if this is the exact target element.
|
||||
@@ -874,7 +942,11 @@ impl VirtualDom {
|
||||
name = "VirtualDom::handle_non_bubbling_event"
|
||||
)]
|
||||
fn handle_non_bubbling_event(&mut self, node: ElementRef, name: &str, uievent: Event<dyn Any>) {
|
||||
let el_ref = &self.mounts[node.mount.0].node;
|
||||
let Some(mount) = self.mounts.get(node.mount.0) else {
|
||||
// If the node is suspended and not mounted, we can just ignore the event
|
||||
return;
|
||||
};
|
||||
let el_ref = &mount.node;
|
||||
let node_template = el_ref.template.get();
|
||||
let target_path = node.path;
|
||||
|
||||
@@ -884,7 +956,7 @@ impl VirtualDom {
|
||||
for attr in attrs.iter() {
|
||||
// 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 attr.name.get(2..) == Some(name) && target_path == this_path {
|
||||
if let AttributeValue::Listener(listener) = &attr.value {
|
||||
self.runtime.rendering.set(false);
|
||||
listener.call(uievent.clone());
|
||||
@@ -907,3 +979,18 @@ impl Drop for VirtualDom {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Yield control back to the async scheduler. This is used to give the scheduler a chance to run other pending work. Or cancel the task if the client has disconnected.
|
||||
async fn yield_now() {
|
||||
let mut yielded = false;
|
||||
std::future::poll_fn::<(), _>(move |cx| {
|
||||
if !yielded {
|
||||
cx.waker().wake_by_ref();
|
||||
yielded = true;
|
||||
std::task::Poll::Pending
|
||||
} else {
|
||||
std::task::Poll::Ready(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
Reference in new issue
Block a user