linesmith 0.1.3

A Rust status line for Claude Code and other AI coding CLIs
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
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! Reusable `ListScreen` widget per ADR-0016.
//!
//! Owns cursor + move-mode state and exposes a pure `handle_key` so
//! screens can unit-test their dispatch tables without ratatui in
//! the loop. The render path uses ratatui's `List` + `ListState`
//! for free scrolling, with a custom layout around it for the
//! title, help row, and bottom description.
//!
//! Keymap:
//!
//! - ↑/↓ — wrap-around cursor in normal mode; swap-with-neighbor
//!   in move-mode (no wrap, since teleporting a row across the list
//!   is rarely the user's intent).
//! - Enter — when `move_mode_supported`, toggle move-mode; otherwise
//!   emit `Activate` so the caller opens the highlighted row.
//! - Esc — in move-mode, exit move-mode; otherwise `Unhandled` (so
//!   the global quit handler in [`super::app`] fires).
//! - lowercase ASCII letter with no modifiers, listed in
//!   `verb_letters`, in normal mode — `Action(letter)`. The widget
//!   doesn't know what each letter means; the caller maps it to its
//!   own action enum.

use std::borrow::Cow;

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{List, ListItem, ListState, Paragraph};
use ratatui::Frame;

/// Cursor + move-mode state owned by each screen that hosts a
/// `ListScreen`.
#[derive(Debug, Default, Clone)]
pub(super) struct ListScreenState {
    cursor: usize,
    move_mode: bool,
}

// `cursor()`, `move_mode()`, `set_cursor()`, and `new()` are
// exercised by tests but no production caller reads them yet.
// clippy's dead-code lint runs against the production build only,
// so test usage alone won't suppress the warning.
//
// `new()` is also kept to wrap `Default::default()` — without that
// indirection, `field_reassign_with_default` fires on the natural
// test pattern of constructing-then-tweaking a single field.
#[allow(dead_code)]
impl ListScreenState {
    pub(super) fn new() -> Self {
        Self::default()
    }

    pub(super) fn cursor(&self) -> usize {
        self.cursor
    }

    pub(super) fn move_mode(&self) -> bool {
        self.move_mode
    }

    /// Force the cursor to a specific row, clamped to `[0, num_rows)`.
    /// Callers use this after operations that shrink `num_rows` so
    /// the cursor stays in range.
    pub(super) fn set_cursor(&mut self, idx: usize, num_rows: usize) {
        self.cursor = if num_rows == 0 {
            0
        } else {
            idx.min(num_rows - 1)
        };
    }
}

/// Outcome of one [`handle_key`] call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ListOutcome {
    /// Widget handled the key internally; caller does nothing more.
    Consumed,
    /// Enter pressed in a non-move-mode-supporting screen — caller
    /// opens / activates the row at `state.cursor()`.
    Activate,
    /// A registered verb-letter was pressed in normal mode. Caller
    /// looks up the letter in its own action table.
    Action(char),
    /// In move-mode: caller must (1) swap rows `from` and `to` in
    /// their data and (2) call `state.set_cursor(to, num_rows)` to
    /// track the moved row. Failing to do BOTH leaves the user's
    /// data and cursor out of sync. The widget intentionally does
    /// NOT mutate the cursor here — a missed acknowledgement leaves
    /// the cursor frozen, which is visually obvious instead of
    /// silently desynced. See ADR-0022.
    MoveSwap { from: usize, to: usize },
    /// Widget did not claim the key; caller can apply its own
    /// fallback (e.g. screen-specific keys) or let it bubble up.
    Unhandled,
}

/// One row in a [`render`] call.
#[derive(Debug, Clone)]
pub(super) struct ListRowData<'a> {
    pub(super) label: Cow<'a, str>,
    pub(super) description: Cow<'a, str>,
}

/// One verb in the help row, rendered as `letter label · letter
/// label · …` so the user always sees the active dispatch table
/// for the current screen.
///
/// `letter` must be an ASCII lowercase character and must appear
/// in the `verb_letters` slice passed to [`handle_key`]. Uppercase
/// or non-ASCII letters are silently ignored at dispatch time
/// (the widget gates `Action` on the same constraint), and a
/// letter not present in `verb_letters` produces a help row that
/// advertises a key that doesn't dispatch.
#[derive(Debug, Clone, Copy)]
pub(super) struct VerbHint<'a> {
    pub(super) letter: char,
    pub(super) label: &'a str,
}

