datui-lib 0.4.4

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
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
//! End-to-end coverage of every place the app puts a text field in front of the
//! user.
//!
//! The widget tests in `widgets::text_input` cover the field in isolation.
//! These drive the real `App` instead, one key event at a time, so that each
//! prior use of the old wrapped-textarea widget has a test that says what the
//! user sees: the command line (rows, SQL and q), the export path, the
//! chart axis filters, the sort and pivot filters, and the multi-line view
//! description.

use std::io::Write;
use std::sync::mpsc::{self, Receiver, Sender};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};

use crate::widgets::text_input::TextInput;
use crate::{App, AppEvent, InputMode, OpenOptions, Overlay};

/// An app with a small CSV loaded, driven the way the real event loop drives it.
///
/// Keys are delivered one at a time, and every follow-up the app asks for is
/// run before the next key: chained events immediately, background results as
/// they arrive on the channel. Without that the app stays busy and drops keys,
/// which is exactly what a user would never see.
struct Harness {
    app: App,
    rx: Receiver<AppEvent>,
    _dir: tempfile::TempDir,
}

impl Harness {
    fn with_data() -> Self {
        Self::with_csv("name,age\nada,36\ngrace,45\nalan,41")
    }

    fn with_csv(contents: &str) -> Self {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("people.csv");
        let mut file = std::fs::File::create(&path).expect("create csv");
        writeln!(file, "{contents}").expect("write csv");
        drop(file);

        let (tx, rx): (Sender<AppEvent>, Receiver<AppEvent>) = mpsc::channel();
        let mut app = App::new(tx, crate::tests::test_runtime());
        // A cache of its own: the process-wide test cache is shared by tests running
        // at once, and one test's `:2` turned up as another's newest query.
        app.cache = crate::cache::CacheManager::with_dir(dir.path().join("cache"));
        let mut harness = Harness { app, rx, _dir: dir };
        harness.run(AppEvent::Open(vec![path], OpenOptions::default()));
        assert!(
            harness.app.data_table_state.is_some(),
            "the CSV should have loaded"
        );
        harness
    }

    /// Loaded, with `:` preferring q.
    fn q_style() -> Self {
        let mut h = Self::with_data();
        h.app.app_config.query.default_mode = crate::QueryMode::Q;
        h
    }

    /// Run `event` and everything that follows from it.
    fn run(&mut self, event: AppEvent) {
        self.run_until(Some(event), |_| false);
    }

    /// Run `event`, if any, and what follows from it until `stop` holds between two
    /// events or nothing is left to do. A result still out when it stops waits on the
    /// channel until the next run handles it.
    fn run_until(&mut self, event: Option<AppEvent>, stop: impl Fn(&App) -> bool) {
        let mut next = event;
        // Waits on the work, not on a quiet spell; the deadline is only a hang guard.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
        loop {
            if let Some(event) = next.take() {
                if let AppEvent::Crash(message) = &event {
                    panic!("the app crashed: {message}");
                }
                next = self.app.event(event);
                continue;
            }
            if stop(&self.app) {
                break;
            }
            if let Ok(event) = self.rx.try_recv() {
                next = Some(event);
                continue;
            }
            // The run loop paints after every update, and a count waiting on that starts.
            if self.app.count_waits_for_a_frame() {
                next = Some(AppEvent::FramePainted);
                continue;
            }
            if crate::tests::work_pending(&self.app) {
                assert!(
                    std::time::Instant::now() < deadline,
                    "background work never reported back"
                );
                next = self
                    .rx
                    .recv_timeout(std::time::Duration::from_millis(50))
                    .ok();
                continue;
            }
            break;
        }
    }

    fn press(&mut self, code: KeyCode) {
        self.press_with(code, KeyModifiers::NONE);
    }

    fn press_with(&mut self, code: KeyCode, modifiers: KeyModifiers) {
        self.run(AppEvent::Key(KeyEvent::new(code, modifiers)));
    }

    fn type_str(&mut self, text: &str) {
        for c in text.chars() {
            self.press(KeyCode::Char(c));
        }
    }
}

