abstracttui 0.4.1

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
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
//! Select-family unit tests (split file, `#[path]`-included as
//! `select::tests`). Faces mount into a real `UiTree` with popups on a
//! real overlay store; events route driver-style (overlays first,
//! topmost modal wins) — the 0250 movement-vs-activation split and
//! the dismiss contract are exercised through real dispatch.
use std::cell::RefCell;
use std::rc::Rc;

use super::*;
use crate::base::Point;
use crate::reactive::{create_root, flush_effects, RootScope};
use crate::theme::default_theme;
use crate::ui::{text, BufferCanvas, KeyEvent, MouseEvent, UiEvent, UiTree};

const VP: Size = Size::new(30, 12);

struct Rig {
    _root: RootScope,
    tree: UiTree,
    overlays: Overlays,
}

impl Rig {
    /// Driver-order routing: overlays first, root tree on fall-through.
    fn send(&mut self, ev: &UiEvent) {
        if self.overlays.dispatch(ev).is_none() {
            self.tree.dispatch(ev);
        }
        flush_effects();
    }

    fn key(&mut self, k: Key) {
        self.send(&UiEvent::Key(KeyEvent::plain(k)));
    }

    fn type_str(&mut self, s: &str) {
        for ch in s.chars() {
            self.key(Key::Char(ch));
        }
    }

    fn click(&mut self, x: i32, y: i32) {
        self.send(&UiEvent::Mouse(MouseEvent {
            pos: Point::new(x, y),
            kind: MouseKind::Down(MouseButton::Left),
            mods: Mods::NONE,
        }));
        self.send(&UiEvent::Mouse(MouseEvent {
            pos: Point::new(x, y),
            kind: MouseKind::Up(MouseButton::Left),
            mods: Mods::NONE,
        }));
    }

    /// The one open popup (modal overlay tree), drawn: (bounds, rows).
    fn popup(&self) -> Option<(crate::base::Rect, Vec<String>)> {
        let (tree, bounds) = {
            let store = self.overlays.store().borrow();
            store
                .meta
                .iter()
                .zip(&store.layers)
                .find_map(|(m, l)| match &m.content {
                    super::super::overlays::OverlayContent::Tree {
                        tree, modal: true, ..
                    } => Some((tree.handle(), l.bounds())),
                    _ => None,
                })?
        };
        let mut tree = tree.handle();
        tree.layout();
        let mut canvas = BufferCanvas::new(bounds.size());
        tree.draw(&mut canvas);
        let rows = (0..bounds.h).map(|y| canvas.row_text(y)).collect();
        Some((bounds, rows))
    }

    /// Popup row index (0-based within the popup) wearing the
    /// selection-pair highlight.
    fn highlight_row(&self) -> Option<usize> {
        let sel_bg = default_theme().tokens.selection_bg;
        let (bounds, _) = self.popup()?;
        let store = self.overlays.store().borrow();
        let tree = store.meta.iter().find_map(|m| match &m.content {
            super::super::overlays::OverlayContent::Tree {
                tree, modal: true, ..
            } => Some(tree.handle()),
            _ => None,
        })?;
        drop(store);
        let mut tree = tree.handle();
        tree.layout();
        let mut canvas = BufferCanvas::new(bounds.size());
        tree.draw(&mut canvas);
        (0..bounds.h as usize).find(|y| {
            canvas
                .cell(Point::new(1, *y as i32))
                .is_some_and(|c| c.2 == sel_bg)
        })
    }
}

/// Mount one face view at the top row of a 30x12 world.
fn rig(build: impl FnOnce(Scope, &Overlays) -> crate::ui::View) -> Rig {
    super::super::viewport::publish_viewport(VP);
    let overlays = Overlays::new();
    overlays.ensure_root(VP);
    let mut tree = UiTree::new(VP);
    let ov = overlays.clone();
    let (root, ()) = create_root(|cx| {
        let face = build(cx, &ov);
        let view = Element::new()
            .style(LayoutStyle::column().width(Dimension::Percent(1.0)).h(VP.h))
            .child(face)
            .child(text("below content"))
            .build();
        tree.mount(cx, view);
    });
    tree.layout();
    let mut rig = Rig {
        _root: root,
        tree,
        overlays,
    };
    rig.key(Key::Tab); // focus the trigger
    rig
}

