quvyta-framework 0.1.32

A Rust framework for building terminal applications
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
//! Checkboxes, and the two-cell choice box they share with radio groups.

use std::time::Duration;

use super::ToggleMessage;
use super::press::{self, Press};
use crate::event::Event;
use crate::geometry::{Rect, Size};
use crate::motion::{Easing, Tween};
use crate::style::CellStyle;
use crate::text;
use crate::theme::State;
use crate::widget::{EventCx, MeasureCx, PaintCx, Widget};

/// Width of the choice box, in cells.
pub(super) const BOX: u16 = 2;

/// Width of the check style's box, in cells.
const CHECK_BOX: u16 = 3;

/// Cells between a mark and its label.
pub(super) const LABEL_GAP: u16 = 2;

/// How many `motion.step`s a choice box takes to blend between empty and filled: as long as a
/// switch knob takes to cross its track, so the toggles of a form change together.
const BLEND_STEPS: u32 = 3;

/// Time between frames while a box blends.
const BLEND_FRAME: Duration = Duration::from_millis(16);

/// How a [`Checkbox`] looks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CheckboxStyle {
    /// A two-cell box of solid colour: filled when checked, the empty tone when not, and filled
    /// in its left cell only when partly checked. No glyph, so it looks the same in every glyph
    /// mode. It looks exactly like a radio group's box.
    #[default]
    Box,
    /// A three-cell box with a check `✓` when checked and a dash when partly checked.
    Check,
}

/// A box that is checked or not, with an optional label.
///
/// The default box is two cells of solid colour that blend from the empty tone to the filled
/// tone over the theme's `motion.step` times three when it changes; with reduced motion the
/// change is immediate. A partly checked box (a parent of some checked items) fills its left
/// cell. [`CheckboxStyle::Check`] draws the older three-cell box with a check or a dash. Enter,
/// Space or a click on the box or the label toggles it. The application owns the state.
///
/// Style keys: `checkbox` (`bg`, `fg`) with states `hover`, `focus`, `checked`, `disabled` and
/// variant `partial` (check style); `checkbox-label` (`fg`, `bold`) with the same states;
/// `checkbox-description` (`fg`) with the same states.
pub struct Checkbox<Msg> {
    label: Option<String>,
    description: Option<String>,
    checked: bool,
    partial: bool,
    style: CheckboxStyle,
    disabled: bool,
    on_toggle: Option<ToggleMessage<Msg>>,
}

impl<Msg> Checkbox<Msg> {
    /// A checkbox showing `checked`.
    #[must_use]
    pub fn new(checked: bool) -> Self {
        Self {
            label: None,
            description: None,
            checked,
            partial: false,
            style: CheckboxStyle::Box,
            disabled: false,
            on_toggle: None,
        }
    }

    /// Text after the box; clicking it toggles too.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// A faint explanation under the label, starting in the label's column and wrapping there,
    /// such as what checking the box will do. Clicking it toggles the box, as the label does.
    #[must_use]
    pub fn description(mut self, text: impl Into<String>) -> Self {
        self.description = Some(text.into());
        self
    }

    /// Cells from the checkbox's left edge to the first letter of its label: where text that
    /// belongs to the label, drawn outside the checkbox, lines up with it.
    #[must_use]
    pub fn label_column(&self) -> u16 {
        self.box_width().saturating_add(LABEL_GAP)
    }

    /// Shows the box partly checked. Toggling a partly checked box asks for `true`.
    #[must_use]
    pub fn partial(mut self, partial: bool) -> Self {
        self.partial = partial;
        self
    }

    /// Chooses how the box looks.
    #[must_use]
    pub fn style(mut self, style: CheckboxStyle) -> Self {
        self.style = style;
        self
    }

    /// Greys the checkbox out; it cannot be focused or toggled.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Message for the new state when the checkbox is toggled.
    #[must_use]
    pub fn on_toggle(mut self, message: impl Fn(bool) -> Msg + 'static) -> Self {
        self.on_toggle = Some(Box::new(message));
        self
    }

    fn active(&self) -> bool {
        !self.disabled && self.on_toggle.is_some()
    }

    /// The description wrapped to the room right of the label's column in `width` cells.
    fn description_lines(&self, width: u16) -> Vec<String> {
        let room = width.saturating_sub(self.label_column()).max(1);
        self.description.as_deref().map_or_else(Vec::new, |description| text::wrap(description, room))
    }