/// The single visible line of a field, as the terminal would show it.
fn drawn(input: &TextInput, width: u16) -> String {
    let rect = Rect::new(0, 0, width, 1);
    let mut buf = Buffer::empty(rect);
    input.render(rect, &mut buf);
    (0..width)
        .map(|x| buf[(x, 0)].symbol().to_string())
        .collect::<String>()
        .trim_end()
        .to_string()
}

// ---------------------------------------------------------------------------
// The query bar
// ---------------------------------------------------------------------------

#[test]
fn typing_a_query_and_submitting_it_applies_the_query() {
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    assert_eq!(h.app.input_mode, InputMode::Editing);

    h.type_str("select name where age > 40");
    assert_eq!(
        h.app.prompt.query_input.value(),
        "select name where age > 40"
    );
    assert_eq!(
        drawn(&h.app.prompt.query_input, 40),
        "select name where age > 40"
    );

    h.press(KeyCode::Enter);
    assert!(h.app.at_table());
    let state = h.app.data_table_state.as_ref().expect("state");
    assert_eq!(state.get_active_query(), "select name where age > 40");
}

#[test]
fn reopening_the_query_bar_shows_the_query_that_is_running() {
    // Reopening has to put the live query back on screen, not the blank field
    // that Esc left behind: the user edits from where they were.
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    h.type_str("select name where age > 40");
    h.press(KeyCode::Enter);

    h.press(KeyCode::Esc);
    h.press(KeyCode::Char(':'));

    assert_eq!(
        h.app.prompt.query_input.value(),
        "select name where age > 40"
    );
    assert_eq!(
        drawn(&h.app.prompt.query_input, 40),
        "select name where age > 40"
    );
    assert_eq!(
        h.app.prompt.query_input.cursor(),
        "select name where age > 40".chars().count()
    );
}

#[test]
fn esc_leaves_the_query_bar_without_running_anything() {
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    h.type_str("select name where age > 40");
    h.press(KeyCode::Esc);

    assert!(h.app.at_table());
    let state = h.app.data_table_state.as_ref().expect("state");
    assert_eq!(state.get_active_query(), "");
}

#[test]
fn editing_keys_work_in_the_query_bar() {
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    h.type_str("select nme");
    h.press(KeyCode::Backspace);
    h.press(KeyCode::Backspace);
    h.type_str("ame");
    assert_eq!(h.app.prompt.query_input.value(), "select name");

    h.press(KeyCode::Home);
    assert_eq!(h.app.prompt.query_input.cursor(), 0);
    h.press(KeyCode::Delete);
    assert_eq!(h.app.prompt.query_input.value(), "elect name");
    h.press(KeyCode::End);
    assert_eq!(h.app.prompt.query_input.cursor(), 10);
}

#[test]
fn the_query_bar_recalls_earlier_queries_with_the_arrow_keys() {
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    h.type_str("select name where age > 40");
    h.press(KeyCode::Enter);

    h.press(KeyCode::Char(':'));
    h.press(KeyCode::Up);
    assert_eq!(
        h.app.prompt.query_input.value(),
        "select name where age > 40"
    );
    assert_eq!(
        drawn(&h.app.prompt.query_input, 40),
        "select name where age > 40"
    );
}

#[test]
fn the_command_line_goes_to_a_row_and_keeps_the_query() {
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    h.type_str("select name where age > 40");
    h.press(KeyCode::Enter);

    // Reopened, the line holds the query in effect, selected: digits replace it.
    query_screen(&mut h.app);
    h.press(KeyCode::Char(':'));
    assert_eq!(h.app.input_mode, InputMode::Editing);
    assert_eq!(
        h.app.prompt.query_input.value(),
        "select name where age > 40"
    );
    h.type_str("2");
    assert_eq!(h.app.prompt.query_input.value(), "2");
    assert_eq!(crate::render::input_strip::prefix(&h.app), "row:");
    h.press(KeyCode::Enter);
    assert!(h.app.at_table());
    let state = h.app.data_table_state.as_ref().expect("state");
    assert_eq!(state.cursor_row(), 1, "row 2 of the view");
    assert_eq!(
        state.get_active_query(),
        "select name where age > 40",
        "a row number runs nothing"
    );
}

