datui-lib 0.4.0

Data Exploration in the Terminal (library)
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! One focus convention for every form and dialog.
//!
//! A form is an ordered list of fields, each of a [`FieldKind`]. A modal says which
//! fields it shows right now and which one has focus ([`Form`]); this module moves
//! focus and decides what a key means, so every dialog answers the same keys the
//! same way:
//!
//! | Key | Does |
//! |---|---|
//! | Tab / Shift+Tab, ↓ / ↑ | next / previous field, wrapping |
//! | ← / → | step a choice; move the cursor in a text field |
//! | Space | toggle a checkbox, next value of a choice, open a picker, press a button |
//! | Enter | submit, from any field (a multiline field types it; Ctrl+J submits) |
//! | Esc | cancel the form (an open picker closes first: [`picker_key`]) |
//! | Ctrl+P / Ctrl+N | history in a text field |
//!
//! `h` `j` `k` `l` are the arrows on a field that does not type. What a submit, a
//! step or an action does stays with the modal: [`key`] says which happened, to
//! which field.

use crate::widgets::ui::PickerState;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

/// How a field takes keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldKind {
    /// One line of text. The arrows across and every editing key are its own;
    /// Ctrl+P / Ctrl+N recall its history.
    Text,
    /// Several lines: Enter breaks the line, and ↑ / ↓ move between lines,
    /// leaving the field only from its first or last line ([`Form::text_edge`]).
    MultilineText,
    /// A value from a short list: ← / → step it, Space takes the next, wrapping.
    Choice,
    /// On or off: Space, ← or → flip it.
    Checkbox,
    /// A value from a list too long to step through: Space opens a picker. A
    /// pick-one picker also steps with ← / →; `multi` marks one that toggles
    /// several values, which does not.
    Picker { multi: bool },
    /// An action: Space does it.
    Button,
}

impl FieldKind {
    /// Whether the field takes typed characters, so letters are not keys there.
    pub fn types(self) -> bool {
        matches!(self, Self::Text | Self::MultilineText)
    }
}

/// What a key did to a form, for the modal to carry out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormKey<F> {
    /// Focus moved; nothing else to do.
    Moved,
    /// Enter (or Ctrl+J): apply the form.
    Submit,
    /// Esc: close the form, discarding its edits.
    Cancel,
    /// Step the field's value by `delta` (-1 or 1): ← / → on a choice or a pick-one
    /// picker, Space on a choice.
    Step(F, i8),
    /// Act on the field: flip a checkbox, open a picker, press a button.
    Act(F),
    /// The key belongs to the focused text field: hand it to its input.
    Text(F),
    /// Not a form key here; the modal's own keys (or none) take it.
    Other,
}

/// A form: its fields in order and the one with focus. The modal owns both; the
/// default methods move focus the same way for every form.
pub trait Form {
    /// The modal's name for a field.
    type Field: Copy + Eq + std::fmt::Debug;

    /// The fields on screen, top to bottom, each with its kind. A field the current
    /// state hides or disables is left out, so focus never lands on it.
    fn fields(&self) -> Vec<(Self::Field, FieldKind)>;

    fn focused(&self) -> Self::Field;

    /// Put focus on `field`. Called only with a field of [`Form::fields`]; a modal
    /// that shows a text cursor in the focused field syncs it here.
    fn set_focused(&mut self, field: Self::Field);

    /// For a multiline field: whether its cursor is on the first line, and on the
    /// last, where ↑ and ↓ leave it.
    fn text_edge(&self, _field: Self::Field) -> (bool, bool) {
        (true, true)
    }

    /// Whether `field` is a row of a list (a sort, a filter, a column) rather than a
    /// setting. A click on a list row only focuses it, so it can be picked to move or
    /// remove without changing it; a click on it once focused acts. A setting (a
    /// checkbox, a choice, a button) acts on the first click.
    fn list_row(&self, _field: Self::Field) -> bool {
        false
    }