    fn box_width(&self) -> u16 {
        match self.style {
            CheckboxStyle::Box => BOX,
            CheckboxStyle::Check => CHECK_BOX,
        }
    }
}

/// The blend of every choice box a widget draws, by index.
#[derive(Debug, Default)]
struct BoxBlends(Vec<Tween>);

/// How filled choice box `index` of this widget is, moving towards `target` (0 empty, 1 filled).
/// A box starts at its first target without animating.
fn blend(cx: &mut PaintCx<'_>, index: usize, target: f32) -> f32 {
    if cx.reduced_motion() {
        return target;
    }
    let now = cx.now();
    let duration = cx.env().theme().motion().step * BLEND_STEPS;
    let blends = &mut cx.memory::<BoxBlends>().0;
    if blends.len() <= index {
        blends.resize(index + 1, Tween::settled(target));
    }
    let tween = &mut blends[index];
    if tween.target() != target {
        tween.retarget(target, now, duration, Easing::Linear);
    }
    let (value, running) = (tween.value(now), tween.is_running(now));
    if running {
        cx.request_frame_in(BLEND_FRAME);
    }
    value
}

/// Paints a two-cell choice box at `(x, y)` from the `bg` of `widget`/`variant`: each cell mixes
/// the empty colour (the states without `checked`) into the filled colour (with `checked`) by its
/// fill. Blends are kept per `index` so a group of boxes animates each one on its own.
pub(super) fn paint_box(
    cx: &mut PaintCx<'_>,
    at: (i32, i32),
    style: (&str, Option<&str>),
    states: &[State],
    blends: (usize, [f32; 2]),
) {
    let (widget, variant) = style;
    let mut empty_states: Vec<State> = states.iter().copied().filter(|s| *s != State::Checked).collect();
    let empty = cx.style(widget, variant, &empty_states).text().bg.unwrap_or_else(|| cx.color("raised"));
    empty_states.push(State::Checked);
    let filled = cx.style(widget, variant, &empty_states).text().bg.unwrap_or_else(|| cx.color("accent"));
    let (index, targets) = blends;
    for (cell, target) in (0..BOX).zip(targets) {
        let fill = blend(cx, index * usize::from(BOX) + usize::from(cell), target);
        cx.clear(Rect::new(at.0 + i32::from(cell), at.1, 1, 1), empty.mix(filled, fill));
    }
}

