rdom-tui 0.5.0

Terminal rendering layer for rdom-core — flexbox layout, TUI styles, key/mouse events. Use rdom-core directly for headless DOM manipulation.
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
//! `<input type="checkbox">` + `<input type="radio">` default
//! action tests.

use crossterm::event::{
    Event as CtEvent, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers, MouseButton,
    MouseEvent as CtMouseEvent, MouseEventKind,
};
use rdom_core::{ListenerOptions, NodeId};
use std::cell::Cell;
use std::cell::RefCell;
use std::rc::Rc;

use crate::TuiDom;
use crate::layout::Size;
use crate::render::{Terminal, TestBackend};
use crate::runtime::app::App;
use crate::style::{Stylesheet, TuiStyle};

fn test_app(dom: TuiDom, sheet: Stylesheet) -> App<TestBackend> {
    let backend = TestBackend::new(40, 5);
    let terminal = Terminal::new(backend).unwrap();
    App::with_backend(dom, sheet, terminal).unwrap()
}

fn click_at(app: &mut App<TestBackend>, x: u16, y: u16) {
    for kind in [
        MouseEventKind::Down(MouseButton::Left),
        MouseEventKind::Up(MouseButton::Left),
    ] {
        app.handle_event(CtEvent::Mouse(CtMouseEvent {
            kind,
            column: x,
            row: y,
            modifiers: KeyModifiers::empty(),
        }));
    }
}

fn key_press(code: KeyCode, modifiers: KeyModifiers) -> CtEvent {
    CtEvent::Key(KeyEvent {
        code,
        modifiers,
        kind: KeyEventKind::Press,
        state: KeyEventState::empty(),
    })
}

/// Build a `<input type="checkbox">` parented under root, with a UA
/// stylesheet overridden to give the widget a fixed (10×1) size for
/// predictable click coordinates.
fn checkbox_app() -> (App<TestBackend>, NodeId) {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let cb = dom.create_element("input");
    dom.set_attribute(cb, "type", "checkbox").unwrap();
    dom.append_child(root, cb).unwrap();

    let sheet = Stylesheet::new().rule_unchecked(
        "input[type=checkbox]",
        TuiStyle::new()
            .width(Size::Fixed(10))
            .height(Size::Fixed(1)),
    );
    let app = test_app(dom, sheet);
    (app, cb)
}

/// Build a radio group: three radios with `name="g"`. Returns
/// (app, [r1, r2, r3]).
fn radio_group_app() -> (App<TestBackend>, [NodeId; 3]) {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let make = |dom: &mut TuiDom, i: usize| {
        let r = dom.create_element("input");
        dom.set_attribute(r, "type", "radio").unwrap();
        dom.set_attribute(r, "name", "g").unwrap();
        dom.set_attribute(r, "id", &format!("r{}", i)).unwrap();
        dom.append_child(root, r).unwrap();
        r
    };
    let ids = [make(&mut dom, 0), make(&mut dom, 1), make(&mut dom, 2)];
    let sheet = Stylesheet::new().rule_unchecked(
        "input[type=radio]",
        TuiStyle::new()
            .width(Size::Fixed(10))
            .height(Size::Fixed(1)),
    );
    let app = test_app(dom, sheet);
    (app, ids)
}

// ── Checkbox: click toggles ───────────────────────────────────────

#[test]
fn click_on_checkbox_toggles_checked_attribute() {
    let (mut app, cb) = checkbox_app();
    app.draw_if_dirty().unwrap();
    assert!(!app.dom().node(cb).has_attribute("checked"));

    click_at(&mut app, 1, 0);
    assert!(app.dom().node(cb).has_attribute("checked"));

    click_at(&mut app, 1, 0);
    assert!(!app.dom().node(cb).has_attribute("checked"));
}

