quvyta-framework 0.1.35

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
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
use super::*;
use crate::color::Rgb;
use crate::env::Env;
use crate::event::{MouseButton, MouseKind};
use crate::icons::Glyph;
use crate::icons::GlyphMode;
use crate::keymap::Scope;
use crate::runtime::{App, Command, Harness};
use crate::text;
use crate::widget::{Align, Length, View};
use crate::widgets::ContextItem;

struct Demo {
    rows: Arc<[TableRow]>,
    selected: Option<usize>,
    opened: Vec<usize>,
    checked: Option<Vec<bool>>,
    sort: Option<(usize, SortDirection)>,
    wide: bool,
    /// Whether every row carries a menu of its own.
    menu: bool,
    /// The rows a menu entry was chosen on, in order.
    removed: Vec<usize>,
    /// Whether Enter and a click open a row's menu instead of opening the row.
    menu_on_activate: bool,
    /// A row whose menu has nothing in it.
    bare: Option<usize>,
}

#[derive(Clone)]
enum Msg {
    Select(usize),
    Open(usize),
    Toggle(usize),
    Sort(usize, SortDirection),
    Remove(usize),
}

impl App for Demo {
    type Msg = Msg;
    fn update(&mut self, msg: Msg) -> Command<Msg> {
        match msg {
            Msg::Select(i) => self.selected = Some(i),
            Msg::Open(i) => self.opened.push(i),
            Msg::Toggle(i) => {
                if let Some(checked) = &mut self.checked {
                    checked[i] = !checked[i];
                }
            }
            Msg::Sort(column, direction) => self.sort = Some((column, direction)),
            Msg::Remove(i) => self.removed.push(i),
        }
        Command::none()
    }
    fn view(&self, ui: &mut View<'_, Msg>) {
        let mut columns = vec![
            Column::new("Name").sortable(true),
            Column::new("CPU").width(ColumnWidth::Fit).align(Align::End).sortable(true),
        ];
        if self.wide {
            columns.push(Column::new("Image").width(ColumnWidth::Fixed(12)));
            columns.push(Column::new("Ports").width(ColumnWidth::Fixed(12)));
        }
        let mut table = Table::new(columns, Arc::clone(&self.rows))
            .selected(self.selected)
            .empty_text("No containers")
            .on_select(Msg::Select)
            .on_activate(Msg::Open)
            .on_toggle(Msg::Toggle)
            .on_sort(Msg::Sort);
        if let Some((column, direction)) = self.sort {
            table = table.sort(column, direction);
        }
        if let Some(checked) = &self.checked {
            table = table.checked(checked.clone());
        }
        if self.menu {
            let rows = Arc::clone(&self.rows);
            let bare = self.bare;
            table = table
                .context_menu(move |index| {
                    if Some(index) == bare {
                        return Vec::new();
                    }
                    let name = rows[index].cells[0].text.clone();
                    vec![ContextItem::new(format!("Remove {name}"), Msg::Remove(index))]
                })
                .menu_on_activate(self.menu_on_activate);
        }
        ui.add(table).width(Length::Fill(1)).height(Length::Fill(1)).id("table");
    }
}

fn rows(count: usize) -> Arc<[TableRow]> {
    (0..count)
        .map(|i| TableRow::new([format!("svc-{i}"), format!("{}%", i * 3), "nginx".into(), "80".into()]))
        .collect()
}

fn demo(count: usize) -> Demo {
    Demo {
        rows: rows(count),
        selected: None,
        opened: Vec::new(),
        checked: None,
        sort: None,
        wide: false,
        menu: false,
        removed: Vec::new(),
        menu_on_activate: false,
        bare: None,
    }
}

#[test]
fn header_rows_and_right_aligned_numbers() {
    let mut h = Harness::new(demo(3), 30, 4);
    h.set_glyph_mode(GlyphMode::Unicode);
    assert_eq!(
        h.screen(),
        "  Name                     CPU\n  svc-0                     0%\n  svc-1                     3%\n  svc-2                     6%\n"
    );
    let raised = h.env().theme().color("raised");
    assert_eq!(h.bg(10, 0), raised, "the header sits on the raised surface");
    assert_eq!(h.fg(2, 0), h.env().theme().color("muted"), "titles are faint");
}

