htui 0.2.0

A terminal HTML/CSS renderer with an embedded JavaScript engine — build interactive TUIs from HTML, CSS and JS
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
//! Tests for `el.classList` (live DOMTokenList): token reads / writes,
//! browser token semantics (order preservation, empty / whitespace rejection),
//! liveness and dirty tracking. Pure in-memory — no terminal required.

use htui::events::EventBindings;
use htui::script::ScriptEngine;
use htui::tdom::node::{NodeArena, NodeId};

/// Evaluate `String(expr)` and return its text.
fn eval_str(engine: &mut ScriptEngine, expr: &str) -> String {
    let v = engine
        .eval_source(&format!("String({expr})"))
        .expect("eval must succeed");
    v.as_string()
        .map(|s| s.to_std_string_lossy())
        .unwrap_or_default()
}

/// `NodeId` of the element whose `id` attribute equals `id`.
fn find_node_by_id(arena: &NodeArena, id: &str) -> NodeId {
    arena
        .iter()
        .find(|(_, n)| n.attributes.get("id").map(String::as_str) == Some(id))
        .map(|(nid, _)| nid)
        .expect("element with id exists")
}

/// The element's `className`, read from the live arena after JS ran.
fn class_name(engine: &ScriptEngine, id: &str) -> String {
    let arena = engine.arena();
    let node = find_node_by_id(&arena, id);
    arena
        .get(node)
        .and_then(|n| n.attributes.get("class").cloned())
        .unwrap_or_default()
}

// ============================================================
// Basic reads
// ============================================================

#[test]
fn class_list_reads_the_class_attribute() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b c"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.length"),
        "3"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.item(1)"
        ),
        "b"
    );
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList[2]"),
        "c"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.contains('a')"
        ),
        "true"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.contains('x')"
        ),
        "false"
    );
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.value"),
        "a b c",
        "classList.value mirrors className"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "String(document.getElementById('d').classList)"
        ),
        "a b c",
        "String(classList) is the attribute value"
    );
}

#[test]
fn class_list_empty_when_no_class() {
    let mut engine = ScriptEngine::new(r#"<div id="d"></div>"#, "", EventBindings::default())
        .expect("engine initializes");
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.length"),
        "0"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.contains('x')"
        ),
        "false"
    );
}

// ============================================================
// add / remove
// ============================================================

#[test]
fn class_list_add_appends_and_preserves_order() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    eval_str(
        &mut engine,
        "(function(){ var l = document.getElementById('d').classList; l.add('x', 'y'); l.add('a'); })()",
    );
    // New tokens append at the end; an existing token is not duplicated.
    assert_eq!(class_name(&engine, "d"), "a b x y");
    // The change is visible in the live token list.
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.length"),
        "4"
    );
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList[3]"),
        "y"
    );
}

#[test]
fn class_list_remove_preserves_relative_order() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b c d"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    eval_str(
        &mut engine,
        "(function(){ var l = document.getElementById('d').classList; l.remove('b', 'a', 'zz'); })()",
    );
    assert_eq!(
        class_name(&engine, "d"),
        "c d",
        "remaining tokens keep their order"
    );
    // Removing everything empties the class attribute.
    eval_str(
        &mut engine,
        "(function(){ var l = document.getElementById('d').classList; l.remove('c', 'd'); })()",
    );
    assert_eq!(class_name(&engine, "d"), "");
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.length"),
        "0"
    );
}

#[test]
fn class_list_add_unchanged_token_does_not_mark_dirty() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    // Adding an already-present token changes nothing: no re-render.
    eval_str(
        &mut engine,
        "(function(){ document.getElementById('d').classList.add('a'); })()",
    );
    let dirty = engine.take_dirty();
    assert!(
        dirty.is_empty(),
        "no-op add must not schedule a re-render: {dirty:?}"
    );
}

// ============================================================
// toggle / replace
// ============================================================

#[test]
fn class_list_toggle_returns_the_new_state() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.toggle('a')"
        ),
        "false"
    );
    assert_eq!(class_name(&engine, "d"), "b");
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.toggle('a')"
        ),
        "true"
    );
    assert_eq!(class_name(&engine, "d"), "b a", "toggled-on token appends");
    // Forced states never flip the opposite way and report the forced value.
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.toggle('b', true)"
        ),
        "true"
    );
    assert_eq!(class_name(&engine, "d"), "b a");
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.toggle('a', false)"
        ),
        "false"
    );
    assert_eq!(class_name(&engine, "d"), "b");
}

#[test]
fn class_list_replace_swaps_a_present_token() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.replace('a', 'z')"
        ),
        "true"
    );
    assert_eq!(class_name(&engine, "d"), "b z");
    // Replacing an absent token is a no-op returning false.
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList.replace('nope', 'q')"
        ),
        "false"
    );
    assert_eq!(class_name(&engine, "d"), "b z");
}

// ============================================================
// value / iteration
// ============================================================

