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
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user