    /// The focused field's kind; `None` when focus is on a field not shown.
    fn focused_kind(&self) -> Option<FieldKind> {
        let focused = self.focused();
        self.fields()
            .into_iter()
            .find(|(field, _)| *field == focused)
            .map(|(_, kind)| kind)
    }

    /// Focus `field` if the form shows it: a click on a row, or a modal moving
    /// focus itself. Returns whether it did.
    fn focus(&mut self, field: Self::Field) -> bool {
        let shown = self.fields().iter().any(|(f, _)| *f == field);
        if shown {
            self.set_focused(field);
        }
        shown
    }

    /// Move focus `delta` fields along, wrapping. A focus the form no longer shows
    /// counts from the top.
    fn move_focus(&mut self, delta: isize) {
        let fields = self.fields();
        if fields.is_empty() {
            return;
        }
        let focused = self.focused();
        let n = fields.len() as isize;
        let next = match fields.iter().position(|(f, _)| *f == focused) {
            Some(at) => (at as isize + delta).rem_euclid(n),
            None if delta < 0 => n - 1,
            None => 0,
        };
        self.set_focused(fields[next as usize].0);
    }

    fn focus_next(&mut self) {
        self.move_focus(1);
    }

    fn focus_prev(&mut self) {
        self.move_focus(-1);
    }

    /// After a change that hides fields: when the focused one went, focus the first
    /// field instead, so it never points at nothing.
    fn settle_focus(&mut self) {
        if self.focused_kind().is_none()
            && let Some((first, _)) = self.fields().first().copied()
        {
            self.set_focused(first);
        }
    }
}

fn plain(event: &KeyEvent) -> bool {
    event
        .modifiers
        .intersection(KeyModifiers::CONTROL | KeyModifiers::ALT)
        .is_empty()
}

/// What `event` does to `form` while no picker is open. Focus moves happen here;
/// everything else is returned for the modal to do.
pub fn key<T: Form + ?Sized>(form: &mut T, event: &KeyEvent) -> FormKey<T::Field> {
    let ctrl = event.modifiers.contains(KeyModifiers::CONTROL);
    let shift = event.modifiers.contains(KeyModifiers::SHIFT);
    let Some(kind) = form.focused_kind() else {
        // Focus on nothing (a form with no fields, or one just emptied): only the
        // ways in and out work.
        form.settle_focus();
        return match event.code {
            KeyCode::Esc => FormKey::Cancel,
            KeyCode::Enter => FormKey::Submit,
            _ => FormKey::Other,
        };
    };
    let field = form.focused();
    // A field that does not type reads hjkl as the arrows.
    let code = match event.code {
        KeyCode::Char('h') if !kind.types() && plain(event) => KeyCode::Left,
        KeyCode::Char('j') if !kind.types() && plain(event) => KeyCode::Down,
        KeyCode::Char('k') if !kind.types() && plain(event) => KeyCode::Up,
        KeyCode::Char('l') if !kind.types() && plain(event) => KeyCode::Right,
        code => code,
    };
    match code {
        KeyCode::Esc => FormKey::Cancel,
        // Ctrl+J beside Ctrl+Enter: some terminals send one as the other.
        KeyCode::Enter | KeyCode::Char('j' | 'J') if ctrl => FormKey::Submit,
        KeyCode::Enter if kind == FieldKind::MultilineText => FormKey::Text(field),
        KeyCode::Enter => FormKey::Submit,
        KeyCode::BackTab => {
            form.focus_prev();
            FormKey::Moved
        }
        KeyCode::Tab if shift => {
            form.focus_prev();
            FormKey::Moved
        }
        KeyCode::Tab => {
            form.focus_next();
            FormKey::Moved
        }
        KeyCode::Up | KeyCode::Down if event.modifiers.is_empty() => {
            let up = code == KeyCode::Up;
            if kind == FieldKind::MultilineText {
                let (first, last) = form.text_edge(field);
                if (up && !first) || (!up && !last) {
                    return FormKey::Text(field);
                }
            }
            form.move_focus(if up { -1 } else { 1 });
            FormKey::Moved
        }
        KeyCode::Left | KeyCode::Right => {
            let delta = if code == KeyCode::Left { -1 } else { 1 };
            match kind {
                FieldKind::Text | FieldKind::MultilineText => FormKey::Text(field),
                FieldKind::Choice | FieldKind::Picker { multi: false } => {
                    FormKey::Step(field, delta)
                }
                FieldKind::Checkbox => FormKey::Act(field),
                FieldKind::Picker { multi: true } | FieldKind::Button => FormKey::Other,
            }
        }
        KeyCode::Char(' ') if plain(event) => match kind {
            FieldKind::Text | FieldKind::MultilineText => FormKey::Text(field),
            FieldKind::Choice => FormKey::Step(field, 1),
            FieldKind::Checkbox | FieldKind::Picker { .. } | FieldKind::Button => {
                FormKey::Act(field)
            }
        },
        _ if kind.types() => FormKey::Text(field),
        _ => FormKey::Other,
    }
}