#[test]
fn class_list_value_setter_replaces_all_tokens() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    eval_str(
        &mut engine,
        "(function(){ document.getElementById('d').classList.value = 'x y'; })()",
    );
    assert_eq!(class_name(&engine, "d"), "x y");
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.length"),
        "2"
    );
}

#[test]
fn class_list_is_iterable() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a b c"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    assert_eq!(
        eval_str(
            &mut engine,
            "[...document.getElementById('d').classList].join(',')"
        ),
        "a,b,c"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "Array.from(document.getElementById('d').classList).join('|')"
        ),
        "a|b|c"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "Array.from(document.getElementById('d').classList.keys()).join(',')"
        ),
        "0,1,2"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "Array.from(document.getElementById('d').classList.values()).join(',')"
        ),
        "a,b,c"
    );
    assert_eq!(
        eval_str(
            &mut engine,
            "Array.from(document.getElementById('d').classList.entries()).map(function (e) { return e[0] + ':' + e[1]; }).join(',')"
        ),
        "0:a,1:b,2:c"
    );
    // forEach passes (token, index, list).
    assert_eq!(
        eval_str(
            &mut engine,
            "(function () { var out = []; document.getElementById('d').classList.forEach(function (t, i) { out.push(i + '=' + t); }); return out.join(','); })()"
        ),
        "0=a,1=b,2=c"
    );
}

// ============================================================
// liveness
// ============================================================

#[test]
fn class_list_is_live_across_attribute_changes() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    let held = eval_str(
        &mut engine,
        "(function () {
          var el = document.getElementById('d');
          var list = el.classList;               // held reference
          el.className = 'x y';                   // className rewrite
          var afterClassName = list.length;       // must see the new tokens
          el.setAttribute('class', 'p q');        // setAttribute rewrite
          var afterAttr = list.contains('p');
          return afterClassName + ':' + afterAttr;
        })()",
    );
    assert_eq!(
        held, "2:true",
        "held classList must reflect later attribute writes"
    );
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').classList.value"),
        "p q"
    );
}

#[test]
fn class_list_mutations_are_visible_to_inner_html() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d"><p id="p" class="a"></p></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    eval_str(
        &mut engine,
        "(function(){ document.getElementById('p').classList.add('hot', 'b'); })()",
    );
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('d').innerHTML"),
        r#"<p id="p" class="a hot b"></p>"#,
        "classList changes appear in serialization in token order"
    );
}

// ============================================================
// token validation
// ============================================================

#[test]
fn class_list_rejects_empty_and_whitespace_tokens() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    // Empty tokens throw SyntaxError across the API surface.
    for expr in [
        "document.getElementById('d').classList.add('')",
        "document.getElementById('d').classList.remove('')",
        "document.getElementById('d').classList.toggle('')",
        "document.getElementById('d').classList.contains('')",
        "document.getElementById('d').classList.replace('', 'x')",
        "document.getElementById('d').classList.replace('x', '')",
    ] {
        let name = eval_str(
            &mut engine,
            &format!(
                "(function () {{ try {{ {expr}; return 'no-throw'; }} catch (e) {{ return e.name; }} }})()"
            ),
        );
        assert_eq!(name, "SyntaxError", "{expr} must throw");
    }
    // Whitespace inside a token is also rejected.
    assert_eq!(
        eval_str(
            &mut engine,
            "(function () { try { document.getElementById('d').classList.add('a b'); return 'no-throw'; } catch (e) { return e.name; } })()"
        ),
        "SyntaxError"
    );
    // A rejected batch leaves the class untouched.
    assert_eq!(class_name(&engine, "d"), "a");
}

// ============================================================
// dirty tracking
// ============================================================

#[test]
fn class_list_changes_mark_the_element_dirty() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    eval_str(
        &mut engine,
        "(function(){ document.getElementById('d').classList.add('b'); })()",
    );
    let dirty = engine.take_dirty();
    let arena = engine.arena();
    let d = find_node_by_id(&arena, "d");
    assert!(
        dirty.nodes.contains(&d),
        "a real classList change must be reported for re-render: {dirty:?}"
    );
}

#[test]
fn class_list_access_returns_the_same_live_instance() {
    let mut engine = ScriptEngine::new(
        r#"<div id="d" class="a"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine initializes");
    assert_eq!(
        eval_str(
            &mut engine,
            "document.getElementById('d').classList === document.getElementById('d').classList"
        ),
        "true",
        "repeated access returns the same instance (browser identity)"
    );
    // A held reference keeps tracking attribute changes made through other
    // paths (the cached instance is the live view, not a snapshot).
    eval_str(
        &mut engine,
        "globalThis.cl = document.getElementById('d').classList",
    );
    eval_str(
        &mut engine,
        "document.getElementById('d').className = 'a b'",
    );
    assert_eq!(
        eval_str(&mut engine, "globalThis.cl.contains('b')"),
        "true",
        "the cached instance must stay live"
    );
}