// ---------------------------------------------------------------------------
// Modal fields
// ---------------------------------------------------------------------------

/// Put the Sort tab's column filter under the cursor.
fn focus_column_filter(app: &mut App) {
    app.sort_filter_modal.active_tab =
        crate::app::modals::sort_filter_modal::SortFilterTab::Columns;
    app.sort_filter_modal.focus = crate::app::modals::sort_filter_modal::SortFilterField::Find;
}

#[test]
fn the_sort_and_filter_modal_filters_columns_as_you_type() {
    let mut h = Harness::with_data();

    h.press(KeyCode::Char('s'));
    assert_eq!(h.app.overlay, Overlay::SortFilter);
    focus_column_filter(&mut h.app);

    h.type_str("ag");
    assert_eq!(h.app.sort_filter_modal.sort.filter_input.value(), "ag");
    assert_eq!(drawn(&h.app.sort_filter_modal.sort.filter_input, 20), "ag");

    h.press(KeyCode::Backspace);
    assert_eq!(h.app.sort_filter_modal.sort.filter_input.value(), "a");
}

#[test]
fn the_view_description_holds_several_lines() {
    let mut h = Harness::with_data();

    // The save gate wants something to save; sort first.
    h.app
        .data_table_state
        .as_mut()
        .expect("data loaded")
        .sort_by(vec!["age".to_string()], vec![false]);
    h.press(KeyCode::Char('v'));
    h.press(KeyCode::Char('s'));
    // Move focus from the name field to the description.
    h.press(KeyCode::Tab);

    h.type_str("first");
    h.press(KeyCode::Enter);
    h.type_str("second");

    let description = &h.app.view_modal.description_input;
    assert_eq!(description.value(), "first\nsecond");
    assert_eq!(description.line_count(), 2);
    assert_eq!(description.cursor_line(), 1);
}

#[test]
fn the_view_description_pages_through_its_lines() {
    let mut h = Harness::with_data();

    // The save gate wants something to save; sort first.
    h.app
        .data_table_state
        .as_mut()
        .expect("data loaded")
        .sort_by(vec!["age".to_string()], vec![false]);
    h.press(KeyCode::Char('v'));
    h.press(KeyCode::Char('s'));
    h.press(KeyCode::Tab);

    for line in 0..8 {
        h.type_str(&format!("line{line}"));
        if line < 7 {
            h.press(KeyCode::Enter);
        }
    }
    assert_eq!(h.app.view_modal.description_input.cursor_line(), 7);

    h.press(KeyCode::PageUp);
    assert_eq!(h.app.view_modal.description_input.cursor_line(), 2);
    h.press(KeyCode::PageUp);
    assert_eq!(h.app.view_modal.description_input.cursor_line(), 0);
    h.press(KeyCode::PageDown);
    assert_eq!(h.app.view_modal.description_input.cursor_line(), 5);
}

#[test]
fn the_view_name_field_takes_text() {
    let mut h = Harness::with_data();

    // The save gate wants something to save; sort first.
    h.app
        .data_table_state
        .as_mut()
        .expect("data loaded")
        .sort_by(vec!["age".to_string()], vec![false]);
    h.press(KeyCode::Char('v'));
    h.press(KeyCode::Char('s'));
    // Creating from a loaded file suggests a name; typing replaces it.
    let suggested = h.app.view_modal.name_input.value().to_string();
    assert!(!suggested.is_empty(), "a name should be suggested");
    h.type_str("by age");

    assert_eq!(h.app.view_modal.name_input.value(), "by age");
    assert_eq!(drawn(&h.app.view_modal.name_input, 20), "by age");

    // Opened again, → keeps the suggestion and typing extends it.
    h.press(KeyCode::Esc);
    h.press(KeyCode::Char('s'));
    assert_eq!(h.app.view_modal.name_input.value(), suggested);
    h.press(KeyCode::Right);
    h.type_str(" v2");
    assert_eq!(
        h.app.view_modal.name_input.value(),
        format!("{suggested} v2")
    );
}

