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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! `<dialog>` show/showModal/close + cancel + form-method-dialog
//! integration 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::runtime::builtins::dialog;
use crate::style::{Stylesheet, TuiStyle};

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

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

fn click(x: u16, y: u16) -> Vec<CtEvent> {
    vec![
        CtEvent::Mouse(CtMouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: x,
            row: y,
            modifiers: KeyModifiers::empty(),
        }),
        CtEvent::Mouse(CtMouseEvent {
            kind: MouseEventKind::Up(MouseButton::Left),
            column: x,
            row: y,
            modifiers: KeyModifiers::empty(),
        }),
    ]
}

/// Build a `<dialog>` parented under root. Returns (app, dialog_id).
fn dialog_app() -> (App<TestBackend>, NodeId) {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    dom.append_child(root, dlg).unwrap();
    let app = test_app(dom, Stylesheet::new());
    (app, dlg)
}

// ── show / showModal / close — pure API ────────────────────────────

#[test]
fn show_sets_open_attribute() {
    let (mut app, dlg) = dialog_app();
    dialog::show(app.dom_mut(), dlg);
    assert!(app.dom().node(dlg).has_attribute("open"));
    assert!(!dialog::is_modal(app.dom(), dlg));
}

#[test]
fn show_modal_sets_open_and_modal_marker() {
    let (mut app, dlg) = dialog_app();
    dialog::show_modal(app.dom_mut(), dlg);
    assert!(app.dom().node(dlg).has_attribute("open"));
    assert!(dialog::is_modal(app.dom(), dlg));
}

#[test]
fn show_after_show_modal_clears_modal_marker() {
    let (mut app, dlg) = dialog_app();
    dialog::show_modal(app.dom_mut(), dlg);
    dialog::show(app.dom_mut(), dlg);
    assert!(app.dom().node(dlg).has_attribute("open"));
    assert!(!dialog::is_modal(app.dom(), dlg));
}

#[test]
fn close_clears_open_attribute_and_stores_return_value() {
    let (mut app, dlg) = dialog_app();
    dialog::show(app.dom_mut(), dlg);
    dialog::close(app.dom_mut(), dlg, "ok");
    assert!(!app.dom().node(dlg).has_attribute("open"));
    assert_eq!(dialog::return_value(app.dom(), dlg), "ok");
}

#[test]
fn close_fires_close_event_on_dialog() {
    let (mut app, dlg) = dialog_app();
    dialog::show(app.dom_mut(), dlg);
    let fired = Rc::new(Cell::new(0u32));
    let f = fired.clone();
    app.dom_mut()
        .add_event_listener(dlg, "close", ListenerOptions::default(), move |_| {
            f.set(f.get() + 1);
        })
        .unwrap();
    dialog::close(app.dom_mut(), dlg, "");
    assert_eq!(fired.get(), 1);
}

#[test]
fn close_event_does_not_bubble() {
    let (mut app, dlg) = dialog_app();
    let root = app.dom().root();
    dialog::show(app.dom_mut(), dlg);
    let saw = Rc::new(Cell::new(false));
    let s = saw.clone();
    app.dom_mut()
        .add_event_listener(root, "close", ListenerOptions::default(), move |_| {
            s.set(true);
        })
        .unwrap();
    dialog::close(app.dom_mut(), dlg, "");
    assert!(!saw.get(), "close must not bubble past dialog");
}

#[test]
fn close_on_already_closed_dialog_is_noop() {
    let (mut app, dlg) = dialog_app();
    let fired = Rc::new(Cell::new(0u32));
    let f = fired.clone();
    app.dom_mut()
        .add_event_listener(dlg, "close", ListenerOptions::default(), move |_| {
            f.set(f.get() + 1);
        })
        .unwrap();
    dialog::close(app.dom_mut(), dlg, "x");
    assert_eq!(fired.get(), 0);
    assert_eq!(dialog::return_value(app.dom(), dlg), "");
}

// ── Esc cancel (modal vs non-modal) ────────────────────────────────

