quvyta-framework 0.1.33

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
//! Forms: fields laid out together, an error summary and Enter moving to the next field.

use super::cells;
use super::{Field, FormErrors};
use crate::event::Event;
use crate::geometry::{Rect, Size, clamp_u16};
use crate::keymap::Key;
use crate::text;
use crate::widget::{Axis, EventCx, Flex, Length, MeasureCx, Node, NodeMut, PaintCx, View, Widget};

/// Rows between the error summary and the first field.
const SUMMARY_GAP: u16 = 1;

/// A column of [`Field`]s that share one label layout, with an optional summary of problems
/// above them.
///
/// Enter in a field whose control does not use it (a text input without `on_submit`) moves
/// focus to the next field, and from the last field on to whatever follows the form, usually
/// its submit button. The form does not validate: the application checks its values into
/// [`FormErrors`], passes each message to its field and, on submit, returns
/// [`FormErrors::focus_first`].
///
/// Style keys: `form-summary` (`bg`, `padding`), `form-summary-title` (`fg`, `bold`),
/// `form-summary-marker` and `form-summary-item` (`fg`). The summary title is
/// `quvyta.form.summary` with `n` problems; its marker is the `error` icon.
pub struct Form<Msg> {
    label_width: Option<u16>,
    gap: u16,
    summary: Vec<String>,
    body: Vec<Node<Msg>>,
}

/// Adds fields to a [`Form`] inside [`Form::show`].
pub struct FormFields<'v, 'a, Msg> {
    ui: &'v mut View<'a, Msg>,
    label_width: Option<u16>,
}

impl<'a, Msg: 'static> FormFields<'_, 'a, Msg> {
    /// Adds `field` with the control built by `control`. The field takes the form's label
    /// width unless it has its own.
    pub fn field(&mut self, mut field: Field<Msg>, control: impl FnOnce(&mut View<'_, Msg>)) -> NodeMut<'_, Msg> {
        if field.label_width.is_none() {
            field.label_width = self.label_width;
        }
        self.ui.add_with(field, control).fill_width()
    }

    /// The form's column, for content between fields such as a sub-heading.
    pub fn ui(&mut self) -> &mut View<'a, Msg> {
        self.ui
    }
}

impl<Msg: 'static> Form<Msg> {
    /// A form with labels above controls and a row between fields.
    #[must_use]
    pub fn new() -> Self {
        Self { label_width: None, gap: 1, summary: Vec::new(), body: Vec::new() }
    }

    /// Puts every field's label in a column `cells` wide beside its control while the form is
    /// wide enough; on narrow screens labels move above controls.
    #[must_use]
    pub fn label_width(mut self, cells: u16) -> Self {
        self.label_width = Some(cells);
        self
    }

    /// Rows between fields; 1 by default.
    #[must_use]
    pub fn gap(mut self, rows: u16) -> Self {
        self.gap = rows;
        self
    }

    /// Lists every problem of `errors` above the fields. Nothing is shown while there are none.
    #[must_use]
    pub fn summary(mut self, errors: &FormErrors) -> Self {
        self.summary = errors.iter().map(|(_, message)| message.to_owned()).collect();
        self
    }

    /// Adds the form to `ui` with the fields `build` adds.
    pub fn show<'v>(
        mut self,
        ui: &'v mut View<'_, Msg>,
        build: impl FnOnce(&mut FormFields<'_, '_, Msg>),
    ) -> NodeMut<'v, Msg> {
        let mut children = Vec::new();
        build(&mut FormFields { ui: &mut ui.nested(&mut children), label_width: self.label_width });
        let mut column = Node::new(Flex::new(Axis::Column, children), 0);
        column.layout.gap = self.gap;
        column.layout.width = Length::Fill(1);
        self.body = vec![column];
        ui.add(self).fill_width()
    }

    /// Rows the error summary takes with `vertical_padding` above and below its lines, and the
    /// gap after it; nothing while there are no problems.
    fn summary_height(&self, vertical_padding: u16) -> u16 {
        if self.summary.is_empty() {
            return 0;
        }
        let rows = clamp_u16(i32::try_from(self.summary.len()).unwrap_or(i32::MAX)).saturating_add(1);
        cells::sum([rows, vertical_padding.saturating_mul(2), SUMMARY_GAP])
    }
}