/// Caller-supplied configuration for one [`render`] call.
#[derive(Debug, Clone)]
pub(super) struct ListScreenView<'a> {
    pub(super) title: &'a str,
    pub(super) rows: &'a [ListRowData<'a>],
    pub(super) verbs: &'a [VerbHint<'a>],
    /// When true, Enter toggles move-mode (Items Editor, Line
    /// Picker). When false, Enter emits `Activate` so the caller
    /// can open the highlighted row (Main Menu, Theme Picker).
    pub(super) move_mode_supported: bool,
}

/// Pure key dispatch. Mutates `state` for cursor / move-mode
/// changes; returns the [`ListOutcome`] the caller should react to.
///
/// Cursor preprocessing: before any key is interpreted, the cursor
/// is clamped to `[0, num_rows)`. This protects the widget against
/// stale cursors that index past the end of a list that shrank
/// between renders (e.g. after a delete) when the caller forgot to
/// call `state.set_cursor`.
pub(super) fn handle_key(
    state: &mut ListScreenState,
    key: KeyEvent,
    num_rows: usize,
    verb_letters: &[char],
    move_mode_supported: bool,
) -> ListOutcome {
    if num_rows == 0 {
        state.cursor = 0;
    } else if state.cursor >= num_rows {
        state.cursor = num_rows - 1;
    }
    // Defend against a screen that previously rendered with
    // `move_mode_supported = true` (entering move-mode) and then
    // flips support back off. Without this clamp the dispatch
    // would still route through `handle_move_mode` even though the
    // help row no longer claims to support it. If we were in
    // move-mode, drop the trigger key — reinterpreting a swap-intent
    // press as navigation would surprise the user (ADR-0022).
    if !move_mode_supported {
        let was_in_move_mode = state.move_mode;
        state.move_mode = false;
        if was_in_move_mode {
            return ListOutcome::Unhandled;
        }
    }

    if state.move_mode {
        return handle_move_mode(state, key, num_rows);
    }
    handle_normal_mode(state, key, num_rows, verb_letters, move_mode_supported)
}

/// Move-mode dispatch. Keys outside the navigation set fall
/// through to `Unhandled` (not `Consumed`) so verb letters never
/// reorder rows by accident.
fn handle_move_mode(state: &mut ListScreenState, key: KeyEvent, num_rows: usize) -> ListOutcome {
    if key.modifiers != KeyModifiers::NONE {
        return ListOutcome::Unhandled;
    }
    match key.code {
        KeyCode::Esc | KeyCode::Enter => {
            state.move_mode = false;
            ListOutcome::Consumed
        }
        KeyCode::Up if num_rows >= 2 && state.cursor > 0 => {
            let from = state.cursor;
            let to = from - 1;
            ListOutcome::MoveSwap { from, to }
        }
        KeyCode::Down if num_rows >= 2 && state.cursor + 1 < num_rows => {
            let from = state.cursor;
            let to = from + 1;
            ListOutcome::MoveSwap { from, to }
        }
        KeyCode::Up | KeyCode::Down => ListOutcome::Consumed,
        _ => ListOutcome::Unhandled,
    }
}

fn handle_normal_mode(
    state: &mut ListScreenState,
    key: KeyEvent,
    num_rows: usize,
    verb_letters: &[char],
    move_mode_supported: bool,
) -> ListOutcome {
    match (key.code, key.modifiers) {
        (KeyCode::Up, KeyModifiers::NONE) => {
            if num_rows == 0 {
                return ListOutcome::Consumed;
            }
            state.cursor = if state.cursor == 0 {
                num_rows - 1
            } else {
                state.cursor - 1
            };
            ListOutcome::Consumed
        }
        (KeyCode::Down, KeyModifiers::NONE) => {
            if num_rows == 0 {
                return ListOutcome::Consumed;
            }
            state.cursor = if state.cursor + 1 >= num_rows {
                0
            } else {
                state.cursor + 1
            };
            ListOutcome::Consumed
        }
        (KeyCode::Enter, KeyModifiers::NONE) => {
            if num_rows == 0 {
                return ListOutcome::Unhandled;
            }
            if move_mode_supported {
                state.move_mode = true;
                ListOutcome::Consumed
            } else {
                ListOutcome::Activate
            }
        }
        (KeyCode::Char(c), KeyModifiers::NONE)
            if num_rows > 0 && c.is_ascii_lowercase() && verb_letters.contains(&c) =>
        {
            ListOutcome::Action(c)
        }
        _ => ListOutcome::Unhandled,
    }
}