#[test]
fn the_melt_name_fields_replace_their_defaults_when_typed_over() {
    use crate::app::modals::pivot_melt_modal::PivotMeltFocus;
    let mut h = Harness::with_data();
    let to_variable_row = |h: &mut Harness| {
        h.press(KeyCode::Char('p'));
        h.press(KeyCode::Right);
        while h.app.pivot_melt_modal.focus != PivotMeltFocus::MeltVariable {
            h.press(KeyCode::Tab);
        }
    };

    to_variable_row(&mut h);
    assert_eq!(
        h.app.pivot_melt_modal.melt_variable_input.value(),
        "variable"
    );
    h.type_str("field");
    h.press(KeyCode::Tab);
    h.type_str("reading");
    assert_eq!(h.app.pivot_melt_modal.melt_variable_input.value(), "field");
    assert_eq!(h.app.pivot_melt_modal.melt_value_input.value(), "reading");

    // Opened again, → keeps the default and typing extends it; Tab past a
    // default leaves it as it was.
    h.press(KeyCode::Esc);
    to_variable_row(&mut h);
    h.press(KeyCode::Right);
    h.type_str("_name");
    h.press(KeyCode::Tab);
    assert_eq!(
        h.app.pivot_melt_modal.melt_variable_input.value(),
        "variable_name"
    );
    assert_eq!(h.app.pivot_melt_modal.melt_value_input.value(), "value");
}

#[test]
fn unicode_survives_a_round_trip_through_a_field() {
    let mut h = Harness::q_style();

    h.press(KeyCode::Char(':'));
    h.type_str("where name == \"café\"");
    assert_eq!(h.app.prompt.query_input.value(), "where name == \"café\"");
    h.press(KeyCode::Backspace);
    assert_eq!(h.app.prompt.query_input.value(), "where name == \"café");
}

#[test]
fn every_field_starts_empty_and_unfocused() {
    // The modals build their fields fresh each time they open; a field that
    // kept the last value would leak one modal's text into the next.
    let mut h = Harness::with_data();

    h.press(KeyCode::Char('s'));
    focus_column_filter(&mut h.app);
    h.type_str("ag");
    assert_eq!(h.app.sort_filter_modal.sort.filter_input.value(), "ag");
    h.press(KeyCode::Esc);
    h.press(KeyCode::Char('s'));

    assert_eq!(h.app.sort_filter_modal.sort.filter_input.value(), "");
}

#[test]
fn the_export_modal_takes_a_path() {
    let mut h = Harness::with_data();

    h.press(KeyCode::Char('e'));
    assert!(matches!(h.app.overlay, Overlay::Export { .. }));

    // The modal suggests a filename; replace it with one of our own.
    let suggested = h.app.export_modal.path_input.value().to_string();
    for _ in 0..suggested.chars().count() {
        h.press(KeyCode::Backspace);
    }
    h.type_str("out.csv");

    assert_eq!(h.app.export_modal.path_input.value(), "out.csv");
    assert_eq!(drawn(&h.app.export_modal.path_input, 30), "out.csv");
}

#[test]
fn the_pivot_and_melt_modal_opens_a_picker_narrowed_as_you_type() {
    let mut h = Harness::with_data();

    h.press(KeyCode::Char('p'));
    assert_eq!(h.app.overlay, Overlay::PivotMelt);
    h.app.pivot_melt_modal.focus = crate::app::modals::pivot_melt_modal::PivotMeltFocus::PivotIndex;

    // Space opens a picked row's Picker; typing narrows it.
    h.press(KeyCode::Char(' '));
    h.type_str("na");
    let picker = h.app.pivot_melt_modal.picker.as_ref().expect("picker open");
    assert_eq!(picker.filter, "na");
    assert!(picker.filtered().iter().all(|(_, c)| c.contains("na")));
}