#[test]
fn selection_slides_only_the_first_cell() {
    let mut h = Harness::new(demo(3), 30, 4);
    h.press("tab").press("down");
    assert_eq!(h.app().selected, Some(0));
    let screen = h.screen();
    assert_eq!(screen.lines().nth(1), Some("▌  svc-0                    0%"), "{screen}");
    h.press("down");
    let active: Option<Rgb> = h.env().theme().color("active");
    assert_eq!(h.bg(20, 2), active);
    h.press("enter");
    assert_eq!(h.app().opened, vec![1]);
    assert_ne!(h.bg(20, 2), active, "activation flashes the row");
}

#[test]
fn sorts_from_titles_and_keys() {
    let mut h = Harness::new(demo(3), 30, 4);
    h.click_text("CPU");
    assert_eq!(h.app().sort, Some((1, SortDirection::Ascending)));
    assert!(h.screen().starts_with("  Name                   ↑ CPU"), "{}", h.screen());
    h.click_text("CPU");
    assert_eq!(h.app().sort, Some((1, SortDirection::Descending)));
    h.press("tab").press("s");
    assert_eq!(h.app().sort, Some((0, SortDirection::Ascending)));
    h.press("shift+s");
    assert_eq!(h.app().sort, Some((0, SortDirection::Descending)));
}

#[test]
fn virtualises_huge_tables_and_follows_the_selection() {
    let mut h = Harness::new(demo(200_000), 30, 6);
    h.press("tab").press("end");
    assert_eq!(h.app().selected, Some(199_999));
    let screen = h.screen();
    assert!(screen.contains("svc-199999"), "{screen}");
    assert!(!super::super::scrollbar::column(&h, 29).chars().skip(1).any(|c| c == ' '), "{screen}");
    h.press("pgup");
    assert_eq!(h.app().selected, Some(199_994));
}

#[test]
fn overflowing_columns_scroll_sideways() {
    let mut app = demo(2);
    app.wide = true;
    let mut h = Harness::new(app, 30, 3);
    let screen = h.screen();
    assert!(screen.contains("Name") && !screen.contains("Ports"), "{screen}");
    assert!(screen.lines().next().is_some_and(|l| l.ends_with('▶')), "{screen}");
    h.press("tab").press("right").press("right").press("right");
    let screen = h.screen();
    assert!(screen.contains("Ports") && !screen.contains("Name"), "{screen}");
    assert!(screen.starts_with('◀'), "{screen}");
    h.press("left").press("left").press("left");
    assert!(h.screen().contains("Name"));
}

#[test]
fn the_scroll_arrows_are_buttons() {
    let mut app = demo(2);
    app.wide = true;
    let mut h = Harness::new(app, 30, 3);
    h.set_glyph_mode(GlyphMode::Unicode);
    let screen = h.screen();
    let lines: Vec<&str> = screen.lines().collect();
    assert!(lines[0].ends_with(" ▶"), "the arrow has its own cell:\n{screen}");
    assert!(lines[1..].iter().all(|line| line.chars().count() < 29), "no value runs under the arrow:\n{screen}");
    let color = |h: &Harness<Demo>, token: &str| h.env().theme().color(token);
    assert_eq!(h.fg(29, 0), color(&h, "dim"), "a clickable arrow is not faint");
    h.hover(29, 0);
    assert_eq!(h.bg(29, 0), color(&h, "active"), "it rises under the pointer");
    assert_eq!(h.fg(29, 0), color(&h, "text"));
    h.click(29, 0).click(29, 0).click(29, 0);
    let screen = h.screen();
    assert!(screen.contains("Ports") && !screen.contains("Name"), "{screen}");
    assert!(screen.starts_with('◀') && !screen.lines().next().is_some_and(|l| l.ends_with('▶')), "{screen}");
    h.click(0, 0);
    assert!(h.screen().lines().next().is_some_and(|l| l.ends_with('▶')), "{}", h.screen());
    h.click(0, 0).click(0, 0);
    assert!(h.screen().starts_with("  Name"), "back at the first column the arrow is gone:\n{}", h.screen());
    h.click(0, 0);
    assert_eq!(h.app().sort, None, "a press where no arrow is drawn does nothing");
}

#[test]
fn a_clipped_last_column_leaves_the_arrow_and_its_air_free() {
    let mut app = demo(2);
    app.wide = true;
    let mut h = Harness::new(app, 36, 3);
    h.set_glyph_mode(GlyphMode::Unicode);
    assert_eq!(h.screen().lines().next(), Some("  Name      CPU  Image         Po… ▶"), "{}", h.screen());
    let mut app = demo(2);
    app.wide = true;
    let mut h = Harness::new(app, 38, 3);
    h.set_glyph_mode(GlyphMode::Unicode);
    assert_eq!(h.screen().lines().next(), Some("  Name      CPU  Image         Ports ▶"), "{}", h.screen());
}