#[test]
fn click_on_checkbox_fires_input_then_change() {
    let (mut app, cb) = checkbox_app();
    let order = Rc::new(RefCell::new(Vec::<&'static str>::new()));
    for ty in ["input", "change"] {
        let o = order.clone();
        app.dom_mut()
            .add_event_listener(cb, ty, ListenerOptions::default(), move |_| {
                o.borrow_mut().push(ty);
            })
            .unwrap();
    }
    app.draw_if_dirty().unwrap();
    click_at(&mut app, 1, 0);

    assert_eq!(*order.borrow(), vec!["input", "change"]);
}

#[test]
fn prevent_default_on_click_blocks_checkbox_toggle() {
    let (mut app, cb) = checkbox_app();
    app.dom_mut()
        .add_event_listener(cb, "click", ListenerOptions::default(), |ctx| {
            ctx.event.prevent_default();
        })
        .unwrap();
    app.draw_if_dirty().unwrap();
    click_at(&mut app, 1, 0);
    assert!(!app.dom().node(cb).has_attribute("checked"));
}

#[test]
fn disabled_checkbox_does_not_toggle_on_click() {
    let (mut app, cb) = checkbox_app();
    app.dom_mut().set_attribute(cb, "disabled", "").unwrap();
    app.draw_if_dirty().unwrap();
    click_at(&mut app, 1, 0);
    assert!(!app.dom().node(cb).has_attribute("checked"));
}

/// P7-FIELDSET-DISABLED-1: a checkbox inside a `<fieldset disabled>` is
/// disabled (HTML §4.10.18.5) and a click does not toggle it; one inside
/// the fieldset's first `<legend>` does toggle.
#[test]
fn checkbox_in_a_disabled_fieldset_does_not_toggle_but_one_in_its_legend_does() {
    use crate::accessors::TuiAccessorsMut;
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let fs = dom.create_element("fieldset");
    dom.set_attribute(fs, "disabled", "").unwrap();
    dom.append_child(root, fs).unwrap();
    let legend = dom.create_element("legend");
    dom.append_child(fs, legend).unwrap();
    let in_legend = dom.create_element("input");
    dom.set_attribute(in_legend, "type", "checkbox").unwrap();
    dom.append_child(legend, in_legend).unwrap();
    let inside = dom.create_element("input");
    dom.set_attribute(inside, "type", "checkbox").unwrap();
    dom.append_child(fs, inside).unwrap();
    let mut app = test_app(dom, Stylesheet::new());
    app.draw_if_dirty().unwrap();

    app.dom_mut().node_mut(inside).click();
    assert!(!app.dom().node(inside).has_attribute("checked"));
    app.dom_mut().node_mut(in_legend).click();
    assert!(app.dom().node(in_legend).has_attribute("checked"));
}

#[test]
fn initially_checked_checkbox_unchecks_on_click() {
    let (mut app, cb) = checkbox_app();
    app.dom_mut().set_attribute(cb, "checked", "").unwrap();
    app.draw_if_dirty().unwrap();
    click_at(&mut app, 1, 0);
    assert!(!app.dom().node(cb).has_attribute("checked"));
}

// ── Checkbox: Space activates ─────────────────────────────────────

#[test]
fn space_on_focused_checkbox_toggles() {
    let (mut app, cb) = checkbox_app();
    app.dom_mut().set_focused(Some(cb));
    app.handle_event(key_press(KeyCode::Char(' '), KeyModifiers::empty()));
    assert!(app.dom().node(cb).has_attribute("checked"));
}

#[test]
fn enter_on_focused_checkbox_does_not_toggle() {
    // Per HTML, Enter on a checkbox does NOT toggle (it submits the
    // surrounding form, when one exists). Enter activation is
    // button-only. C.4c will wire up the form-submit redirect.
    let (mut app, cb) = checkbox_app();
    app.dom_mut().set_focused(Some(cb));
    app.handle_event(key_press(KeyCode::Enter, KeyModifiers::empty()));
    assert!(!app.dom().node(cb).has_attribute("checked"));
}

#[test]
fn ctrl_space_does_not_toggle_checkbox() {
    let (mut app, cb) = checkbox_app();
    app.dom_mut().set_focused(Some(cb));
    app.handle_event(key_press(KeyCode::Char(' '), KeyModifiers::CONTROL));
    assert!(!app.dom().node(cb).has_attribute("checked"));
}

// ── Radio: click selects + sibling unchecking ─────────────────────

#[test]
fn click_on_radio_checks_it_and_unchecks_siblings() {
    // Drive r2's selection via the focused-Space activation path
    // — equivalent to a click on r2, but layout-independent so the
    // test isn't sensitive to inline / block flow nuances.
    let (mut app, [r1, r2, r3]) = radio_group_app();
    app.dom_mut().set_attribute(r1, "checked", "").unwrap();
    app.dom_mut().set_focused(Some(r2));
    app.handle_event(key_press(KeyCode::Char(' '), KeyModifiers::empty()));

    assert!(!app.dom().node(r1).has_attribute("checked"));
    assert!(app.dom().node(r2).has_attribute("checked"));
    assert!(!app.dom().node(r3).has_attribute("checked"));
}

#[test]
fn re_clicking_already_checked_radio_is_noop() {
    let (mut app, [r1, _r2, _r3]) = radio_group_app();
    app.dom_mut().set_attribute(r1, "checked", "").unwrap();
    let fired = Rc::new(Cell::new(0u32));
    let f = fired.clone();
    app.dom_mut()
        .add_event_listener(r1, "change", ListenerOptions::default(), move |_| {
            f.set(f.get() + 1);
        })
        .unwrap();
    app.draw_if_dirty().unwrap();

    click_at(&mut app, 1, 0);

    assert!(app.dom().node(r1).has_attribute("checked"));
    assert_eq!(fired.get(), 0, "no change event when state didn't change");
}

#[test]
fn radio_groups_with_different_names_are_independent() {
    let (mut app, [r1, _, _]) = radio_group_app();
    let r_other = app.dom_mut().create_element("input");
    app.dom_mut()
        .set_attribute(r_other, "type", "radio")
        .unwrap();
    app.dom_mut()
        .set_attribute(r_other, "name", "other")
        .unwrap();
    app.dom_mut().set_attribute(r_other, "checked", "").unwrap();
    let root = app.dom().root();
    app.dom_mut().append_child(root, r_other).unwrap();
    app.draw_if_dirty().unwrap();

    // Click r1 in group "g" — must not touch r_other in group "other".
    click_at(&mut app, 1, 0);
    assert!(app.dom().node(r1).has_attribute("checked"));
    assert!(app.dom().node(r_other).has_attribute("checked"));
}

// ── Radio: the group follows the form owner (HTML §4.10.5.1.18) ───

/// A radio with the given attributes under `parent`.
fn radio_under(dom: &mut TuiDom, parent: NodeId, attrs: &[(&str, &str)]) -> NodeId {
    let r = dom.create_element("input");
    dom.set_attribute(r, "type", "radio").unwrap();
    for (k, v) in attrs {
        dom.set_attribute(r, k, v).unwrap();
    }
    dom.append_child(parent, r).unwrap();
    r
}

fn form_under(dom: &mut TuiDom, parent: NodeId, id: &str) -> NodeId {
    let f = dom.create_element("form");
    dom.set_attribute(f, "id", id).unwrap();
    dom.append_child(parent, f).unwrap();
    f
}

fn press_space_on(app: &mut App<TestBackend>, radio: NodeId) {
    app.dom_mut().set_focused(Some(radio));
    app.handle_event(key_press(KeyCode::Char(' '), KeyModifiers::empty()));
}

#[test]
fn same_named_radios_in_two_forms_toggle_independently() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let fa = form_under(&mut dom, root, "a");
    let fb = form_under(&mut dom, root, "b");
    let a1 = radio_under(&mut dom, fa, &[("name", "g"), ("checked", "")]);
    let b1 = radio_under(&mut dom, fb, &[("name", "g")]);
    let mut app = test_app(dom, Stylesheet::new());

    press_space_on(&mut app, b1);
    assert!(app.dom().node(b1).has_attribute("checked"));
    assert!(
        app.dom().node(a1).has_attribute("checked"),
        "a radio in another form is in another group"
    );
}

#[test]
fn a_radio_outside_a_form_with_a_form_attribute_groups_with_that_form() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let f = form_under(&mut dom, root, "f");
    let inside = radio_under(&mut dom, f, &[("name", "g"), ("checked", "")]);
    let pointing = radio_under(&mut dom, root, &[("name", "g"), ("form", "f")]);
    let unowned = radio_under(&mut dom, root, &[("name", "g"), ("checked", "")]);
    let mut app = test_app(dom, Stylesheet::new());

    press_space_on(&mut app, pointing);
    assert!(app.dom().node(pointing).has_attribute("checked"));
    assert!(
        !app.dom().node(inside).has_attribute("checked"),
        "form=f puts the radio in f's group"
    );
    assert!(
        app.dom().node(unowned).has_attribute("checked"),
        "an unowned radio is in the no-owner group"
    );
}