/// Ctrl+T switches between SQL and q, the text going with it; the choice is
/// remembered the next time the line opens on no query.
#[test]
fn ctrl_t_switches_the_language_and_keeps_the_text() {
    let mut h = Harness::with_data();
    h.press(KeyCode::Char(':'));
    let first = h.app.prompt.query_mode;
    h.type_str("abc");
    h.press_with(KeyCode::Char('t'), KeyModifiers::CONTROL);
    let second = h.app.prompt.query_mode;
    if crate::QueryMode::available().len() > 1 {
        assert_ne!(second, first);
    }
    h.type_str("d");
    assert_eq!(
        h.app.query_prompt_text(),
        Some("abcd"),
        "the chord typed nothing"
    );
    h.press(KeyCode::Esc);
    h.press(KeyCode::Char(':'));
    assert_eq!(h.app.prompt.query_mode, second, "remembered");
}

/// The query in effect arrives selected; switched to the other language it stays
/// selected, so typing there states a new query rather than appending to the old.
#[cfg(feature = "sql")]
#[test]
fn ctrl_t_over_the_restored_query_keeps_it_selected() {
    let mut h = Harness::q_style();
    h.press(KeyCode::Char(':'));
    h.type_str("select name");
    h.press(KeyCode::Enter);
    h.press(KeyCode::Char(':'));
    h.press_with(KeyCode::Char('t'), KeyModifiers::CONTROL);
    assert_eq!(h.app.prompt.query_mode, crate::QueryMode::Sql);
    h.type_str("SELECT age FROM df");
    assert_eq!(h.app.query_prompt_text(), Some("SELECT age FROM df"));
}

/// Esc closes the prompt whole from every mode. The q path used to leave
/// the prompt's input type behind.
#[test]
fn esc_closes_the_query_prompt_from_every_mode() {
    let mut h = Harness::with_data();
    for &mode in crate::QueryMode::available() {
        h.press(KeyCode::Char(':'));
        while h.app.prompt.query_mode != mode {
            h.press_with(KeyCode::Char('t'), KeyModifiers::CONTROL);
        }
        h.press(KeyCode::Esc);
        assert!(h.app.at_table(), "{mode:?}");
        assert_eq!(h.app.prompt.input_type, None, "{mode:?}");
        assert_eq!(h.app.query_prompt_mode(), None, "{mode:?}");
    }
}

fn query_screen(app: &mut App) -> String {
    let area = Rect::new(0, 0, 100, 20);
    let mut buf = Buffer::empty(area);
    app.render(area, &mut buf);
    buf.content().iter().map(|c| c.symbol()).collect()
}

/// As a find is typed, the cells it matches among the rows on hand light up and
/// are counted; Ctrl+G keeps only the rows that match, as a filter.
#[test]
fn a_find_lights_up_matches_and_keeps_them() {
    let mut h = Harness::with_data();
    query_screen(&mut h.app);
    h.press(KeyCode::Char('/'));
    h.type_str("al");
    assert_eq!(h.app.live_on_screen(), Some(1), "alan");
    let drawn = query_screen(&mut h.app);
    assert!(drawn.contains("1 on screen"), "{drawn}");
    h.press_with(KeyCode::Char('g'), KeyModifiers::CONTROL);
    assert!(h.app.at_table());
    let state = h.app.data_table_state.as_ref().expect("state");
    assert_eq!(state.num_rows(), 1, "only alan's row has al");
    assert_eq!(state.view_filters()[0].describe(), "has \"al\"");
    let drawn = query_screen(&mut h.app);
    assert!(drawn.contains("has \"al\""), "the footer shows it: {drawn}");
}