#[test]
fn check_marks_stay_put_while_the_first_cell_slides() {
    let mut app = demo(2);
    app.checked = Some(vec![false, false]);
    let mut h = Harness::new(app, 30, 3);
    h.hover(10, 2);
    assert_eq!(
        h.screen(),
        "    Name                   CPU\n  ☐ svc-0                   0%\n▌ ☐  svc-1                  3%\n"
    );
    let mut env = crate::env::Env::builtin();
    env.set_slide(false);
    let mut app = demo(2);
    app.checked = Some(vec![false, false]);
    let mut h = Harness::with_env(app, env, 30, 3);
    h.hover(10, 2);
    assert_eq!(
        h.screen(),
        "    Name                   CPU\n  ☐ svc-0                   0%\n▌ ☐ svc-1                   3%\n"
    );
}

#[test]
fn multi_select_marks_and_click_toggle() {
    let mut app = demo(2);
    app.checked = Some(vec![false, false]);
    let mut h = Harness::new(app, 30, 3);
    h.hover(10, 2).click(2, 2);
    assert_eq!(h.app().checked.as_deref(), Some(&[false, true][..]));
    assert_eq!((h.app().selected, h.app().opened.as_slice()), (None, &[][..]), "the mark only toggles");
    assert_eq!(h.screen().lines().nth(2), Some("▌ ☑  svc-1                  3%"), "{}", h.screen());
    assert_eq!(h.fg(2, 2), h.env().theme().color("accent"));
    h.click(3, 1);
    assert_eq!(h.app().checked.as_deref(), Some(&[true, true][..]), "the cell after the mark toggles too");
    h.click(4, 1);
    assert_eq!((h.app().selected, h.app().opened.as_slice()), (Some(0), &[0][..]), "the first cell opens the row");
    h.press("down").press("space");
    assert_eq!(h.app().checked.as_deref(), Some(&[true, false][..]));
}

#[test]
fn empty_and_ascii_and_narrow() {
    let h = Harness::new(demo(0), 30, 3);
    assert_eq!(h.screen(), "  Name                     CPU\n  No containers\n\n");
    let mut h = Harness::new(demo(1), 9, 2);
    h.set_glyph_mode(GlyphMode::Ascii);
    let screen = h.screen();
    assert!(!screen.contains('['), "{screen}");
    assert_eq!(screen.lines().count(), 2);
}

#[test]
fn huge_fixed_columns_scroll_instead_of_overflowing() {
    struct Wide;
    impl App for Wide {
        type Msg = ();
        fn update(&mut self, _: ()) -> Command<()> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, ()>) {
            let columns = [
                Column::new("Name").width(ColumnWidth::Fixed(40_000)),
                Column::new("Image").width(ColumnWidth::Fixed(40_000)),
            ];
            ui.add(Table::<()>::new(columns, rows(2))).fill();
        }
    }
    let h = Harness::new(Wide, 30, 3);
    assert!(h.screen().starts_with("  Name"), "{}", h.screen());
}

/// A table whose column titles and whose one name are all wider than their columns.
struct Cramped;

impl App for Cramped {
    type Msg = ();
    fn update(&mut self, _: ()) -> Command<()> {
        Command::none()
    }
    fn view(&self, ui: &mut View<'_, ()>) {
        let columns = [
            Column::new("Container name").width(ColumnWidth::Fixed(8)),
            Column::new("Processor").width(ColumnWidth::Fixed(6)),
        ];
        let rows: Arc<[TableRow]> = vec![TableRow::new(["kubernetes-dashboard-proxy", "12%"])].into();
        ui.add(Table::<()>::new(columns, rows)).fill();
    }
}

/// Every character on screen that an ASCII terminal cannot show, with its cell.
fn non_ascii_cells<A: App>(h: &Harness<A>) -> Vec<(u16, u16, String)> {
    let buffer = h.buffer();
    let area = buffer.area;
    let mut found = Vec::new();
    for y in 0..area.height {
        for x in 0..area.width {
            let symbol = buffer[(x, y)].symbol();
            if !symbol.is_ascii() {
                found.push((x, y, symbol.to_owned()));
            }
        }
    }
    found
}