/// The name comparison is exact (HTML: "equals"), not case-folded.
#[test]
fn radio_names_that_differ_in_case_are_different_groups() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let upper = radio_under(&mut dom, root, &[("name", "G"), ("checked", "")]);
    let lower = radio_under(&mut dom, root, &[("name", "g")]);
    let mut app = test_app(dom, Stylesheet::new());

    press_space_on(&mut app, lower);
    assert!(app.dom().node(upper).has_attribute("checked"));
}

#[test]
fn arrow_navigation_stays_inside_the_form_owners_group() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let fa = form_under(&mut dom, root, "a");
    let fb = form_under(&mut dom, root, "b");
    let a1 = radio_under(&mut dom, fa, &[("name", "g")]);
    let a2 = radio_under(&mut dom, fa, &[("name", "g")]);
    let _b1 = radio_under(&mut dom, fb, &[("name", "g")]);
    let mut app = test_app(dom, Stylesheet::new());

    app.dom_mut().set_focused(Some(a2));
    app.handle_event(key_press(KeyCode::Down, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(a1), "wraps within form a");
}

// ── Radio: arrow-key navigation ────────────────────────────────────

#[test]
fn down_arrow_moves_focus_to_next_radio_in_group() {
    let (mut app, [r1, r2, _r3]) = radio_group_app();
    app.dom_mut().set_focused(Some(r1));
    app.handle_event(key_press(KeyCode::Down, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(r2));
}

#[test]
fn right_arrow_also_moves_to_next_radio() {
    let (mut app, [r1, r2, _r3]) = radio_group_app();
    app.dom_mut().set_focused(Some(r1));
    app.handle_event(key_press(KeyCode::Right, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(r2));
}

#[test]
fn up_arrow_moves_focus_to_previous_radio_in_group() {
    let (mut app, [r1, r2, _r3]) = radio_group_app();
    app.dom_mut().set_focused(Some(r2));
    app.handle_event(key_press(KeyCode::Up, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(r1));
}

#[test]
fn down_arrow_at_last_radio_wraps_to_first() {
    let (mut app, [r1, _r2, r3]) = radio_group_app();
    app.dom_mut().set_focused(Some(r3));
    app.handle_event(key_press(KeyCode::Down, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(r1));
}

#[test]
fn up_arrow_at_first_radio_wraps_to_last() {
    let (mut app, [r1, _r2, r3]) = radio_group_app();
    app.dom_mut().set_focused(Some(r1));
    app.handle_event(key_press(KeyCode::Up, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(r3));
}

#[test]
fn arrow_with_modifier_does_not_navigate() {
    let (mut app, [r1, _, _]) = radio_group_app();
    app.dom_mut().set_focused(Some(r1));
    app.handle_event(key_press(KeyCode::Down, KeyModifiers::SHIFT));
    assert_eq!(app.dom().focused(), Some(r1));
}

#[test]
fn arrow_on_radio_without_name_is_noop() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let r = dom.create_element("input");
    dom.set_attribute(r, "type", "radio").unwrap();
    // No `name` — not in any group.
    dom.append_child(root, r).unwrap();
    let mut app = test_app(dom, Stylesheet::new());
    app.dom_mut().set_focused(Some(r));
    app.handle_event(key_press(KeyCode::Down, KeyModifiers::empty()));
    assert_eq!(app.dom().focused(), Some(r));
}

// ── Space activation on radio ──────────────────────────────────────

#[test]
fn space_on_focused_radio_selects_it() {
    let (mut app, [_r1, r2, _r3]) = radio_group_app();
    app.dom_mut().set_focused(Some(r2));
    app.handle_event(key_press(KeyCode::Char(' '), KeyModifiers::empty()));
    assert!(app.dom().node(r2).has_attribute("checked"));
}

// ── A toggle next to prose is still a toggle ─────────────────────

/// A click on a checkbox beside prose flips it and selects no text.
/// The mousedown may still collapse the selection at the nearest text
/// (the empty-space snap of `position_at`, like a browser mousedown
/// outside text — the collapsed caret is invisible in non-editable
/// content), but the drag takes no pointer capture, so the click
/// reaches the box. The UA sheet declares no `user-select` on toggles
/// (P6G-TOGGLE-USER-SELECT-REVERT-1); this pins that the click works
/// without it.
#[test]
fn click_on_checkbox_beside_text_toggles_and_selects_no_text() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let p = dom.create_element("p");
    let t = dom.create_text_node("some prose");
    dom.append_child(p, t).unwrap();
    let cb = dom.create_element("input");
    dom.set_attribute(cb, "type", "checkbox").unwrap();
    dom.append_child(root, p).unwrap();
    dom.append_child(root, cb).unwrap();
    // Rows: 0 = prose, 1 = checkbox.
    let sheet = Stylesheet::new()
        .rule_unchecked("p", TuiStyle::new().height(Size::Fixed(1)))
        .rule_unchecked(
            "input[type=checkbox]",
            TuiStyle::new()
                .display(crate::layout::Display::Block)
                .width(Size::Fixed(10))
                .height(Size::Fixed(1)),
        );
    let mut app = test_app(dom, sheet);
    app.draw_if_dirty().unwrap();

    click_at(&mut app, 1, 1);
    assert!(
        app.dom().node(cb).has_attribute("checked"),
        "the click reached the box"
    );
    assert!(
        app.dom().selection().is_none_or(|s| s.is_collapsed()),
        "no text was selected"
    );
}

/// P6G-SELECTION-CAPTURE-1: the click reaches the toggle because the
/// selection drag takes no pointer capture — not because of a UA
/// `user-select: none`. With `user-select` set back to `auto` the empty-
/// space snap may start a selection in the prose, and the box still flips.
#[test]
fn click_on_user_select_auto_checkbox_beside_text_still_toggles() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let p = dom.create_element("p");
    let t = dom.create_text_node("some prose");
    dom.append_child(p, t).unwrap();
    let cb = dom.create_element("input");
    dom.set_attribute(cb, "type", "checkbox").unwrap();
    dom.append_child(root, p).unwrap();
    dom.append_child(root, cb).unwrap();
    let sheet = Stylesheet::new()
        .rule_unchecked("p", TuiStyle::new().height(Size::Fixed(1)))
        .rule_unchecked(
            "input[type=checkbox]",
            TuiStyle::new()
                .display(crate::layout::Display::Block)
                .width(Size::Fixed(10))
                .height(Size::Fixed(1))
                .user_select(crate::layout::UserSelect::Auto),
        );
    let mut app = test_app(dom, sheet);
    app.draw_if_dirty().unwrap();

    click_at(&mut app, 1, 1);
    assert!(
        app.dom().node(cb).has_attribute("checked"),
        "the click reached the box"
    );
    click_at(&mut app, 1, 1);
    assert!(
        !app.dom().node(cb).has_attribute("checked"),
        "and a second click flips it back"
    );
}

/// HTML §2.3.3: `type="CHECKBOX"` is the Checkbox state — the toggle
/// behavior and the UA glyph rule both apply (`P7-FORM-ENUM-CASE-1`).
#[test]
fn uppercase_checkbox_type_toggles_and_gets_the_ua_glyph() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let cb = dom.create_element("input");
    dom.set_attribute(cb, "type", "CHECKBOX").unwrap();
    dom.set_attribute(cb, "class", "box").unwrap();
    dom.append_child(root, cb).unwrap();
    let sheet = Stylesheet::new().rule_unchecked(
        ".box",
        TuiStyle::new()
            .width(Size::Fixed(10))
            .height(Size::Fixed(1)),
    );
    let mut app = test_app(dom, sheet);
    app.draw_if_dirty().unwrap();
    click_at(&mut app, 1, 0);
    assert!(app.dom().node(cb).has_attribute("checked"));
    assert!(
        app.dom()
            .matches(cb, "input[type=checkbox]:checked")
            .unwrap(),
        "the UA `input[type=checkbox]` rules match an uppercase type"
    );
}