plexus-ui-engine 0.4.1

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! UI-6's testing surface: hot-swap, the last good version, the sections,
//! the section menu.

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 = "";

/// A compiled tree for `name`: one `p` (clicks go to `bump` when it has
/// handlers) whose text is `text`, a Rhai expression; `state` its declared
/// state; `uses` its methods.
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()
}

/// Version `version`'s manifest of `components` — `(name, tree, handlers,
/// uses)` — each component's files kept in `files` under that version.
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)
}

/// The nodes a call since `mark` made or changed.
fn touched(r: &Recording, mark: usize) -> Vec<u32> {
    r.calls_since(mark).iter().map(Call::node).collect()
}

/// Two components mounted; a new manifest changes one's tree hash: that
/// one remounts into its element with the same props and its state (the
/// same shape); the other is not touched. A state of another shape starts
/// anew; a handlers-only change remounts too.
#[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");

    // Another shape: the new initial state.
    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>");

    // Only the handlers changed: remounted; the new fold runs.
    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>");

    // The same hashes again: nothing.
    let at = r.mark();
    assert_eq!(app.swap("v5", v4), SwapReport::default());
    assert!(r.calls_since(at).is_empty());
}

/// The new tree is malformed: the old DOM stays, its state and nodes as
/// they were, the element carries `data-failed` with the version that
/// failed, and the console names the component and the version; handlers
/// refused (a call outside `uses`) likewise. At first mount, a refused
/// component is drawn as failed and the console names the method.
#[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}");

    // Handlers that call outside `uses`: refused, the old kept.
    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>"#);
    // Still live on its last good: its fold runs.
    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>"#);

    // At first mount: drawn as failed, the console naming the method.
    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"));
}

/// A layout with two sections: `main` takes the manifest's default, `side`
/// is assigned a component of another version — the engine asks for that
/// version's files (`needs`), and draws it when they come; `slot_changed`
/// for `main` remounts it alone, in its element, its props kept.
#[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", &note, 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");

    // Cleared: back to the default.
    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));
}

/// STUDIO-9: a component pinned to another version than the page's places
/// its children of that version — a section's v0 `rows-card` placing
/// `tag-chip` draws v0's `tag-chip` in the child's own element (one
/// element, as inline), asked for as any section's component and drawn when
/// it comes, the page told to fetch it; the page's own `rows-card` places
/// the page's `tag-chip` inline, as ever.
#[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"
    );
}

/// STUDIO-9: a hot-swap where a changed parent now places a child — an
/// unchanged one is the old version's files under the new one, drawn at
/// once; a new one the page has not fetched waits for its files in its own
/// element, the page told, and is drawn when they come (one element).
#[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>");

    // v2: rows-card places tag-chip (unchanged) and new-badge (new); only
    // rows-card's files fetched, as the page fetches what changed.
    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");
}

/// STUDIO-9's second look: a swap keeps the unchanged components under the
/// new version by sharing their text — a session of authors (a drop, an
/// undo, a redo…) does not keep a copy of the bundle per swap.
#[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");
}

/// The section menu: the live bundle's components by name; for the
/// section's component, only the stored versions whose hash for it differs
/// from the live one's, newest first, the live one excluded.
#[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", &note, 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())),  // the live one
        ("v3".to_string(), Some(live)),          // the same hash as live
        ("v2".to_string(), entry("two")),
        ("v1".to_string(), entry("one")),
        ("v0".to_string(), None),                // no hello-card in it
    ];
    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");
}

/// UI-8: a declared prop the mount does not pass is there as null — the
/// route `#/` gives `board-layout` no `filter`, and its expressions read
/// `filter == ()` rather than fail on a name not found.
#[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" })));
}

/// A component whose `live` reads `state.q` with `debounce_ms: 80`, and a
/// handler that sets `state.q`: typing runs the snapshot again once, 80 ms
/// after, with the new params — through eval_params and the wiring.
#[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>"));
}

/// FRAME-16: a `live` whose `when` reads `state.q` asks nothing while it is
/// empty — the palette's `find` at boot — and runs once it turns true, after
/// its debounce, with the params of that moment; turned false again, nothing more is asked
/// however the params move; true again, it runs again.
#[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 }));
}

// ── FRAME-30: a component's sheet, adopted ────────────────────────────────

/// [`tree`] with a sheet: its mark `mark`.
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()
}

/// [`manifest`], each styled component's sheet's text kept too.
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
}

/// The key a sheet is adopted by: the component and its text's sha256.
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()
}

/// A styled component's sheet is adopted before it is drawn — once for
/// every instance of it — its element carries the mark, and the sheet is
/// dropped with the last instance; an unstyled one adopts nothing.
#[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());
}

/// A push whose sheet changed trades it: the new sheet adopted before the
/// old is dropped, the mark moved; two versions of one component whose
/// sheets differ carry two sheets.
#[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>"#);

    // v1's again in a section beside v2's: two sheets.
    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));

    // A tree that names a sheet whose text never came: drawn, without it, said.
    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());
}

/// A module's sheet: named by its entry's `css`, a change to it alone swaps
/// the module.
#[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");
}

/// FRAME-36: a tree with `keys`, its fold `bump` on `j` and on `g b`.
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 }
}

/// FRAME-36: an rhx component's keys run its folds while it is mounted, a
/// hot swap carries them to the new version (once), and they go with it.
#[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())])]);

    // A swap of its handlers: the new version's keys, once.
    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");
}