#[test]
fn in_ascii_mode_a_cut_name_and_a_cut_title_end_in_an_ascii_mark() {
    let mut h = Harness::new(Cramped, 24, 3);
    h.set_glyph_mode(GlyphMode::Ascii);
    let ascii = h.screen();
    assert_eq!(non_ascii_cells(&h), [], "nothing an ASCII terminal cannot show:\n{ascii}");
    let mut lines = ascii.lines();
    let (header, row) = (lines.next().unwrap_or_default(), lines.next().unwrap_or_default());
    assert!(header.contains("Cont") && header.matches(text::ASCII_ELLIPSIS).count() == 2, "{header:?}");
    assert!(row.contains("kube") && row.contains(text::ASCII_ELLIPSIS), "the name is cut, and shows it: {row:?}");

    h.set_glyph_mode(GlyphMode::Unicode);
    let unicode = h.screen();
    assert_eq!(unicode.matches(text::ELLIPSIS).count(), 3, "Unicode keeps the ellipsis:\n{unicode}");
    assert_eq!(
        unicode.replace(text::ELLIPSIS, text::ASCII_ELLIPSIS),
        ascii,
        "the mark takes the ellipsis's cell and nothing else moves"
    );
}

const FIREFOX: char = '\u{e745}';

/// Two rows whose names carry a glyph: a literal one and an icon of the set.
fn icon_demo(name: &str) -> Demo {
    let rows: Arc<[TableRow]> = vec![
        TableRow::new([TableCell::new(name).icon(Glyph::literal(FIREFOX), None), TableCell::new("3%")]),
        TableRow::new([TableCell::new("projects").icon(Glyph::key("folder"), None), TableCell::new("0%")]),
    ]
    .into();
    Demo { rows, ..demo(0) }
}

/// Where `text` is on screen, as the cell coordinates the colour checks take.
fn spot(h: &Harness<Demo>, text: &str) -> (u16, u16) {
    let (x, y) = h.find(text).unwrap_or_else(|| panic!("`{text}` is drawn:\n{}", h.screen()));
    (u16::try_from(x).unwrap_or(0), u16::try_from(y).unwrap_or(0))
}

#[test]
fn a_cell_glyph_is_muted_and_takes_the_row_text_colour_when_the_row_is_selected() {
    let mut h = Harness::new(icon_demo("firefox"), 30, 3);
    h.set_glyph_mode(GlyphMode::Unicode);
    let muted = h.env().theme().color("muted");
    let (x, y) = spot(&h, &FIREFOX.to_string());
    let screen = h.screen();
    let row = screen.lines().nth(1).unwrap_or_default();
    assert!(row.starts_with(&format!("  {FIREFOX} firefox ")) && row.ends_with(" 3%"), "{row:?}");
    assert_eq!(h.fg(x, y), muted, "a glyph is quieter than the name");
    assert_ne!(h.fg(x + 2, y), muted);
    let folder = h.env().icons().glyph("folder").into_owned();
    let (fx, fy) = spot(&h, &folder);
    assert_eq!((fx, h.fg(fx, fy)), (2, muted));
    h.press("tab").press("down");
    assert_eq!(h.app().selected, Some(0));
    let (x, y) = spot(&h, &FIREFOX.to_string());
    assert_eq!(h.fg(x, y), h.fg(x + 2, y), "on the selected row the glyph takes the name's colour");
    assert_ne!(h.fg(x, y), muted);
    assert_eq!(h.fg(fx, fy), muted, "the other row keeps its quiet glyph");
}

#[test]
fn a_narrow_column_cuts_the_text_and_keeps_the_glyph_and_its_space() {
    for mode in [GlyphMode::Unicode, GlyphMode::Ascii] {
        let mut h = Harness::new(icon_demo("firefox-developer-edition"), 16, 3);
        h.set_glyph_mode(mode);
        let screen = h.screen();
        let row = screen.lines().nth(1).unwrap_or_default();
        assert!(row.starts_with(&format!("  {FIREFOX} fir")), "{mode:?}: {row:?}");
        let mark = if mode == GlyphMode::Ascii { text::ASCII_ELLIPSIS } else { text::ELLIPSIS };
        assert!(row.contains(mark), "{mode:?}: {row:?}");
        let folder = h.env().icons().glyph("folder").into_owned();
        let row = screen.lines().nth(2).unwrap_or_default();
        assert!(row.starts_with(&format!("  {folder} pro")), "{mode:?}: {row:?}");
    }
    let mut h = Harness::new(icon_demo("firefox"), 9, 3);
    h.set_glyph_mode(GlyphMode::Unicode);
    let row = h.screen().lines().nth(1).unwrap_or_default().to_owned();
    assert!(row.starts_with(&format!("  {FIREFOX} ")), "even with no room for a letter: {row:?}");
}