impl<Msg: 'static> Widget<Msg> for Checkbox<Msg> {
    fn measure(&self, _cx: &mut MeasureCx<'_>, available: Size) -> Size {
        let label = self.label.as_deref().map_or(0, |label| text::width(label).saturating_add(LABEL_GAP));
        let lines = self.description_lines(available.width);
        let described = lines
            .iter()
            .map(|line| text::width(line))
            .max()
            .map_or(0, |width| width.saturating_add(self.label_column()));
        let height = u16::try_from(lines.len()).unwrap_or(u16::MAX).saturating_add(1);
        Size::new(self.box_width().saturating_add(label).max(described), height).min(available)
    }

    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
        let mut states = if self.active() { cx.pressable_states() } else { Vec::new() };
        if self.disabled {
            states.push(State::Disabled);
        }
        if self.checked || self.partial {
            states.push(State::Checked);
        }
        let box_width = self.box_width();
        match self.style {
            CheckboxStyle::Box => {
                let left = if self.checked || self.partial { 1.0 } else { 0.0 };
                let right = if self.checked { 1.0 } else { 0.0 };
                paint_box(cx, (area.x, area.y), ("checkbox", None), &states, (0, [left, right]));
            }
            CheckboxStyle::Check => {
                let variant = (self.partial && !self.checked).then_some("partial");
                let style = cx.style("checkbox", variant, &states).text();
                let background = style.bg.unwrap_or_else(|| cx.color("raised"));
                cx.clear(Rect::new(area.x, area.y, box_width.min(area.width), 1), background);
                if self.checked || self.partial {
                    let key = if self.checked { "check" } else { "check-partial" };
                    let glyph = cx.env().icons().glyph(key).into_owned();
                    cx.text(area.x + 1, area.y, &glyph, CellStyle { bg: None, ..style }, 1);
                }
            }
        }
        if let Some(label) = &self.label {
            let label_style = cx.style("checkbox-label", None, &states).text();
            let budget = area.width.saturating_sub(box_width + LABEL_GAP);
            let shown = text::truncate(label, budget).into_owned();
            cx.text(area.x + i32::from(box_width + LABEL_GAP), area.y, &shown, label_style, budget);
        }
        let description_style = cx.style("checkbox-description", None, &states).text();
        let column = area.x + i32::from(self.label_column());
        let budget = area.width.saturating_sub(self.label_column());
        for (y, line) in (area.y + 1..area.bottom()).zip(self.description_lines(area.width)) {
            cx.text(column, y, &line, description_style, budget);
        }
        if self.active() {
            cx.register_hit(area);
        }
    }

    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
        if !self.active() {
            return false;
        }
        match press::read(cx, event) {
            Press::Ignored => false,
            Press::Used => true,
            Press::Key | Press::Click(..) => {
                if let Some(message) = &self.on_toggle {
                    cx.emit(message(!self.checked || self.partial));
                }
                true
            }
        }
    }

    fn focusable(&self) -> bool {
        self.active()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::icons::GlyphMode;
    use crate::runtime::{App, Command, Harness};
    use crate::widget::View;

    #[derive(Default)]
    struct Demo {
        checked: bool,
        partial: bool,
        style: CheckboxStyle,
        disabled: bool,
    }

    impl App for Demo {
        type Msg = bool;
        fn update(&mut self, on: bool) -> Command<bool> {
            self.checked = on;
            self.partial = false;
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, bool>) {
            ui.add(
                Checkbox::new(self.checked)
                    .partial(self.partial)
                    .style(self.style)
                    .disabled(self.disabled)
                    .label("Autosave")
                    .on_toggle(|on| on),
            )
            .id("box");
        }
    }

    /// A checkbox with a description, in the style `style`.
    struct Described {
        checked: bool,
        style: CheckboxStyle,
    }

    impl App for Described {
        type Msg = bool;
        fn update(&mut self, on: bool) -> Command<bool> {
            self.checked = on;
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, bool>) {
            ui.add(
                Checkbox::new(self.checked)
                    .style(self.style)
                    .label("Keep backups")
                    .description("Old copies stay in the backup folder for thirty days")
                    .on_toggle(|on| on),
            );
        }
    }

    fn column_of(h: &Harness<Described>, word: &str) -> (i32, i32) {
        h.find(word).unwrap_or_else(|| panic!("{word}:\n{}", h.screen()))
    }

    #[test]
    fn a_description_starts_in_the_labels_column_and_wraps_there() {
        for style in [CheckboxStyle::Box, CheckboxStyle::Check] {
            let h = Harness::new(Described { checked: false, style }, 30, 5);
            let (label, row) = column_of(&h, "Keep");
            let (old, below) = column_of(&h, "Old");
            assert_eq!((old, below), (label, row + 1), "{style:?}:\n{}", h.screen());
            let (days, last) = column_of(&h, "days");
            assert!(last > below, "a narrow box wraps the description:\n{}", h.screen());
            assert!(days >= label, "and every line keeps to the column:\n{}", h.screen());
            assert_eq!(i32::from(Checkbox::<bool>::new(false).style(style).label_column()), label);
        }
    }

    #[test]
    fn clicking_the_description_toggles_the_box() {
        let mut h = Harness::new(Described { checked: false, style: CheckboxStyle::Box }, 60, 3);
        let (x, y) = column_of(&h, "thirty");
        h.click(x, y);
        assert!(h.app().checked);
    }

    #[test]
    fn the_default_box_is_two_cells_of_colour_that_fill_when_checked() {
        let mut h = Harness::new(Demo::default(), 20, 1);
        h.set_reduced_motion(true);
        assert_eq!(h.screen(), "    Autosave\n", "no glyph, no bracket");
        let theme = h.env().theme().clone();
        assert_eq!(
            (h.bg(0, 0), h.bg(1, 0), h.bg(2, 0)),
            (theme.color("raised"), theme.color("raised"), theme.color("canvas"))
        );
        h.click_text("Autosave");
        assert!(h.app().checked);
        h.hover(19, 0);
        assert_eq!(h.screen(), "    Autosave\n", "a checkbox shows no pillar");
        assert_eq!((h.bg(0, 0), h.bg(1, 0)), (theme.color("accent"), theme.color("accent")));
        h.press("tab").press("space");
        assert!(!h.app().checked, "the keyboard toggles too");
    }

    #[test]
    fn the_whole_label_area_toggles() {
        let mut h = Harness::new(Demo::default(), 20, 1);
        for x in [0, 1, 2, 3, 6, 11] {
            let before = h.app().checked;
            h.click(x, 0);
            assert_ne!(h.app().checked, before, "a click at column {x} toggles");
        }
    }

    #[test]
    fn hover_lightens_the_empty_box_and_keyboard_focus_tints_it() {
        let mut h = Harness::new(Demo::default(), 20, 1);
        let theme = h.env().theme().clone();
        let rest = h.bg(0, 0);
        h.hover(6, 0);
        assert_eq!(h.bg(0, 0), theme.color("active"));
        assert_ne!(h.bg(0, 0), rest);
        h.hover(19, 0);
        assert_eq!(h.bg(0, 0), rest);
        h.hover(40, 0).press("tab");
        assert_ne!(h.bg(0, 0), rest, "keyboard focus shows on the box");
        assert_ne!(h.bg(0, 0), theme.color("accent"), "focus is a tint, not the checked fill");
    }

    #[test]
    fn checking_blends_the_colour_over_three_steps_and_reduced_motion_jumps() {
        let mut h = Harness::new(Demo::default(), 20, 1);
        let theme = h.env().theme().clone();
        let step = theme.motion().step;
        h.hover(40, 0);
        h.send(true);
        let (empty, filled) = (theme.color("raised").expect("raised"), theme.color("accent").expect("accent"));
        assert_eq!(h.bg(0, 0), Some(empty), "the change starts from the empty tone");
        h.advance(step * 3 / 2);
        let middle = empty.mix(filled, 0.5);
        let shown = h.bg(0, 0).expect("colour");
        let close = |a: u8, b: u8| a.abs_diff(b) <= 3;
        assert!(close(shown.r, middle.r) && close(shown.g, middle.g), "halfway is the middle colour: {shown:?}");
        assert_eq!(h.bg(0, 0), h.bg(1, 0), "both cells blend together");
        h.advance(step * 2);
        assert_eq!(h.bg(0, 0), Some(filled));
        h.set_reduced_motion(true);
        h.send(false);
        assert_eq!(h.bg(1, 0), Some(empty), "reduced motion empties at once");
    }

    #[test]
    fn partial_fills_the_left_cell_and_asks_for_checked() {
        let mut h = Harness::new(Demo { partial: true, ..Demo::default() }, 20, 1);
        let theme = h.env().theme().clone();
        assert_eq!(h.screen(), "    Autosave\n");
        assert_eq!((h.bg(0, 0), h.bg(1, 0)), (theme.color("accent"), theme.color("raised")));
        h.click_text("Autosave");
        assert!(h.app().checked);
    }

    #[test]
    fn ascii_mode_draws_the_same_box() {
        let mut h = Harness::new(Demo { checked: true, ..Demo::default() }, 20, 1);
        let unicode = (h.screen(), h.bg(0, 0), h.bg(1, 0));
        h.set_glyph_mode(GlyphMode::Ascii);
        assert_eq!((h.screen(), h.bg(0, 0), h.bg(1, 0)), unicode);
    }

    #[test]
    fn disabled_uses_the_disabled_tones_and_ignores_presses() {
        let mut h = Harness::new(Demo { checked: true, disabled: true, ..Demo::default() }, 20, 1);
        let theme = h.env().theme().clone();
        assert_eq!(h.bg(0, 0), theme.color("active"));
        assert_eq!(h.fg(4, 0), theme.color("muted"));
        h.click_text("Autosave").press("tab").press("space");
        assert!(h.app().checked);
        let h = Harness::new(Demo { disabled: true, ..Demo::default() }, 20, 1);
        assert_eq!(h.bg(0, 0), theme.color("raised"));
    }

    #[test]
    fn the_check_style_keeps_the_three_cell_box_with_a_mark() {
        let mut h = Harness::new(Demo { style: CheckboxStyle::Check, ..Demo::default() }, 20, 1);
        h.set_glyph_mode(GlyphMode::Unicode);
        assert_eq!(h.screen(), "     Autosave\n");
        assert_eq!(h.bg(1, 0), h.env().theme().color("raised"));
        h.click_text("Autosave");
        assert_eq!(h.screen(), " ✓   Autosave\n");
        let mut h = Harness::new(Demo { style: CheckboxStyle::Check, partial: true, ..Demo::default() }, 20, 1);
        h.set_glyph_mode(GlyphMode::Unicode);
        assert_eq!(h.screen(), " –   Autosave\n");
    }

    #[test]
    fn a_narrow_space_keeps_the_box_and_cuts_the_label() {
        let h = Harness::new(Demo::default(), 8, 1);
        assert_eq!(h.screen(), "    Aut…\n");
    }
}