#[test]
fn esc_in_modal_dialog_fires_cancel_then_closes() {
    let (mut app, dlg) = dialog_app();
    dialog::show_modal(app.dom_mut(), dlg);
    let order = Rc::new(RefCell::new(Vec::<&'static str>::new()));
    for ty in ["cancel", "close"] {
        let o = order.clone();
        app.dom_mut()
            .add_event_listener(dlg, ty, ListenerOptions::default(), move |_| {
                o.borrow_mut().push(ty);
            })
            .unwrap();
    }
    app.dom_mut().set_focused(Some(dlg));
    app.handle_event(key(KeyCode::Esc));
    assert_eq!(*order.borrow(), vec!["cancel", "close"]);
    assert!(!app.dom().node(dlg).has_attribute("open"));
}

#[test]
fn esc_in_non_modal_dialog_does_nothing() {
    let (mut app, dlg) = dialog_app();
    dialog::show(app.dom_mut(), dlg);
    let fired = Rc::new(Cell::new(false));
    let f = fired.clone();
    app.dom_mut()
        .add_event_listener(dlg, "cancel", ListenerOptions::default(), move |_| {
            f.set(true);
        })
        .unwrap();
    app.dom_mut().set_focused(Some(dlg));
    app.handle_event(key(KeyCode::Esc));
    assert!(!fired.get());
    assert!(app.dom().node(dlg).has_attribute("open"));
}

#[test]
fn prevent_default_on_cancel_keeps_modal_dialog_open() {
    let (mut app, dlg) = dialog_app();
    dialog::show_modal(app.dom_mut(), dlg);
    app.dom_mut()
        .add_event_listener(dlg, "cancel", ListenerOptions::default(), |ctx| {
            ctx.event.prevent_default();
        })
        .unwrap();
    app.dom_mut().set_focused(Some(dlg));
    app.handle_event(key(KeyCode::Esc));
    assert!(app.dom().node(dlg).has_attribute("open"));
}

#[test]
fn esc_with_modifier_does_not_trigger_cancel() {
    let (mut app, dlg) = dialog_app();
    dialog::show_modal(app.dom_mut(), dlg);
    app.dom_mut().set_focused(Some(dlg));
    app.handle_event(CtEvent::Key(KeyEvent::new(
        KeyCode::Esc,
        KeyModifiers::SHIFT,
    )));
    assert!(app.dom().node(dlg).has_attribute("open"));
}

#[test]
fn esc_outside_any_dialog_does_nothing() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let p = dom.create_element("p");
    dom.append_child(root, p).unwrap();
    let mut app = test_app(dom, Stylesheet::new());
    app.dom_mut().set_focused(Some(p));
    // No panic, no crash — that's the whole test.
    app.handle_event(key(KeyCode::Esc));
}

#[test]
fn esc_on_focused_element_inside_modal_dialog_closes_dialog() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    let inner = dom.create_element("button");
    dom.append_child(dlg, inner).unwrap();
    dom.append_child(root, dlg).unwrap();
    let mut app = test_app(dom, Stylesheet::new());
    dialog::show_modal(app.dom_mut(), dlg);
    app.dom_mut().set_focused(Some(inner));
    app.handle_event(key(KeyCode::Esc));
    assert!(!app.dom().node(dlg).has_attribute("open"));
}

// ── <form method="dialog"> integration ─────────────────────────────

#[test]
fn form_method_dialog_submit_closes_enclosing_dialog_with_button_value() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    let form = dom.create_element("form");
    dom.set_attribute(form, "method", "dialog").unwrap();
    let btn = dom.create_element("input");
    dom.set_attribute(btn, "type", "submit").unwrap();
    dom.set_attribute(btn, "value", "confirm").unwrap();
    dom.append_child(form, btn).unwrap();
    dom.append_child(dlg, form).unwrap();
    dom.append_child(root, dlg).unwrap();

    let sheet = Stylesheet::new().rule_unchecked(
        "input[type=submit]",
        TuiStyle::new()
            .width(Size::Fixed(10))
            .height(Size::Fixed(1)),
    );
    let mut app = test_app(dom, sheet);
    dialog::show_modal(app.dom_mut(), dlg);
    app.draw_if_dirty().unwrap();

    // UA `<dialog>` chrome: 1-cell border + padding 1 2. The
    // submit button sits at the dialog's content-area origin
    // (col = border + padding-left = 3, row = border + padding-
    // top = 2). Click at col 5 row 2 lands inside the button.
    for ev in click(5, 2) {
        app.handle_event(ev);
    }

    assert!(!app.dom().node(dlg).has_attribute("open"));
    assert_eq!(dialog::return_value(app.dom(), dlg), "confirm");
}

#[test]
fn form_method_dialog_submit_does_not_close_if_submit_handler_prevents() {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    let form = dom.create_element("form");
    dom.set_attribute(form, "method", "dialog").unwrap();
    let btn = dom.create_element("input");
    dom.set_attribute(btn, "type", "submit").unwrap();
    dom.append_child(form, btn).unwrap();
    dom.append_child(dlg, form).unwrap();
    dom.append_child(root, dlg).unwrap();

    let sheet = Stylesheet::new().rule_unchecked(
        "input[type=submit]",
        TuiStyle::new()
            .width(Size::Fixed(10))
            .height(Size::Fixed(1)),
    );
    let mut app = test_app(dom, sheet);
    app.dom_mut()
        .add_event_listener(form, "submit", ListenerOptions::default(), |ctx| {
            ctx.event.prevent_default();
        })
        .unwrap();
    dialog::show_modal(app.dom_mut(), dlg);
    app.draw_if_dirty().unwrap();

    for ev in click(1, 0) {
        app.handle_event(ev);
    }

    assert!(app.dom().node(dlg).has_attribute("open"));
}

