abstracttui 0.3.4

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
//! components — the shareable-component pattern, concretely.
//!
//! THE REFERENCE for app authors: how to build reusable components with
//! props, children and events — "like a React web page" — from plain
//! functions. No macros, no registry: a component is
//!
//! ```text
//! fn my_component(cx: Scope, t: &TokenSet, props...) -> View
//! ```
//!
//! - PROPS are arguments (owned data + `Signal<T>` for live bindings).
//! - CHILDREN are `View` arguments (composition — see `field`).
//! - EVENTS are `impl FnMut(..) + 'static` callbacks (see `StatCard`'s
//!   `on_click`), captured into the widget's handlers.
//! - STATE lives in signals created by the CALLER (or the component's
//!   own `cx` for private state); writes re-render exactly the `Dyn`
//!   regions that read them.
//!
//! The screen composes the same three components repeatedly with
//! different props: a toolbar, three clickable stat cards (one component,
//! three instances, independent counters), and a settings form whose
//! fields wrap ANY child widget — with a live summary reading the same
//! signals the form writes.
//!
//! Keys: Tab focus · Enter/Space activate · type in the field ·
//! Ctrl+T theme · q quit.
//!
//! Docs: docs/api.md § "ui — elements, views, composition" and § "Disclosure — the fold/unfold card".
//!
//! OWNER: DESIGN.

mod common;

use abstracttui::prelude::*;
use abstracttui::theme::themes;
use abstracttui::ui::{MouseKind, Phase, UiEvent};

