ntui 0.3.1

An Ink-style TUI library for Rust: components, hooks, flexbox layout, and fullscreen rendering.
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
use crate::component::Component;
use crate::element::Element;
use crate::hooks::Hooks;
use crate::hooks::input::KeyCode;
use crate::props::{
    AlignItems, Anchor, Dimension, FlexDirection, JustifyContent, TextProps, TextWrap, ViewProps,
};
use crate::style::{Color, Weight};
use crate::widgets::callback::Callback;

/// A centered dialog over a darkened backdrop covering the whole terminal.
/// Esc calls `on_close`. Sized from [`Hooks::use_terminal_size`] rather than
/// `Dimension::Percent`, since percentages on an absolutely-positioned
/// (overlay) box would resolve against an unpredictable containing
/// block — explicit cell sizes sidestep that entirely.
///
/// A cell grid has no real alpha, so "backdrop" here is a solid color (a
/// darkened variant of the theme surface) — a see-through dim of whatever
/// was underneath is not possible on a cell grid, not merely unimplemented.
/// There is no drop-shadow rect either; unlike the alpha limitation, that
/// one could be added later (an offset `View` behind the dialog) but isn't
/// here yet.
#[derive(Clone, PartialEq, Default)]
pub struct ModalProps {
    pub title: String,
    pub message: String,
    pub on_close: Option<Callback>,
}