/// Render the list screen into `area`. Layout (top to bottom):
/// title, help row, blank, scrolling list, blank, description.
/// An empty rows slice still paints the title and help-row
/// chrome; the list and description slots stay blank.
pub(super) fn render(
    state: &ListScreenState,
    view: &ListScreenView<'_>,
    area: Rect,
    frame: &mut Frame,
) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // title
            Constraint::Length(1), // help row
            Constraint::Length(1), // blank
            Constraint::Min(1),    // list body
            Constraint::Length(1), // blank
            Constraint::Length(1), // description
        ])
        .split(area);

    let title = Paragraph::new(Line::from(Span::styled(
        view.title,
        Style::default().add_modifier(Modifier::BOLD),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(title, chunks[0]);

    let help = Paragraph::new(help_line(
        view.verbs,
        state.move_mode,
        view.move_mode_supported,
    ))
    .alignment(Alignment::Center);
    frame.render_widget(help, chunks[1]);

    // Clamp once — `handle_key` clamps on entry, but `render` can
    // run between a data mutation and the next key event (e.g. an
    // async data load that resolves mid-frame). Without one
    // clamped value driving both the highlight and the description,
    // a stale cursor highlights row N while the description shows
    // empty.
    let cursor = if view.rows.is_empty() {
        0
    } else {
        state.cursor.min(view.rows.len() - 1)
    };

    let items: Vec<ListItem<'_>> = view
        .rows
        .iter()
        .map(|row| ListItem::new(Line::from(row.label.as_ref())))
        .collect();
    let highlight_style = if state.move_mode {
        Style::default().add_modifier(Modifier::REVERSED)
    } else {
        Style::default().add_modifier(Modifier::BOLD)
    };
    let list = List::new(items)
        .highlight_symbol("")
        .highlight_style(highlight_style);

    let mut list_state = ListState::default();
    if !view.rows.is_empty() {
        list_state.select(Some(cursor));
    }
    frame.render_stateful_widget(list, chunks[3], &mut list_state);

    let description = view
        .rows
        .get(cursor)
        .map(|row| row.description.as_ref())
        .unwrap_or("");
    let description =
        Paragraph::new(Line::from(Span::raw(description))).alignment(Alignment::Center);
    frame.render_widget(description, chunks[5]);
}

/// Build the help-row line. In move-mode, the verb table is
/// suppressed in favor of a one-line reminder of what move-mode
/// does, since verbs don't dispatch in move-mode and advertising
/// them would mislead the user. When `move_mode_supported` is true
/// and the user isn't yet in move-mode, append an "Enter move-mode"
/// hint so the keypress is discoverable.
fn help_line<'a>(
    verbs: &'a [VerbHint<'a>],
    move_mode: bool,
    move_mode_supported: bool,
) -> Line<'a> {
    if move_mode {
        return Line::from(Span::styled(
            "move-mode: ↑↓ reorder · Esc/Enter exit",
            Style::default().add_modifier(Modifier::ITALIC),
        ));
    }
    let mut spans: Vec<Span<'a>> = Vec::with_capacity(verbs.len() * 4 + 2);
    for (idx, verb) in verbs.iter().enumerate() {
        if idx > 0 {
            spans.push(Span::raw(" · "));
        }
        spans.push(Span::styled(
            verb.letter.to_string(),
            Style::default().add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::raw(" "));
        spans.push(Span::raw(verb.label));
    }
    if move_mode_supported {
        if !spans.is_empty() {
            spans.push(Span::raw(" · "));
        }
        spans.push(Span::styled(
            "Enter",
            Style::default().add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::raw(" move-mode"));
    }
    Line::from(spans)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

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

    fn key_mod(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, mods)
    }

    #[test]
    fn default_state_is_cursor_zero_normal_mode() {
        let s = ListScreenState::new();
        assert_eq!(s.cursor(), 0);
        assert!(!s.move_mode());
    }

    #[test]
    fn down_advances_cursor() {
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], false);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 1);
    }

    #[test]
    fn up_at_top_wraps_to_bottom() {
        // ↑↓ wrap so the user never has to page back through the
        // list to reach the other end.
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Up), 3, &[], false);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 2);
    }

    #[test]
    fn down_at_bottom_wraps_to_top() {
        let mut s = ListScreenState::new();
        s.set_cursor(2, 3);
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], false);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn arrows_on_empty_list_are_no_op() {
        // num_rows=0 has no valid cursor; the widget eats the keys
        // without panicking on a bad index.
        let mut s = ListScreenState::new();
        assert_eq!(
            handle_key(&mut s, key(KeyCode::Up), 0, &[], false),
            ListOutcome::Consumed,
        );
        assert_eq!(
            handle_key(&mut s, key(KeyCode::Down), 0, &[], false),
            ListOutcome::Consumed,
        );
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn enter_with_move_mode_supported_toggles_into_move_mode() {
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Enter), 3, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert!(s.move_mode());
    }

    #[test]
    fn enter_without_move_mode_returns_activate() {
        // Main Menu shape: Enter on a row opens that screen, so the
        // outcome has to surface as a distinct caller signal — not
        // `Consumed` (which would silently do nothing).
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Enter), 3, &[], false);
        assert_eq!(out, ListOutcome::Activate);
        assert!(!s.move_mode());
    }

    #[test]
    fn enter_on_empty_list_is_unhandled_regardless_of_move_mode_supported() {
        // No cursor target → no `Activate` and no point entering
        // move-mode against zero rows. Bubble up so the caller can
        // show its own empty-state guidance.
        let mut s = ListScreenState::new();
        assert_eq!(
            handle_key(&mut s, key(KeyCode::Enter), 0, &[], true),
            ListOutcome::Unhandled,
        );
        assert_eq!(
            handle_key(&mut s, key(KeyCode::Enter), 0, &[], false),
            ListOutcome::Unhandled,
        );
    }

    #[test]
    fn esc_in_normal_mode_is_unhandled_for_global_quit() {
        // The global Esc=quit handler in `app::update` runs only
        // when the screen returns the key unconsumed; if the widget
        // ate Esc here, the user couldn't quit from a list screen.
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Esc), 3, &[], false);
        assert_eq!(out, ListOutcome::Unhandled);
    }

    #[test]
    fn esc_in_move_mode_exits_move_mode() {
        let mut s = ListScreenState::new();
        s.move_mode = true;
        let out = handle_key(&mut s, key(KeyCode::Esc), 3, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert!(!s.move_mode());
    }

    #[test]
    fn enter_in_move_mode_exits_move_mode() {
        // Symmetric with Esc — either key is accepted so whichever
        // one is closer to the user's hands works.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        let out = handle_key(&mut s, key(KeyCode::Enter), 3, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert!(!s.move_mode());
    }

    #[test]
    fn move_mode_down_requests_swap_without_moving_cursor() {
        // A regression that re-adds the cursor mutation here would
        // silently advance the highlight even when the caller forgot
        // to swap the underlying rows (ADR-0022).
        let mut s = ListScreenState::new();
        s.move_mode = true;
        s.set_cursor(0, 3);
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], true);
        assert_eq!(out, ListOutcome::MoveSwap { from: 0, to: 1 });
        assert_eq!(s.cursor(), 0);
        assert!(s.move_mode());
    }

    #[test]
    fn move_mode_up_requests_swap_without_moving_cursor() {
        // Mirror of the down-direction test; same ADR-0022 invariant.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        s.set_cursor(2, 3);
        let out = handle_key(&mut s, key(KeyCode::Up), 3, &[], true);
        assert_eq!(out, ListOutcome::MoveSwap { from: 2, to: 1 });
        assert_eq!(s.cursor(), 2);
        assert!(s.move_mode());
    }

    #[test]
    fn caller_ack_between_swaps_advances_to_next_neighbor() {
        // Round-trip pin for ADR-0022. The caller's responsibility is
        // (a) swap rows[from] / rows[to] and (b) call
        // set_cursor(to, num_rows). Driving two ↓s with the
        // acknowledgement between catches a future refactor that
        // re-adds widget cursor mutation alongside an existing
        // caller — the second emission would skip a row to
        // MoveSwap { from: 2, to: 3 } (panic on rows.swap) instead
        // of the expected { from: 1, to: 2 }.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        s.set_cursor(0, 3);
        let first = handle_key(&mut s, key(KeyCode::Down), 3, &[], true);
        assert_eq!(first, ListOutcome::MoveSwap { from: 0, to: 1 });
        s.set_cursor(1, 3);
        let second = handle_key(&mut s, key(KeyCode::Down), 3, &[], true);
        assert_eq!(second, ListOutcome::MoveSwap { from: 1, to: 2 });
    }

    #[test]
    fn move_mode_down_with_stale_cursor_clamps_before_swap_check() {
        // The top-of-handle_key clamp runs before the move-mode
        // bottom-guard, so a stale cursor (e.g. caller's data
        // shrank without a matching set_cursor) can't emit a
        // MoveSwap with `to` past num_rows-1. ADR-0022 makes the
        // caller responsible for cursor sync; this pins the
        // widget's defensive clamp in move-mode specifically.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        s.cursor = 99;
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 2);
        assert!(s.move_mode());
    }

    #[test]
    fn move_mode_up_at_top_does_not_swap_or_wrap() {
        // Wrapping during move-mode would teleport a row across the
        // list — confusing UX. Stay put without emitting a swap.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        s.set_cursor(0, 3);
        let out = handle_key(&mut s, key(KeyCode::Up), 3, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn move_mode_down_at_bottom_does_not_swap_or_wrap() {
        let mut s = ListScreenState::new();
        s.move_mode = true;
        s.set_cursor(2, 3);
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 2);
    }

    #[test]
    fn move_mode_with_one_row_is_consumed_no_swap() {
        // num_rows<2 means a swap is impossible. Don't emit a
        // MoveSwap with from==to (caller would do a no-op clone)
        // and don't panic on the index math.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        let out = handle_key(&mut s, key(KeyCode::Down), 1, &[], true);
        assert_eq!(out, ListOutcome::Consumed);
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn move_mode_verb_letter_is_unhandled() {
        // Verbs are gated to normal mode so pressing one (e.g. 'd'
        // for delete) while reordering can't accidentally trigger
        // a destructive action.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        let out = handle_key(&mut s, key(KeyCode::Char('d')), 3, &['d'], true);
        assert_eq!(out, ListOutcome::Unhandled);
        assert!(s.move_mode());
    }

    #[test]
    fn registered_verb_letter_emits_action() {
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Char('a')), 3, &['a', 'd'], false);
        assert_eq!(out, ListOutcome::Action('a'));
    }

    #[test]
    fn unregistered_letter_is_unhandled() {
        // Only letters in the registered verb list emit actions;
        // everything else bubbles up so the screen / global
        // dispatcher can choose its own fallback.
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Char('z')), 3, &['a', 'd'], false);
        assert_eq!(out, ListOutcome::Unhandled);
    }

    #[test]
    fn verb_letter_with_modifier_is_unhandled() {
        // Shift+a or Ctrl+a should NOT match the registered 'a'
        // verb — the user pressing a chord never meant to trigger
        // the bare-letter action.
        let mut s = ListScreenState::new();
        let shift = handle_key(
            &mut s,
            key_mod(KeyCode::Char('a'), KeyModifiers::SHIFT),
            3,
            &['a'],
            false,
        );
        assert_eq!(shift, ListOutcome::Unhandled);
        let ctrl = handle_key(
            &mut s,
            key_mod(KeyCode::Char('a'), KeyModifiers::CONTROL),
            3,
            &['a'],
            false,
        );
        assert_eq!(ctrl, ListOutcome::Unhandled);
    }

    #[test]
    fn uppercase_letter_in_verb_list_still_does_not_dispatch() {
        // Defense against a caller that violates the
        // lowercase-only `VerbHint::letter` contract: even if
        // 'A' is registered, the dispatch arm rejects it via the
        // ascii-lowercase guard. Without that guard, a typo'd
        // VerbHint would let users trigger actions through chord
        // keys that produce uppercase Chars.
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Char('A')), 3, &['A'], false);
        assert_eq!(out, ListOutcome::Unhandled);
    }

    #[test]
    fn verb_letter_on_empty_list_returns_unhandled() {
        // Empty-list defenses are uniform across Enter and verb
        // letters; both bubble up so a caller's `Action` handler
        // that reads `state.cursor()` never sees an out-of-range
        // index.
        let mut s = ListScreenState::new();
        let out = handle_key(&mut s, key(KeyCode::Char('a')), 0, &['a'], false);
        assert_eq!(out, ListOutcome::Unhandled);
    }

    #[test]
    fn move_mode_supported_flipping_off_drops_trigger_key() {
        // Per ADR-0022: a screen that previously rendered with
        // move-mode support (entering move-mode) and then flips
        // support back off drops the trigger keypress. The user's
        // ↓ meant "swap with the row below" — silently reinterpreting
        // it as "navigate down" would surprise them. Move-mode is
        // cleared and the cursor stays put; the caller's next
        // keypress lands in normal-mode cleanly.
        let mut s = ListScreenState::new();
        s.move_mode = true;
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], false);
        assert!(!s.move_mode());
        assert_eq!(out, ListOutcome::Unhandled);
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn enter_with_stale_cursor_clamps_before_activate() {
        // The clamp at the top of `handle_key` runs before the
        // Enter→Activate arm, so a caller reading `state.cursor()`
        // after Activate gets a valid index even when the list
        // shrank under the cursor between events.
        let mut s = ListScreenState::new();
        s.cursor = 5;
        let out = handle_key(&mut s, key(KeyCode::Enter), 3, &[], false);
        assert_eq!(out, ListOutcome::Activate);
        assert_eq!(s.cursor(), 2);
    }

    #[test]
    fn move_mode_arrows_with_modifier_are_unhandled() {
        // The chord guard at the top of `handle_move_mode` is the
        // entire defense against accidental swaps from chord keys.
        // A simplification pass that drops the guard would silently
        // make Shift+Down reorder rows. Ctrl variant covers a
        // future modifier-set typo that special-cases SHIFT.
        for mods in [KeyModifiers::SHIFT, KeyModifiers::CONTROL] {
            let mut s = ListScreenState::new();
            s.move_mode = true;
            s.set_cursor(1, 3);
            let out = handle_key(&mut s, key_mod(KeyCode::Down, mods), 3, &[], true);
            assert_eq!(out, ListOutcome::Unhandled, "mods={mods:?}");
            assert_eq!(
                s.cursor(),
                1,
                "chord arrow must not move cursor (mods={mods:?})"
            );
        }
    }

    #[test]
    fn arrows_with_modifier_in_normal_mode_are_unhandled() {
        // ↑/↓ match `(KeyCode::Up, KeyModifiers::NONE)` exactly;
        // chord arrows fall through to the `_` arm. A future
        // change to `(KeyCode::Up, _)` would silently eat chord
        // arrows that a parent screen might want to interpret.
        for mods in [KeyModifiers::SHIFT, KeyModifiers::CONTROL] {
            let mut s = ListScreenState::new();
            let out = handle_key(&mut s, key_mod(KeyCode::Down, mods), 3, &[], false);
            assert_eq!(out, ListOutcome::Unhandled, "mods={mods:?}");
            assert_eq!(s.cursor(), 0);
        }
    }

    #[test]
    fn handle_key_clamps_cursor_and_drops_move_mode_trigger_in_one_call() {
        // Combined stale state: cursor past end, move_mode flag
        // stale, and `move_mode_supported = false`. The cursor
        // clamp still runs (99 → 2) but the trigger keypress is
        // dropped per ADR-0022 — no normal-mode wrap. Pin the
        // post-clamp outcome so a refactor that consolidates the
        // two clamps into a helper but forgets to call one of
        // them still trips this test.
        let mut s = ListScreenState::new();
        s.cursor = 99;
        s.move_mode = true;
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], false);
        assert!(!s.move_mode(), "move_mode should clear");
        assert_eq!(out, ListOutcome::Unhandled);
        assert_eq!(s.cursor(), 2, "cursor clamped 99→2 and stays there");
    }

    #[test]
    fn cursor_is_clamped_when_list_shrinks_under_it() {
        // A delete that drops the row count without the caller
        // calling set_cursor leaves the cursor past the end. The
        // widget defends by clamping on the next handle_key.
        let mut s = ListScreenState::new();
        s.cursor = 5; // pretend we deleted from a 6-row list
        let out = handle_key(&mut s, key(KeyCode::Down), 3, &[], false);
        assert_eq!(out, ListOutcome::Consumed);
        // After clamp, cursor was 2 (last row); ↓ wraps to 0.
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn set_cursor_clamps_to_valid_range() {
        let mut s = ListScreenState::new();
        s.set_cursor(99, 4);
        assert_eq!(s.cursor(), 3);
        s.set_cursor(99, 0);
        assert_eq!(s.cursor(), 0);
    }

    #[test]
    fn render_smoke_paints_title_cursor_and_description() {
        // End-to-end render check via TestBackend. The frame
        // contains the title, the cursor symbol on the highlighted
        // row, the rendered row labels, and the highlighted row's
        // description. Catches regressions in layout chunk math
        // and in the highlight_symbol/list-state wiring that pure
        // `handle_key` tests can't.
        let backend = TestBackend::new(40, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let mut s = ListScreenState::new();
        s.set_cursor(1, 3);
        let rows = [
            ListRowData {
                label: Cow::Borrowed("First"),
                description: Cow::Borrowed("desc-A"),
            },
            ListRowData {
                label: Cow::Borrowed("Second"),
                description: Cow::Borrowed("desc-B"),
            },
            ListRowData {
                label: Cow::Borrowed("Third"),
                description: Cow::Borrowed("desc-C"),
            },
        ];
        let verbs = [VerbHint {
            letter: 'a',
            label: "add",
        }];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: false,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect();
                format!("{row}\n")
            })
            .collect();
        assert!(dump.contains("Demo"), "title missing:\n{dump}");
        assert!(dump.contains("a add"), "help row missing 'a add':\n{dump}");
        assert!(
            dump.contains("▶ Second"),
            "cursor on row 1 missing:\n{dump}"
        );
        assert!(dump.contains("First"), "row 0 label missing:\n{dump}");
        assert!(dump.contains("Third"), "row 2 label missing:\n{dump}");
        assert!(
            dump.contains("desc-B"),
            "highlighted row's description missing:\n{dump}",
        );
        assert!(
            !dump.contains("desc-A"),
            "non-highlighted description leaked:\n{dump}",
        );
    }

    #[test]
    fn render_in_move_mode_shows_move_mode_help_row() {
        // Pin the help-row swap: in move-mode the verb table is
        // hidden in favor of a move-mode reminder. Without this the
        // help row would advertise verbs that are gated off.
        let backend = TestBackend::new(60, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let mut s = ListScreenState::new();
        s.move_mode = true;
        let rows = [ListRowData {
            label: Cow::Borrowed("Only"),
            description: Cow::Borrowed("desc"),
        }];
        let verbs = [VerbHint {
            letter: 'a',
            label: "add",
        }];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: true,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect();
                format!("{row}\n")
            })
            .collect();
        assert!(
            dump.contains("move-mode"),
            "move-mode help row missing:\n{dump}",
        );
        assert!(
            !dump.contains("a add"),
            "verb-table help row leaked into move-mode:\n{dump}",
        );
    }

    #[test]
    fn render_advertises_enter_move_mode_when_supported_but_not_active() {
        // Discoverability: a list that supports move-mode but isn't
        // currently in move-mode should mention Enter in the help
        // row. Without this hint the user has to guess that Enter
        // does anything different than on a non-reorderable list.
        let backend = TestBackend::new(60, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let s = ListScreenState::new();
        let rows = [ListRowData {
            label: Cow::Borrowed("Only"),
            description: Cow::Borrowed("desc"),
        }];
        let verbs = [VerbHint {
            letter: 'a',
            label: "add",
        }];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: true,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect();
                format!("{row}\n")
            })
            .collect();
        assert!(dump.contains("a add"), "verbs still listed:\n{dump}");
        assert!(
            dump.contains("Enter move-mode"),
            "Enter hint missing:\n{dump}",
        );
    }

    #[test]
    fn render_clamps_stale_cursor_for_both_highlight_and_description() {
        // `handle_key` clamps on entry, but `render` can run
        // between a data mutation and the next event. The
        // description lookup is the load-bearing side: without
        // the clamp, `view.rows.get(99)` returns `None` and the
        // slot goes blank while ratatui's own internal clamp
        // still highlights the last row. Pinning both halves here
        // catches a regression that drops the description clamp
        // and pretends the description is "supposed to be empty
        // at the edge."
        let backend = TestBackend::new(40, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let mut s = ListScreenState::new();
        s.cursor = 99;
        let rows = [
            ListRowData {
                label: Cow::Borrowed("First"),
                description: Cow::Borrowed("desc-A"),
            },
            ListRowData {
                label: Cow::Borrowed("Second"),
                description: Cow::Borrowed("desc-B"),
            },
            ListRowData {
                label: Cow::Borrowed("Third"),
                description: Cow::Borrowed("desc-C"),
            },
        ];
        let verbs: [VerbHint<'_>; 0] = [];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: false,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect();
                format!("{row}\n")
            })
            .collect();
        assert!(
            dump.contains("▶ Third"),
            "highlight should clamp to last row:\n{dump}",
        );
        assert!(
            dump.contains("desc-C"),
            "description should clamp to same row as highlight:\n{dump}",
        );
    }

    #[test]
    fn render_with_empty_rows_does_not_panic() {
        // A list with zero rows still has to render the chrome
        // (title, help) without indexing into an empty rows slice.
        let backend = TestBackend::new(40, 10);
        let mut terminal = Terminal::new(backend).expect("backend");
        let s = ListScreenState::new();
        let rows: [ListRowData<'_>; 0] = [];
        let verbs: [VerbHint<'_>; 0] = [];
        let view = ListScreenView {
            title: "Empty",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: false,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect();
                format!("{row}\n")
            })
            .collect();
        assert!(dump.contains("Empty"), "title still renders:\n{dump}");
    }

    /// Dump the buffer preserving full grapheme symbols. The other
    /// dumps in this module use `.chars().next().unwrap_or(' ')`,
    /// which silently drops trailing codepoints of multi-codepoint
    /// graphemes (emoji with VS16 / skin-tone modifiers, ZWJ
    /// sequences, regional-indicator pairs). `Cell::symbol()`
    /// returns `" "` for both pre-fill cells and wide-glyph trailing
    /// cells, so a single `push_str` covers every shape.
    fn dump_buffer(buf: &ratatui::buffer::Buffer) -> String {
        let mut out =
            String::with_capacity((buf.area.width as usize + 1) * buf.area.height as usize);
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                out.push_str(buf[(x, y)].symbol());
            }
            out.push('\n');
        }
        out
    }

    #[test]
    fn render_long_label_truncates_without_panic() {
        // ratatui's `List` truncates (not wraps) when a label exceeds
        // the column count. Pin that: a 200-char label in a 20-column
        // backend must not push the help-row or description out of
        // their layout slots.
        let backend = TestBackend::new(20, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let s = ListScreenState::new();
        let long_label: String = "X".repeat(200);
        let rows = [ListRowData {
            label: Cow::Owned(long_label.clone()),
            description: Cow::Borrowed("desc-A"),
        }];
        let verbs = [VerbHint {
            letter: 'a',
            label: "add",
        }];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: false,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump = dump_buffer(&buf);
        assert!(dump.contains("Demo"), "title missing:\n{dump}");
        assert!(dump.contains("a add"), "help row missing:\n{dump}");
        assert!(
            dump.contains("desc-A"),
            "description missing (long label pushed it off?):\n{dump}",
        );
        // Pin both the cursor placement and a meaningful run of
        // the long label (the 20-col backend leaves room for at least
        // 13 X's after the 2-cell `▶ ` symbol; a regression that
        // truncated the label to ~1 char would leave `▶ X` matching
        // but this stronger run wouldn't).
        assert!(
            dump.contains("▶ XXXXXXXXXXXXX"),
            "cursor + long-label run missing:\n{dump}"
        );
    }

    #[test]
    fn render_wide_grapheme_label_preserves_cell_layout() {
        // A 2-cell-wide CJK grapheme must render at its full cell
        // width without breaking cursor placement or the row below.
        // A regression that re-treats it as 1-cell-wide would
        // truncate or overlap the description.
        let backend = TestBackend::new(40, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let s = ListScreenState::new();
        let rows = [ListRowData {
            // U+4E2D (中) is canonical 2-cell width per unicode-width.
            label: Cow::Borrowed("中文"),
            description: Cow::Borrowed("cjk-desc"),
        }];
        let verbs = [VerbHint {
            letter: 'a',
            label: "add",
        }];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: false,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump = dump_buffer(&buf);
        assert!(dump.contains(""), "wide grapheme '中' missing:\n{dump}");
        assert!(dump.contains(""), "wide grapheme '文' missing:\n{dump}");
        assert!(
            dump.contains("cjk-desc"),
            "description should still render below wide label:\n{dump}",
        );
        // Every wide grapheme must be followed by an empty or space
        // trailing cell (`""` = ratatui convention; `" "` = buffer
        // pre-fill). A 1-cell regression surfaces as a non-space
        // trailing cell — overlap or layout compression.
        let mut found_lead = 0_usize;
        for y in 0..buf.area.height {
            for x in 0..buf.area.width.saturating_sub(1) {
                let lead = buf[(x, y)].symbol();
                if lead == "" || lead == "" {
                    let trail = buf[(x + 1, y)].symbol();
                    assert!(
                        trail.is_empty() || trail == " ",
                        "trailing cell after {lead:?} should be empty or space, got {trail:?}",
                    );
                    found_lead += 1;
                }
            }
        }
        // Double-paint regression (grapheme at two adjacent cells)
        // would push this past 2.
        assert_eq!(
            found_lead, 2,
            "expected exactly one '中' and one '文' in the buffer:\n{dump}",
        );
    }

    #[test]
    fn render_multi_verb_help_row_uses_middle_dot_separator() {
        // Pin the `·` (U+00B7) separator between verb hints. Existing
        // tests assert `dump.contains("a add")` but don't pin the
        // separator — a regression to `,` or a dropped separator
        // would still pass.
        let backend = TestBackend::new(60, 12);
        let mut terminal = Terminal::new(backend).expect("backend");
        let s = ListScreenState::new();
        let rows = [ListRowData {
            label: Cow::Borrowed("Only"),
            description: Cow::Borrowed("desc"),
        }];
        let verbs = [
            VerbHint {
                letter: 'a',
                label: "add",
            },
            VerbHint {
                letter: 'd',
                label: "delete",
            },
        ];
        let view = ListScreenView {
            title: "Demo",
            rows: &rows,
            verbs: &verbs,
            move_mode_supported: false,
        };
        terminal
            .draw(|frame| render(&s, &view, frame.area(), frame))
            .expect("draw");
        let buf = terminal.backend().buffer().clone();
        let dump = dump_buffer(&buf);
        assert!(
            dump.contains("a add · d delete"),
            "help row missing `·` separator between verbs:\n{dump}",
        );
    }
}