fn fruit_options() -> Vec<SelectOption> {
    vec![
        SelectOption::new("alpha").hint("first"),
        SelectOption::new("beta"),
        SelectOption::new("banana"),
        SelectOption::new("gamma").disabled(true),
        SelectOption::new("delta"),
    ]
}

fn face_layout() -> LayoutStyle {
    LayoutStyle::default().w(24).h(1).shrink(0.0)
}

// ------------------------------------------------------------------ Select

#[test]
fn select_arrows_move_highlight_only_and_enter_commits_once() {
    // The 0250 regression as a birth test: movement never writes the
    // bound value; Enter commits exactly once.
    let value_holder: Rc<RefCell<Option<Signal<usize>>>> = Default::default();
    let changes: Rc<RefCell<Vec<usize>>> = Default::default();
    let vh = value_holder.clone();
    let ch = changes.clone();
    let mut rig = rig(move |cx, ov| {
        let value = cx.signal(0usize);
        *vh.borrow_mut() = Some(value);
        Select::new(fruit_options())
            .value(value)
            .layout(face_layout())
            .overlays(ov)
            .on_change(move |i| ch.borrow_mut().push(i))
            .element(cx, &default_theme().tokens)
            .build()
    });
    let value = value_holder.borrow().unwrap();
    assert!(rig.popup().is_none(), "closed at mount");
    rig.key(Key::Enter); // open
    let (bounds, rows) = rig.popup().expect("popup open");
    assert_eq!(bounds.y, 1, "below the trigger row");
    assert_eq!(bounds.w, 24, "MatchAnchor width");
    assert!(rows[0].contains("alpha"), "{rows:?}");
    assert!(rows[0].contains("first"), "hint renders");
    assert_eq!(rig.highlight_row(), Some(0), "seeded on the value");
    rig.key(Key::Down);
    rig.key(Key::Down);
    assert_eq!(rig.highlight_row(), Some(2), "highlight moved");
    assert_eq!(value.get_untracked(), 0, "arrows never write the value");
    assert!(changes.borrow().is_empty(), "no on_change on move");
    rig.key(Key::Enter);
    assert_eq!(value.get_untracked(), 2, "Enter committed the highlight");
    assert_eq!(changes.borrow().as_slice(), [2], "exactly one on_change");
    assert!(rig.popup().is_none(), "commit closed the popup");
}

/// Disposal-safety law (backlog 0297): a commit `on_change` may
/// dispose the FACE's scope synchronously — the pick-then-close modal.
/// The disposed scope is the one owning the MOUNTED subtree (the real
/// modal shape: signals AND mounted instances die together — the
/// documented dyn_view-vs-dyn_view_scoped rule; disposing only a build
/// scope under a live mount is the zombie-view misuse the runtime's
/// panic message already teaches). The popup's content scope is a
/// child of the face's, so the disposal CASCADES: the AnchorGone
/// cleanup removes the layer while the callback runs, and the
/// post-callback dismiss inside `commit_and_close` finds the popup
/// already ended (idempotent no-op) — no dead-signal write anywhere.
/// Audited clean at filing; pinned because the cleanliness hangs on
/// that cascade, not on ordering alone. The bound value lives OUTSIDE
/// the modal scope (the app owns it) and carries the committed pick
/// out of the closed modal.
#[test]
fn select_commit_on_change_may_dispose_the_faces_scope() {
    super::super::viewport::publish_viewport(VP);
    let overlays = Overlays::new();
    overlays.ensure_root(VP);
    let mut tree = UiTree::new(VP);
    let ov = overlays.clone();
    let value_holder: Rc<RefCell<Option<Signal<usize>>>> = Default::default();
    let vh = value_holder.clone();
    let changes: Rc<RefCell<Vec<usize>>> = Default::default();
    let ch = changes.clone();
    let (root, ()) = create_root(|cx| {
        let modal_cx = cx.child();
        let value = cx.signal(usize::MAX); // app-owned: survives the close
        *vh.borrow_mut() = Some(value);
        let face = Select::new(fruit_options())
            .value(value)
            .layout(face_layout())
            .overlays(&ov)
            .on_change(move |i| {
                ch.borrow_mut().push(i);
                modal_cx.dispose();
            })
            .element(modal_cx, &default_theme().tokens)
            .build();
        // The rig's wrapper shape, but owned by the MODAL scope: the
        // trigger keeps its one row (room below for the popup) and the
        // whole mounted subtree dies with `modal_cx`.
        let view = Element::new()
            .style(LayoutStyle::column().width(Dimension::Percent(1.0)).h(VP.h))
            .child(face)
            .child(text("below content"))
            .build();
        tree.mount(modal_cx, view);
    });
    tree.layout();
    let mut rig = Rig {
        _root: root,
        tree,
        overlays,
    };
    rig.key(Key::Tab); // focus the trigger
    let value = value_holder.borrow().unwrap();
    rig.key(Key::Enter); // open
    assert!(rig.popup().is_some(), "popup open");
    rig.key(Key::Enter); // commit alpha -> on_change -> dispose
    assert_eq!(value.get_untracked(), 0, "commit landed before the close");
    assert_eq!(changes.borrow().as_slice(), [0], "exactly one on_change");
    assert!(
        rig.popup().is_none(),
        "cascade took the popup with the scope"
    );
    assert_eq!(rig.tree.instance_count(), 0, "face subtree unmounted");
}

