extern crate self as krab_client;
use krab_core::Node;
#[cfg(feature = "web")]
use std::cell::{Cell, RefCell};
#[cfg(feature = "web")]
use std::collections::{HashMap, VecDeque};
#[cfg(feature = "web")]
use std::panic::{catch_unwind, AssertUnwindSafe};
#[cfg(feature = "web")]
use std::rc::Rc;
use wasm_bindgen::prelude::*;
#[cfg(feature = "web")]
use wasm_bindgen::JsCast;
use web_sys::console;
#[cfg(feature = "web")]
use web_sys::{Element, HtmlElement, Node as WebNode, NodeList};
#[cfg(feature = "web")]
type EventClosure = Closure<dyn FnMut(web_sys::Event)>;
#[cfg(feature = "web")]
type EventClosureMap = std::collections::HashMap<u32, Vec<(String, EventClosure)>>;
#[cfg(feature = "web")]
type DynamicRegionMap = std::collections::HashMap<u32, Rc<RefCell<Vec<WebNode>>>>;
#[cfg(feature = "web")]
thread_local! {
static EVENT_CLOSURES: RefCell<EventClosureMap> = RefCell::new(EventClosureMap::new());
static NEXT_DOM_ID: std::cell::Cell<u32> = const { std::cell::Cell::new(1) };
static DYNAMIC_REGIONS: RefCell<DynamicRegionMap> = RefCell::new(DynamicRegionMap::new());
}
pub use krab_core::signal::*;
pub mod components;
pub use components::*;
pub mod router;
pub use krab_core::action::{create_action, Action};
pub use krab_core::resource::{
create_resource, create_resource_with_initial, Resource, ResourceState,
};
#[cfg(all(feature = "web", target_arch = "wasm32"))]
pub fn spawn<F>(future: F)
where
F: std::future::Future<Output = ()> + 'static,
{
wasm_bindgen_futures::spawn_local(future);
}
pub type ComponentFactory = fn(props_json: String) -> Node;
pub struct IslandDefinition {
pub name: &'static str,
pub factory: ComponentFactory,
}
inventory::collect!(IslandDefinition);
#[cfg(any(feature = "web", test))]
fn node_attribute_value<'a>(node: &'a Node, name: &str) -> Option<&'a str> {
let Node::Element(element) = node else {
return None;
};
element
.attributes
.iter()
.find(|attr| attr.name == name)
.map(|attr| attr.value.as_str())
}
#[cfg(any(feature = "web", test))]
fn boundary_state_from_factory_node(node: &Node) -> Option<&str> {
node_attribute_value(node, "data-krab-boundary-state")
}
#[cfg(feature = "web")]
fn node_hydration_id(node: &Node) -> Option<&str> {
node_attribute_value(node, krab_core::HYDRATION_NODE_ID_ATTR)
}
#[cfg(any(feature = "web", test))]
fn classify_boundary_state(factory_state: Option<&str>, mismatch_count: u32) -> &'static str {
match factory_state {
Some("decode-error") => "decode-error",
Some("error") => "error",
_ if mismatch_count > 0 => "patched",
_ => "ok",
}
}
#[cfg(feature = "web")]
#[derive(Debug, Clone)]
struct HydrationBoundary {
island: String,
id: String,
}
#[cfg(feature = "web")]
#[derive(Debug, Clone, Copy, Default)]
struct HydrationStats {
consumed: u32,
replacements: u32,
appends: u32,
removals: u32,
reorders: u32,
text_patches: u32,
marker_mismatches: u32,
}
#[cfg(feature = "web")]
impl HydrationStats {
fn with_consumed(mut self, consumed: u32) -> Self {
self.consumed = consumed;
self
}
fn merge(&mut self, other: Self) {
self.consumed += other.consumed;
self.replacements += other.replacements;
self.appends += other.appends;
self.removals += other.removals;
self.reorders += other.reorders;
self.text_patches += other.text_patches;
self.marker_mismatches += other.marker_mismatches;
}
fn mismatch_count(self) -> u32 {
self.replacements
+ self.appends
+ self.removals
+ self.reorders
+ self.text_patches
+ self.marker_mismatches
}
}
#[cfg(feature = "web")]
pub fn log_hydration_diagnostic(scope: &str, name: &str, detail: &str) {
let payload = serde_json::json!({
"scope": scope,
"island": name,
"detail": detail,
})
.to_string();
console::error_1(&payload.into());
}
#[cfg(feature = "web")]
fn log_hydration_boundary_diagnostic(
level: &str,
scope: &str,
boundary: &HydrationBoundary,
reason: &str,
detail: &str,
path: Option<&str>,
) {
let payload = serde_json::json!({
"scope": scope,
"island": boundary.island,
"boundary_id": boundary.id,
"reason": reason,
"detail": detail,
"path": path,
})
.to_string();
match level {
"error" => console::error_1(&payload.into()),
_ => console::warn_1(&payload.into()),
}
}
#[cfg(feature = "web")]
fn describe_dom_node(node: &WebNode) -> String {
if node.node_type() == 3 {
return format!("#text({})", node.text_content().unwrap_or_default());
}
if let Some(element) = node.dyn_ref::<Element>() {
return format!("<{}>", element.tag_name().to_lowercase());
}
format!("node_type:{}", node.node_type())
}
#[cfg(feature = "web")]
fn dom_hydration_id(node: &WebNode) -> Option<String> {
node.dyn_ref::<Element>()
.and_then(|element| element.get_attribute(krab_core::HYDRATION_NODE_ID_ATTR))
}
#[cfg(feature = "web")]
fn child_path(parent_path: &str, child_index: usize) -> String {
if parent_path.is_empty() {
child_index.to_string()
} else {
format!("{parent_path}.{child_index}")
}
}
#[cfg(feature = "web")]
fn extra_dom_path(parent_path: &str, child_index: u32) -> String {
if parent_path.is_empty() {
format!("extra@{child_index}")
} else {
format!("{parent_path}.extra@{child_index}")
}
}
#[cfg(feature = "web")]
fn find_dom_node_with_hydration_id(
node_list: &NodeList,
start_index: u32,
expected_id: &str,
) -> Option<u32> {
(start_index..node_list.length()).find(|index| {
node_list
.item(*index)
.and_then(|node| dom_hydration_id(&node))
.as_deref()
== Some(expected_id)
})
}
#[cfg(feature = "web")]
fn realign_node_by_hydration_id(
parent: &WebNode,
node_list: &NodeList,
index: u32,
expected_id: &str,
boundary: &HydrationBoundary,
path: &str,
) -> (Option<WebNode>, HydrationStats) {
let current_node = node_list.item(index);
if current_node.as_ref().and_then(dom_hydration_id).as_deref() == Some(expected_id) {
return (current_node, HydrationStats::default());
}
if let Some(found_index) = find_dom_node_with_hydration_id(node_list, index + 1, expected_id) {
let Some(found_node) = node_list.item(found_index) else {
return (current_node, HydrationStats::default());
};
if let Err(err) = parent.insert_before(&found_node, current_node.as_ref()) {
console::error_1(
&format!(
"{{\"scope\":\"hydrate_recursive\",\"detail\":\"insert_before failed\",\"error\":\"{:?}\"}}",
err
)
.into(),
);
return (current_node, HydrationStats::default());
}
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"marker_reordered_dom_node",
&format!(
"moved node with hydration marker {} from DOM index {} to {}",
expected_id, found_index, index
),
Some(path),
);
return (
Some(found_node),
HydrationStats {
reorders: 1,
..HydrationStats::default()
},
);
}
if let Some(current_node) = current_node {
if let Some(actual_id) = dom_hydration_id(¤t_node) {
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"element_marker_mismatch",
&format!(
"expected hydration marker {} but found {} at DOM index {}",
expected_id, actual_id, index
),
Some(path),
);
return (
Some(current_node),
HydrationStats {
marker_mismatches: 1,
..HydrationStats::default()
},
);
}
}
(node_list.item(index), HydrationStats::default())
}
#[wasm_bindgen]
pub fn hydrate() {
console::log_1(&"Hydrating Krab app...".into());
#[cfg(feature = "web")]
{
let Some(window) = web_sys::window() else {
console::error_1(&"{\"scope\":\"hydrate\",\"detail\":\"missing window\"}".into());
return;
};
let Some(document) = window.document() else {
console::error_1(&"{\"scope\":\"hydrate\",\"detail\":\"missing document\"}".into());
return;
};
let islands = match document.query_selector_all("[data-island]") {
Ok(nodes) => nodes,
Err(err) => {
console::error_1(
&format!(
"{{\"scope\":\"hydrate\",\"detail\":\"query_selector_all failed\",\"error\":\"{:?}\"}}",
err
)
.into(),
);
return;
}
};
for i in 0..islands.length() {
let Some(element) = islands.item(i) else {
console::warn_1(&format!("Missing island element at index {}", i).into());
continue;
};
let Ok(html_element) = element.clone().dyn_into::<HtmlElement>() else {
console::warn_1(
&format!("Island node at index {} is not an HtmlElement", i).into(),
);
continue;
};
let Some(name) = html_element.get_attribute("data-island") else {
console::warn_1(
&format!("Island element at index {} missing data-island", i).into(),
);
continue;
};
let boundary_id_attr = html_element.get_attribute("data-krab-boundary-id");
let boundary = HydrationBoundary {
island: name.clone(),
id: boundary_id_attr
.clone()
.unwrap_or_else(|| format!("{name}:legacy-{i}")),
};
if boundary_id_attr.is_none() {
log_hydration_boundary_diagnostic(
"warn",
"hydrate",
&boundary,
"missing_boundary_id",
"server markup missing data-krab-boundary-id; using DOM index fallback",
None,
);
}
let _ = html_element.set_attribute("data-krab-boundary", &boundary.island);
let _ = html_element.set_attribute("data-krab-boundary-id", &boundary.id);
let _ = html_element.set_attribute("data-krab-boundary-mismatches", "0");
let _ = html_element.set_attribute("data-krab-boundary-state", "hydrating");
let props_json = html_element
.get_attribute("data-props")
.unwrap_or_else(|| "{}".to_string());
let definition = inventory::iter::<IslandDefinition>
.into_iter()
.find(|def| def.name == name);
if let Some(def) = definition {
console::log_1(&format!("Hydrating island: {}", name).into());
match catch_unwind(AssertUnwindSafe(|| (def.factory)(props_json))) {
Ok(node) => {
let node = krab_core::annotate_hydration_tree(node, &boundary.id);
let factory_state = boundary_state_from_factory_node(&node);
let stats = hydrate_node(element.clone(), &node, &boundary);
let mismatch_count = stats.mismatch_count();
let _ = html_element.set_attribute(
"data-krab-boundary-mismatches",
&mismatch_count.to_string(),
);
let _ = html_element.set_attribute(
"data-krab-boundary-state",
classify_boundary_state(factory_state, mismatch_count),
);
if mismatch_count > 0 {
log_hydration_boundary_diagnostic(
"warn",
"hydrate",
&boundary,
"boundary_patched",
&format!(
"patched DOM during hydration (replacements={}, appends={}, removals={}, reorders={}, text_patches={})",
stats.replacements,
stats.appends,
stats.removals,
stats.reorders,
stats.text_patches
),
None,
);
}
}
Err(_) => {
log_hydration_boundary_diagnostic(
"error",
"hydrate",
&boundary,
"factory_panic",
"factory panic captured",
None,
);
let _ = html_element.set_attribute("data-krab-boundary-state", "error");
html_element.set_inner_html(
"<div role=\"alert\">Hydration fallback rendered.</div>",
);
}
}
} else {
let _ =
html_element.set_attribute("data-krab-boundary-state", "missing-definition");
log_hydration_boundary_diagnostic(
"error",
"hydrate",
&boundary,
"missing_island_definition",
"no registered island definition found",
None,
);
}
}
}
}
#[cfg(feature = "web")]
fn hydrate_node(real_node: WebNode, v_node: &Node, boundary: &HydrationBoundary) -> HydrationStats {
hydrate_children(&real_node, std::slice::from_ref(v_node), boundary, "")
}
#[cfg(feature = "web")]
fn hydrate_children(
parent: &WebNode,
v_nodes: &[Node],
boundary: &HydrationBoundary,
parent_path: &str,
) -> HydrationStats {
let child_nodes = parent.child_nodes();
let mut dom_index = 0;
let mut stats = HydrationStats::default();
for (child_index, v_node) in v_nodes.iter().enumerate() {
let path = child_path(parent_path, child_index);
let child_stats =
hydrate_recursive(parent, &child_nodes, dom_index, v_node, boundary, &path);
dom_index += child_stats.consumed;
stats.merge(child_stats);
}
while child_nodes.length() > dom_index {
let Some(extra_node) = child_nodes.item(dom_index) else {
break;
};
let path = extra_dom_path(parent_path, dom_index);
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"unexpected_dom_node",
"removing extra DOM node that was not present in the expected tree",
Some(&path),
);
remove_dom_node_closures(&extra_node);
if let Err(err) = parent.remove_child(&extra_node) {
console::error_1(
&format!(
"{{\"scope\":\"hydrate_recursive\",\"detail\":\"remove_child failed\",\"error\":\"{:?}\"}}",
err
)
.into(),
);
break;
}
stats.removals += 1;
}
stats
}
#[cfg(feature = "web")]
fn replace_dom_node(parent: &WebNode, old: &WebNode, v_node: &Node, scope: &str) {
let Some(new_node) = create_dom_node(v_node) else {
return;
};
remove_dom_node_closures(old);
if let Err(err) = parent.replace_child(&new_node, old) {
console::error_1(
&format!(
"{{\"scope\":\"{scope}\",\"detail\":\"replace_child failed\",\"error\":\"{err:?}\"}}"
)
.into(),
);
}
}
#[cfg(feature = "web")]
fn append_dom_node(parent: &WebNode, v_node: &Node, scope: &str) {
let Some(new_node) = create_dom_node(v_node) else {
return;
};
if let Err(err) = parent.append_child(&new_node) {
console::error_1(
&format!(
"{{\"scope\":\"{scope}\",\"detail\":\"append_child failed\",\"error\":\"{err:?}\"}}"
)
.into(),
);
}
}
#[cfg(feature = "web")]
fn detach_element_events(real_el: &Element) {
let Ok(id_val) = js_sys::Reflect::get(real_el.as_ref(), &JsValue::from_str("__krab_id")) else {
return;
};
let Some(id) = id_val.as_f64() else {
return;
};
let Some(pairs) = EVENT_CLOSURES.with(|v| v.borrow_mut().remove(&(id as u32))) else {
return;
};
for (name, closure) in &pairs {
let _ = real_el.remove_event_listener_with_callback(name, closure.as_ref().unchecked_ref());
}
}
#[cfg(feature = "web")]
fn attach_element_events(real_el: &Element, v_el: &krab_core::Element, scope: &str) {
let mut node_closures = Vec::new();
for event in &v_el.events {
let name = event.name.clone();
let callback = event.callback.clone();
let closure =
Closure::wrap(Box::new(move |e: web_sys::Event| callback(e)) as Box<dyn FnMut(_)>);
if let Err(err) =
real_el.add_event_listener_with_callback(&name, closure.as_ref().unchecked_ref())
{
console::error_1(
&format!(
"{{\"scope\":\"{scope}\",\"detail\":\"failed to attach event listener\",\"event\":\"{name}\",\"error\":\"{err:?}\"}}"
)
.into(),
);
}
node_closures.push((name, closure));
}
if node_closures.is_empty() {
return;
}
let id = NEXT_DOM_ID.with(|id| {
let v = id.get();
id.set(v + 1);
v
});
let _ = js_sys::Reflect::set(
real_el.as_ref(),
&JsValue::from_str("__krab_id"),
&JsValue::from_f64(id as f64),
);
EVENT_CLOSURES.with(|v| v.borrow_mut().insert(id, node_closures));
}
#[cfg(feature = "web")]
fn hydrate_element(
parent: &WebNode,
node_list: &NodeList,
index: u32,
v_node: &Node,
v_el: &krab_core::Element,
boundary: &HydrationBoundary,
path: &str,
) -> HydrationStats {
let (aligned_node_opt, alignment_stats) = match node_hydration_id(v_node) {
Some(expected_id) => {
realign_node_by_hydration_id(parent, node_list, index, expected_id, boundary, path)
}
None => (node_list.item(index), HydrationStats::default()),
};
let Some(real_node) = aligned_node_opt else {
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"missing_dom_node",
&format!(
"expected <{}> but DOM child was missing; appending",
v_el.tag
),
Some(path),
);
append_dom_node(parent, v_node, "hydrate_recursive");
let mut stats = HydrationStats {
consumed: 1,
appends: 1,
..HydrationStats::default()
};
stats.merge(alignment_stats);
return stats;
};
let matching_el = real_node
.dyn_ref::<Element>()
.filter(|real_el| real_el.tag_name().eq_ignore_ascii_case(&v_el.tag));
if let Some(real_el) = matching_el {
attach_element_events(real_el, v_el, "hydrate_recursive");
let mut stats =
hydrate_children(&real_node, &v_el.children, boundary, path).with_consumed(1);
stats.merge(alignment_stats);
return stats;
}
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"element_tag_mismatch",
&format!(
"expected <{}> but found {} at DOM index {}",
v_el.tag,
describe_dom_node(&real_node),
index
),
Some(path),
);
replace_dom_node(parent, &real_node, v_node, "hydrate_recursive");
let mut stats = HydrationStats {
consumed: 1,
replacements: 1,
..HydrationStats::default()
};
stats.merge(alignment_stats);
stats
}
#[cfg(feature = "web")]
fn hydrate_text(
parent: &WebNode,
real_node_opt: Option<WebNode>,
v_node: &Node,
text: &str,
boundary: &HydrationBoundary,
path: &str,
) -> HydrationStats {
const TEXT_NODE: u16 = 3;
let Some(real_node) = real_node_opt else {
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"missing_dom_node",
&format!("expected text {text:?} but DOM child was missing; appending"),
Some(path),
);
append_dom_node(parent, v_node, "hydrate_recursive");
return HydrationStats {
consumed: 1,
appends: 1,
..HydrationStats::default()
};
};
if real_node.node_type() != TEXT_NODE {
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"expected_text_found_non_text_node",
&format!(
"expected text {:?} but found {}; replacing node",
text,
describe_dom_node(&real_node)
),
Some(path),
);
replace_dom_node(parent, &real_node, v_node, "hydrate_recursive");
return HydrationStats {
consumed: 1,
replacements: 1,
..HydrationStats::default()
};
}
let actual = real_node.text_content().unwrap_or_default();
if actual == text {
return HydrationStats {
consumed: 1,
..HydrationStats::default()
};
}
log_hydration_boundary_diagnostic(
"warn",
"hydrate_recursive",
boundary,
"text_content_mismatch",
&format!("expected text {text:?} but found {actual:?}; patching text node"),
Some(path),
);
real_node.set_text_content(Some(text));
HydrationStats {
consumed: 1,
text_patches: 1,
..HydrationStats::default()
}
}
#[cfg(feature = "web")]
fn hydrate_recursive(
parent: &WebNode,
node_list: &NodeList,
index: u32,
v_node: &Node,
boundary: &HydrationBoundary,
path: &str,
) -> HydrationStats {
let real_node_opt = node_list.item(index);
match v_node {
Node::Element(v_el) => {
hydrate_element(parent, node_list, index, v_node, v_el, boundary, path)
}
Node::Text(text) => hydrate_text(parent, real_node_opt, v_node, text, boundary, path),
Node::Fragment(children) => {
let mut consumed = 0;
let mut stats = HydrationStats::default();
for (child_index, child) in children.iter().enumerate() {
let child_stats = hydrate_recursive(
parent,
node_list,
index + consumed,
child,
boundary,
&child_path(path, child_index),
);
consumed += child_stats.consumed;
stats.merge(child_stats);
}
stats
}
Node::Dynamic(f) => {
let cells = DynamicRegionCells {
rendered: Rc::new(RefCell::new(Vec::new())),
current_vnode: Rc::new(RefCell::new(None)),
anchor: Rc::new(RefCell::new(None)),
empty_position: Rc::new(RefCell::new(None)),
};
let stats_cell: Rc<RefCell<HydrationStats>> =
Rc::new(RefCell::new(HydrationStats::default()));
let f = f.clone();
let first_run = Rc::new(Cell::new(true));
let effect_cells = DynamicRegionCells {
rendered: cells.rendered.clone(),
current_vnode: cells.current_vnode.clone(),
anchor: cells.anchor.clone(),
empty_position: cells.empty_position.clone(),
};
let parent = parent.clone();
let node_list = node_list.clone();
let boundary = boundary.clone();
let path = path.to_string();
let stats_for_effect = stats_cell.clone();
create_effect(move || {
let new_v_node = f();
if first_run.get() {
first_run.set(false);
let stats = hydrate_recursive(
&parent,
&node_list,
index,
&new_v_node,
&boundary,
&path,
);
*effect_cells.rendered.borrow_mut() = (0..stats.consumed)
.filter_map(|offset| node_list.item(index + offset))
.collect();
*effect_cells.empty_position.borrow_mut() = parent
.dyn_ref::<Element>()
.cloned()
.map(|el| (el, node_list.item(index + stats.consumed)));
*effect_cells.current_vnode.borrow_mut() = Some(new_v_node);
*stats_for_effect.borrow_mut() = stats;
return;
}
update_dynamic_region(&effect_cells, new_v_node);
});
let stats = *stats_cell.borrow();
let _ = cells;
stats
}
}
}
#[cfg(feature = "web")]
fn remove_dom_node_closures(node: &WebNode) {
if let Ok(id_val) = js_sys::Reflect::get(node.as_ref(), &JsValue::from_str("__krab_id")) {
if let Some(id_f64) = id_val.as_f64() {
EVENT_CLOSURES.with(|v| v.borrow_mut().remove(&(id_f64 as u32)));
}
}
let child_nodes = node.child_nodes();
for i in 0..child_nodes.length() {
if let Some(child) = child_nodes.item(i) {
remove_dom_node_closures(&child);
}
}
}
#[cfg(feature = "web")]
struct DynamicRegionCells {
rendered: Rc<RefCell<Vec<WebNode>>>,
current_vnode: Rc<RefCell<Option<Node>>>,
anchor: Rc<RefCell<Option<WebNode>>>,
empty_position: Rc<RefCell<Option<EmptyRunPosition>>>,
}
#[cfg(feature = "web")]
type EmptyRunPosition = (Element, Option<WebNode>);
#[cfg(feature = "web")]
fn update_dynamic_region(cells: &DynamicRegionCells, new_v_node: Node) {
let previous_nodes = cells.rendered.borrow().clone();
let previous_vnode = cells.current_vnode.borrow_mut().take();
let anchor_node = {
let existing = cells.anchor.borrow().clone();
match existing {
Some(anchor) => anchor,
None => {
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
*cells.current_vnode.borrow_mut() = Some(new_v_node);
return;
};
let created: WebNode = document.create_comment("krab-dynamic").into();
let inserted = if let Some(last) = previous_nodes.last() {
last.parent_node()
.map(|parent| {
let _ = parent.insert_before(&created, last.next_sibling().as_ref());
})
.is_some()
} else if let Some((parent, next)) = cells.empty_position.borrow().as_ref() {
let next_ok = next
.as_ref()
.filter(|n| n.parent_node().as_deref() == Some(parent.as_ref()));
let _ = parent.insert_before(&created, next_ok);
true
} else {
false
};
if !inserted {
*cells.current_vnode.borrow_mut() = Some(new_v_node);
return;
}
register_dynamic_region(&created, cells.rendered.clone());
*cells.anchor.borrow_mut() = Some(created.clone());
created
}
}
};
let Some(parent) = anchor_node
.parent_node()
.and_then(|node| node.dyn_into::<Element>().ok())
else {
*cells.current_vnode.borrow_mut() = Some(new_v_node);
return;
};
let next = reconcile_range(
&parent,
previous_nodes,
previous_vnode.as_slice(),
std::slice::from_ref(&new_v_node),
Some(&anchor_node),
);
match next {
Some(nodes) => *cells.rendered.borrow_mut() = nodes,
None => {
let stale = std::mem::take(&mut *cells.rendered.borrow_mut());
for node in &stale {
remove_tracked_node(&parent, node);
}
let mut fresh_tracked = Vec::new();
for (insert, tracked) in create_run_nodes(&new_v_node) {
let _ = parent.insert_before(&insert, Some(&anchor_node));
fresh_tracked.push(tracked);
}
*cells.rendered.borrow_mut() = fresh_tracked;
}
}
*cells.current_vnode.borrow_mut() = Some(new_v_node);
}
#[cfg(feature = "web")]
fn patch_dom(
_parent: &WebNode,
real_node: &WebNode,
old_vnode: &Node,
new_vnode: &Node,
) -> Option<WebNode> {
match (old_vnode, new_vnode) {
(Node::Text(old_text), Node::Text(new_text)) => {
if old_text != new_text {
real_node.set_text_content(Some(new_text));
}
Some(real_node.clone())
}
(Node::Element(old_el), Node::Element(new_el)) if old_el.tag == new_el.tag => {
let el = real_node.dyn_ref::<Element>()?;
for old_attr in &old_el.attributes {
if !new_el.attributes.iter().any(|a| a.name == old_attr.name) {
let _ = el.remove_attribute(&old_attr.name);
}
}
for new_attr in &new_el.attributes {
let old_attr = old_el.attributes.iter().find(|a| a.name == new_attr.name);
if old_attr.map(|a| &a.value) != Some(&new_attr.value) {
let _ = el.set_attribute(&new_attr.name, &new_attr.value);
}
}
if !old_el.events.is_empty() || !new_el.events.is_empty() {
detach_element_events(el);
attach_element_events(el, new_el, "patch_dom");
}
patch_children(el, &old_el.children, &new_el.children)?;
Some(real_node.clone())
}
_ => None,
}
}
#[cfg(feature = "web")]
fn flatten_children<'a>(nodes: &'a [Node], out: &mut Vec<&'a Node>) {
for node in nodes {
match node {
Node::Fragment(children) => flatten_children(children, out),
other => out.push(other),
}
}
}
#[cfg(feature = "web")]
fn reconcile_key(node: &Node) -> Option<&str> {
node_hydration_id(node)
}
#[cfg(feature = "web")]
fn patch_children(el: &Element, old_children: &[Node], new_children: &[Node]) -> Option<()> {
let child_nodes = el.child_nodes();
let existing: Vec<WebNode> = (0..child_nodes.length())
.filter_map(|index| child_nodes.item(index))
.collect();
reconcile_range(el, existing, old_children, new_children, None).map(|_| ())
}
#[cfg(feature = "web")]
fn reconcile_range(
el: &Element,
existing_nodes: Vec<WebNode>,
old_children: &[Node],
new_children: &[Node],
anchor: Option<&WebNode>,
) -> Option<Vec<WebNode>> {
let mut old_flat: Vec<&Node> = Vec::new();
flatten_children(old_children, &mut old_flat);
let mut new_flat: Vec<&Node> = Vec::new();
flatten_children(new_children, &mut new_flat);
let mut existing: Vec<Option<WebNode>> = existing_nodes.into_iter().map(Some).collect();
if existing.len() != old_flat.len() {
return None;
}
let mut consumed = vec![false; existing.len()];
let mut placed: Vec<WebNode> = Vec::with_capacity(new_flat.len());
let mut keyed_sources: HashMap<&str, VecDeque<usize>> = HashMap::new();
for (index, old) in old_flat.iter().enumerate() {
if let Some(key) = reconcile_key(old) {
keyed_sources.entry(key).or_default().push_back(index);
}
}
let run_start: Option<WebNode> = existing
.first()
.and_then(|node| node.clone())
.or_else(|| anchor.cloned());
for (target_index, new_child) in new_flat.iter().enumerate() {
let keyed_source = reconcile_key(new_child)
.and_then(|key| keyed_sources.get_mut(key))
.and_then(VecDeque::pop_front);
let source_index = keyed_source.or_else(|| {
let positional = target_index;
let free = positional < consumed.len() && !consumed[positional];
let unkeyed = old_flat
.get(positional)
.is_some_and(|old| reconcile_key(old).is_none());
(free && unkeyed).then_some(positional)
});
match source_index {
Some(source) => {
consumed[source] = true;
let node = existing[source].clone()?;
if patch_dom(el, &node, old_flat[source], new_child).is_none() {
let (replacement, tracked) = create_tracked_child(new_child)?;
remove_region_content(el, &node);
remove_dom_node_closures(&node);
el.replace_child(&replacement, &node).ok()?;
existing[source] = Some(tracked);
}
let node = existing[source].clone()?;
place_before(el, &node, placed.last(), run_start.as_ref());
placed.push(node);
}
None => {
let (created, tracked) = create_tracked_child(new_child)?;
place_before(el, &created, placed.last(), run_start.as_ref());
placed.push(tracked);
}
}
}
for (index, node) in existing.iter().enumerate() {
if consumed[index] {
continue;
}
if let Some(node) = node {
remove_tracked_node(el, node);
}
}
Some(placed)
}
#[cfg(feature = "web")]
fn place_before(
el: &Element,
node: &WebNode,
previous: Option<&WebNode>,
run_start: Option<&WebNode>,
) {
let target = match previous {
Some(previous) => previous.next_sibling(),
None => run_start.cloned().or_else(|| el.first_child()),
};
if target.as_ref() == Some(node) {
return;
}
let _ = el.insert_before(node, target.as_ref());
}
#[cfg(all(feature = "web", target_arch = "wasm32"))]
#[doc(hidden)]
pub fn build_dom_for_test(node: &Node) -> Option<WebNode> {
create_dom_node(node)
}
#[cfg(feature = "web")]
fn create_element_node(document: &web_sys::Document, el: &krab_core::Element) -> Option<WebNode> {
let element = match document.create_element(&el.tag) {
Ok(element) => element,
Err(err) => {
console::error_1(
&format!(
"{{\"scope\":\"create_dom_node\",\"detail\":\"create_element failed\",\"tag\":\"{}\",\"error\":\"{:?}\"}}",
el.tag, err
)
.into(),
);
return Some(document.create_comment("krab-create-element-error").into());
}
};
for attr in &el.attributes {
if let Err(err) = element.set_attribute(&attr.name, &attr.value) {
console::error_1(
&format!(
"{{\"scope\":\"create_dom_node\",\"detail\":\"set_attribute failed\",\"attribute\":\"{}\",\"error\":\"{:?}\"}}",
attr.name, err
)
.into(),
);
}
}
attach_element_events(&element, el, "create_dom_node");
for child in &el.children {
let Some(child_node) = create_dom_node(child) else {
continue;
};
if let Err(err) = element.append_child(&child_node) {
console::error_1(
&format!(
"{{\"scope\":\"create_dom_node\",\"detail\":\"append child failed\",\"error\":\"{err:?}\"}}"
)
.into(),
);
}
}
Some(element.into())
}
#[cfg(feature = "web")]
fn create_dom_node(v_node: &Node) -> Option<WebNode> {
let document = web_sys::window().and_then(|w| w.document())?;
match v_node {
Node::Element(el) => create_element_node(&document, el),
Node::Text(text) => Some(document.create_text_node(text).into()),
Node::Fragment(nodes) => {
let frag = document.create_document_fragment();
for node in nodes {
if let Some(child_node) = create_dom_node(node) {
if let Err(err) = frag.append_child(&child_node) {
console::error_1(
&format!(
"{{\"scope\":\"create_dom_node\",\"detail\":\"append fragment child failed\",\"error\":\"{:?}\"}}",
err
)
.into(),
);
}
}
}
Some(frag.into())
}
Node::Dynamic(f) => {
let anchor: WebNode = document.create_comment("krab-dynamic").into();
let cells = DynamicRegionCells {
rendered: Rc::new(RefCell::new(Vec::new())),
current_vnode: Rc::new(RefCell::new(None)),
anchor: Rc::new(RefCell::new(Some(anchor.clone()))),
empty_position: Rc::new(RefCell::new(None)),
};
register_dynamic_region(&anchor, cells.rendered.clone());
let f = f.clone();
let first_run = Rc::new(Cell::new(true));
let initial_inserts: Rc<RefCell<Vec<WebNode>>> = Rc::new(RefCell::new(Vec::new()));
let effect_cells = DynamicRegionCells {
rendered: cells.rendered.clone(),
current_vnode: cells.current_vnode.clone(),
anchor: cells.anchor.clone(),
empty_position: cells.empty_position.clone(),
};
let inserts_for_effect = initial_inserts.clone();
create_effect(move || {
let new_v_node = f();
if first_run.get() {
first_run.set(false);
let mut inserts = Vec::new();
let mut tracked = Vec::new();
for (insert, track) in create_run_nodes(&new_v_node) {
inserts.push(insert);
tracked.push(track);
}
*inserts_for_effect.borrow_mut() = inserts;
*effect_cells.rendered.borrow_mut() = tracked;
*effect_cells.current_vnode.borrow_mut() = Some(new_v_node);
return;
}
update_dynamic_region(&effect_cells, new_v_node);
});
let container = document.create_document_fragment();
for node in initial_inserts.borrow().iter() {
let _ = container.append_child(node);
}
let _ = container.append_child(&anchor);
Some(container.into())
}
}
}
#[cfg(feature = "web")]
fn create_tracked_child(new_child: &Node) -> Option<(WebNode, WebNode)> {
let created = create_dom_node(new_child)?;
let tracked = if matches!(new_child, Node::Dynamic(_)) {
created.last_child()?
} else {
created.clone()
};
Some((created, tracked))
}
#[cfg(feature = "web")]
fn create_run_nodes(node: &Node) -> Vec<(WebNode, WebNode)> {
let mut flat: Vec<&Node> = Vec::new();
flatten_children(std::slice::from_ref(node), &mut flat);
flat.iter()
.filter_map(|child| create_tracked_child(child))
.collect()
}
#[cfg(feature = "web")]
fn register_dynamic_region(anchor: &WebNode, rendered: Rc<RefCell<Vec<WebNode>>>) {
let id = NEXT_DOM_ID.with(|id| {
let v = id.get();
id.set(v + 1);
v
});
let _ = js_sys::Reflect::set(
anchor.as_ref(),
&JsValue::from_str("__krab_region"),
&JsValue::from_f64(id as f64),
);
DYNAMIC_REGIONS.with(|regions| regions.borrow_mut().insert(id, rendered));
}
#[cfg(feature = "web")]
fn remove_region_content(el: &Element, node: &WebNode) {
let Ok(id_val) = js_sys::Reflect::get(node.as_ref(), &JsValue::from_str("__krab_region"))
else {
return;
};
let Some(id) = id_val.as_f64() else {
return;
};
let Some(rendered) = DYNAMIC_REGIONS.with(|regions| regions.borrow_mut().remove(&(id as u32)))
else {
return;
};
for inner in rendered.borrow().iter() {
remove_tracked_node(el, inner);
}
}
#[cfg(feature = "web")]
fn remove_tracked_node(el: &Element, node: &WebNode) {
remove_region_content(el, node);
remove_dom_node_closures(node);
let _ = el.remove_child(node);
}
#[wasm_bindgen(start)]
pub fn start() {
console::log_1(&"Krab Client initialized".into());
}
#[cfg(test)]
mod tests {
use super::*;
use krab_core::{Attribute, Element, Node};
#[test]
fn boundary_state_from_factory_node_reads_decode_error_marker() {
let fallback = Node::Element(Element {
tag: "div".to_string(),
attributes: vec![Attribute::new(
"data-krab-boundary-state".to_string(),
"decode-error".to_string(),
)],
children: vec![],
events: vec![],
});
assert_eq!(
boundary_state_from_factory_node(&fallback),
Some("decode-error")
);
}
#[test]
fn classify_boundary_state_prefers_factory_error_and_patch_counts() {
assert_eq!(
classify_boundary_state(Some("decode-error"), 3),
"decode-error"
);
assert_eq!(classify_boundary_state(None, 2), "patched");
assert_eq!(classify_boundary_state(None, 0), "ok");
}
}