#[test]
fn a_one_cell_glyph_takes_one_cell_and_one_space_in_a_fitting_column() {
    /// A fitting column of kinds, whose cell is a glyph and `pkg`, or the same written as text.
    struct Kinds(bool);
    impl App for Kinds {
        type Msg = ();
        fn update(&mut self, _: ()) -> Command<()> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, ()>) {
            let columns = [Column::new("Kind").width(ColumnWidth::Fit), Column::new("Name")];
            let kind = if self.0 { TableCell::new("pkg").icon(Glyph::literal('▲'), None) } else { "▲ pkg".into() };
            let rows = vec![TableRow::new([kind, TableCell::new("firefox")])];
            ui.add(Table::<()>::new(columns, rows)).fill();
        }
    }
    let mut glyph = Harness::new(Kinds(true), 24, 2);
    glyph.set_glyph_mode(GlyphMode::Unicode);
    let mut text = Harness::new(Kinds(false), 24, 2);
    text.set_glyph_mode(GlyphMode::Unicode);
    assert_eq!(glyph.screen(), text.screen(), "the glyph and its space are two cells, like `▲ `");
}

/// A table whose rows each carry a menu, with the motion off so a menu is there at once.
fn menu_demo(count: usize) -> Harness<Demo> {
    let mut demo = demo(count);
    demo.menu = true;
    let mut h = Harness::new(demo, 30, 8);
    h.set_glyph_mode(GlyphMode::Unicode).set_reduced_motion(true).render();
    h
}

/// Right-clicks the cell at `(x, y)`.
fn right_click(h: &mut Harness<Demo>, x: i32, y: i32) {
    h.mouse(MouseKind::Down(MouseButton::Right), x, y);
    h.mouse(MouseKind::Up(MouseButton::Right), x, y);
    h.render();
}

#[test]
fn a_rows_menu_acts_on_the_row_that_was_right_clicked_and_not_on_the_selected_one() {
    let mut h = menu_demo(5);
    h.send(Msg::Select(0));
    let (x, y) = h.find("svc-3").expect("the row is on screen");
    right_click(&mut h, x, y);
    assert!(h.screen().contains("Remove svc-3"), "the menu is the row's own:\n{}", h.screen());
    assert_eq!(h.app().selected, Some(3), "the row the menu belongs to became the selection");
    h.click_text("Remove svc-3").render();
    assert_eq!(h.app().removed, vec![3], "the entry acts on the row that was clicked");
}

#[test]
fn the_menu_key_opens_the_menu_of_the_selected_row() {
    let mut h = menu_demo(5);
    h.press("tab").press("down").press("down");
    assert_eq!(h.app().selected, Some(1));
    h.press("menu").render();
    assert!(h.screen().contains("Remove svc-1"), "{}", h.screen());
    h.press("enter").render();
    assert_eq!(h.app().removed, vec![1]);
}

#[test]
fn the_menu_key_scrolls_the_selected_row_into_view_first() {
    let mut h = menu_demo(200);
    h.press("tab").press("end");
    assert_eq!(h.app().selected, Some(199));
    h.press("menu").render();
    assert!(h.screen().contains("Remove svc-199"), "{}", h.screen());
}

#[test]
fn a_right_press_beside_the_menu_closes_it_without_choosing() {
    let mut h = menu_demo(5);
    let (x, y) = h.find("svc-1").expect("the row is on screen");
    right_click(&mut h, x, y);
    assert!(h.screen().contains("Remove svc-1"), "{}", h.screen());
    let (other_x, other_y) = h.find("svc-4").expect("another row");
    right_click(&mut h, other_x, other_y);
    assert!(h.screen().contains("Remove svc-4"), "the other row's menu took its place:\n{}", h.screen());
    assert!(h.app().removed.is_empty(), "nothing was chosen");
}

#[test]
fn a_right_press_on_the_header_or_beside_the_rows_opens_nothing() {
    let mut h = menu_demo(3);
    right_click(&mut h, 4, 0);
    assert!(!h.screen().contains("Remove"), "the header has no row menu:\n{}", h.screen());
    right_click(&mut h, 4, 6);
    assert!(!h.screen().contains("Remove"), "below the last row there is no row:\n{}", h.screen());
}

#[test]
fn a_menu_row_keeps_its_surface_raised_while_its_menu_is_open() {
    let mut h = menu_demo(5);
    let (x, y) = h.find("svc-2").expect("the row is on screen");
    let row = u16::try_from(y).expect("a row on screen");
    let resting = h.bg(1, row);
    right_click(&mut h, x, y);
    assert_ne!(h.bg(1, row), resting, "the row the menu acts on stays lit:\n{}", h.screen());
}