/// What a key did in an open picker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PickerKey {
    /// Moved or narrowed the list; nothing else to do.
    Handled,
    /// Esc: close the picker, choosing nothing.
    Close,
    /// Enter, or Space on a pick-one list: take the cursor's item and close.
    Choose,
    /// Space on a list that takes several: flip the cursor's item, staying open.
    Toggle,
    /// Tab / Shift+Tab: choose, close, and move focus on (`true`) or back.
    ChooseAndMove(bool),
    /// Not a picker key.
    Other,
}

/// What `event` does in an open picker: type to narrow, ↑↓ move, Space chooses
/// (or toggles in a list of several), Enter chooses, Esc closes the picker only.
/// A space never reaches the narrowing filter: it would match nothing and blank
/// the list under the key that opened it.
pub fn picker_key(picker: &mut PickerState, multi: bool, event: &KeyEvent) -> PickerKey {
    let shift = event.modifiers.contains(KeyModifiers::SHIFT);
    match event.code {
        KeyCode::Esc => PickerKey::Close,
        KeyCode::Enter => PickerKey::Choose,
        KeyCode::BackTab => PickerKey::ChooseAndMove(false),
        KeyCode::Tab => PickerKey::ChooseAndMove(!shift),
        KeyCode::Up => {
            picker.move_up();
            PickerKey::Handled
        }
        KeyCode::Down => {
            picker.move_down();
            PickerKey::Handled
        }
        KeyCode::Char(' ') if multi => PickerKey::Toggle,
        KeyCode::Char(' ') => PickerKey::Choose,
        KeyCode::Backspace => {
            picker.backspace();
            PickerKey::Handled
        }
        KeyCode::Char(c) => {
            picker.filter_key(c, event.modifiers);
            PickerKey::Handled
        }
        _ => PickerKey::Other,
    }
}

/// Index `at` stepped by `delta` through `len` values, wrapping.
pub fn step_index(at: usize, len: usize, delta: i8) -> usize {
    if len == 0 {
        return 0;
    }
    (at as isize + delta as isize).rem_euclid(len as isize) as usize
}