/// A prompt on a terminal too short for it draws what fits and nothing past the
/// screen: the status line first.
#[test]
fn a_prompt_on_a_tiny_terminal_draws_what_fits() {
    let mut h = Harness::with_data();
    for open in ['/', ':'] {
        h.press(KeyCode::Char(open));
        h.type_str("al");
        for (width, height) in [(1, 1), (20, 1), (20, 2), (40, 3), (5, 4)] {
            let area = Rect::new(0, 0, width, height);
            let mut buf = Buffer::empty(area);
            h.app.render(area, &mut buf);
        }
        h.press(KeyCode::Esc);
    }
}

/// Kept over every column, a find searches the columns it searched: a hidden one
/// keeps no row.
#[test]
fn a_kept_find_searches_the_shown_columns() {
    let mut h = Harness::with_data();
    h.run(AppEvent::Applied(crate::Applied::ColumnOrder(
        vec!["age".to_string()],
        0,
    )));
    h.press(KeyCode::Char('/'));
    h.type_str("al");
    h.press_with(KeyCode::Char('g'), KeyModifiers::CONTROL);
    let state = h.app.data_table_state.as_ref().expect("state");
    assert_eq!(state.num_rows(), 0, "name is hidden, so alan is not kept");
}

/// A find kept over every column keeps the columns it searched: hiding one later
/// changes neither the rows kept nor what the script filters on, through a sort.
#[test]
fn a_kept_find_keeps_its_columns_when_the_layout_changes() {
    let mut h = Harness::with_data();
    h.press(KeyCode::Char('/'));
    h.type_str("al");
    h.press_with(KeyCode::Char('g'), KeyModifiers::CONTROL);
    let rows = |h: &Harness| h.app.data_table_state.as_ref().unwrap().num_rows();
    assert_eq!(rows(&h), 1);
    h.run(AppEvent::Applied(crate::Applied::ColumnOrder(
        vec!["age".to_string()],
        0,
    )));
    h.run(AppEvent::Applied(crate::Applied::Sort(
        vec!["age".to_string()],
        vec![true],
    )));
    assert_eq!(rows(&h), 1, "alan is still kept on name");
    let state = h.app.data_table_state.as_ref().unwrap();
    let searched: Vec<String> = state
        .python_steps()
        .iter()
        .find_map(|step| match step {
            crate::export::python_script::Step::Filter(filters) => {
                Some(filters[0].searched.iter().map(|(n, _)| n.clone()).collect())
            }
            _ => None,
        })
        .expect("a filter step");
    assert!(searched.contains(&"name".to_string()), "{searched:?}");
}

/// The footer growing a line keeps the cursor on the record it was on, even on the
/// bottom row of the page.
#[test]
fn the_cursor_keeps_its_record_when_the_footer_grows() {
    let csv: String = std::iter::once("n".to_string())
        .chain((0..200).map(|i| i.to_string()))
        .collect::<Vec<_>>()
        .join("\n");
    let mut h = Harness::with_csv(&csv);
    query_screen(&mut h.app);
    // The rows a page this tall needs, as the run loop reads them after a draw.
    h.run(AppEvent::Collect);
    query_screen(&mut h.app);
    let visible = h.app.data_table_state.as_ref().unwrap().visible_rows;
    h.app
        .data_table_state
        .as_mut()
        .unwrap()
        .table_state
        .select(Some(visible - 1));
    let row = h.app.data_table_state.as_ref().unwrap().cursor_row();
    assert_eq!(row, visible - 1, "on the bottom row");
    h.press(KeyCode::Char('/'));
    query_screen(&mut h.app);
    let state = h.app.data_table_state.as_ref().unwrap();
    assert!(state.visible_rows < visible, "the prompt took a row");
    assert_eq!(state.cursor_row(), row, "the same record");
}