#[test]
fn a_table_without_a_menu_answers_no_right_press() {
    let mut h = Harness::new(demo(3), 30, 6);
    h.set_glyph_mode(GlyphMode::Unicode).set_reduced_motion(true).render();
    right_click(&mut h, 4, 1);
    assert!(!h.screen().contains("Remove"), "nothing opens:\n{}", h.screen());
    assert!(h.app().removed.is_empty() && h.app().opened.is_empty(), "and the right button does nothing else");
}

/// A table whose rows' menus open on Enter and a click, row 2's menu being empty.
fn activating_menu_demo() -> Harness<Demo> {
    let mut demo = demo(5);
    demo.menu = true;
    demo.menu_on_activate = true;
    demo.bare = Some(2);
    let mut h = Harness::new(demo, 30, 8);
    h.set_glyph_mode(GlyphMode::Unicode).set_reduced_motion(true).render();
    h
}

#[test]
fn enter_opens_the_menu_of_the_selected_row_when_that_is_what_activating_does() {
    let mut h = activating_menu_demo();
    h.press("tab").press("down").press("down");
    assert_eq!(h.app().selected, Some(1));
    h.press("enter").render();
    assert!(h.screen().contains("Remove svc-1"), "Enter opened the row's menu:\n{}", h.screen());
    assert!(h.app().opened.is_empty(), "and did not open the row");
    h.press("enter").render();
    assert_eq!(h.app().removed, vec![1], "the first entry is chosen with Enter");
}

#[test]
fn a_click_on_a_row_opens_its_menu_where_it_was_clicked() {
    let mut h = activating_menu_demo();
    let (x, y) = h.find("svc-3").expect("the row is on screen");
    h.click(x, y).render();
    assert!(h.screen().contains("Remove svc-3"), "the click opened the row's own menu:\n{}", h.screen());
    assert_eq!(h.app().selected, Some(3), "the row became the selection");
    assert!(h.app().opened.is_empty(), "the row itself was not opened");
    h.click_text("Remove svc-3").render();
    assert_eq!(h.app().removed, vec![3]);
}

#[test]
fn a_row_with_an_empty_menu_opens_nothing_on_enter_or_a_click() {
    let mut h = activating_menu_demo();
    let before = h.screen();
    let (x, y) = h.find("svc-2").expect("the row is on screen");
    h.click(x, y).render();
    assert!(!h.screen().contains("Remove"), "no layer for an empty menu:\n{}", h.screen());
    assert_eq!(h.app().selected, Some(2), "the click still selects the row");
    h.press("enter").render();
    assert!(!h.screen().contains("Remove"), "nor on Enter:\n{}", h.screen());
    assert!(h.app().opened.is_empty() && h.app().removed.is_empty(), "nothing was sent");
    assert_ne!(before, h.screen(), "only the selection moved");
}

#[test]
fn esc_closes_an_activated_menu_and_the_keys_go_back_to_the_rows() {
    let mut h = activating_menu_demo();
    h.press("tab").press("down").press("enter").render();
    assert!(h.screen().contains("Remove svc-0"), "{}", h.screen());
    h.press("esc").render();
    assert!(!h.screen().contains("Remove"), "Esc closed it:\n{}", h.screen());
    h.press("down");
    assert_eq!(h.app().selected, Some(1), "the table has the keys again");
}

#[test]
fn without_the_option_enter_and_a_click_open_the_row_even_with_a_menu() {
    let mut h = menu_demo(5);
    h.press("tab").press("down").press("enter").render();
    assert_eq!(h.app().opened, vec![0], "Enter opens the row as before");
    let (x, y) = h.find("svc-3").expect("the row is on screen");
    h.click(x, y).render();
    assert_eq!(h.app().opened, vec![0, 3], "and so does a click");
    assert!(!h.screen().contains("Remove"), "no menu opened:\n{}", h.screen());
}