/// P7-FORM-OWNER-1 (HTML §4.10.19.6): the submitter's `formmethod`
/// overrides the form's `method` — `formmethod="dialog"` closes the
/// dialog from a `method="get"` form, `formmethod="get"` keeps it open
/// from a `method="dialog"` form.
#[test]
fn submitter_formmethod_overrides_the_forms_method_for_dialog_close() {
    use crate::accessors::TuiAccessorsMut;
    for (form_method, button_method, closes) in [("get", "dialog", true), ("dialog", "get", false)]
    {
        let mut dom: TuiDom = TuiDom::new();
        let root = dom.root();
        let dlg = dom.create_element("dialog");
        let form = dom.create_element("form");
        dom.set_attribute(form, "method", form_method).unwrap();
        let btn = dom.create_element("button");
        dom.set_attribute(btn, "formmethod", button_method).unwrap();
        dom.set_attribute(btn, "value", "ok").unwrap();
        dom.append_child(form, btn).unwrap();
        dom.append_child(dlg, form).unwrap();
        dom.append_child(root, dlg).unwrap();
        let mut app = test_app(dom, Stylesheet::new());
        dialog::show_modal(app.dom_mut(), dlg);
        app.draw_if_dirty().unwrap();

        app.dom_mut().node_mut(btn).click();

        assert_eq!(
            !app.dom().node(dlg).has_attribute("open"),
            closes,
            "method={form_method} formmethod={button_method}"
        );
        if closes {
            assert_eq!(dialog::return_value(app.dom(), dlg), "ok");
        }
    }
}

#[test]
fn form_with_method_get_does_not_close_dialog_on_submit() {
    // Regression guard: only `method="dialog"` triggers the
    // auto-close. A normal form inside a dialog still fires
    // submit but leaves the dialog open.
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    let form = dom.create_element("form");
    // No method="dialog" — defaults to "get".
    let btn = dom.create_element("input");
    dom.set_attribute(btn, "type", "submit").unwrap();
    dom.append_child(form, btn).unwrap();
    dom.append_child(dlg, form).unwrap();
    dom.append_child(root, dlg).unwrap();

    let sheet = Stylesheet::new().rule_unchecked(
        "input[type=submit]",
        TuiStyle::new()
            .width(Size::Fixed(10))
            .height(Size::Fixed(1)),
    );
    let mut app = test_app(dom, sheet);
    dialog::show_modal(app.dom_mut(), dlg);
    app.draw_if_dirty().unwrap();

    for ev in click(1, 0) {
        app.handle_event(ev);
    }

    assert!(app.dom().node(dlg).has_attribute("open"));
}

// ── Step 6: typed toggle event detail ──────────────────────────────

#[test]
fn dialog_show_and_close_fire_toggle_events_with_typed_state_transitions() {
    // Open + close transitions both fire a `toggle` event whose
    // detail.as_toggle() carries the correct old/new ToggleState.
    use rdom_core::ToggleState;
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    dom.append_child(root, dlg).unwrap();

    let mut app = test_app(dom, Stylesheet::new());

    let captured: Rc<RefCell<Vec<(ToggleState, ToggleState)>>> = Rc::new(RefCell::new(Vec::new()));
    {
        let captured = captured.clone();
        app.dom_mut()
            .add_event_listener(dlg, "toggle", ListenerOptions::default(), move |ctx| {
                let d = ctx
                    .event
                    .detail
                    .as_toggle()
                    .expect("toggle must carry EventDetail::Toggle");
                captured.borrow_mut().push((d.old_state, d.new_state));
            })
            .unwrap();
    }

    dialog::show(app.dom_mut(), dlg);
    dialog::close(app.dom_mut(), dlg, "");

    assert_eq!(
        *captured.borrow(),
        vec![
            (ToggleState::Closed, ToggleState::Open),
            (ToggleState::Open, ToggleState::Closed),
        ]
    );
}

#[test]
fn dialog_show_modal_fires_toggle_event_closed_to_open() {
    use rdom_core::ToggleState;
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    dom.append_child(root, dlg).unwrap();

    let mut app = test_app(dom, Stylesheet::new());
    let captured: Rc<Cell<Option<(ToggleState, ToggleState)>>> = Rc::new(Cell::new(None));
    {
        let captured = captured.clone();
        app.dom_mut()
            .add_event_listener(dlg, "toggle", ListenerOptions::default(), move |ctx| {
                let d = ctx.event.detail.as_toggle().expect("typed Toggle detail");
                captured.set(Some((d.old_state, d.new_state)));
            })
            .unwrap();
    }

    dialog::show_modal(app.dom_mut(), dlg);

    assert_eq!(
        captured.get(),
        Some((ToggleState::Closed, ToggleState::Open))
    );
}