/// The matches follow the rows on hand: rows read while the prompt is open light up
/// as they arrive, with no key pressed.
#[test]
fn the_live_matches_follow_the_rows_on_hand() {
    let csv: String = std::iter::once("n".to_string())
        .chain((0..200).map(|i| format!("x{i}")))
        .collect::<Vec<_>>()
        .join("\n");
    let mut h = Harness::with_csv(&csv);
    h.press(KeyCode::Char('/'));
    h.type_str("x");
    let before = h
        .app
        .prompt
        .find
        .live
        .as_ref()
        .map_or(0, |l| l.within(0..usize::MAX));
    query_screen(&mut h.app);
    h.run(AppEvent::Collect);
    let after = h
        .app
        .prompt
        .find
        .live
        .as_ref()
        .map_or(0, |l| l.within(0..usize::MAX));
    let state = h.app.data_table_state.as_ref().unwrap();
    let on_screen = state.visible_rows.min(state.num_rows());
    assert_eq!(
        h.app.live_on_screen(),
        Some(on_screen),
        "every row on screen has its match"
    );
    assert!(after > before, "{before} -> {after}");
}

/// The view moving past the rows the matches were worked out over, with the prompt
/// open, lights the rows it comes to.
#[test]
fn the_live_matches_follow_the_view_past_their_window() {
    let csv: String = std::iter::once("n".to_string())
        .chain((0..200).map(|i| format!("x{i}")))
        .collect::<Vec<_>>()
        .join("\n");
    let mut h = Harness::with_csv(&csv);
    query_screen(&mut h.app);
    h.press(KeyCode::Char('/'));
    h.type_str("x");
    query_screen(&mut h.app);
    let state = h.app.data_table_state.as_mut().unwrap();
    let page = state.visible_rows;
    let start = 4 * page;
    let collect = state.scroll_to(start);
    let lit = |h: &Harness| {
        h.app
            .prompt
            .find
            .live
            .as_ref()
            .map_or(0, |l| l.within(start..start + page))
    };
    assert_eq!(lit(&h), 0, "past the window the prompt opened over");
    // The collect the scroll asks for, or any event, looks again.
    h.run(if collect {
        AppEvent::Collect
    } else {
        AppEvent::FramePainted
    });
    query_screen(&mut h.app);
    assert_eq!(
        h.app.live_on_screen(),
        Some(page),
        "every row on screen lit"
    );
    assert_eq!(lit(&h), page);
}

/// A resize sets the rows on screen as it draws, after the event pass: the frame
/// that drew it works the matches out again and wakes the loop to draw them.
#[test]
fn the_live_matches_follow_a_resize() {
    let csv: String = std::iter::once("n".to_string())
        .chain((0..200).map(|i| format!("x{i}")))
        .collect::<Vec<_>>()
        .join("\n");
    let mut h = Harness::with_csv(&csv);
    // Rows on hand for the tall view, read before the prompt opens on a short one.
    let area = Rect::new(0, 0, 100, 120);
    h.app.render(area, &mut Buffer::empty(area));
    h.run(AppEvent::Collect);
    query_screen(&mut h.app);
    h.press(KeyCode::Char('/'));
    h.type_str("x");
    let short = h.app.data_table_state.as_ref().unwrap().visible_rows;
    h.app.render(area, &mut Buffer::empty(area));
    let tall = h.app.data_table_state.as_ref().unwrap().visible_rows;
    assert!(tall > 3 * short, "{short} -> {tall}");
    assert!(h.app.live_on_screen().unwrap() < tall, "the window lags");
    while h.rx.try_recv().is_ok() {}
    h.app.frame_painted();
    assert!(
        std::iter::from_fn(|| h.rx.try_recv().ok()).any(|e| matches!(e, AppEvent::Wake)),
        "the loop is woken to draw them"
    );
    assert_eq!(h.app.live_on_screen(), Some(tall));
}

/// Letters in order: `gce` finds grace.
#[test]
fn a_fuzzy_find_matches_letters_in_order() {
    let mut h = Harness::with_data();
    query_screen(&mut h.app);
    h.press(KeyCode::Char('/'));
    h.press_with(KeyCode::Char('t'), KeyModifiers::CONTROL);
    h.type_str("gce");
    assert_eq!(h.app.live_on_screen(), Some(1));
    h.press_with(KeyCode::Char('g'), KeyModifiers::CONTROL);
    let state = h.app.data_table_state.as_ref().expect("state");
    assert_eq!(state.num_rows(), 1);
}