#[test]
fn a_faint_cell_takes_the_selected_rows_colour_when_its_row_is_selected() {
    let rows: Arc<[TableRow]> = (0..3)
        .map(|i| TableRow::new([TableCell::new(format!("svc-{i}")), TableCell::new("idle").role("faint")]))
        .collect();
    let mut h = Harness::new(Demo { rows: Arc::clone(&rows), ..demo(0) }, 40, 6);
    h.set_glyph_mode(GlyphMode::Unicode);
    let colour = |h: &Harness<Demo>, row: i32| {
        let (x, y) = h
            .screen()
            .lines()
            .enumerate()
            .filter(|(_, line)| line.contains("idle"))
            .map(|(y, line)| (line.find("idle").map_or(0, |b| text::width(&line[..b])), y))
            .nth(usize::try_from(row).unwrap_or(0))
            .expect("an idle cell");
        h.fg(x, u16::try_from(y).unwrap_or(0))
    };
    let faint = h
        .env()
        .theme()
        .typography("faint")
        .and_then(|props| crate::style::WidgetStyle::new(props.clone(), 0.0).text().fg);
    assert_eq!(colour(&h, 1), faint, "an unselected faint cell is in the faint colour");
    let mut h = Harness::new(Demo { rows, selected: Some(1), ..demo(0) }, 40, 6);
    h.set_glyph_mode(GlyphMode::Unicode);
    let name = h.find("svc-1").expect("row");
    let selected_text = h.fg(u16::try_from(name.0).unwrap_or(0), u16::try_from(name.1).unwrap_or(0));
    assert_eq!(colour(&h, 1), selected_text, "on the selected row it reads like the row");
    assert_ne!(colour(&h, 0), selected_text, "the other rows keep it faint");
}

struct Wrapping {
    selected: Option<usize>,
    wrap: bool,
}

impl App for Wrapping {
    type Msg = usize;
    fn update(&mut self, index: usize) -> Command<usize> {
        self.selected = Some(index);
        Command::none()
    }
    fn view(&self, ui: &mut View<'_, usize>) {
        let rows: Arc<[TableRow]> = ["alpha", "beta", "gamma"].map(|name| TableRow::new([name])).to_vec().into();
        ui.add(Table::new([Column::new("Name")], rows).selected(self.selected).wrap(self.wrap).on_select(|i| i)).fill();
    }
}

/// The first cell of the row the pillar stands on.
fn pillar_row(h: &Harness<Wrapping>) -> String {
    let screen = h.screen();
    let line = screen.lines().find(|line| line.starts_with('▌')).unwrap_or_default();
    line.trim_start_matches('▌').trim().to_owned()
}

#[test]
fn a_wrapping_table_goes_round_its_ends_and_stops_otherwise() {
    let mut h = Harness::new(Wrapping { selected: None, wrap: true }, 20, 5);
    h.set_reduced_motion(true);
    h.press("tab").press("end").press("down");
    assert_eq!(pillar_row(&h), "alpha", "down on the last row reaches the first");
    h.press("up");
    assert_eq!(pillar_row(&h), "gamma", "up on the first row reaches the last");
    h.press("pgdn");
    assert_eq!(pillar_row(&h), "gamma", "a page stops at the end");

    let mut h = Harness::new(Wrapping { selected: None, wrap: false }, 20, 5);
    h.set_reduced_motion(true);
    h.press("tab").press("end").press("down");
    assert_eq!(pillar_row(&h), "gamma");
}

/// A table of a million rows built only as they are drawn, counting how many were built.
struct Lazy {
    selected: Option<usize>,
    built: std::rc::Rc<std::cell::Cell<usize>>,
}

impl App for Lazy {
    type Msg = usize;
    fn update(&mut self, row: usize) -> Command<usize> {
        self.selected = Some(row);
        Command::none()
    }
    fn view(&self, ui: &mut View<'_, usize>) {
        let built = std::rc::Rc::clone(&self.built);
        let columns = [Column::new("Line"), Column::new("Bytes").width(ColumnWidth::Fit)];
        let table = Table::lazy(columns, 1_000_000, move |row| {
            built.set(built.get() + 1);
            TableRow::new([format!("line {row}"), "1234567890".to_owned()])
        })
        .selected(self.selected)
        .on_select(|row| row);
        ui.add(table).fill();
    }
}

#[test]
fn a_lazy_table_builds_only_the_rows_it_draws() {
    let built = std::rc::Rc::new(std::cell::Cell::new(0));
    let mut h = Harness::new(Lazy { selected: None, built: std::rc::Rc::clone(&built) }, 40, 8);
    assert!(h.screen().contains("line 0"), "{}", h.screen());
    assert!(built.get() <= 2 * 7, "the first frame built {} rows for seven on screen", built.get());
    built.set(0);
    h.press("tab").press("end");
    assert_eq!(h.app().selected, Some(999_999));
    assert!(h.screen().contains("line 999999"), "{}", h.screen());
    assert!(built.get() <= 4 * 7, "two keys built {} rows of a million", built.get());
}