#[test]
fn select_escape_and_outside_press_abandon_without_committing() {
    let value_holder: Rc<RefCell<Option<Signal<usize>>>> = Default::default();
    let changes: Rc<RefCell<Vec<usize>>> = Default::default();
    let vh = value_holder.clone();
    let ch = changes.clone();
    let mut rig = rig(move |cx, ov| {
        let value = cx.signal(1usize);
        *vh.borrow_mut() = Some(value);
        Select::new(fruit_options())
            .value(value)
            .layout(face_layout())
            .overlays(ov)
            .on_change(move |i| ch.borrow_mut().push(i))
            .element(cx, &default_theme().tokens)
            .build()
    });
    let value = value_holder.borrow().unwrap();
    rig.key(Key::Enter);
    rig.key(Key::Down);
    rig.key(Key::Escape);
    assert!(rig.popup().is_none(), "Escape closed");
    assert_eq!(value.get_untracked(), 1, "Escape abandoned the move");
    assert!(changes.borrow().is_empty());
    // Outside press: dismiss without acting (and without commit).
    rig.key(Key::Enter);
    rig.key(Key::Down);
    assert!(rig.popup().is_some());
    rig.click(28, 10); // outside the popup
    assert!(rig.popup().is_none(), "outside press dismissed");
    assert_eq!(value.get_untracked(), 1);
    assert!(changes.borrow().is_empty());
    // The trigger keeps focus: Enter reopens straight away.
    rig.key(Key::Enter);
    assert!(rig.popup().is_some(), "focus returned to the trigger");
}

#[test]
fn select_type_ahead_prefix_jump_cycle_and_disabled_skip() {
    let mut rig = rig(move |cx, ov| {
        Select::new(fruit_options())
            .layout(face_layout())
            .overlays(ov)
            .element(cx, &default_theme().tokens)
            .build()
    });
    rig.key(Key::Enter); // open (no value bound: placeholder, seed = first enabled)
    assert_eq!(rig.highlight_row(), Some(0));
    rig.key(Key::Char('b'));
    assert_eq!(rig.highlight_row(), Some(1), "prefix jump to beta");
    rig.key(Key::Char('b'));
    assert_eq!(rig.highlight_row(), Some(2), "same-char cycle to banana");
    rig.key(Key::Char('b'));
    assert_eq!(rig.highlight_row(), Some(1), "cycle wraps back to beta");
    // Accumulated prefix: "de" jumps to delta.
    rig.key(Key::Escape);
    rig.key(Key::Enter);
    rig.type_str("de");
    assert_eq!(rig.highlight_row(), Some(4), "prefix 'de' -> delta");
    // 'g' targets only the DISABLED gamma: the highlight stays put.
    rig.key(Key::Escape);
    rig.key(Key::Enter);
    rig.key(Key::Char('g'));
    assert_eq!(rig.highlight_row(), Some(0), "disabled options never match");
    // Arrow movement skips the disabled row too: from banana(2), Down
    // lands on delta(4). Fresh open — the type-ahead buffer holds "g"
    // within its window (a failed match never resets it).
    rig.key(Key::Escape);
    rig.key(Key::Enter);
    rig.key(Key::Char('b'));
    rig.key(Key::Char('a')); // "ba" -> banana
    assert_eq!(rig.highlight_row(), Some(2));
    rig.key(Key::Down);
    assert_eq!(rig.highlight_row(), Some(4), "skipped disabled gamma");
}