#[test]
fn dialog_show_on_already_open_does_not_refire_toggle() {
    // Calling show() / show_modal() on an already-open dialog is
    // idempotent — no state change, no toggle event.
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let dlg = dom.create_element("dialog");
    dom.append_child(root, dlg).unwrap();
    let mut app = test_app(dom, Stylesheet::new());

    let count = Rc::new(Cell::new(0u32));
    {
        let count = count.clone();
        app.dom_mut()
            .add_event_listener(dlg, "toggle", ListenerOptions::default(), move |_| {
                count.set(count.get() + 1);
            })
            .unwrap();
    }

    dialog::show(app.dom_mut(), dlg);
    dialog::show(app.dom_mut(), dlg); // already open — no event
    dialog::show_modal(app.dom_mut(), dlg); // also no event (still open)
    assert_eq!(count.get(), 1);
}

// ── HTML §4.11.4 modal dialogs: focusing steps, focus trap, Esc ─────

/// Dialog with two buttons inside and one button outside.
fn modal_fixture() -> (App<TestBackend>, NodeId, NodeId, NodeId, NodeId) {
    let mut dom: TuiDom = TuiDom::new();
    let root = dom.root();
    let outside = dom.create_element("button");
    let dlg = dom.create_element("dialog");
    let first = dom.create_element("button");
    let second = dom.create_element("button");
    dom.append_child(dlg, first).unwrap();
    dom.append_child(dlg, second).unwrap();
    dom.append_child(root, outside).unwrap();
    dom.append_child(root, dlg).unwrap();
    let app = test_app(dom, Stylesheet::new());
    (app, dlg, outside, first, second)
}

/// `showModal()` runs the dialog focusing steps: the first focusable
/// descendant gets focus, and the previously focused element is
/// remembered so `close()` can return focus to it.
#[test]
fn show_modal_focuses_first_descendant_and_close_restores_focus() {
    let (mut app, dlg, outside, first, _) = modal_fixture();
    app.draw_if_dirty().unwrap();
    app.dom_mut().set_focused(Some(outside));
    dialog::show_modal(app.dom_mut(), dlg);
    app.draw_if_dirty().unwrap();
    assert_eq!(
        app.dom().focused(),
        Some(first),
        "focus moves into the dialog"
    );
    dialog::close(app.dom_mut(), dlg, "");
    assert_eq!(
        app.dom().focused(),
        Some(outside),
        "focus returns to the previously focused element"
    );
}

/// While a modal dialog is open the rest of the document is inert:
/// Tab cycles among the dialog's focusable descendants only.
#[test]
fn tab_is_trapped_inside_an_open_modal_dialog() {
    let (mut app, dlg, outside, first, second) = modal_fixture();
    app.draw_if_dirty().unwrap();
    dialog::show_modal(app.dom_mut(), dlg);
    app.draw_if_dirty().unwrap();
    assert_eq!(app.dom().focused(), Some(first));
    app.handle_event(key(KeyCode::Tab));
    assert_eq!(app.dom().focused(), Some(second));
    app.handle_event(key(KeyCode::Tab));
    assert_eq!(
        app.dom().focused(),
        Some(first),
        "wraps inside the dialog, never reaches `outside`"
    );
    let _ = outside;
}

/// Esc cancels the open modal dialog even when focus is not inside it
/// (with the rest of the document inert, the dialog is the only
/// interactive content).
#[test]
fn esc_cancels_the_open_modal_regardless_of_focus_location() {
    let (mut app, dlg, outside, _, _) = modal_fixture();
    app.draw_if_dirty().unwrap();
    dialog::show_modal(app.dom_mut(), dlg);
    app.draw_if_dirty().unwrap();
    // Force focus elsewhere (a consumer calling focus() directly).
    app.dom_mut().set_focused(Some(outside));
    app.handle_event(key(KeyCode::Esc));
    assert!(
        !app.dom().node(dlg).has_attribute("open"),
        "modal closed by Esc"
    );
}

/// `close()` returns focus only to an element that is still focusable;
/// a previously focused element that became disabled is skipped (HTML
/// falls back to the body — here, no focus).
#[test]
fn close_does_not_focus_a_previously_focused_element_that_is_no_longer_focusable() {
    let (mut app, dlg, outside, _, _) = modal_fixture();
    app.draw_if_dirty().unwrap();
    app.dom_mut().set_focused(Some(outside));
    dialog::show_modal(app.dom_mut(), dlg);
    app.dom_mut()
        .set_attribute(outside, "disabled", "")
        .unwrap();
    dialog::close(app.dom_mut(), dlg, "");
    assert_ne!(app.dom().focused(), Some(outside));
}