#[test]
fn a_lazy_tables_fitted_column_fits_its_title() {
    let h = Harness::new(Lazy { selected: None, built: std::rc::Rc::default() }, 40, 4);
    let header = h.screen().lines().next().unwrap_or_default().to_owned();
    // The rows are not all known, so the column is as wide as its title and its cells are cut.
    assert!(header.contains("Bytes"), "{header}");
    assert!(!h.screen().contains("1234567890"), "{}", h.screen());
}

/// A music player's songs: the table holds the focus almost all the time, so its keymap binds
/// `space` to the application's own play and pause, which the table can either keep or let through.
struct Player {
    /// What the table is told about Space; `None` leaves the option at its default.
    space_activates: Option<bool>,
    /// Whether the table shows a check mark on every row.
    marks: bool,
    checked: Vec<bool>,
    selected: Option<usize>,
    opened: Vec<usize>,
    played: usize,
}

#[derive(Clone)]
enum PlayerMsg {
    Select(usize),
    Open(usize),
    Toggle(usize),
    Play,
}

impl App for Player {
    type Msg = PlayerMsg;
    fn update(&mut self, msg: PlayerMsg) -> Command<PlayerMsg> {
        match msg {
            PlayerMsg::Select(index) => self.selected = Some(index),
            PlayerMsg::Open(index) => self.opened.push(index),
            PlayerMsg::Toggle(index) => {
                if let Some(checked) = self.checked.get_mut(index) {
                    *checked = !*checked;
                }
            }
            PlayerMsg::Play => self.played += 1,
        }
        Command::none()
    }
    fn action(&self, name: &str) -> Option<PlayerMsg> {
        matches!(name, "play").then_some(PlayerMsg::Play)
    }
    fn view(&self, ui: &mut View<'_, PlayerMsg>) {
        let mut table = Table::new([Column::new("Song")], songs()).selected(self.selected);
        if let Some(on) = self.space_activates {
            table = table.space_activates(on);
        }
        table = table.on_select(PlayerMsg::Select).on_activate(PlayerMsg::Open);
        if self.marks {
            table = table.checked(self.checked.clone()).on_toggle(PlayerMsg::Toggle);
        }
        ui.add(table).fill();
    }
}

fn songs() -> Arc<[TableRow]> {
    ["blue monday", "just like heaven", "painted in blue"].map(|name| TableRow::new([name])).to_vec().into()
}

/// A player whose songs table is asked to leave Space to the application, or not, with or without
/// check marks on the rows.
fn player(space_activates: Option<bool>, marks: bool) -> Harness<Player> {
    let mut env = Env::builtin();
    env.keymap_mut().bind(Scope::App, "play", &["space".parse().expect("a chord")]);
    Harness::with_env(
        Player { space_activates, marks, checked: vec![false; 3], selected: None, opened: Vec::new(), played: 0 },
        env,
        24,
        6,
    )
}

#[test]
fn space_leaves_the_table_for_the_application_when_the_table_asks_for_it() {
    let mut h = player(Some(false), false);
    h.press("tab").press("down");
    assert_eq!(h.app().selected, Some(0), "the table holds the focus and the cursor is on a row");
    h.press("space");
    assert_eq!(h.app().played, 1, "Space reached the application's own action");
    assert!(h.app().opened.is_empty(), "and no row was opened instead");
    h.press("enter");
    assert_eq!(h.app().opened, vec![0], "Enter still opens the row");
    h.click_text("painted in blue");
    assert_eq!(h.app().opened, vec![0, 2], "and a click is the same as it always was");
}

#[test]
fn by_default_space_opens_the_row_and_the_application_never_hears_of_it() {
    let mut h = player(None, false);
    h.press("tab").press("down").press("space");
    assert_eq!(h.app().opened, vec![0], "Space opens the cursor's row");
    assert_eq!(h.app().played, 0, "so the application's own action is not reached");
}

#[test]
fn a_table_that_checks_rows_leaves_space_alone_as_well() {
    let mut h = player(Some(false), true);
    h.press("tab").press("down").press("space");
    assert_eq!(h.app().checked, [false, false, false], "the key checked no row");
    assert_eq!(h.app().played, 1, "and went to the application as before");
    let (_, y) = h.find("painted in blue").expect("the third song's row is on screen");
    h.click(2, y);
    assert_eq!(h.app().checked, [false, false, true], "a click on the mark still checks the row:\n{}", h.screen());

    let mut h = player(Some(true), true);
    h.press("tab").press("down").press("space");
    assert_eq!(h.app().checked, [true, false, false], "while the option is on, Space checks the row");
    assert_eq!(h.app().played, 0, "and does not reach the application");
}