#[test]
fn select_commit_on_move_previews_live_and_escape_restores() {
    let value_holder: Rc<RefCell<Option<Signal<usize>>>> = Default::default();
    let changes: Rc<RefCell<Vec<usize>>> = Default::default();
    let vh = value_holder.clone();
    let ch = changes.clone();
    let mut rig = rig(move |cx, ov| {
        let value = cx.signal(0usize);
        *vh.borrow_mut() = Some(value);
        Select::new(fruit_options())
            .value(value)
            .commit_on_move(true)
            .layout(face_layout())
            .overlays(ov)
            .on_change(move |i| ch.borrow_mut().push(i))
            .element(cx, &default_theme().tokens)
            .build()
    });
    let value = value_holder.borrow().unwrap();
    rig.key(Key::Enter);
    rig.key(Key::Down);
    assert_eq!(value.get_untracked(), 1, "move committed live (opt-in)");
    rig.key(Key::Down);
    assert_eq!(value.get_untracked(), 2);
    assert_eq!(changes.borrow().as_slice(), [1, 2]);
    rig.key(Key::Escape);
    assert_eq!(
        value.get_untracked(),
        0,
        "Escape restored the pre-open value"
    );
    assert_eq!(changes.borrow().as_slice(), [1, 2, 0]);
}

#[test]
fn select_disabled_neither_focuses_nor_opens_and_empty_options_never_open() {
    let mut rig = rig(move |cx, ov| {
        Select::new(fruit_options())
            .disabled(true)
            .layout(face_layout())
            .overlays(ov)
            .element(cx, &default_theme().tokens)
            .build()
    });
    // Tab found nothing focusable; Enter/click open nothing.
    rig.key(Key::Enter);
    assert!(rig.popup().is_none(), "disabled never opens by key");
    rig.click(2, 0);
    assert!(rig.popup().is_none(), "disabled never opens by click");

    let mut empty_rig = self::rig(move |cx, ov| {
        Select::new(Vec::new())
            .layout(face_layout())
            .overlays(ov)
            .element(cx, &default_theme().tokens)
            .build()
    });
    empty_rig.key(Key::Enter);
    assert!(empty_rig.popup().is_none(), "no options = nothing to open");
}

#[test]
fn select_click_trigger_opens_and_click_row_commits() {
    let value_holder: Rc<RefCell<Option<Signal<usize>>>> = Default::default();
    let vh = value_holder.clone();
    let mut rig = rig(move |cx, ov| {
        let value = cx.signal(0usize);
        *vh.borrow_mut() = Some(value);
        Select::new(fruit_options())
            .value(value)
            .layout(face_layout())
            .overlays(ov)
            .element(cx, &default_theme().tokens)
            .build()
    });
    let value = value_holder.borrow().unwrap();
    rig.click(2, 0); // the trigger row
    let (bounds, rows) = rig.popup().expect("click opened");
    let beta_row = rows.iter().position(|r| r.contains("beta")).unwrap() as i32;
    rig.click(bounds.x + 2, bounds.y + beta_row);
    assert!(rig.popup().is_none(), "click committed and closed");
    assert_eq!(value.get_untracked(), 1, "beta committed");
    // Clicking a DISABLED row does nothing (popup stays).
    rig.click(2, 0);
    let (bounds, rows) = rig.popup().expect("reopened");
    let gamma_row = rows.iter().position(|r| r.contains("gamma")).unwrap() as i32;
    rig.click(bounds.x + 2, bounds.y + gamma_row);
    assert!(rig.popup().is_some(), "disabled row ignored the click");
    assert_eq!(value.get_untracked(), 1);
}