fn main() -> abstracttui::base::Result<()> {
    if !abstracttui::term::have_tty() {
        println!("components: needs an interactive terminal — skipping cleanly");
        return Ok(());
    }
    let mut app = App::new(Size::new(96, 30));
    let quitter = app.quitter();
    app.mount(move |cx| {
        let theme = use_theme(cx);
        // App state: plain signals. Components receive them as props.
        let deploys = cx.signal(12u32);
        let alerts = cx.signal(2u32);
        let uptime_days = cx.signal(97u32);
        let name = cx.signal(String::from("orion"));
        let notify = cx.signal(true);
        let channel = cx.signal(0usize);
        let theme_ix = cx.signal(0usize);
        let features = cx.signal(Vec::<String>::new());
        // App-owned fold state for the CONTROLLED disclosure card —
        // the external button flips it (the 0850 toggle-all shape).
        let ext_folded = cx.signal(true);

        Element::new()
            .style(LayoutStyle::column().padding(Edges::all(1)).gap(1))
            .shortcut(KeyChord::plain(Key::Char('q')), move |_| quitter.quit())
            .shortcut(KeyChord::new(Mods::CTRL, Key::Char('t')), move |_| {
                theme_ix.update(|i| *i = (*i + 1) % themes().len());
                set_theme_by_id(themes()[theme_ix.get_untracked()].id);
            })
            // One theme generation: rebuilt with fresh tokens on switch.
            .child(dyn_view_scoped(LayoutStyle::default().grow(1.0), move |gcx| {
                let t = theme.get().tokens;
                Element::new()
                    .style(LayoutStyle::column().gap(1))
                    // -- component #1: Toolbar { children } --------------
                    .child(toolbar(
                        &t,
                        vec![
                            Button::new("deploy")
                                .on_click(move || deploys.update(|n| *n += 1))
                                .element(gcx, &t)
                                .build(),
                            Button::new("ack alert")
                                .on_click(move || alerts.update(|n| *n = n.saturating_sub(1)))
                                .element(gcx, &t)
                                .build(),
                            Button::new("disabled").disabled(true).element(gcx, &t).build(),
                        ],
                    ))
                    // -- component #2: StatCard, three instances ---------
                    // Same function, different props/events; each card's
                    // value is a live Dyn over its own signal. h(5) is
                    // exactly border + label/value/arrow; shrink(0.0)
                    // keeps those rows honest when the terminal is short
                    // (fixed chrome never silently collapses — the form
                    // below scrolls instead).
                    .child(
                        Element::new()
                            .style(LayoutStyle::row().gap(2).h(5).shrink(0.0))
                            .child(stat_card(&t, "deploys", deploys, Trend::Up, move || {
                                deploys.update(|n| *n += 1)
                            }))
                            .child(stat_card(&t, "alerts", alerts, Trend::Down, move || {
                                alerts.update(|n| *n = n.saturating_sub(1))
                            }))
                            .child(stat_card(&t, "uptime d", uptime_days, Trend::Flat, move || {
                                uptime_days.update(|n| *n += 1)
                            }))
                            .build(),
                    )
                    // -- component #3: Field { label, child } ------------
                    // The child is ANY View: input, checkbox, radio — the
                    // wrapper never knows what it hosts (composition).
                    // Field rows stack gaplessly (a form reads fine
                    // dense) so the whole card fits a 30-row terminal
                    // with every row visible; the live summary sits
                    // below the fields.
                    .child(
                        Block::new()
                            .title("settings")
                            .fill(t.surface)
                            .shadow(t.shadow_ground)
                            .layout(
                                LayoutStyle::column()
                                    .gap(1)
                                    .grow(1.0)
                                    .padding(Edges::hv(1, 0)),
                            )
                            .child(
                                Element::new()
                                    .style(LayoutStyle::column())
                                    .child(field(
                                        &t,
                                        "name",
                                        TextInput::new()
                                            .value(name)
                                            .placeholder("service name…")
                                            .layout(LayoutStyle::default().w(32).h(1))
                                            .element(gcx, &t)
                                            .build(),
                                    ))
                                    .child(field(
                                        &t,
                                        "notifications",
                                        Checkbox::new("page the on-call")
                                            .checked(notify)
                                            .element(gcx, &t)
                                            .build(),
                                    ))
                                    .child(field(
                                        &t,
                                        "channel",
                                        RadioGroup::new(vec![
                                            "stable".to_string(),
                                            "beta".to_string(),
                                            "nightly".to_string(),
                                        ])
                                        .selection(channel)
                                        .element(gcx, &t)
                                        .build(),
                                    ))
                                    // -- the 0500 choice family ----------
                                    // The SAME channel signal as the radio
                                    // above: committing here moves the
                                    // radio dot too.
                                    .child(field(
                                        &t,
                                        "channel select",
                                        Select::new(vec![
                                            SelectOption::new("stable").hint("lts"),
                                            SelectOption::new("beta"),
                                            SelectOption::new("nightly").hint("daily"),
                                        ])
                                        .value(channel)
                                        .layout(LayoutStyle::default().w(28).h(1).shrink(0.0))
                                        .element(gcx, &t)
                                        .build(),
                                    ))
                                    // The consumer's /theme case: pick a
                                    // theme by typing — commit applies it
                                    // live.
                                    .child(field(
                                        &t,
                                        "theme",
                                        Combobox::new(
                                            themes()
                                                .iter()
                                                .map(|th| {
                                                    SelectOption::new(th.label).hint(
                                                        if th.dark { "dark" } else { "light" },
                                                    )
                                                })
                                                .collect(),
                                        )
                                        .value(theme_ix)
                                        .placeholder("type to search themes…")
                                        .on_change(|i| {
                                            set_theme_by_id(themes()[i].id);
                                        })
                                        .layout(LayoutStyle::default().w(28).h(1).shrink(0.0))
                                        .element(gcx, &t)
                                        .build(),
                                    ))
                                    .child(field(
                                        &t,
                                        "features",
                                        MultiSelect::new(vec![
                                            SelectOption::new("autosave"),
                                            SelectOption::new("telemetry"),
                                            SelectOption::new("backups"),
                                            SelectOption::new("beta api").disabled(true),
                                        ])
                                        .values(features)
                                        .placeholder("enable features…")
                                        .layout(LayoutStyle::default().w(28).h(1).shrink(0.0))
                                        .element(gcx, &t)
                                        .build(),
                                    ))
                                    .build(),
                            )
                            // Live summary: a Dyn reading the SAME signals
                            // the form writes — edits appear as you type.
                            .child(dyn_view(LayoutStyle::default().h(1).shrink(0.0), move || {
                                let ch = ["stable", "beta", "nightly"][channel.get().min(2)];
                                text(format!(
                                    "→ {} · notifications {} · {} channel · {} features",
                                    if name.get().is_empty() { "unnamed".into() } else { name.get() },
                                    if notify.get() { "on" } else { "off" },
                                    ch,
                                    features.get().len(),
                                ))
                            }))
                            .element(&t)
                            .build(),
                    )
                    // -- component #4: Disclosure cards ------------------
                    // Progressive disclosure, three state modes: card 1
                    // starts OPEN (uncontrolled initial state), card 2
                    // folds a long body behind a capped scroll region
                    // (unfold it: 4 rows + a scrollbar), card 3's fold
                    // state lives in an app signal the external button
                    // writes (the toggle-all policy shape). Click a
                    // title row or focus it and press Enter/Space.
                    .child(
                        Element::new()
                            .style(LayoutStyle::row().gap(2).shrink(0.0))
                            .child(
                                Button::new("toggle 3rd")
                                    .on_click(move || ext_folded.update(|f| *f = !*f))
                                    .element(gcx, &t)
                                    .build(),
                            )
                            .child(
                                Disclosure::markdown("welcome", "**hello** — this card starts open")
                                    .initially_folded(false)
                                    .max_body_rows(3)
                                    .layout(card_slot())
                                    .element(gcx, &t)
                                    .build(),
                            )
                            .child(
                                Disclosure::text("build log", build_log())
                                    .detail("14 lines")
                                    .max_body_rows(4)
                                    .layout(card_slot())
                                    .element(gcx, &t)
                                    .build(),
                            )
                            .child(
                                Disclosure::text("external", "fold state lives in an app signal")
                                    .folded(ext_folded)
                                    .layout(card_slot())
                                    .element(gcx, &t)
                                    .build(),
                            )
                            .build(),
                    )
                    .child(text(
                        "tab focus · enter/space activate · click cards · ctrl+t theme · q quit",
                    ))
                    .build()
            }))
            .build()
    })?;
    app.run()
}

