use super::*;
use crate::live::ManualClock;
use crate::transport::FakeWire;
use crate::tree::{Call, Recording};
use serde_json::json;
use std::rc::Rc;
const BUMP: &str = "fn bump(state, ev) { state.n += 1; state }\n";
const BUMP_TEN: &str = "fn bump(state, ev) { state.n += 10; state }\n";
const NONE: &str = "";
fn tree(name: &str, props: &[&str], state: Value, text: &str, handlers: &str, uses: &[&str]) -> String {
let p = if handlers.is_empty() {
json!({ "el": "p", "children": [ { "text": { "expr": text } } ] })
} else {
json!({ "el": "p", "on": { "click": "bump" }, "children": [ { "text": { "expr": text } } ] })
};
json!({
"name": name, "abi": "engine/1", "props": props, "state": state, "live": {}, "uses": uses,
"handlers": sha256_hex(handlers), "tree": [ p ]
})
.to_string()
}
fn manifest(version: &str, components: &[(&str, &str, &str, &[&str])], files: &mut Files) -> Manifest {
let mut m = Manifest { abi: "engine/1".into(), contract: "unknown".into(), commit: "menger@0000000".into(), ..Manifest::default() };
for (name, tree, handlers, uses) in components {
files.put_version(version, name, tree, handlers);
let entry = ComponentEntry { tree: sha256_hex(tree), handlers: sha256_hex(handlers), uses: uses.iter().map(|u| u.to_string()).collect(), ..ComponentEntry::default() };
m.components.insert(name.to_string(), entry);
}
m
}
fn obj(v: Value) -> Map<String, Value> {
v.as_object().cloned().expect("an object")
}
type TestApp = Rc<App<Recording, FakeWire, ManualClock>>;
fn app() -> (Recording, TestApp) {
let r = Recording::new();
let app = App::new(&Runtime::new(), r.clone(), FakeWire::new(), ManualClock::new());
(r, app)
}
fn touched(r: &Recording, mark: usize) -> Vec<u32> {
r.calls_since(mark).iter().map(Call::node).collect()
}
#[test]
fn a_hot_swap_remounts_only_what_changed_and_keeps_state_of_the_same_shape() {
let (r, app) = app();
let mut files = Files::default();
let a1 = tree("a-one", &["id"], json!({ "n": 0 }), r#""one " + id + ": " + state.n"#, BUMP, &[]);
let b = tree("b-two", &["id"], json!({}), r#""two " + id"#, NONE, &[]);
let v1 = manifest("v1", &[("a-one", &a1, BUMP, &[]), ("b-two", &b, NONE, &[])], &mut files);
app.provide(&files);
app.load("v1", v1);
let a = app.mount(&r.root(), "a-one", obj(json!({ "id": "T-1" }))).expect("a mounts");
let bm = app.mount(&r.root(), "b-two", obj(json!({ "id": "T-9" }))).expect("b mounts");
assert_eq!(r.html(0), "<a-one><p>one T-1: 0</p></a-one><b-two><p>two T-9</p></b-two>");
let p = r.find_tag("p")[0];
r.fire(p, "click", json!({}));
r.fire(p, "click", json!({}));
assert_eq!(app.state_of(a), obj(json!({ "n": 2 })), "two folds ran");
assert_eq!(r.html(0), "<a-one><p>one T-1: 2</p></a-one><b-two><p>two T-9</p></b-two>");
let (a_el, b_nodes) = (app.element_of(a), r.under(app.element_of(bm)));
let at = r.mark();
let a2 = tree("a-one", &["id"], json!({ "n": 0 }), r#""uno " + id + ": " + state.n"#, BUMP, &[]);
let v2 = manifest("v2", &[("a-one", &a2, BUMP, &[]), ("b-two", &b, NONE, &[])], &mut files);
app.provide(&files);
let report = app.swap("v2", v2);
assert_eq!(report, SwapReport { remounted: vec![a], failed: vec![] }, "only a-one's hash changed");
assert_eq!(r.html(0), "<a-one><p>uno T-1: 2</p></a-one><b-two><p>two T-9</p></b-two>", "remounted, its state carried over");
assert_eq!(app.element_of(a), a_el, "into the same element");
assert_eq!(app.props_of(a), obj(json!({ "id": "T-1" })), "with the same props");
assert!(touched(&r, at).iter().all(|n| !b_nodes.contains(n)), "b-two untouched: {:?}", r.calls_since(at));
assert_eq!(app.drawn_from(a).0, "v2");
assert_eq!(app.drawn_from(bm).0, "v1", "b-two still drawn from v1: its hashes did not change");
let a3 = tree("a-one", &["id"], json!({ "n": 0, "extra": "" }), r#""tres " + id + ": " + state.n"#, BUMP, &[]);
let v3 = manifest("v3", &[("a-one", &a3, BUMP, &[]), ("b-two", &b, NONE, &[])], &mut files);
app.provide(&files);
assert_eq!(app.swap("v3", v3).remounted, [a]);
assert_eq!(app.state_of(a), obj(json!({ "n": 0, "extra": "" })), "a new shape starts from its initial state");
assert_eq!(r.html(0), "<a-one><p>tres T-1: 0</p></a-one><b-two><p>two T-9</p></b-two>");
let a4 = tree("a-one", &["id"], json!({ "n": 0, "extra": "" }), r#""tres " + id + ": " + state.n"#, BUMP_TEN, &[]);
let v4 = manifest("v4", &[("a-one", &a4, BUMP_TEN, &[]), ("b-two", &b, NONE, &[])], &mut files);
app.provide(&files);
assert_eq!(app.swap("v4", v4.clone()).remounted, [a]);
r.fire(r.find_tag("p")[0], "click", json!({}));
assert_eq!(r.html(0), "<a-one><p>tres T-1: 10</p></a-one><b-two><p>two T-9</p></b-two>");
let at = r.mark();
assert_eq!(app.swap("v5", v4), SwapReport::default());
assert!(r.calls_since(at).is_empty());
}
#[test]
fn a_failed_mount_keeps_the_last_good_version() {
let (r, app) = app();
let mut files = Files::default();
let a1 = tree("a-one", &["id"], json!({ "n": 0 }), r#""one " + id + ": " + state.n"#, BUMP, &[]);
let v1 = manifest("v1", &[("a-one", &a1, BUMP, &[])], &mut files);
let v1_tree = v1.components["a-one"].tree.clone();
app.provide(&files);
app.load("v1", v1);
let a = app.mount(&r.root(), "a-one", obj(json!({ "id": "T-1" }))).expect("mounts");
r.fire(r.find_tag("p")[0], "click", json!({}));
assert_eq!(r.html(0), "<a-one><p>one T-1: 1</p></a-one>");
let inner = r.under(app.element_of(a));
let at = r.mark();
let broken = r#"{ "name": "a-one", "abi": "engine/1", "tree": [ { "el": "#;
let v2 = manifest("v2", &[("a-one", broken, BUMP, &[])], &mut files);
app.provide(&files);
let report = app.swap("v2", v2);
assert!(report.remounted.is_empty());
assert_eq!(report.failed.len(), 1, "a-one failed: {report:?}");
assert_eq!(report.failed[0].0, a);
assert_eq!(r.html(0), r#"<a-one data-failed="v2"><p>one T-1: 1</p></a-one>"#, "the last good DOM, marked");
assert_eq!(r.under(app.element_of(a)), inner, "the same nodes");
assert!(r.calls_since(at).iter().all(|c| matches!(c, Call::SetAttr { name, .. } if name == "data-failed")), "nothing drawn but the mark: {:?}", r.calls_since(at));
assert_eq!(app.state_of(a), obj(json!({ "n": 1 })));
assert_eq!(app.drawn_from(a), ("v1".to_string(), v1_tree.clone(), sha256_hex(BUMP)), "still v1's");
let said = app.console().join("\n");
assert!(said.contains("a-one") && said.contains("v2"), "the console names the component and the version: {said}");
let sneaky = "fn bump(state, ev) { call(\"tickets.delete\", #{ ids: [ev.props.id] }); state }\n";
let a3 = tree("a-one", &["id"], json!({ "n": 0 }), r#""three " + id"#, sneaky, &["tickets.update"]);
let v3 = manifest("v3", &[("a-one", &a3, sneaky, &["tickets.update"])], &mut files);
app.provide(&files);
let report = app.swap("v3", v3);
assert_eq!(report.failed.len(), 1);
assert!(report.failed[0].1.contains("tickets.delete"), "why names the method: {}", report.failed[0].1);
assert_eq!(r.html(0), r#"<a-one data-failed="v3"><p>one T-1: 1</p></a-one>"#);
r.fire(r.find_tag("p")[0], "click", json!({}));
assert_eq!(r.html(0), r#"<a-one data-failed="v3"><p>one T-1: 2</p></a-one>"#);
let (r, app) = self::app();
let mut files = Files::default();
let v1 = manifest("v1", &[("c-bad", &a3, sneaky, &["tickets.update"])], &mut files);
app.provide(&files);
app.load("v1", v1);
let refused = app.mount(&r.root(), "c-bad", obj(json!({ "id": "T-1" })));
assert!(matches!(&refused, Err(SwapError::Failed { component, message }) if component == "c-bad" && message.contains("tickets.delete")), "{refused:?}");
assert_eq!(r.html(0), r#"<c-bad data-failed="v1"></c-bad>"#, "drawn as failed");
assert!(app.console().join("\n").contains("tickets.delete"));
}
#[test]
fn a_section_mounts_its_assignment_and_remounts_on_slot_changed() {
let (r, app) = app();
let mut files = Files::default();
let layout = json!({
"name": "page-shell", "abi": "engine/1", "props": ["id"], "state": {}, "live": {}, "uses": [],
"handlers": sha256_hex(NONE),
"tree": [
{ "el": "header", "children": [ { "text": "head" } ] },
{ "slot": "main", "props": { "id": { "expr": "id" } } },
{ "slot": "side", "props": { "id": { "expr": "id" } } }
]
})
.to_string();
let hello = tree("hello-card", &["id"], json!({ "n": 0 }), r#""hello " + id"#, BUMP, &[]);
let note = tree("note-card", &["id"], json!({}), r#""note " + id"#, NONE, &[]);
let old_hello = tree("hello-card", &["id"], json!({ "n": 0 }), r#""old hello " + id"#, BUMP, &[]);
let mut v1 = manifest("v1", &[("page-shell", &layout, NONE, &[]), ("hello-card", &hello, BUMP, &[]), ("note-card", ¬e, NONE, &[])], &mut files);
v1.slots.insert("page-shell".into(), BTreeMap::from([("main".to_string(), "hello-card".to_string()), ("side".to_string(), "note-card".to_string())]));
app.provide(&files);
app.load("v1", v1);
app.set_assignments(vec![Assignment { layout: "page-shell".into(), slot: "side".into(), component: "hello-card".into(), version: "v0".into() }]);
app.mount(&r.root(), "page-shell", obj(json!({ "id": "T-1" }))).expect("the layout mounts");
assert_eq!(app.needs(), [("v0".to_string(), "hello-card".to_string())], "the engine asks for v0's hello-card");
assert_eq!(
r.html(0),
concat!(
"<page-shell><header>head</header>",
r#"<div data-layout="page-shell" data-slot="main"><hello-card><p>hello T-1</p></hello-card></div>"#,
r#"<div data-layout="page-shell" data-slot="side"></div>"#,
"</page-shell>"
),
"main: the default; side: waiting on v0's files"
);
let mut fetched = Files::default();
fetched.put_version("v0", "hello-card", &old_hello, BUMP);
app.provide(&fetched);
assert!(app.needs().is_empty(), "nothing more asked");
assert_eq!(
r.html(0),
concat!(
"<page-shell><header>head</header>",
r#"<div data-layout="page-shell" data-slot="main"><hello-card><p>hello T-1</p></hello-card></div>"#,
r#"<div data-layout="page-shell" data-slot="side"><hello-card><p>old hello T-1</p></hello-card></div>"#,
"</page-shell>"
),
"side: its assignment, from v0"
);
let (main, side) = (app.section("page-shell", "main").expect("main"), app.section("page-shell", "side").expect("side"));
assert_eq!(app.drawn_from(side).0, "v0");
assert_eq!(app.drawn_from(main).0, "v1");
assert_eq!(app.props_of(main), obj(json!({ "id": "T-1" })), "the slot's attributes are its props");
let main_div = r.find_attr("data-slot", "main")[0];
let keep: Vec<u32> = r.under(r.find_attr("data-slot", "side")[0]).into_iter().chain(r.find_tag("header")).collect();
let at = r.mark();
app.slot_changed(Assignment { layout: "page-shell".into(), slot: "main".into(), component: "note-card".into(), version: "v1".into() });
assert_eq!(
r.html(0),
concat!(
"<page-shell><header>head</header>",
r#"<div data-layout="page-shell" data-slot="main"><note-card><p>note T-1</p></note-card></div>"#,
r#"<div data-layout="page-shell" data-slot="side"><hello-card><p>old hello T-1</p></hello-card></div>"#,
"</page-shell>"
)
);
assert!(touched(&r, at).iter().all(|n| !keep.contains(n)), "the side and the header untouched: {:?}", r.calls_since(at));
assert_eq!(r.find_attr("data-slot", "main"), [main_div], "the section's element kept");
let now = app.section("page-shell", "main").expect("main");
assert_eq!(app.props_of(now), obj(json!({ "id": "T-1" })), "its props kept");
assert_eq!(app.section("page-shell", "side"), Some(side), "the side instance is the same one");
app.slot_reset("page-shell", "main");
assert!(r.html(0).contains(r#"data-slot="main"><hello-card><p>hello T-1</p></hello-card></div>"#), "{}", r.html(0));
}
#[test]
fn a_child_is_drawn_from_its_parents_version() {
let (r, app) = app();
let told = Rc::new(std::cell::Cell::new(0));
let t2 = told.clone();
app.set_on_need(Rc::new(move || t2.set(t2.get() + 1)));
let mut files = Files::default();
let layout = json!({
"name": "page-shell", "abi": "engine/1", "props": [], "state": {}, "live": {}, "uses": [],
"handlers": sha256_hex(NONE), "tree": [ { "slot": "main", "props": {} }, { "slot": "side", "props": {} } ]
})
.to_string();
let rows = |text: &str| {
json!({
"name": "rows-card", "abi": "engine/1", "props": [], "state": {}, "live": {}, "uses": [], "handlers": sha256_hex(NONE),
"tree": [ { "el": "section", "children": [ { "text": text }, { "component": "tag-chip", "props": { "id": "T-1" } } ] } ]
})
.to_string()
};
let chip = tree("tag-chip", &["id"], json!({}), r#""chip " + id"#, NONE, &[]);
let old_chip = tree("tag-chip", &["id"], json!({}), r#""old chip " + id"#, NONE, &[]);
let mut v1 = manifest("v1", &[("page-shell", &layout, NONE, &[]), ("rows-card", &rows("new"), NONE, &[]), ("tag-chip", &chip, NONE, &[])], &mut files);
v1.slots.insert("page-shell".into(), BTreeMap::from([("main".to_string(), "rows-card".to_string())]));
app.provide(&files);
app.load("v1", v1);
app.set_assignments(vec![Assignment { layout: "page-shell".into(), slot: "side".into(), component: "rows-card".into(), version: "v0".into() }]);
app.mount(&r.root(), "page-shell", Map::new()).expect("the layout mounts");
let mut fetched = Files::default();
fetched.put_version("v0", "rows-card", &rows("old"), NONE);
app.provide(&fetched);
assert_eq!(app.needs(), [("v0".to_string(), "tag-chip".to_string())], "v0's rows-card asks for v0's tag-chip");
assert!(told.get() > 0, "the page is told to fetch it");
let mut more = Files::default();
more.put_version("v0", "tag-chip", &old_chip, NONE);
app.provide(&more);
assert_eq!(
r.html(0),
concat!(
"<page-shell>",
r#"<div data-layout="page-shell" data-slot="main"><rows-card><section>new<tag-chip><p>chip T-1</p></tag-chip></section></rows-card></div>"#,
r#"<div data-layout="page-shell" data-slot="side"><rows-card><section>old<tag-chip><p>old chip T-1</p></tag-chip></section></rows-card></div>"#,
"</page-shell>"
),
"main: the page's rows-card and its tag-chip inline; side: v0's, its tag-chip v0's, one element each"
);
}
#[test]
fn a_child_a_hot_swap_brings_is_drawn() {
let (r, app) = app();
let told = Rc::new(std::cell::Cell::new(0));
let t2 = told.clone();
app.set_on_need(Rc::new(move || t2.set(t2.get() + 1)));
let mut files = Files::default();
let rows = |kids: &[&str]| {
let mut c = vec![json!({ "text": "rows" })];
c.extend(kids.iter().map(|k| json!({ "component": k, "props": { "id": "T-1" } })));
json!({ "name": "rows-card", "abi": "engine/1", "props": [], "state": {}, "live": {}, "uses": [], "handlers": sha256_hex(NONE), "tree": [ { "el": "section", "children": c } ] }).to_string()
};
let chip = tree("tag-chip", &["id"], json!({}), r#""chip " + id"#, NONE, &[]);
let badge = tree("new-badge", &["id"], json!({}), r#""badge " + id"#, NONE, &[]);
let v1 = manifest("v1", &[("rows-card", &rows(&[]), NONE, &[]), ("tag-chip", &chip, NONE, &[])], &mut files);
app.provide(&files);
app.load("v1", v1);
app.mount(&r.root(), "rows-card", Map::new()).expect("rows-card mounts");
assert_eq!(r.html(0), "<rows-card><section>rows</section></rows-card>");
let mut all = Files::default();
let v2 = manifest("v2", &[("rows-card", &rows(&["tag-chip", "new-badge"]), NONE, &[]), ("tag-chip", &chip, NONE, &[]), ("new-badge", &badge, NONE, &[])], &mut all);
let mut changed = Files::default();
changed.put_version("v2", "rows-card", &rows(&["tag-chip", "new-badge"]), NONE);
app.provide(&changed);
let before = told.get();
app.swap("v2", v2);
assert_eq!(app.needs(), [("v2".to_string(), "new-badge".to_string())], "only the new one asked for");
assert!(told.get() > before, "the page is told to fetch it");
assert_eq!(r.html(0), "<rows-card><section>rows<tag-chip><p>chip T-1</p></tag-chip><new-badge></new-badge></section></rows-card>", "the unchanged one at once; the new one waiting");
let mut more = Files::default();
more.put_version("v2", "new-badge", &badge, NONE);
app.provide(&more);
assert_eq!(r.html(0), "<rows-card><section>rows<tag-chip><p>chip T-1</p></tag-chip><new-badge><p>badge T-1</p></new-badge></section></rows-card>", "drawn when it came, in its own element");
}
#[test]
fn a_swap_shares_the_unchanged_files() {
let (r, app) = app();
let mut files = Files::default();
let big = tree("big-card", &["id"], json!({}), &format!("\"{}\" + id", "x".repeat(20_000)), NONE, &[]);
let rows = |n: u32| tree("rows-card", &[], json!({}), &format!("\"rows {n}\""), NONE, &[]);
let v1 = manifest("v1", &[("rows-card", &rows(1), NONE, &[]), ("big-card", &big, NONE, &[])], &mut files);
app.provide(&files);
app.load("v1", v1);
app.mount(&r.root(), "rows-card", Map::new()).expect("mounts");
let start = app.st.borrow().files.kept_bytes();
for n in 2..=4 {
let v = format!("v{n}");
let mut all = Files::default();
let m = manifest(&v, &[("rows-card", &rows(n), NONE, &[]), ("big-card", &big, NONE, &[])], &mut all);
let mut changed = Files::default();
changed.put_version(&v, "rows-card", &rows(n), NONE);
app.provide(&changed);
app.swap(&v, m);
assert!(app.st.borrow().files.version(&v, "big-card").is_some(), "{v} keeps big-card");
}
let grown = app.st.borrow().files.kept_bytes() - start;
assert!(grown < 2_000, "three swaps kept {grown} more bytes: big-card was copied, not shared");
}
#[test]
fn the_menu_lists_live_components_and_other_versions_newest_first() {
let (r, app) = app();
let mut files = Files::default();
let layout = json!({
"name": "page-shell", "abi": "engine/1", "props": [], "state": {}, "live": {}, "uses": [],
"handlers": sha256_hex(NONE), "tree": [ { "slot": "main", "props": {} } ]
})
.to_string();
let hello = tree("hello-card", &[], json!({}), r#""hello""#, NONE, &[]);
let note = tree("note-card", &[], json!({}), r#""note""#, NONE, &[]);
let mut v4 = manifest("v4", &[("page-shell", &layout, NONE, &[]), ("hello-card", &hello, NONE, &[]), ("note-card", ¬e, NONE, &[])], &mut files);
v4.slots.insert("page-shell".into(), BTreeMap::from([("main".to_string(), "hello-card".to_string())]));
app.provide(&files);
app.load("v4", v4.clone());
app.mount(&r.root(), "page-shell", Map::new()).expect("mounts");
let entry = |text: &str| Some(ComponentEntry { tree: sha256_hex(text), handlers: sha256_hex(NONE), uses: vec![], ..ComponentEntry::default() });
let live = v4.components["hello-card"].clone();
let versions = vec![
("v4".to_string(), Some(live.clone())), ("v3".to_string(), Some(live)), ("v2".to_string(), entry("two")),
("v1".to_string(), entry("one")),
("v0".to_string(), None), ];
let menu = app.menu("page-shell", "main", &versions);
assert_eq!(menu.component, "hello-card");
assert_eq!(menu.components, ["hello-card", "note-card", "page-shell"], "the live bundle's components by name");
assert_eq!(menu.versions, ["v2", "v1"], "only differing hashes, newest first, live excluded");
}
#[test]
fn a_declared_prop_not_passed_is_null() {
let (r, app) = app();
let mut files = Files::default();
let t = tree("board-layout", &["filter"], json!({}), r#"if filter == () { "none" } else { filter }"#, NONE, &[]);
let m = manifest("v1", &[("board-layout", &t, NONE, &[])], &mut files);
app.provide(&files);
app.load("v1", m);
let root = r.root();
let id = app.mount(&root, "board-layout", Map::new()).expect("mounted");
assert_eq!(app.props_of(id), obj(json!({ "filter": null })));
assert!(r.html(root).contains("none"), "drawn as none: {}", r.html(root));
let id2 = app.mount(&root, "board-layout", obj(json!({ "filter": "status Ready" }))).expect("mounted");
assert_eq!(app.props_of(id2), obj(json!({ "filter": "status Ready" })));
}
#[test]
fn a_handler_moves_a_lives_params_and_it_re_runs_after_its_debounce() {
let (r, wire, clock) = (Recording::new(), FakeWire::new(), ManualClock::new());
let app = App::new(&Runtime::new(), r.clone(), wire.clone(), clock.clone());
let mut files = Files::default();
let typed = "fn typed(state, ev) { state.q = ev.value; state }\n";
let palette = json!({
"name": "jump-palette", "abi": "engine/1", "props": [], "state": { "q": "" }, "uses": ["tickets.find"],
"live": { "found": { "snapshot": "tickets.find", "params": { "query": { "expr": "state.q" }, "limit": 20 }, "changes_params": {}, "key": "id", "on": {}, "debounce_ms": 80 } },
"handlers": sha256_hex(typed),
"tree": [
{ "el": "input", "on": { "input": "typed" }, "children": [] },
{ "el": "p", "children": [ { "text": { "expr": "found.status" } } ] }
]
})
.to_string();
let v1 = manifest("v1", &[("jump-palette", &palette, typed, &["tickets.find"])], &mut files);
app.provide(&files);
app.load("v1", v1);
app.mount(&r.root(), "jump-palette", Map::new()).expect("mounts");
assert_eq!(wire.opened_of("tickets.find").len(), 1, "the first snapshot at mount");
assert_eq!(wire.opened_of("tickets.find")[0].params, json!({ "query": "", "limit": 20 }));
assert!(wire.opened_of("tickets.watch").is_empty(), "a live without changes: no watch");
wire.answer(wire.last_of("tickets.find"), [json!({ "type": "summary", "summary": { "id": "T-1" } })]);
assert!(r.html(0).contains("<p>live</p>"), "{}", r.html(0));
let input = r.find_tag("input")[0];
r.fire(input, "input", json!({ "value": "kil" }));
clock.advance(30);
r.fire(input, "input", json!({ "value": "kiln" }));
clock.advance(79);
assert_eq!(wire.opened_of("tickets.find").len(), 1, "79 ms after the last keystroke: not yet");
clock.advance(1);
assert_eq!(wire.opened_of("tickets.find").len(), 2, "80 ms after: once");
assert_eq!(wire.opened_of("tickets.find")[1].params, json!({ "query": "kiln", "limit": 20 }), "with the new params");
assert!(r.html(0).contains("<p>resyncing</p>"), "the old rows kept while it runs: {}", r.html(0));
wire.answer(wire.last_of("tickets.find"), []);
assert!(r.html(0).contains("<p>live</p>"));
}
#[test]
fn a_live_held_by_when_asks_nothing_until_it_turns_true() {
let (r, wire, clock) = (Recording::new(), FakeWire::new(), ManualClock::new());
let app = App::new(&Runtime::new(), r.clone(), wire.clone(), clock.clone());
let mut files = Files::default();
let typed = "fn typed(state, ev) { state.q = ev.value; state }\n";
let palette = json!({
"name": "jump-palette", "abi": "engine/1", "props": [], "state": { "q": "" }, "uses": ["tickets.find"],
"live": { "found": { "snapshot": "tickets.find", "params": { "query": { "expr": "state.q" }, "limit": 12 }, "changes_params": {}, "key": "id", "on": {}, "debounce_ms": 80, "when": { "expr": "state.q" } } },
"handlers": sha256_hex(typed),
"tree": [
{ "el": "input", "on": { "input": "typed" }, "children": [] },
{ "el": "p", "children": [ { "text": { "expr": "found.status" } } ] }
]
})
.to_string();
let v1 = manifest("v1", &[("jump-palette", &palette, typed, &["tickets.find"])], &mut files);
app.provide(&files);
app.load("v1", v1);
app.mount(&r.root(), "jump-palette", Map::new()).expect("mounts");
clock.advance(1_000);
assert!(wire.opened_of("tickets.find").is_empty(), "held at mount: no call while state.q is empty");
assert!(wire.opened().is_empty(), "nothing at all asked: {:?}", wire.opened());
assert!(r.html(0).contains("<p>pending</p>"), "drawn, pending: {}", r.html(0));
let input = r.find_tag("input")[0];
r.fire(input, "input", json!({ "value": "k" }));
clock.advance(30);
r.fire(input, "input", json!({ "value": "kiln" }));
clock.advance(79);
assert!(wire.opened_of("tickets.find").is_empty(), "turned true, it waits its debounce like any change: a query typed is one call");
clock.advance(1);
assert_eq!(wire.opened_of("tickets.find").len(), 1, "turned true: one call");
assert_eq!(wire.opened_of("tickets.find")[0].params, json!({ "query": "kiln", "limit": 12 }), "with the params of that moment");
wire.answer(wire.last_of("tickets.find"), [json!({ "type": "summary", "summary": { "id": "T-1" } })]);
assert!(r.html(0).contains("<p>live</p>"), "{}", r.html(0));
r.fire(input, "input", json!({ "value": "" }));
clock.advance(1_000);
assert_eq!(wire.opened_of("tickets.find").len(), 1, "false again: nothing more asked");
r.fire(input, "input", json!({ "value": "glaze" }));
clock.advance(80);
assert_eq!(wire.opened_of("tickets.find").len(), 2, "true again: it runs again");
assert_eq!(wire.opened_of("tickets.find")[1].params, json!({ "query": "glaze", "limit": 12 }));
}
fn styled(name: &str, text: &str, mark: &str) -> String {
let mut t: Value = serde_json::from_str(&tree(name, &["id"], json!({}), text, NONE, &[])).unwrap();
t["css"] = json!(mark);
t.to_string()
}
fn styled_manifest(version: &str, components: &[(&str, &str)], files: &mut Files) -> Manifest {
let all: Vec<(&str, &str, &str, &[&str])> = components.iter().map(|(n, t)| (*n, *t, NONE, &[][..])).collect();
let m = manifest(version, &all, files);
for (name, tree) in components {
if let Some(mark) = serde_json::from_str::<Value>(tree).unwrap()["css"].as_str() {
files.put_sheet(version, name, &format!("{name}[data-css=\"{mark}\"] p {{ padding: 1px }}"));
}
}
m
}
fn key(name: &str, mark: &str) -> String {
format!("{name}@{}", sha256_hex(&format!("{name}[data-css=\"{mark}\"] p {{ padding: 1px }}")))
}
fn sheets_of(r: &Recording, mark: usize) -> Vec<(String, bool)> {
r.calls_since(mark).into_iter().filter_map(|c| if let Call::Sheet { key, on } = c { Some((key, on)) } else { None }).collect()
}
#[test]
fn a_sheet_lands_with_the_first_mount_and_goes_with_the_last() {
let (r, app) = app();
let mut files = Files::default();
let row = styled("s-row", r#""row " + id"#, "aaaa0001");
let plain = tree("p-row", &["id"], json!({}), r#""plain " + id"#, NONE, &[]);
let v1 = styled_manifest("v1", &[("s-row", &row), ("p-row", &plain)], &mut files);
app.provide(&files);
app.load("v1", v1);
let at = r.mark();
let a = app.mount(&r.root(), "s-row", obj(json!({ "id": "A" }))).unwrap();
let calls = r.calls_since(at);
let sheet_at = calls.iter().position(|c| matches!(c, Call::Sheet { on: true, .. })).expect("the sheet is adopted");
let p_at = calls.iter().position(|c| matches!(c, Call::Create { tag, .. } if tag == "p")).expect("the row is drawn");
assert!(sheet_at < p_at, "the sheet before the draw: {calls:?}");
assert_eq!(sheets_of(&r, at), [(key("s-row", "aaaa0001"), true)]);
assert_eq!(r.html(0), r#"<s-row data-css="aaaa0001"><p>row A</p></s-row>"#, "the element carries the mark");
let b = app.mount(&r.root(), "s-row", obj(json!({ "id": "B" }))).unwrap();
let at = r.mark();
app.mount(&r.root(), "p-row", obj(json!({ "id": "C" }))).unwrap();
assert!(sheets_of(&r, at).is_empty(), "no <style>, no sheet");
assert_eq!(app.sheets(), BTreeMap::from([(key("s-row", "aaaa0001"), 2)]), "one sheet, two instances");
let at = r.mark();
app.unmount(a);
assert!(sheets_of(&r, at).is_empty(), "another instance holds it");
app.unmount(b);
assert_eq!(sheets_of(&r, at), [(key("s-row", "aaaa0001"), false)], "the last instance drops it");
assert!(app.sheets().is_empty());
}
#[test]
fn a_hot_swap_trades_the_sheet_and_two_versions_carry_two() {
let (r, app) = app();
let mut files = Files::default();
let v1 = styled_manifest("v1", &[("s-row", &styled("s-row", r#""row " + id"#, "aaaa0001"))], &mut files);
app.provide(&files);
app.load("v1", v1);
app.mount(&r.root(), "s-row", obj(json!({ "id": "A" }))).unwrap();
let mut files = Files::default();
let v2 = styled_manifest("v2", &[("s-row", &styled("s-row", r#""row " + id"#, "bbbb0002"))], &mut files);
app.provide(&files);
let at = r.mark();
let report = app.swap("v2", v2);
assert_eq!(report.remounted.len(), 1, "a changed sheet is a changed tree: {report:?}");
assert_eq!(sheets_of(&r, at), [(key("s-row", "bbbb0002"), true), (key("s-row", "aaaa0001"), false)], "adopted, then dropped");
assert_eq!(r.html(0), r#"<s-row data-css="bbbb0002"><p>row A</p></s-row>"#);
let (r, app) = self::app();
let mut files = Files::default();
let layout = json!({
"name": "two-up", "abi": "engine/1", "props": [], "state": {}, "live": {}, "uses": [], "handlers": sha256_hex(NONE),
"tree": [ { "slot": "left", "props": {} }, { "slot": "right", "props": {} } ]
})
.to_string();
let mut m = styled_manifest("v2", &[("two-up", &layout), ("s-row", &styled("s-row", r#""new""#, "bbbb0002"))], &mut files);
m.slots.insert("two-up".into(), BTreeMap::from([("left".to_string(), "s-row".to_string()), ("right".to_string(), "s-row".to_string())]));
files.put_version("v1", "s-row", &styled("s-row", r#""old""#, "aaaa0001"), NONE);
files.put_sheet("v1", "s-row", "s-row[data-css=\"aaaa0001\"] p { padding: 1px }");
app.provide(&files);
app.load("v2", m);
app.set_assignments(vec![Assignment { layout: "two-up".into(), slot: "right".into(), component: "s-row".into(), version: "v1".into() }]);
app.mount(&r.root(), "two-up", Map::new()).unwrap();
assert_eq!(app.sheets(), BTreeMap::from([(key("s-row", "aaaa0001"), 1), (key("s-row", "bbbb0002"), 1)]), "two versions, two sheets");
assert!(r.html(0).contains(r#"<s-row data-css="aaaa0001"><p>old</p></s-row>"#) && r.html(0).contains(r#"<s-row data-css="bbbb0002"><p>new</p></s-row>"#), "{}", r.html(0));
let (r, app) = self::app();
let mut files = Files::default();
let m = manifest("v1", &[("s-row", &styled("s-row", r#""bare""#, "cccc0003"), NONE, &[])], &mut files);
app.provide(&files);
app.load("v1", m);
app.mount(&r.root(), "s-row", Map::new()).unwrap();
assert!(app.sheets().is_empty() && app.console().iter().any(|l| l.contains("none was fetched")), "{:?}", app.console());
}
#[test]
fn a_modules_sheet_is_its_entrys_and_a_change_swaps_it() {
let one = ComponentEntry { profile: "svelte/1".into(), module: "m1".into(), css: "c1".into(), ..ComponentEntry::default() };
let two = ComponentEntry { css: "c2".into(), ..one.clone() };
assert_ne!(one.hashes(), two.hashes(), "a sheet changed is a module changed");
let m = Manifest::parse(r#"{ "components": { "a-b": { "profile": "svelte/1", "module": "m1", "css": "c1", "uses": [] }, "c-d": { "tree": "t", "handlers": "h", "uses": [] } } }"#).unwrap();
assert_eq!(m.components["a-b"], one);
assert_eq!(m.components["c-d"].css, "", "no css, none");
}
fn keyed(name: &str, handlers: &str) -> String {
let mut t: Value = serde_json::from_str(&tree(name, &[], json!({ "n": 0 }), r#""n " + state.n"#, handlers, &[])).unwrap();
t["keys"] = json!({ "j": { "to": "bump" }, "g b": { "to": "bump", "label": "go" } });
t.to_string()
}
fn pressed(chord: &str, at_ms: u64) -> crate::keys::Press {
crate::keys::Press { chord: chord.into(), key: chord.into(), editable: false, activatable: false, repeat: false, target: Value::Null, at_ms }
}
#[test]
fn an_rhx_components_keys_run_its_folds_and_go_with_it() {
let (r, app) = app();
let mut files = Files::default();
let t1 = keyed("k-one", BUMP);
let v1 = manifest("v1", &[("k-one", &t1, BUMP, &[])], &mut files);
app.provide(&files);
app.load("v1", v1);
let id = app.mount(&r.root(), "k-one", Map::new()).expect("it mounts");
assert!(app.press(&pressed("j", 0)), "a bound key is the host's");
assert!(!app.press(&pressed("x", 0)), "an unbound one is not");
assert!(app.press(&pressed("g", 100)) && app.press(&pressed("b", 500)), "a sequence");
assert_eq!(app.state_of(id), obj(json!({ "n": 2 })));
assert_eq!(app.bus().keys().groups(), vec![("k-one".to_string(), vec![("g b".to_string(), "go".to_string()), ("j".to_string(), "bump".to_string())])]);
let t2 = keyed("k-one", BUMP_TEN);
let v2 = manifest("v2", &[("k-one", &t2, BUMP_TEN, &[])], &mut files);
app.provide(&files);
app.swap("v2", v2);
assert_eq!(app.bus().keys().len(), 2, "the old version's keys went with it");
assert!(app.press(&pressed("j", 2_000)));
assert_eq!(app.state_of(id), obj(json!({ "n": 12 })), "the new fold, once");
app.unmount(id);
assert!(app.bus().keys().is_empty());
assert!(!app.press(&pressed("j", 3_000)), "gone with the component: the browser's again");
}