use crate::signal::{provide_context, use_context};
use crate::Node;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_SUSPENSE_ID: AtomicU64 = AtomicU64::new(1);
fn next_suspense_id() -> String {
format!("s{}", NEXT_SUSPENSE_ID.fetch_add(1, Ordering::Relaxed))
}
struct Source {
is_pending: Rc<dyn Fn() -> bool>,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
streamable: Rc<Cell<bool>>,
}
struct SuspenseState {
id: String,
sources: RefCell<Vec<Source>>,
}
#[derive(Clone)]
pub struct SuspenseContext {
state: Rc<SuspenseState>,
}
#[derive(Clone)]
pub struct SourceHandle {
streamable: Rc<Cell<bool>>,
}
impl SourceHandle {
pub fn mark_streamable(&self) {
self.streamable.set(true);
}
}
impl SuspenseContext {
fn new() -> Self {
Self {
state: Rc::new(SuspenseState {
id: next_suspense_id(),
sources: RefCell::new(Vec::new()),
}),
}
}
pub fn id(&self) -> &str {
&self.state.id
}
pub fn register(&self, is_pending: impl Fn() -> bool + 'static) -> SourceHandle {
let streamable = Rc::new(Cell::new(false));
self.state.sources.borrow_mut().push(Source {
is_pending: Rc::new(is_pending),
streamable: streamable.clone(),
});
SourceHandle { streamable }
}
pub fn is_pending(&self) -> bool {
let sources: Vec<Rc<dyn Fn() -> bool>> = self
.state
.sources
.borrow()
.iter()
.map(|source| source.is_pending.clone())
.collect();
sources
.iter()
.fold(false, |pending, is_pending| is_pending() | pending)
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn pending_sources_are_streamable(&self) -> bool {
let sources: Vec<(Rc<dyn Fn() -> bool>, bool)> = self
.state
.sources
.borrow()
.iter()
.map(|source| (source.is_pending.clone(), source.streamable.get()))
.collect();
crate::signal::untrack(|| {
sources
.iter()
.all(|(is_pending, streamable)| *streamable || !is_pending())
})
}
pub fn source_count(&self) -> usize {
self.state.sources.borrow().len()
}
}
pub fn use_suspense() -> Option<SuspenseContext> {
use_context::<SuspenseContext>()
}
pub(crate) fn open_marker(id: &str) -> String {
format!("krab:suspense:{id}:pending")
}
pub(crate) fn resolved_marker(id: &str) -> String {
format!("krab:suspense:{id}:resolved")
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn deferred_end_marker(id: &str) -> String {
format!("/krab:suspense:{id}")
}
pub fn suspense<F, C>(fallback: F, children: C) -> Node
where
F: Fn() -> Node + 'static,
C: FnOnce() -> Node,
{
let context = SuspenseContext::new();
let owner = crate::signal::Owner::new();
let content = {
let context = context.clone();
owner.with(move || {
provide_context(context);
children()
})
};
Node::Dynamic(Rc::new(move || {
let id = context.id();
if context.is_pending() {
#[cfg(not(target_arch = "wasm32"))]
if let Some(deferred) =
crate::render_stream::defer_boundary(&context, &content, &owner, &fallback)
{
return deferred;
}
Node::Fragment(vec![
Node::Comment(open_marker(id)),
fallback(),
Node::Comment(resolved_marker(id)),
])
} else {
Node::Fragment(vec![
Node::Comment(open_marker(id)),
content.clone(),
Node::Comment(resolved_marker(id)),
])
}
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::resource::{create_resource, create_resource_with_initial};
use crate::signal::{create_signal, with_owner};
use crate::{Element, Render};
fn p(text: &str) -> Node {
Node::Element(Element {
tag: "p".to_string(),
attributes: vec![],
children: vec![Node::Text(text.to_string())],
events: vec![],
})
}
#[test]
fn a_boundary_without_sources_renders_its_children() {
let html = with_owner(|| suspense(|| p("loading"), || p("done")).render());
assert!(html.contains("<p>done</p>"), "{html}");
assert!(!html.contains("loading"));
assert!(html.starts_with("<!--krab:suspense:s"), "{html}");
assert!(html.ends_with(":resolved-->"), "{html}");
assert!(crate::render_stream::is_finalized_ssr_snapshot(&html));
}
#[test]
fn a_pending_resource_renders_the_fallback_on_the_server() {
let html = with_owner(|| {
suspense(
|| p("loading"),
|| {
let user = create_resource(|| 1u32, |n| async move { Ok::<_, String>(n) });
Node::Dynamic(Rc::new(move || {
p(&format!("user {:?}", user.value().get()))
}))
},
)
.render()
});
assert!(html.contains("<p>loading</p>"), "{html}");
assert!(!html.contains("user"), "{html}");
assert!(crate::render_stream::is_finalized_ssr_snapshot(&html));
}
#[test]
fn a_resource_with_initial_data_renders_the_children_on_the_server() {
let html = with_owner(|| {
suspense(
|| p("loading"),
|| {
let user = create_resource_with_initial(
Some("ada".to_string()),
|| 1u32,
|_| async move { Ok::<_, String>("x".to_string()) },
);
Node::Dynamic(Rc::new(move || p(&user.value().get().unwrap_or_default())))
},
)
.render()
});
assert!(html.contains("<p>ada</p>"), "{html}");
assert!(!html.contains("loading"), "{html}");
}
#[test]
fn resources_register_with_the_nearest_boundary_only() {
let (outer_ctx, inner_ctx) = with_owner(|| {
let mut outer = None;
let mut inner = None;
let _ = suspense(
|| p("outer"),
|| {
outer = use_suspense();
let _ = create_resource(|| (), |_| async move { Ok::<_, String>(()) });
suspense(
|| p("inner"),
|| {
inner = use_suspense();
let _ = create_resource(|| (), |_| async move { Ok::<_, String>(()) });
let _ = create_resource(|| (), |_| async move { Ok::<_, String>(()) });
p("x")
},
)
},
);
(outer, inner)
});
let (outer, inner) = (outer_ctx.expect("outer"), inner_ctx.expect("inner"));
assert_ne!(outer.id(), inner.id());
assert_eq!(outer.source_count(), 1);
assert_eq!(inner.source_count(), 2);
assert!(use_suspense().is_none(), "no boundary outside the scope");
}
#[test]
fn the_boundary_switches_when_its_source_settles() {
let (ready, set_ready) = create_signal(false);
let rendered = Rc::new(RefCell::new(String::new()));
with_owner(|| {
let node = suspense(
|| p("loading"),
move || {
if let Some(ctx) = use_suspense() {
ctx.register(move || !ready.get());
}
p("content")
},
);
let sink = rendered.clone();
crate::signal::create_effect(move || {
*sink.borrow_mut() = node.render();
});
});
assert!(rendered.borrow().contains("loading"));
set_ready.set(true);
assert!(
rendered.borrow().contains("content"),
"{}",
rendered.borrow()
);
assert!(!rendered.borrow().contains("loading"));
}
}