#[test]
fn select_trigger_renders_value_placeholder_and_a11y_roles() {
    let mut rig = rig(move |cx, ov| {
        Element::new()
            .style(LayoutStyle::column().gap(0))
            .child(
                Select::new(fruit_options())
                    .placeholder("pick a fruit")
                    .layout(face_layout())
                    .overlays(ov)
                    .element(cx, &default_theme().tokens)
                    .build(),
            )
            .build()
    });
    // Placeholder (nothing chosen): faint tone + text.
    rig.tree.layout();
    let mut canvas = BufferCanvas::new(VP);
    rig.tree.draw(&mut canvas);
    assert!(canvas.row_text(0).contains("pick a fruit"));
    assert!(canvas.row_text(0).contains("▾"), "chevron affordance");
    assert_eq!(
        canvas.cell(Point::new(1, 0)).unwrap().1,
        default_theme().tokens.text_faint,
        "placeholder ink is text_faint"
    );
    // A11y: closed control reports Button (the trigger IS a button
    // opening a menu; `Role::Select` is parked in the 0.3 budget —
    // 0002 entry 1) + the current choice as value; the popup reports
    // menu/menuitem.
    let snapshot = rig.tree.accessibility_tree();
    let entry = snapshot
        .find(crate::ui::Role::Button)
        .expect("select trigger reports Role::Button");
    assert_eq!(entry.value.as_deref(), Some("pick a fruit"));
    rig.key(Key::Enter);
    let store = rig.overlays.store().borrow();
    let mut popup_tree = store
        .meta
        .iter()
        .find_map(|m| match &m.content {
            super::super::overlays::OverlayContent::Tree {
                tree, modal: true, ..
            } => Some(tree.handle()),
            _ => None,
        })
        .expect("popup");
    drop(store);
    let popup_snapshot = popup_tree.accessibility_tree();
    assert!(popup_snapshot.find(crate::ui::Role::Menu).is_some());
    assert!(popup_snapshot.find(crate::ui::Role::MenuItem).is_some());
}

// Combobox + MultiSelect cases live in a sibling (file budget);
// they reuse this module's Rig through `super::`.
#[path = "select_tests_faces.rs"]
mod faces;

// SelectHandle (0296 programmatic open) cases — same split pattern.
#[path = "select_tests_handle.rs"]
mod handle_tests;

/// Wave-12 reentrancy pin (the SharedCallback held-borrow contract):
/// a commit `on_change` that OPENS A MODAL mid-callback — synchronous
/// overlay-tree mount, layout solve, and `focus_init` all run while
/// the select's `on_change` RefCell borrow is held. Safe because
/// nothing in the modal-open path re-enters the select's slot (fact 1
/// of the contract) and the callback's signal traffic is batched past
/// the borrow (fact 2). If `Modal::open` ever grows a synchronous
/// blur/redispatch into the OPENER's tree, this test is the tripwire.
#[test]
fn callback_reentrancy_pin_on_change_opens_a_modal() {
    let value_holder: Rc<RefCell<Option<Signal<usize>>>> = Default::default();
    let vh = value_holder.clone();
    let modal_holder: Rc<RefCell<Option<super::super::popups::Modal>>> = Default::default();
    let mh = modal_holder.clone();
    let mut rig = rig(move |cx, ov| {
        let value = cx.signal(0usize);
        *vh.borrow_mut() = Some(value);
        let ov_for_change = ov.clone();
        Select::new(fruit_options())
            .value(value)
            .layout(face_layout())
            .overlays(ov)
            .on_change(move |_| {
                let modal = super::super::popups::Modal::open(
                    &ov_for_change,
                    cx,
                    VP,
                    Size::new(20, 5),
                    |_mcx| text("confirm?"),
                );
                *mh.borrow_mut() = Some(modal);
            })
            .element(cx, &default_theme().tokens)
            .build()
    });
    let value = value_holder.borrow().unwrap();
    rig.key(Key::Enter); // open the popup
    assert!(rig.popup().is_some(), "popup open");
    rig.key(Key::Down); // highlight beta
    rig.key(Key::Enter); // commit -> on_change opens the modal mid-borrow
    assert_eq!(value.get_untracked(), 1, "commit landed");
    let modal = modal_holder.borrow_mut().take().expect("modal opened");
    assert!(
        modal.layer().is_alive(),
        "modal survived the mid-callback open"
    );
    // The only modal tree left is the MODAL (the select popup ended
    // with the commit); its content proves which tree we found.
    let (_, rows) = rig.popup().expect("the modal tree");
    assert!(
        rows.iter().any(|r| r.contains("confirm?")),
        "modal content on screen, select popup gone: {rows:?}"
    );
    modal.close();
}