impl<Msg: 'static> Default for Form<Msg> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Msg: 'static> Widget<Msg> for Form<Msg> {
    fn measure(&self, cx: &mut MeasureCx<'_>, available: Size) -> Size {
        let padding = cx.env().theme().style("form-summary", None, &[]).pair("padding").unwrap_or((1, 2));
        let summary = self.summary_height(padding.0);
        let body = self.body.first().map_or(Size::default(), |body| {
            cx.measure_child(body, Size::new(available.width, available.height.saturating_sub(summary)))
        });
        let widest = self
            .summary
            .iter()
            .map(|line| cells::sum([text::width(line), padding.1.saturating_mul(2), 3]))
            .max()
            .unwrap_or(0);
        Size::new(body.width.max(widest), body.height.saturating_add(summary)).min(available)
    }

    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
        let style = cx.style("form-summary", None, &[]);
        let padding = style.padding();
        let summary_height = self.summary_height(padding.top);
        if !self.summary.is_empty() {
            let block = Rect::new(area.x, area.y, area.width, summary_height - SUMMARY_GAP);
            cx.clear(block, style.text().bg.unwrap_or_else(|| cx.color("surface")));
            let inner = block.inset(padding);
            let marker = cx.env().icons().glyph("error").into_owned();
            let indent = text::width(&marker).saturating_add(2);
            let marker_style = cx.style("form-summary-marker", None, &[]).text();
            cx.text(inner.x, inner.y, &marker, marker_style, inner.width);
            let title = crate::t!("quvyta.form.summary", n = self.summary.len());
            let budget = inner.width.saturating_sub(indent);
            let title_style = cx.style("form-summary-title", None, &[]).text();
            let shown = text::truncate(&title, budget).into_owned();
            cx.text(inner.x + i32::from(indent), inner.y, &shown, title_style, budget);
            let item_style = cx.style("form-summary-item", None, &[]).text();
            for (row, message) in self.summary.iter().enumerate() {
                let y = inner.y + 1 + i32::try_from(row).unwrap_or(i32::MAX);
                let shown = text::truncate(message, budget).into_owned();
                cx.text(inner.x + i32::from(indent), y, &shown, item_style, budget);
            }
        }
        if let Some(body) = self.body.first() {
            let rest = Rect::new(
                area.x,
                area.y + i32::from(summary_height),
                area.width,
                area.height.saturating_sub(summary_height),
            );
            cx.paint_child(body, rest);
        }
    }

    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
        match event {
            Event::Key(key) if key.is_plain(Key::Enter) => {
                cx.focus_next();
                true
            }
            _ => false,
        }
    }

    fn children(&self) -> &[Node<Msg>] {
        &self.body
    }

    fn children_mut(&mut self) -> &mut [Node<Msg>] {
        &mut self.body
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::{App, Command, Harness};
    use crate::widgets::{Button, TextInput, ToastKind};

    #[derive(Default)]
    struct Signup {
        name: String,
        image: String,
        errors: FormErrors,
        submitted: bool,
        label_width: Option<u16>,
        summary: bool,
        /// A warning under the name control, which the application builds from the value and which
        /// never becomes a problem.
        warning: Option<&'static str>,
    }

    #[derive(Clone)]
    enum Msg {
        Name(String),
        Image(String),
        Submit,
    }

    impl Signup {
        fn validate(&mut self) {
            self.errors.check("name", self.name.chars().count() >= 3, "Use at least 3 characters");
            self.errors.check("image", !self.image.is_empty(), "Choose an image");
        }
    }

    impl App for Signup {
        type Msg = Msg;
        fn update(&mut self, msg: Msg) -> Command<Msg> {
            match msg {
                Msg::Name(name) => self.name = name,
                Msg::Image(image) => self.image = image,
                Msg::Submit => {
                    self.validate();
                    self.submitted = self.errors.is_empty();
                    return self.errors.focus_first();
                }
            }
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            let mut form = Form::new();
            if let Some(width) = self.label_width {
                form = form.label_width(width);
            }
            if self.summary {
                form = form.summary(&self.errors);
            }
            form.show(ui, |form| {
                form.field(
                    Field::new("Name")
                        .required(true)
                        .hint("Lowercase")
                        .error(self.errors.get("name"))
                        .warning(self.warning),
                    |ui| {
                        ui.add(TextInput::new(&self.name).invalid(self.errors.has("name")).on_change(Msg::Name))
                            .width(Length::Cells(20))
                            .id("name");
                    },
                );
                form.field(Field::new("Image").error(self.errors.get("image")), |ui| {
                    ui.add(TextInput::new(&self.image).on_change(Msg::Image)).width(Length::Cells(20)).id("image");
                });
            });
            ui.add(Button::new("Create").on_press(Msg::Submit)).id("create");
        }
    }

    /// A field to fill and a value to read, labels beside them.
    struct Install;

    impl App for Install {
        type Msg = String;
        fn update(&mut self, _: String) -> Command<String> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, String>) {
            Form::new().label_width(10).show(ui, |form| {
                form.field(Field::new("Name"), |ui| {
                    ui.add(TextInput::new("notes").on_change(|text| text)).width(Length::Cells(20));
                });
                form.field(Field::new("Folder").value("~/.local/share/notes"), |_| {});
            });
        }
    }

    #[test]
    fn a_value_field_lines_up_with_the_controls_and_its_label_steps_back() {
        let h = Harness::new(Install, 50, 6);
        let (value_x, value_y) = h.find("~/.local").unwrap_or_else(|| panic!("{}", h.screen()));
        let (_, name_y) = h.find("Name").expect("label");
        assert!(value_y > name_y);
        assert_eq!(value_x, 12, "the value starts in the controls' column, ten for labels and a gap:\n{}", h.screen());
        let (label_x, label_y) = h.find("Folder").expect("label");
        let muted = h.env().theme().color("muted");
        let at = |x: i32, y: i32| (u16::try_from(x).unwrap_or(0), u16::try_from(y).unwrap_or(0));
        let (x, y) = at(label_x, label_y);
        assert_eq!(h.fg(x, y), muted, "the value's label is faint");
        let (x, y) = at(h.find("Name").expect("label").0, name_y);
        assert_ne!(h.fg(x, y), muted, "a control's label is not");
    }

    #[test]
    fn labels_above_with_required_word_hint_and_error() {
        let mut h = Harness::new(Signup::default(), 40, 8);
        assert_eq!(h.screen(), "Name  required\n  ❯\nLowercase\n\nImage\n  ❯\n  Create\n\n");
        h.press("tab").type_text("ab");
        h.send(Msg::Submit);
        assert_eq!(h.screen().lines().nth(2), Some("✕ Use at least 3 characters"));
        assert_eq!(h.fg(2, 2), Some(h.env().theme().color("danger").expect("danger")));
        assert!(h.is_focused("name"), "submit focuses the first problem");
    }

    #[test]
    fn label_brightens_while_its_control_has_focus() {
        let mut h = Harness::new(Signup::default(), 40, 8);
        let idle = h.fg(0, 0);
        h.press("tab");
        assert_ne!(h.fg(0, 0), idle);
        assert!(h.is_bold(0, 0));
    }

    #[test]
    fn enter_moves_to_the_next_field_and_then_to_the_button() {
        let mut h = Harness::new(Signup::default(), 40, 8);
        h.press("tab").press("enter");
        assert!(h.is_focused("image"));
        h.press("enter");
        assert!(h.is_focused("create"));
        h.press("enter");
        assert!(!h.app().submitted);
        assert!(h.is_focused("name"));
    }

    #[test]
    fn labels_beside_controls_fall_back_above_when_narrow() {
        let app = Signup { label_width: Some(10), ..Signup::default() };
        let mut h = Harness::new(app, 40, 6);
        assert_eq!(h.screen(), "Name          ❯\nrequired    Lowercase\n\nImage         ❯\n  Create\n\n");
        let app = Signup { label_width: Some(10), ..Signup::default() };
        h = Harness::new(app, 24, 7);
        assert!(h.screen().starts_with("Name  required\n  ❯\n"), "{}", h.screen());
    }

    struct Note {
        placeholder: &'static str,
    }

    impl App for Note {
        type Msg = Msg;
        fn update(&mut self, _: Msg) -> Command<Msg> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            Form::new().label_width(16).show(ui, |form| {
                form.field(Field::new("Project"), |ui| {
                    ui.add(TextInput::new("").placeholder("qframe").on_change(Msg::Name));
                });
                form.field(Field::new("Note"), |ui| {
                    ui.add(TextInput::new("").placeholder(self.placeholder).on_change(Msg::Image));
                });
            });
        }
    }

    #[test]
    fn a_control_wider_than_the_room_beside_its_label_goes_under_it_and_keeps_its_placeholder() {
        for placeholder in ["A note for this session", "Eine Notiz für diese Sitzung"] {
            let h = Harness::new(Note { placeholder }, 40, 6);
            let screen = h.screen();
            assert!(!screen.contains('…') && screen.contains(placeholder), "{placeholder}: {screen}");
            let lines: Vec<&str> = screen.lines().collect();
            assert!(lines[0].starts_with("Project") && lines[0].contains("qframe"), "stays beside: {screen}");
            let note = lines.iter().position(|line| line.starts_with("Note")).unwrap_or_else(|| panic!("{screen}"));
            assert_eq!(lines[note].trim_end(), "Note", "the label has its own line: {screen}");
            assert!(lines[note + 1].contains(placeholder), "the control is right under it: {screen}");
        }
    }

    #[test]
    fn a_required_word_too_wide_for_the_label_column_moves_under_the_control() {
        for code in ["en", "de", "fr", "ru"] {
            let app = Signup { label_width: Some(8), ..Signup::default() };
            let mut h = Harness::new(app, 40, 7);
            h.set_locale(code);
            let screen = h.screen();
            let required = h.env().i18n().translate("quvyta.form.required", &[]);
            assert!(screen.contains(&required) && !screen.contains('…'), "{code}: {screen}");
            let lines: Vec<&str> = screen.lines().collect();
            let control = |line: &str| line.find('❯');
            let image = lines.iter().position(|line| line.starts_with("Image")).unwrap_or_else(|| panic!("{screen}"));
            assert_eq!(control(lines[0]), control(lines[image]), "the controls stay in one column: {code}: {screen}");
            if code != "en" {
                assert!(lines[1].trim_start().starts_with(required.as_str()), "under the control: {code}: {screen}");
                assert!(lines[2].trim_start().starts_with("Lowercase"), "the hint follows: {code}: {screen}");
            }
        }
    }

    #[test]
    fn summary_lists_problems_above_the_fields() {
        let app = Signup { summary: true, ..Signup::default() };
        let mut h = Harness::new(app, 40, 14);
        assert!(h.screen().starts_with("Name"));
        h.send(Msg::Submit);
        let screen = h.screen();
        assert!(screen.contains("✕  2 fields need attention"), "{screen}");
        assert!(screen.contains("Use at least 3 characters\n"), "{screen}");
    }

    /// The sign that stands in front of a sentence, and the tone it is drawn in.
    fn signed(h: &Harness<Signup>, sentence: &str, kind: ToastKind) {
        let (x, y) = h.find(sentence).unwrap_or_else(|| panic!("`{sentence}` is not on screen:\n{}", h.screen()));
        let (x, y) = (u16::try_from(x).unwrap_or(0), u16::try_from(y).unwrap_or(0));
        assert_eq!(x, 2, "the sign and a space stand in front of the sentence: {}", h.screen());
        let row = h.screen().lines().nth(usize::from(y)).unwrap_or_default().to_owned();
        assert_eq!(
            row.chars().next(),
            h.env().icons().glyph(kind.icon()).chars().next(),
            "and the sign is the one of its kind: {row}"
        );
        let tone =
            h.env().theme().color(kind.name()).unwrap_or_else(|| panic!("every theme has the four status colours"));
        assert_eq!(h.fg(0, y), Some(tone), "the sign carries the tone: {row}");
        assert_eq!(h.fg(x, y), Some(tone), "and so does the sentence: {row}");
    }

    #[test]
    fn a_warning_is_signed_and_the_form_it_belongs_to_still_submits() {
        let app = Signup {
            name: "web".into(),
            image: "nginx:1.27".into(),
            warning: Some("Not in the shared registry"),
            ..Signup::default()
        };
        let mut h = Harness::new(app, 40, 10);
        h.click_text("Create");
        signed(&h, "Not in the shared registry", ToastKind::Warning);
        assert!(!h.screen().contains("Lowercase"), "the warning stands where the hint was: {}", h.screen());
        assert!(h.app().submitted, "a form whose only note is a warning is still a form one sends");
    }

    #[test]
    fn an_error_takes_the_place_from_the_warning_and_the_form_does_not_submit() {
        let app = Signup {
            name: "w".into(),
            image: "nginx:1.27".into(),
            warning: Some("Not in the shared registry"),
            ..Signup::default()
        };
        let mut h = Harness::new(app, 40, 10);
        h.click_text("Create");
        let screen = h.screen();
        assert!(!screen.contains("Not in the shared registry"), "one place, and the error has it: {screen}");
        signed(&h, "Use at least 3 characters", ToastKind::Danger);
        assert!(!h.app().submitted, "an error is a problem, a warning is only a note");
    }
}