pub struct Modal;
impl Component for Modal {
    type Props = ModalProps;
    fn render(props: &ModalProps, hooks: &mut Hooks) -> Element {
        let theme = hooks.use_theme();
        let (w, h) = hooks.use_terminal_size();

        let on_close = props.on_close.clone();
        hooks.use_input(move |ev, ctx| {
            if ev.code == KeyCode::Esc {
                if let Some(cb) = &on_close {
                    cb.call(());
                }
                ctx.stop_propagation();
            }
        });

        let backdrop = Color::lerp(theme.surface, Color::Black, 0.75);
        let dialog_width = 44.min(w.saturating_sub(4)).max(10);

        let dialog = Element::view(
            ViewProps {
                flex_direction: FlexDirection::Column,
                border_style: theme.border_style,
                border_color: theme.accent,
                background: theme.surface,
                padding: 1,
                gap: 1,
                width: Dimension::Cells(dialog_width),
                ..Default::default()
            },
            vec![
                Element::text(TextProps {
                    content: props.title.clone(),
                    color: theme.accent,
                    weight: Weight::Bold,
                    ..Default::default()
                }),
                Element::text(TextProps {
                    content: props.message.clone(),
                    color: theme.foreground,
                    wrap: TextWrap::Wrap,
                    ..Default::default()
                }),
                Element::text(TextProps {
                    content: "Esc to close".to_string(),
                    color: theme.muted,
                    ..Default::default()
                }),
            ],
        );

        Element::view(
            ViewProps {
                overlay: Some(Anchor::Center),
                width: Dimension::Cells(w),
                height: Dimension::Cells(h),
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                background: backdrop,
                ..Default::default()
            },
            vec![dialog],
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::buffer::Buffer;
    use crate::fiber::FiberTree;
    use crate::hooks::RuntimeHandle;
    use crate::hooks::input::KeyCode;
    use crate::layout::compute_layout;
    use crate::paint::paint;
    use crate::testing::TestTerminal;
    use std::cell::Cell;
    use std::rc::Rc;

    #[tokio::test]
    async fn shows_title_and_message_and_esc_closes() {
        let closed = Rc::new(Cell::new(false));
        let c = closed.clone();
        let mut t = TestTerminal::new(
            40,
            10,
            Element::component::<Modal>(ModalProps {
                title: "Delete file?".into(),
                message: "This can't be undone.".into(),
                on_close: Some(Callback::new(move |()| c.set(true))),
            }),
        )
        .unwrap();
        let out = t.frame_text();
        assert!(out.contains("Delete file?"), "{out:?}");
        assert!(out.contains("undone"), "{out:?}");
        t.send_key(KeyCode::Esc).unwrap();
        assert!(closed.get());
    }

    #[tokio::test]
    async fn backdrop_covers_the_whole_viewport_and_does_not_grow_past_it() {
        let (rt, _rx) = RuntimeHandle::test_handle();
        let mut tree = FiberTree::new();
        tree.mount_root(
            Element::component::<Modal>(ModalProps {
                title: "t".into(),
                message: "m".into(),
                on_close: None,
            }),
            &rt,
        );
        compute_layout(&mut tree, 30, 12);
        let mut buf = Buffer::new(30, 12);
        paint(&tree, &mut buf);
        // Corners should be the darkened backdrop, not left untouched.
        assert_ne!(buf.get(0, 0).bg, Color::Reset);
        assert_ne!(buf.get(29, 11).bg, Color::Reset);
    }

    struct StaticOverlays;
    #[derive(Clone, PartialEq, Default)]
    struct StaticOverlaysProps;
    impl Component for StaticOverlays {
        type Props = StaticOverlaysProps;
        fn render(_: &StaticOverlaysProps, _hooks: &mut Hooks) -> Element {
            Element::fragment(vec![
                Element::text(TextProps {
                    content: "background".into(),
                    ..Default::default()
                }),
                Element::view(
                    ViewProps {
                        overlay: Some(Anchor::TopRight),
                        ..Default::default()
                    },
                    vec![Element::text(TextProps {
                        content: "hint".into(),
                        ..Default::default()
                    })],
                ),
                Element::view(
                    ViewProps {
                        overlay: Some(Anchor::BottomRight),
                        ..Default::default()
                    },
                    vec![Element::text(TextProps {
                        content: "toast".into(),
                        ..Default::default()
                    })],
                ),
            ])
        }
    }

    #[tokio::test]
    async fn static_no_hooks_overlays_position_correctly_through_test_terminal() {
        let t = TestTerminal::new(
            20,
            6,
            Element::component::<StaticOverlays>(StaticOverlaysProps),
        )
        .unwrap();
        let out = t.frame_text();
        eprintln!("static overlays via TestTerminal:\n{out}");
        assert!(
            out.lines().next().unwrap().starts_with("background"),
            "background should be untouched at (0,0): {out:?}"
        );
    }

    struct Toggler;
    #[derive(Clone, PartialEq, Default)]
    struct TogglerProps {
        show: crate::test_util::Shared<Option<crate::hooks::state::State<bool>>>,
    }
    impl Component for Toggler {
        type Props = TogglerProps;
        fn render(props: &TogglerProps, hooks: &mut Hooks) -> Element {
            let show = hooks.use_state(|| true);
            *props.show.lock() = Some(show.clone());
            let mut children = vec![Element::text(TextProps {
                content: "background".into(),
                ..Default::default()
            })];
            if show.get() {
                children.push(Element::component::<Modal>(ModalProps {
                    title: "t".into(),
                    message: "m".into(),
                    on_close: None,
                }));
            }
            Element::fragment(children)
        }
    }

    #[tokio::test]
    async fn closing_the_modal_clears_its_backdrop_from_the_terminal() {
        let show = crate::test_util::Shared::default();
        let mut t = TestTerminal::new(
            20,
            6,
            Element::component::<Toggler>(TogglerProps { show: show.clone() }),
        )
        .unwrap();
        // Sanity: with the modal open, its backdrop should paint over the
        // background text at (0, 0) too (unclipped, on top of everything).
        assert_ne!(
            t.frame_text().lines().next().unwrap().trim(),
            "background",
            "modal should be covering the background text"
        );

        let handle = show.lock().clone().unwrap();
        handle.set(false);
        t.tick().await.unwrap();

        let out = t.frame_text();
        assert_eq!(
            out.lines().next().unwrap().trim(),
            "background",
            "closing the modal should clear its backdrop, not leave it stale: {out:?}"
        );
    }

    struct MultiOverlayToggler;
    #[derive(Clone, PartialEq, Default)]
    struct MultiOverlayTogglerProps {
        show: crate::test_util::Shared<Option<crate::hooks::state::State<bool>>>,
    }
    impl Component for MultiOverlayToggler {
        type Props = MultiOverlayTogglerProps;
        fn render(props: &MultiOverlayTogglerProps, hooks: &mut Hooks) -> Element {
            use crate::props::Anchor;
            use crate::widgets::toast::{Toast, ToastProps};
            use crate::widgets::tooltip::{Tooltip, TooltipProps};

            let show = hooks.use_state(|| true);
            *props.show.lock() = Some(show.clone());
            let mut children = vec![
                Element::text(TextProps {
                    content: "background".into(),
                    ..Default::default()
                }),
                Element::component::<Tooltip>(TooltipProps {
                    message: "hint".into(),
                    anchor: Anchor::TopRight,
                }),
                Element::component::<Toast>(ToastProps {
                    message: "toast".into(),
                    duration: None,
                    ..Default::default()
                }),
            ];
            if show.get() {
                children.push(Element::component::<Modal>(ModalProps {
                    title: "t".into(),
                    message: "m".into(),
                    on_close: None,
                }));
            }
            Element::fragment(children)
        }
    }

    struct RawOverlayToggler;
    #[derive(Clone, PartialEq, Default)]
    struct RawOverlayTogglerProps {
        show: crate::test_util::Shared<Option<crate::hooks::state::State<bool>>>,
    }
    impl Component for RawOverlayToggler {
        type Props = RawOverlayTogglerProps;
        fn render(props: &RawOverlayTogglerProps, hooks: &mut Hooks) -> Element {
            use crate::props::Anchor;

            let show = hooks.use_state(|| true);
            *props.show.lock() = Some(show.clone());
            let mut children = vec![
                Element::text(TextProps {
                    content: "background".into(),
                    ..Default::default()
                }),
                Element::view(
                    ViewProps {
                        overlay: Some(Anchor::TopRight),
                        ..Default::default()
                    },
                    vec![Element::text(TextProps {
                        content: "hint".into(),
                        ..Default::default()
                    })],
                ),
                Element::view(
                    ViewProps {
                        overlay: Some(Anchor::BottomRight),
                        ..Default::default()
                    },
                    vec![Element::text(TextProps {
                        content: "toast".into(),
                        ..Default::default()
                    })],
                ),
            ];
            if show.get() {
                children.push(Element::view(
                    ViewProps {
                        overlay: Some(Anchor::Center),
                        width: Dimension::Cells(10),
                        height: Dimension::Cells(3),
                        border_style: crate::style::BorderStyle::Round,
                        ..Default::default()
                    },
                    vec![],
                ));
            }
            Element::fragment(children)
        }
    }

    #[tokio::test]
    async fn raw_view_overlays_also_clear_correctly_when_one_is_removed() {
        let show = crate::test_util::Shared::default();
        let mut t = TestTerminal::new(
            20,
            6,
            Element::component::<RawOverlayToggler>(RawOverlayTogglerProps { show: show.clone() }),
        )
        .unwrap();
        eprintln!("frame 1 (modal open):\n{}", t.frame_text());
        let handle = show.lock().clone().unwrap();
        handle.set(false);
        t.tick().await.unwrap();
        let out = t.frame_text();
        eprintln!("frame 2 (modal closed):\n{out}");
        assert_eq!(
            out.lines().next().unwrap().trim(),
            "background",
            "closing the raw-view overlay should clear it, not leave it stale: {out:?}"
        );
    }

    #[tokio::test]
    async fn closing_the_modal_clears_its_backdrop_even_alongside_other_overlays() {
        // Toast's own bordered box legitimately reaches row 0 at this small
        // a viewport height, so the right invariant isn't "row 0 is plain
        // background text" — it's "the screen after closing the modal looks
        // exactly like it would if the modal had never opened at all."
        let show = crate::test_util::Shared::default();
        let mut t = TestTerminal::new(
            20,
            10,
            Element::component::<MultiOverlayToggler>(MultiOverlayTogglerProps {
                show: show.clone(),
            }),
        )
        .unwrap();
        let with_modal = t.frame_text();
        assert!(
            with_modal.contains("╭") && with_modal.contains("╰"),
            "modal's dialog border should be visible: {with_modal:?}"
        );

        let handle = show.lock().clone().unwrap();
        handle.set(false);
        t.tick().await.unwrap();
        let after_close = t.frame_text();

        // Now render fresh with the modal never opened at all, at the same
        // size, and compare — this is the actual "did closing fully restore
        // things" invariant, independent of where Toast's own box happens to
        // land.
        let show2 = crate::test_util::Shared::default();
        let fresh = TestTerminal::new(
            20,
            10,
            Element::component::<MultiOverlayToggler>(MultiOverlayTogglerProps {
                show: show2.clone(),
            }),
        )
        .unwrap();
        let handle2 = show2.lock().clone().unwrap();
        handle2.set(false);
        let mut fresh = fresh;
        fresh.tick().await.unwrap();
        let never_opened = fresh.frame_text();

        assert_eq!(
            after_close, never_opened,
            "closing the modal should leave the screen identical to it never having opened"
        );
    }
}