/// `current` stepped by `delta` through `all`, wrapping; the first value when
/// `current` is not among them.
pub fn step_value<T: Copy + PartialEq>(all: &[T], current: T, delta: i8) -> T {
    let at = all.iter().position(|v| *v == current);
    match at {
        Some(at) => all[step_index(at, all.len(), delta)],
        None => all[0],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum F {
        Name,
        Notes,
        Format,
        Header,
        Column,
        Tags,
        Go,
    }

    struct T {
        focus: F,
        show_header: bool,
        edge: (bool, bool),
    }

    impl Form for T {
        type Field = F;
        fn fields(&self) -> Vec<(F, FieldKind)> {
            let mut fields = vec![
                (F::Name, FieldKind::Text),
                (F::Notes, FieldKind::MultilineText),
                (F::Format, FieldKind::Choice),
            ];
            if self.show_header {
                fields.push((F::Header, FieldKind::Checkbox));
            }
            fields.extend([
                (F::Column, FieldKind::Picker { multi: false }),
                (F::Tags, FieldKind::Picker { multi: true }),
                (F::Go, FieldKind::Button),
            ]);
            fields
        }
        fn focused(&self) -> F {
            self.focus
        }
        fn set_focused(&mut self, field: F) {
            self.focus = field;
        }
        fn text_edge(&self, _: F) -> (bool, bool) {
            self.edge
        }
    }

    fn form() -> T {
        T {
            focus: F::Name,
            show_header: true,
            edge: (true, true),
        }
    }

    fn press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn ctrl(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    #[test]
    fn tab_and_the_arrows_walk_every_field_and_wrap() {
        let mut f = form();
        let mut walked = vec![f.focus];
        for _ in 0..7 {
            assert_eq!(key(&mut f, &press(KeyCode::Down)), FormKey::Moved);
            walked.push(f.focus);
        }
        assert_eq!(
            walked,
            [
                F::Name,
                F::Notes,
                F::Format,
                F::Header,
                F::Column,
                F::Tags,
                F::Go,
                F::Name
            ]
        );
        key(&mut f, &press(KeyCode::Up));
        assert_eq!(f.focus, F::Go, "↑ from the first field wraps to the last");
        key(&mut f, &press(KeyCode::Tab));
        assert_eq!(f.focus, F::Name);
        key(&mut f, &press(KeyCode::BackTab));
        assert_eq!(f.focus, F::Go);
        key(&mut f, &KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT));
        assert_eq!(
            f.focus,
            F::Tags,
            "Shift+Tab as Tab with Shift goes back too"
        );
    }

    #[test]
    fn hidden_fields_are_skipped_and_a_hidden_focus_settles() {
        let mut f = form();
        f.show_header = false;
        f.focus = F::Format;
        key(&mut f, &press(KeyCode::Down));
        assert_eq!(f.focus, F::Column);
        f.focus = F::Header;
        f.settle_focus();
        assert_eq!(f.focus, F::Name);
        assert!(!f.focus(F::Header), "a hidden field cannot take focus");
        assert!(f.focus(F::Tags));
        assert_eq!(f.focus, F::Tags);
    }

    #[test]
    fn the_arrows_across_step_choices_and_edit_text() {
        let mut f = form();
        assert_eq!(
            key(&mut f, &press(KeyCode::Left)),
            FormKey::Text(F::Name),
            "a text field keeps ← for its cursor"
        );
        f.focus = F::Format;
        assert_eq!(
            key(&mut f, &press(KeyCode::Left)),
            FormKey::Step(F::Format, -1)
        );
        assert_eq!(
            key(&mut f, &press(KeyCode::Right)),
            FormKey::Step(F::Format, 1)
        );
        f.focus = F::Column;
        assert_eq!(
            key(&mut f, &press(KeyCode::Right)),
            FormKey::Step(F::Column, 1)
        );
        f.focus = F::Tags;
        assert_eq!(key(&mut f, &press(KeyCode::Right)), FormKey::Other);
        f.focus = F::Header;
        assert_eq!(key(&mut f, &press(KeyCode::Right)), FormKey::Act(F::Header));
    }

    #[test]
    fn space_acts_on_the_field() {
        let mut f = form();
        let space = press(KeyCode::Char(' '));
        assert_eq!(key(&mut f, &space), FormKey::Text(F::Name), "text types it");
        f.focus = F::Format;
        assert_eq!(key(&mut f, &space), FormKey::Step(F::Format, 1));
        for field in [F::Header, F::Column, F::Tags, F::Go] {
            f.focus = field;
            assert_eq!(key(&mut f, &space), FormKey::Act(field));
        }
    }

    #[test]
    fn enter_submits_from_any_field_but_types_in_a_multiline_one() {
        let mut f = form();
        for field in [F::Name, F::Format, F::Header, F::Column, F::Tags, F::Go] {
            f.focus = field;
            assert_eq!(key(&mut f, &press(KeyCode::Enter)), FormKey::Submit);
        }
        f.focus = F::Notes;
        assert_eq!(key(&mut f, &press(KeyCode::Enter)), FormKey::Text(F::Notes));
        assert_eq!(key(&mut f, &ctrl('j')), FormKey::Submit);
        assert_eq!(
            key(
                &mut f,
                &KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL)
            ),
            FormKey::Submit
        );
    }

    #[test]
    fn esc_cancels_from_any_field() {
        let mut f = form();
        for field in [F::Name, F::Notes, F::Format, F::Go] {
            f.focus = field;
            assert_eq!(key(&mut f, &press(KeyCode::Esc)), FormKey::Cancel);
        }
    }

    #[test]
    fn history_is_ctrl_p_and_n_and_the_arrows_never_recall() {
        let mut f = form();
        assert_eq!(key(&mut f, &ctrl('p')), FormKey::Text(F::Name));
        assert_eq!(key(&mut f, &ctrl('n')), FormKey::Text(F::Name));
        assert_eq!(key(&mut f, &press(KeyCode::Up)), FormKey::Moved);
        assert_eq!(f.focus, F::Go);
    }

    #[test]
    fn a_multiline_field_keeps_the_arrows_until_its_edge() {
        let mut f = form();
        f.focus = F::Notes;
        f.edge = (false, false);
        assert_eq!(key(&mut f, &press(KeyCode::Up)), FormKey::Text(F::Notes));
        assert_eq!(key(&mut f, &press(KeyCode::Down)), FormKey::Text(F::Notes));
        f.edge = (true, false);
        assert_eq!(key(&mut f, &press(KeyCode::Up)), FormKey::Moved);
        assert_eq!(f.focus, F::Name);
    }

    #[test]
    fn vim_keys_move_only_where_nothing_types() {
        let mut f = form();
        assert_eq!(
            key(&mut f, &press(KeyCode::Char('j'))),
            FormKey::Text(F::Name)
        );
        f.focus = F::Format;
        assert_eq!(
            key(&mut f, &press(KeyCode::Char('l'))),
            FormKey::Step(F::Format, 1)
        );
        key(&mut f, &press(KeyCode::Char('j')));
        assert_eq!(f.focus, F::Header);
        key(&mut f, &press(KeyCode::Char('k')));
        assert_eq!(f.focus, F::Format);
        assert_eq!(key(&mut f, &press(KeyCode::Char('x'))), FormKey::Other);
    }

    #[test]
    fn the_picker_narrows_moves_and_never_types_a_space() {
        let mut p = PickerState::new(vec!["alpha".into(), "beta".into(), "gamma".into()]);
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::Down)),
            PickerKey::Handled
        );
        assert_eq!(p.selected_original(), Some(1));
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::Char('g'))),
            PickerKey::Handled
        );
        assert_eq!(p.filter, "g");
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::Char(' '))),
            PickerKey::Choose
        );
        assert_eq!(
            picker_key(&mut p, true, &press(KeyCode::Char(' '))),
            PickerKey::Toggle
        );
        assert_eq!(p.filter, "g", "a space never narrows");
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::Enter)),
            PickerKey::Choose
        );
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::Esc)),
            PickerKey::Close
        );
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::Tab)),
            PickerKey::ChooseAndMove(true)
        );
        assert_eq!(
            picker_key(&mut p, false, &press(KeyCode::BackTab)),
            PickerKey::ChooseAndMove(false)
        );
    }

    #[test]
    fn steps_wrap_both_ways() {
        assert_eq!(step_index(0, 3, -1), 2);
        assert_eq!(step_index(2, 3, 1), 0);
        assert_eq!(step_value(&['a', 'b', 'c'], 'b', 1), 'c');
        assert_eq!(step_value(&['a', 'b', 'c'], 'z', 1), 'a');
    }
}