/// Trend direction prop for [`stat_card`].
#[derive(Copy, Clone)]
enum Trend {
    Up,
    Down,
    Flat,
}

/// A reusable, clickable stat card: label (the card title), live
/// value, and trend arrow.
/// PROPS: label (data), `value` (live signal), trend; EVENT: `on_click`.
/// Click or focus+Enter fires it. One function — every instance on
/// screen is this.
///
/// Sizing notes worth stealing: the block height is EXPLICIT and
/// shadow-inclusive (title row plus 2 content rows plus bottom border
/// plus 1 shadow row = 5, matching the row's `.h(5)`), and draw closures
/// size themselves (`w(...)`) — a draw element has no intrinsic
/// measure, so an unsized one can solve to zero cells.
fn stat_card(
    t: &TokenSet,
    label: &'static str,
    value: Signal<u32>,
    trend: Trend,
    mut on_click: impl FnMut() + 'static,
) -> View {
    let (arrow, arrow_ink) = match trend {
        Trend::Up => ("▲", t.ok),
        Trend::Down => ("▼", t.error),
        Trend::Flat => ("→", t.text_muted),
    };
    let value_ink = t.accent;
    Block::new()
        .border(BorderKind::Rounded)
        .title(label)
        .fill(t.surface)
        .shadow(t.shadow_ground)
        .layout(LayoutStyle::column().grow(1.0).h(5))
        .child(dyn_view(LayoutStyle::line(1), move || {
            // The card's number is live: only THIS row re-renders when
            // its signal changes.
            let shown = format!("{}", value.get());
            let w = shown.chars().count() as i32 + 1;
            Element::new()
                .style(LayoutStyle::default().h(1).w(w))
                .draw(move |canvas, rect| {
                    canvas.print(
                        Point::new(rect.x, rect.y),
                        &shown,
                        value_ink,
                        Rgba::TRANSPARENT,
                    );
                })
                .build()
        }))
        .child(
            Element::new()
                .style(LayoutStyle::default().h(1).w(2))
                .draw(move |canvas, rect| {
                    canvas.print(
                        Point::new(rect.x, rect.y),
                        arrow,
                        arrow_ink,
                        Rgba::TRANSPARENT,
                    );
                })
                .build(),
        )
        .element(t)
        // Events attach to the ELEMENT the component returns — callers
        // could add more (the component stays open for extension).
        .focusable()
        .on(Phase::Bubble, move |ctx, ev| match ev {
            UiEvent::Mouse(m) if matches!(m.kind, MouseKind::Down(_)) => {
                on_click();
                ctx.stop_propagation();
            }
            UiEvent::Key(k) if k.key == Key::Enter || k.key == Key::Char(' ') => {
                on_click();
                ctx.stop_propagation();
            }
            _ => {}
        })
        .build()
}

/// A labeled form row: `label` in the gutter, ANY child view beside it —
/// children-as-props composition.
fn field(t: &TokenSet, label: &'static str, child: View) -> View {
    let ink = t.text_muted;
    Element::new()
        .style(LayoutStyle::row().gap(1))
        .child(
            Element::new()
                .style(LayoutStyle::default().w(15).h(1))
                .draw(move |canvas, rect| {
                    canvas.print(Point::new(rect.x, rect.y), label, ink, Rgba::TRANSPARENT);
                })
                .build(),
        )
        .child(child)
        .build()
}

/// Equal-split slot for a disclosure card in the demo row: basis 0 +
/// grow shares the row; shrink 0 keeps cards honest under pressure.
fn card_slot() -> LayoutStyle {
    LayoutStyle::column()
        .grow(1.0)
        .basis(Dimension::Cells(0))
        .shrink(0.0)
}

/// 14 log lines — enough to overflow the 4-row body cap and show the
/// scrollbar.
fn build_log() -> String {
    (0..14)
        .map(|i| format!("compiling unit {i:>2} … ok"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// A toolbar strip: children on a raised ground — the simplest
/// children-collection component. `shrink(0.0)`: a toolbar is
/// incompressible chrome (the §"row vanishes" rule).
fn toolbar(t: &TokenSet, children: Vec<View>) -> View {
    let ground = t.surface_raised;
    let ink = t.text;
    Element::new()
        .style(
            LayoutStyle::row()
                .gap(2)
                .h(1)
                .padding(Edges::hv(1, 0))
                .shrink(0.0),
        )
        .draw(move |canvas, rect| {
            canvas.fill(rect, ' ', ink, ground);
        })
        .children(children)
        .build()
}