linear-tui 0.8.0

A TUI client for Linear.app — manage issues, projects, and cycles from your terminal
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
//! Keybindings (Controller).
//!
//! Every documented binding is one row of [`BINDINGS`]: the keys it answers
//! to, the contexts it applies in, what it does, and how the help overlay and
//! the status bar describe it. Dispatch, hints, and help all read that table,
//! so adding a binding means adding a row.
//!
//! The command palette is the fourth reader: a row with a [`Command`] is
//! listed there, with the keys shown next to it, so the palette cannot offer
//! an action the keyboard lacks or advertise a key that does something else.
//!
//! Only the overlays that document their own keys in their frame — the error
//! popup, the help overlay, the pick-one popups, and the palette — keep a
//! hand-written handler.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::api::types::Priority;
use crate::app::{App, FormField, Input, InputMode, Nav, Popup, Screen, TeamSection};
use crate::grouping::Preset;

/// Where a key is pressed. A binding lists the contexts it applies in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ctx {
    IssueList,
    IssueDetail,
    ProjectList,
    ProjectDetail,
    CycleList,
    CycleDetail,
    ViewList,
    /// The navigation sidebar has focus.
    Sidebar,
    /// A `g` is pending; the next key finishes the chord.
    GoTo,
    Search,
    Comment,
    /// Typing a note for the agent.
    Note,
    IssueTitle,
    IssueDescription,
    IssuePriority,
}

impl From<Screen> for Ctx {
    fn from(screen: Screen) -> Self {
        match screen {
            Screen::IssueList => Self::IssueList,
            Screen::IssueDetail => Self::IssueDetail,
            Screen::ProjectList => Self::ProjectList,
            Screen::ProjectDetail => Self::ProjectDetail,
            Screen::CycleList => Self::CycleList,
            Screen::CycleDetail => Self::CycleDetail,
            Screen::ViewList => Self::ViewList,
        }
    }
}

use Ctx::*;

/// Every screen, with the sidebar unfocused.
const SCREENS: &[Ctx] = &[
    IssueList,
    IssueDetail,
    ProjectList,
    ProjectDetail,
    CycleList,
    CycleDetail,
    ViewList,
];
/// Every screen, and the sidebar.
const NORMAL: &[Ctx] = &[
    IssueList,
    IssueDetail,
    ProjectList,
    ProjectDetail,
    CycleList,
    CycleDetail,
    ViewList,
    Sidebar,
];
/// Screens with a cursor over rows.
const LISTS: &[Ctx] = &[
    IssueList,
    ProjectList,
    ProjectDetail,
    CycleList,
    CycleDetail,
    ViewList,
];
/// Screens that scroll: the lists and the issue view.
const SCROLLING: &[Ctx] = &[
    IssueList,
    IssueDetail,
    ProjectList,
    ProjectDetail,
    CycleList,
    CycleDetail,
    ViewList,
];
/// Screens listing issues.
const ISSUE_LISTS: &[Ctx] = &[IssueList, ProjectDetail, CycleDetail];
/// Screens with an issue under the cursor.
const ISSUE_SCREENS: &[Ctx] = &[IssueList, IssueDetail, ProjectDetail, CycleDetail];
/// Top-level destinations, where a number jumps to another one.
const INDEXES: &[Ctx] = &[IssueList, ProjectList, CycleList, ViewList];
/// Where `q` quits rather than steps back.
const TOP_LEVEL: &[Ctx] = &[IssueList, ProjectList, CycleList, ViewList, Sidebar];
/// Where `q` steps back.
const NESTED: &[Ctx] = &[IssueDetail, ProjectDetail, CycleDetail];
/// Team pages, where the team can be switched.
const TEAM_PAGES: &[Ctx] = &[IssueList, ProjectList, CycleList, Sidebar];
/// Text fields.
const TEXT: &[Ctx] = &[Search, Comment, Note, IssueTitle, IssueDescription];
/// Multi-line text fields.
const MULTILINE: &[Ctx] = &[Comment, Note, IssueDescription];
/// The new-issue form, whichever field has focus.
const FORM: &[Ctx] = &[IssueTitle, IssueDescription, IssuePriority];
/// Anything submitted with Ctrl+Enter.
const SUBMITTABLE: &[Ctx] = &[Comment, Note, IssueTitle, IssueDescription, IssuePriority];
/// Every input mode that Esc abandons.
const EDITING: &[Ctx] = &[
    Search,
    Comment,
    Note,
    IssueTitle,
    IssueDescription,
    IssuePriority,
];

/// Which modifiers a [`Key`] requires.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mods {
    /// Anything goes.
    Any,
    /// No Ctrl; Shift and Alt are fine.
    NoCtrl,
    /// Neither Ctrl nor Alt.
    Bare,
    /// Ctrl, with or without Shift.
    Ctrl,
    /// Ctrl without Shift.
    CtrlNoShift,
    /// Ctrl and Shift.
    CtrlShift,
    /// Ctrl or Alt.
    CtrlOrAlt,
}

/// One key a binding answers to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Key {
    code: KeyCode,
    mods: Mods,
}

impl Key {
    fn matches(&self, key: &KeyEvent) -> bool {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        key.code == self.code
            && match self.mods {
                Mods::Any => true,
                Mods::NoCtrl => !ctrl,
                Mods::Bare => !ctrl && !alt,
                Mods::Ctrl => ctrl,
                Mods::CtrlNoShift => ctrl && !shift,
                Mods::CtrlShift => ctrl && shift,
                Mods::CtrlOrAlt => ctrl || alt,
            }
    }
}

/// A character typed without Ctrl.
const fn plain(c: char) -> Key {
    Key {
        code: KeyCode::Char(c),
        mods: Mods::NoCtrl,
    }
}

const fn ctrl(c: char) -> Key {
    Key {
        code: KeyCode::Char(c),
        mods: Mods::Ctrl,
    }
}

const fn ctrl_no_shift(c: char) -> Key {
    Key {
        code: KeyCode::Char(c),
        mods: Mods::CtrlNoShift,
    }
}

const fn ctrl_shift(c: char) -> Key {
    Key {
        code: KeyCode::Char(c),
        mods: Mods::CtrlShift,
    }
}

/// A non-character key, whatever the modifiers.
const fn code(code: KeyCode) -> Key {
    Key {
        code,
        mods: Mods::Any,
    }
}

/// A key without Ctrl or Alt.
const fn bare(code: KeyCode) -> Key {
    Key {
        code,
        mods: Mods::Bare,
    }
}

const fn ctrl_or_alt(code: KeyCode) -> Key {
    Key {
        code,
        mods: Mods::CtrlOrAlt,
    }
}

/// A heading of the help overlay, in the order they are drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Section {
    Navigation,
    Sidebar,
    GoTo,
    ListDisplay,
    IssueActions,
    CopyOpen,
    SearchFilter,
    /// Handing work to a coding agent.
    Agent,
    Mouse,
    Other,
    Scrolling,
    Editing,
}

impl Section {
    pub const ALL: [Section; 12] = [
        Self::Navigation,
        Self::Sidebar,
        Self::GoTo,
        Self::ListDisplay,
        Self::IssueActions,
        Self::CopyOpen,
        Self::SearchFilter,
        Self::Agent,
        Self::Mouse,
        Self::Other,
        Self::Scrolling,
        Self::Editing,
    ];

    /// Where the palette lists the section: acting on the issue at hand
    /// first, as Linear's command menu does, and moving around last.
    fn palette_rank(self) -> u8 {
        match self {
            Self::IssueActions => 0,
            Self::CopyOpen => 1,
            Self::SearchFilter => 2,
            Self::Agent => 2,
            Self::ListDisplay => 3,
            Self::GoTo => 4,
            Self::Navigation => 5,
            Self::Sidebar => 6,
            Self::Other => 7,
            Self::Mouse | Self::Scrolling | Self::Editing => 8,
        }
    }

    pub fn title(self) -> &'static str {
        match self {
            Self::Navigation => "Navigation",
            Self::Sidebar => "Sidebar",
            Self::GoTo => "Go to",
            Self::ListDisplay => "List display",
            Self::IssueActions => "Issue actions",
            Self::CopyOpen => "Copy & open",
            Self::SearchFilter => "Search & filter",
            Self::Agent => "Agent",
            Self::Mouse => "Mouse",
            Self::Other => "Other",
            Self::Scrolling => "Scrolling",
            Self::Editing => "Editing",
        }
    }
}

/// A row of the help overlay.
#[derive(Debug, Clone, Copy)]
pub struct Help {
    pub section: Section,
    /// The keys as written, e.g. `j/k`. One row may cover a pair of bindings.
    pub keys: &'static str,
    pub text: &'static str,
}

/// A status-bar hint.
#[derive(Debug, Clone, Copy)]
pub struct Hint {
    /// Position on the status bar, lowest first; ties keep table order.
    pub rank: u8,
    pub keys: &'static str,
    pub what: &'static str,
    /// Where the hint shows — some or all of the binding's contexts.
    pub on: &'static [Ctx],
}

/// A command palette entry.
#[derive(Debug, Clone, Copy)]
pub struct Command {
    pub section: Section,
    pub title: &'static str,
    /// Other words it is found by.
    pub keywords: &'static [&'static str],
    /// Where the palette offers it — the binding's own contexts unless it
    /// says otherwise, as for the second key of a `g …` chord.
    pub on: &'static [Ctx],
}

/// A keybinding: what it answers to, where, what it does, and how it is shown.
#[derive(Clone, Copy)]
pub struct Binding {
    /// Every key that triggers it — a kitty-protocol original sits next to
    /// its plain-key alias, so the pair cannot drift apart. Empty for a row
    /// that documents input handled elsewhere (the mouse).
    pub keys: &'static [Key],
    pub context: &'static [Ctx],
    pub action: fn(&mut App),
    pub help: Option<Help>,
    pub hint: Option<Hint>,
    pub command: Option<Command>,
    /// Only inside herdr: elsewhere it neither answers nor is listed.
    pub herdr_only: bool,
}

impl Binding {
    const fn help(mut self, section: Section, keys: &'static str, text: &'static str) -> Self {
        self.help = Some(Help {
            section,
            keys,
            text,
        });
        self
    }

    /// A hint on every context the binding applies in.
    const fn hint(self, rank: u8, keys: &'static str, what: &'static str) -> Self {
        let on = self.context;
        self.hint_on(on, rank, keys, what)
    }

    /// A hint on some of the binding's contexts.
    const fn hint_on(
        mut self,
        on: &'static [Ctx],
        rank: u8,
        keys: &'static str,
        what: &'static str,
    ) -> Self {
        self.hint = Some(Hint {
            rank,
            keys,
            what,
            on,
        });
        self
    }

    /// A palette entry, under the binding's help section.
    const fn command(mut self, title: &'static str, keywords: &'static [&'static str]) -> Self {
        let section = match self.help {
            Some(help) => help.section,
            None => Section::Other,
        };
        self.command = Some(Command {
            section,
            title,
            keywords,
            on: self.context,
        });
        self
    }

    /// Offer the palette entry in `on` rather than the binding's contexts.
    const fn on(mut self, on: &'static [Ctx]) -> Self {
        if let Some(command) = &mut self.command {
            command.on = on;
        }
        self
    }

    /// File the palette entry under `section`.
    const fn in_section(mut self, section: Section) -> Self {
        if let Some(command) = &mut self.command {
            command.section = section;
        }
        self
    }

    /// Mark a binding that only makes sense inside herdr.
    const fn herdr_only(mut self) -> Self {
        self.herdr_only = true;
        self
    }

    /// Whether it exists in this terminal.
    pub(crate) fn shown(&self) -> bool {
        !self.herdr_only || crate::herdr::available()
    }

    fn applies_in(&self, ctx: Ctx) -> bool {
        self.context.contains(&ctx)
    }

    fn matches(&self, key: &KeyEvent) -> bool {
        self.keys.iter().any(|k| k.matches(key))
    }
}

const fn bind(keys: &'static [Key], context: &'static [Ctx], action: fn(&mut App)) -> Binding {
    Binding {
        keys,
        context,
        action,
        help: None,
        hint: None,
        command: None,
        herdr_only: false,
    }
}

/// An action reached only from the command palette, in `context`.
const fn palette_only(context: &'static [Ctx], action: fn(&mut App)) -> Binding {
    bind(&[], context, action)
}

/// A help row for input dispatched outside this table.
const fn documented(section: Section, keys: &'static str, text: &'static str) -> Binding {
    bind(&[], &[], |_| {}).help(section, keys, text)
}

/// Every binding. The help overlay lists rows by [`Section`], in table order
/// within each; the status bar orders hints by [`Hint::rank`].
///
/// Shortcuts mirror Linear's own (see AGENTS.md). Where a terminal cannot
/// deliver Linear's key, the original is listed for the kitty keyboard
/// protocol together with a plain alias.
pub static BINDINGS: &[Binding] = &[
    // --- Navigation ---
    // Linear's command menu — Cmd/Ctrl+K. Inside a text field Ctrl+K keeps
    // its readline meaning.
    bind(&[ctrl('k')], NORMAL, App::open_palette)
        .help(Section::Navigation, "C-k", "Command palette")
        .hint_on(SCREENS, 11, "^K", "commands"),
    bind(&[plain('j'), code(KeyCode::Down)], NORMAL, down)
        .help(Section::Navigation, "j/k", "Move cursor down/up")
        .hint_on(
            &[Sidebar, ViewList, ProjectList, CycleList],
            75,
            "j/k",
            "move",
        ),
    bind(&[plain('k'), code(KeyCode::Up)], NORMAL, up),
    // `g` opens a chord: `gg` jumps to the top, `gm`/`gp`/… switch views.
    bind(&[plain('g')], SCROLLING, App::start_goto_chord),
    bind(&[code(KeyCode::Home)], NORMAL, first),
    bind(&[plain('g')], &[Sidebar], first),
    bind(&[plain('G'), code(KeyCode::End)], NORMAL, last).help(
        Section::Navigation,
        "gg/G",
        "First/last item",
    ),
    // Space is Linear's peek; with no split pane it simply opens the row.
    bind(
        &[code(KeyCode::Enter), plain(' ')],
        LISTS,
        App::open_selected,
    )
    .help(Section::Navigation, "Enter", "Open")
    .hint(10, "Enter", "open"),
    bind(
        &[code(KeyCode::Enter), plain(' ')],
        &[Sidebar],
        App::sidebar_activate,
    )
    .hint(76, "Enter", "open"),
    bind(
        &[code(KeyCode::Esc)],
        &[IssueList, IssueDetail, ProjectDetail, CycleDetail],
        back,
    )
    .help(Section::Navigation, "Esc", "Back / close")
    .hint_on(&[IssueDetail], 1, "Esc", "back"),
    bind(&[plain('q')], NESTED, leave),
    // Step to the neighbouring issue without leaving the detail view.
    bind(&[plain('J')], &[IssueDetail], |app| app.step_issue(1))
        .help(Section::Navigation, "J/K", "Next/previous issue (detail)")
        .hint(2, "J/K", "next/prev")
        .command("Next issue", &["down", "step"]),
    bind(&[plain('K')], &[IssueDetail], |app| app.step_issue(-1))
        .command("Previous issue", &["up", "step"])
        .in_section(Section::Navigation),
    // --- Sidebar ---
    bind(&[code(KeyCode::Tab)], SCREENS, |app| {
        app.focus_sidebar(true)
    })
    .help(Section::Sidebar, "Tab", "Focus sidebar / content")
    .hint_on(LISTS, 80, "Tab", "sidebar")
    .command("Focus sidebar", &["navigation"]),
    bind(
        &[code(KeyCode::Tab), code(KeyCode::Esc)],
        &[Sidebar],
        |app| app.focus_sidebar(false),
    )
    .hint(80, "Tab", "content")
    .command("Focus content", &["list"])
    .in_section(Section::Sidebar),
    bind(&[ctrl('b')], NORMAL, App::toggle_sidebar)
        .help(Section::Sidebar, "C-b", "Show/hide sidebar")
        .hint_on(&[Sidebar], 85, "^B", "hide")
        .command("Toggle sidebar", &["show", "hide"]),
    // A tree folds with h/l, as in every file explorer.
    bind(
        &[
            plain('h'),
            code(KeyCode::Left),
            plain('l'),
            code(KeyCode::Right),
        ],
        &[Sidebar],
        App::sidebar_toggle,
    )
    .help(Section::Sidebar, "h/l", "Fold/unfold a Favorites folder")
    .hint(77, "h/l", "fold")
    .command(
        "Fold or unfold folder",
        &["favorites", "collapse", "expand"],
    ),
    // --- Go to: the second key of a `g …` chord ---
    // Linear reaches its view presets with `G` then `A`/`B`/`E` (Active,
    // Backlog, All issues) and its pages with the other letters.
    bind(&[plain('a')], &[GoTo], |app| {
        team_preset(app, Preset::Active)
    })
    .help(Section::GoTo, "g a", "Active issues")
    .hint(0, "a", "active")
    .command("Go to active issues", &["preset"])
    .on(NORMAL),
    bind(&[plain('b')], &[GoTo], |app| {
        team_preset(app, Preset::Backlog)
    })
    .help(Section::GoTo, "g b", "Backlog")
    .hint(0, "b", "backlog")
    .command("Go to backlog", &["preset"])
    .on(NORMAL),
    bind(&[plain('e')], &[GoTo], |app| team_preset(app, Preset::All))
        .help(Section::GoTo, "g e", "All issues")
        .hint(0, "e", "all issues")
        .command("Go to all issues", &["preset", "everything"])
        .on(NORMAL),
    bind(&[plain('m')], &[GoTo], |app| app.activate(Nav::MyIssues))
        .help(Section::GoTo, "g m", "My issues")
        .hint(0, "m", "my issues")
        .command("Go to my issues", &["assigned", "mine"])
        .on(NORMAL),
    bind(&[plain('v')], &[GoTo], |app| app.activate(Nav::Views))
        .help(Section::GoTo, "g v", "Views")
        .hint(0, "v", "views")
        .command("Go to views", &["saved", "custom"])
        .on(NORMAL),
    bind(&[plain('p')], &[GoTo], |app| {
        app.go_to_team_section(TeamSection::Projects)
    })
    .help(Section::GoTo, "g p", "Projects")
    .hint(0, "p", "projects")
    .command("Go to projects", &[])
    .on(NORMAL),
    bind(&[plain('c')], &[GoTo], |app| {
        app.go_to_team_section(TeamSection::Cycles)
    })
    .help(Section::GoTo, "g c", "Cycles")
    .hint(0, "c", "cycles")
    .command("Go to cycles", &["sprint"])
    .on(NORMAL),
    // Inside herdr: the pane of the agent working on the issue. Linear has
    // no agents beside it, and no `g w`.
    bind(&[plain('w')], &[GoTo], App::jump_to_agent)
        .help(
            Section::Agent,
            "g w",
            "Go to the agent working on the issue",
        )
        .hint(0, "w", "agent")
        .command(
            "Go to the agent working on this issue",
            &["herdr", "pane", "workspace"],
        )
        .on(ISSUE_SCREENS)
        .herdr_only(),
    // vim: gg
    bind(&[plain('g')], &[GoTo], first).hint(0, "g", "top"),
    // Destination jumps by number, a TUI shorthand for the sidebar. Linear has
    // no equivalent — it reaches pages with `g …`, which works here too.
    bind(&[plain('1')], INDEXES, App::go_to_team_issues)
        .help(Section::GoTo, "1-5", "Issues/My/Projects/Cycles/Views")
        .command("Go to team issues", &["list"])
        .on(NORMAL),
    bind(&[plain('2')], INDEXES, |app| app.activate(Nav::MyIssues)),
    bind(&[plain('3')], INDEXES, |app| {
        app.go_to_team_section(TeamSection::Projects)
    }),
    bind(&[plain('4')], INDEXES, |app| {
        app.go_to_team_section(TeamSection::Cycles)
    }),
    bind(&[plain('5')], INDEXES, |app| app.activate(Nav::Views)),
    // --- List display ---
    // Neither preset nor grouping has a Linear keybinding — the web app puts
    // both behind a display-options menu — so they take keys Linear leaves free.
    bind(&[code(KeyCode::BackTab)], ISSUE_LISTS, App::cycle_preset)
        .help(
            Section::ListDisplay,
            "S-Tab",
            "Next preset (Active/Backlog/All)",
        )
        .hint(50, "S-Tab", "preset")
        .command("Next preset", &["active", "backlog", "all", "display"]),
    // Linear's Issues / Projects tabs on a Views page.
    bind(&[code(KeyCode::BackTab)], &[ViewList], App::cycle_view_kind)
        .hint(50, "S-Tab", "issues/projects")
        .command("Switch between issue and project views", &["tab"])
        .in_section(Section::ListDisplay),
    bind(&[plain('D')], ISSUE_LISTS, App::cycle_group_by)
        .help(
            Section::ListDisplay,
            "D",
            "Group by status/assignee/\u{2026}",
        )
        .hint(60, "D", "group")
        .command("Next grouping", &["group by", "display"]),
    palette_only(ISSUE_LISTS, App::open_group_by)
        .command(
            "Group by\u{2026}",
            &["status", "assignee", "priority", "project", "display"],
        )
        .in_section(Section::ListDisplay),
    bind(&[plain('z')], ISSUE_LISTS, App::toggle_selected_group)
        .help(Section::ListDisplay, "z / Z", "Fold group / all groups")
        .hint(70, "z", "fold")
        .command("Fold or unfold group", &["collapse", "expand"]),
    bind(&[plain('Z')], ISSUE_LISTS, App::toggle_all_groups)
        .command("Fold or unfold all groups", &["collapse", "expand"])
        .in_section(Section::ListDisplay),
    // --- Notes for the agent, a TUI-only addition: Linear has no agent
    // beside it to hand remarks to. ---
    bind(&[plain('n')], ISSUE_SCREENS, App::start_note_on_issue)
        .help(Section::Agent, "n", "Note on the issue under the cursor")
        .command(
            "Add a note for your agent",
            &["feedback", "remark", "review"],
        ),
    bind(&[plain('N')], SCREENS, App::start_note_on_view)
        .help(Section::Agent, "N", "Note on the whole view")
        .command("Add a note on this view", &["feedback", "remark", "review"]),
    bind(&[ctrl('s')], SCREENS, App::send_notes)
        .help(Section::Agent, "C-s", "Send the notes to your agent")
        .command("Send notes to your agent", &["prompt", "feedback", "herdr"]),
    palette_only(SCREENS, App::discard_notes)
        .command("Discard notes", &["clear", "feedback"])
        .in_section(Section::Agent),
    // --- Issue actions, matching Linear's single-key bindings ---
    // `c` creates an issue from anywhere, as in Linear.
    bind(&[plain('c')], SCREENS, App::start_new_issue)
        .help(Section::IssueActions, "c", "Create issue")
        .hint_on(ISSUE_LISTS, 30, "c", "new")
        .command("Create new issue", &["add", "file"]),
    bind(&[plain('s')], ISSUE_SCREENS, App::open_status_change)
        .help(Section::IssueActions, "s", "Change status")
        .hint(20, "s/p/a", "status/priority/assignee")
        .command("Change status\u{2026}", &["state", "workflow", "move"]),
    bind(&[plain('p')], ISSUE_SCREENS, App::open_priority_change)
        .help(Section::IssueActions, "p", "Change priority")
        .command("Change priority\u{2026}", &["urgency"]),
    // Direct priority — Linear: Shift+1..4 / Shift+0.
    bind(&[plain('!')], ISSUE_SCREENS, |app| {
        app.set_priority(Priority::Urgent)
    })
    .help(
        Section::IssueActions,
        "!@#$)",
        "Urgent/High/Medium/Low/None",
    )
    .command("Set priority to Urgent", &["priority"]),
    bind(&[plain('@')], ISSUE_SCREENS, |app| {
        app.set_priority(Priority::High)
    })
    .command("Set priority to High", &["priority"])
    .in_section(Section::IssueActions),
    bind(&[plain('#')], ISSUE_SCREENS, |app| {
        app.set_priority(Priority::Medium)
    })
    .command("Set priority to Medium", &["priority"])
    .in_section(Section::IssueActions),
    bind(&[plain('$')], ISSUE_SCREENS, |app| {
        app.set_priority(Priority::Low)
    })
    .command("Set priority to Low", &["priority"])
    .in_section(Section::IssueActions),
    bind(&[plain(')')], ISSUE_SCREENS, |app| {
        app.set_priority(Priority::None)
    })
    .command("Remove priority", &["priority", "none"])
    .in_section(Section::IssueActions),
    bind(&[plain('a')], ISSUE_SCREENS, App::open_assignee_change)
        .help(Section::IssueActions, "a", "Assign to someone")
        .command("Assign to\u{2026}", &["assignee", "owner", "unassign"]),
    bind(&[plain('i')], ISSUE_SCREENS, App::assign_to_me)
        .help(Section::IssueActions, "i", "Assign to me")
        .command("Assign to me", &["assignee", "self", "take"]),
    // Add comment — Linear: Ctrl+M. A legacy terminal reports Ctrl+M as
    // Enter, so plain `m` is accepted too (Linear leaves `m` for relations,
    // which this client does not support).
    bind(&[ctrl('m'), plain('m')], ISSUE_SCREENS, App::start_comment)
        .help(Section::IssueActions, "m", "Add comment (Ctrl+M)")
        .hint_on(&[IssueDetail], 21, "m", "comment")
        .command("Add comment", &["reply", "message"]),
    // --- Copy & open ---
    // Copy issue ID — Linear: Ctrl+.
    bind(
        &[ctrl_no_shift('.'), plain('y')],
        ISSUE_SCREENS,
        App::copy_identifier,
    )
    .help(Section::CopyOpen, "y", "Copy issue ID (Ctrl+.)")
    .hint_on(&[IssueDetail], 23, "y", "copy ID")
    .command("Copy issue ID", &["identifier", "clipboard"]),
    // Copy issue URL — Linear: Ctrl+Shift+, (some terminals report `<`).
    bind(
        &[ctrl_shift(','), ctrl_shift('<'), plain('Y')],
        ISSUE_SCREENS,
        App::copy_url,
    )
    .help(Section::CopyOpen, "Y", "Copy issue URL (Ctrl+Shift+,)")
    .command("Copy issue URL", &["link", "clipboard"]),
    // Copy git branch name — Linear: Ctrl+Shift+. (or `>`).
    bind(
        &[ctrl_shift('.'), ctrl_shift('>'), plain('b')],
        ISSUE_SCREENS,
        App::copy_branch_name,
    )
    .help(Section::CopyOpen, "b", "Copy branch name (Ctrl+Shift+.)")
    .command("Copy git branch name", &["clipboard", "checkout"]),
    // A TUI-only action, since Linear is already in the browser.
    bind(&[plain('o')], SCREENS, App::open_in_browser)
        .help(Section::CopyOpen, "o", "Open on linear.app")
        .hint_on(&[IssueDetail], 22, "o", "open")
        .command("Open in browser", &["linear.app", "web"]),
    // --- Search & filter ---
    bind(&[plain('/')], ISSUE_LISTS, App::start_search)
        .help(Section::SearchFilter, "/", "Filter as you type")
        .hint(40, "/", "filter")
        .command("Search in this list", &["find", "filter"]),
    bind(&[code(KeyCode::Enter)], &[Search], App::finish_search).hint(1, "Enter", "keep"),
    bind(&[code(KeyCode::Esc)], EDITING, cancel).hint_on(&[Search], 2, "Esc", "clear"),
    bind(&[ctrl('g')], &[Search], App::search_workspace)
        .help(Section::SearchFilter, "C-g", "Search all of Linear")
        .hint(3, "Ctrl+G", "search all of Linear"),
    bind(&[plain('f')], ISSUE_LISTS, App::open_filter)
        .help(Section::SearchFilter, "f/F", "Filter / clear filters")
        .command("Filter\u{2026}", &["status", "priority"]),
    bind(&[plain('F')], ISSUE_LISTS, App::clear_filters)
        .command("Clear filters", &["reset"])
        .in_section(Section::SearchFilter),
    // --- Mouse, routed by `App::click` ---
    documented(Section::Mouse, "click", "Select; click again to open"),
    documented(Section::Mouse, "click", "Sidebar, chips, group headers"),
    documented(Section::Mouse, "wheel", "Scroll"),
    // --- Other ---
    bind(&[plain('t')], TEAM_PAGES, App::open_team_select)
        .help(Section::Other, "t", "Switch team")
        .command("Switch team\u{2026}", &["workspace"]),
    // Linear syncs live and binds plain `r` to Rename, so this client uses the
    // terminal convention instead and leaves `r` free.
    bind(&[code(KeyCode::F(5)), ctrl('r')], SCREENS, refresh)
        .help(Section::Other, "F5/C-r", "Refresh")
        .hint_on(&[ViewList, ProjectList, CycleList], 90, "^R", "refresh")
        .command("Refresh", &["reload", "sync"]),
    bind(&[plain('?')], NORMAL, App::open_help)
        .help(Section::Other, "?", "Toggle this help")
        .hint(99, "?", "help")
        .command("Show keyboard shortcuts", &["help", "keys"]),
    bind(&[plain('q')], TOP_LEVEL, App::quit)
        .help(Section::Other, "q", "Quit")
        .command("Quit", &["exit", "close"])
        .on(NORMAL),
    // --- Scrolling ---
    bind(&[ctrl('d')], NORMAL, half_page_down).help(
        Section::Scrolling,
        "C-d/C-u",
        "Half page down/up",
    ),
    bind(&[ctrl('u')], NORMAL, half_page_up),
    bind(&[code(KeyCode::PageDown)], SCROLLING, page_down).help(
        Section::Scrolling,
        "PgDn/PgUp",
        "Full page down/up",
    ),
    bind(&[code(KeyCode::PageUp)], SCROLLING, page_up),
    // --- Editing: readline-style, in every text field ---
    bind(&[ctrl('w')], TEXT, |app| edit(app, Input::kill_word)).help(
        Section::Editing,
        "C-w",
        "Delete previous word",
    ),
    bind(&[ctrl('u')], TEXT, |app| edit(app, Input::kill_to_start)).help(
        Section::Editing,
        "C-u/C-k",
        "Delete to start/end",
    ),
    bind(&[ctrl('k')], TEXT, |app| edit(app, Input::kill_to_end)),
    bind(&[ctrl('a'), code(KeyCode::Home)], TEXT, |app| {
        edit(app, Input::home)
    })
    .help(Section::Editing, "C-a/C-e", "Jump to start/end"),
    bind(&[ctrl('e'), code(KeyCode::End)], TEXT, |app| {
        edit(app, Input::end)
    }),
    bind(&[code(KeyCode::Left)], TEXT, |app| edit(app, Input::left)),
    bind(&[code(KeyCode::Right)], TEXT, |app| edit(app, Input::right)),
    bind(&[code(KeyCode::Backspace)], TEXT, |app| {
        edit(app, Input::backspace)
    }),
    bind(&[code(KeyCode::Delete)], TEXT, |app| {
        edit(app, Input::delete)
    }),
    // Ctrl/Alt+Enter submits; a bare Enter breaks the line.
    bind(&[ctrl_or_alt(KeyCode::Enter)], SUBMITTABLE, submit).help(
        Section::Editing,
        "C-Enter",
        "Submit",
    ),
    bind(&[bare(KeyCode::Enter)], MULTILINE, |app| {
        edit(app, |input| input.insert('\n'))
    }),
    // A bare Enter on the title advances rather than inserting a newline.
    bind(&[bare(KeyCode::Enter)], &[IssueTitle], |app| {
        app.new_issue_cycle_field(true)
    }),
    bind(&[code(KeyCode::Tab)], FORM, |app| {
        app.new_issue_cycle_field(true)
    }),
    bind(&[code(KeyCode::BackTab)], FORM, |app| {
        app.new_issue_cycle_field(false)
    }),
    bind(
        &[plain('j'), code(KeyCode::Down), code(KeyCode::Right)],
        &[IssuePriority],
        |app| app.new_issue_cycle_priority(1),
    ),
    bind(
        &[plain('k'), code(KeyCode::Up), code(KeyCode::Left)],
        &[IssuePriority],
        |app| app.new_issue_cycle_priority(-1),
    ),
];

/// The context a key press lands in.
pub fn context(app: &App) -> Ctx {
    match app.view.input_mode {
        InputMode::Search => Search,
        InputMode::Comment => Comment,
        InputMode::Note => Note,
        InputMode::NewIssue => match app.view.new_issue.as_ref().map(|form| form.field) {
            Some(FormField::Description) => IssueDescription,
            Some(FormField::Priority) => IssuePriority,
            Some(FormField::Title) | None => IssueTitle,
        },
        InputMode::Normal if app.view.pending_chord == Some('g') => GoTo,
        InputMode::Normal if app.view.sidebar.focus => Sidebar,
        InputMode::Normal => app.nav.screen.into(),
    }
}

/// The palette's commands for a context: by section, what acts on the issue
/// at hand first, then in table order.
pub fn commands(ctx: Ctx) -> Vec<&'static Binding> {
    let mut commands: Vec<&Binding> = BINDINGS
        .iter()
        .filter(|b| b.shown() && b.command.is_some_and(|c| c.on.contains(&ctx)))
        .collect();
    commands.sort_by_key(|b| b.command.map(|c| c.section.palette_rank()));
    commands
}

impl Key {
    /// How the key is written in the palette, e.g. `s`, `Ctrl+B`, `F5`.
    pub fn label(&self) -> String {
        let name = match self.code {
            KeyCode::Char(' ') => "Space".to_string(),
            KeyCode::Char(c) => match self.mods {
                Mods::Ctrl | Mods::CtrlNoShift | Mods::CtrlShift | Mods::CtrlOrAlt => {
                    c.to_ascii_uppercase().to_string()
                }
                _ => c.to_string(),
            },
            KeyCode::Enter => "Enter".into(),
            KeyCode::Esc => "Esc".into(),
            KeyCode::Tab => "Tab".into(),
            KeyCode::BackTab => "Shift+Tab".into(),
            KeyCode::Backspace => "Backspace".into(),
            KeyCode::Delete => "Del".into(),
            KeyCode::Home => "Home".into(),
            KeyCode::End => "End".into(),
            KeyCode::PageUp => "PgUp".into(),
            KeyCode::PageDown => "PgDn".into(),
            KeyCode::Up => "\u{2191}".into(),
            KeyCode::Down => "\u{2193}".into(),
            KeyCode::Left => "\u{2190}".into(),
            KeyCode::Right => "\u{2192}".into(),
            KeyCode::F(n) => format!("F{n}"),
            other => format!("{other:?}"),
        };
        match self.mods {
            Mods::Ctrl | Mods::CtrlNoShift => format!("Ctrl+{name}"),
            Mods::CtrlShift => format!("Ctrl+Shift+{name}"),
            Mods::CtrlOrAlt => format!("Ctrl+{name}"),
            Mods::Any | Mods::NoCtrl | Mods::Bare => name,
        }
    }
}

impl Binding {
    /// The keys that trigger it, as the palette shows them: the plain alias
    /// first, since it works in every terminal.
    pub fn keys_label(&self) -> String {
        let plain = |k: &&Key| matches!(k.mods, Mods::Any | Mods::NoCtrl | Mods::Bare);
        // A kitty original can come in several spellings (`Ctrl+Shift+,` is
        // also reported as `<`); one of them is enough.
        let labels: Vec<String> = self
            .keys
            .iter()
            .filter(plain)
            .chain(self.keys.iter().find(|k| !plain(k)))
            .map(Key::label)
            .collect();
        labels.join(" / ")
    }
}

/// The status-bar hints for a context, in display order.
pub fn hints(ctx: Ctx) -> Vec<&'static Hint> {
    let mut hints: Vec<&Hint> = BINDINGS
        .iter()
        .filter(|b| b.shown())
        .filter_map(|b| b.hint.as_ref())
        .filter(|h| h.on.contains(&ctx))
        .collect();
    hints.sort_by_key(|h| h.rank);
    hints
}

/// The help overlay's rows under one heading, in table order.
pub fn help_rows(section: Section) -> impl Iterator<Item = &'static Help> {
    BINDINGS
        .iter()
        .filter(|b| b.shown())
        .filter_map(|b| b.help.as_ref())
        .filter(move |h| h.section == section)
}

pub fn handle_key(app: &mut App, key: KeyEvent) {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

    if ctrl && key.code == KeyCode::Char('c') {
        app.quit();
        return;
    }

    // Error popup dismisses on any key
    if app.view.error_popup.is_some() {
        app.dismiss_error();
        return;
    }

    // Help overlay: j/k scrolls, anything else closes
    if app.view.show_help {
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => app.scroll_help(1),
            KeyCode::Char('k') | KeyCode::Up => app.scroll_help(-1),
            _ => app.close_help(),
        }
        return;
    }

    // Esc abandons a half-typed chord
    if key.code == KeyCode::Esc && app.view.pending_chord.take().is_some() {
        return;
    }

    // The palette types into its own query.
    if app.view.popup == Popup::Palette {
        crate::palette::handle_key(app, key);
        return;
    }

    // Popup takes priority
    if app.view.popup != Popup::None {
        handle_popup_keys(app, key);
        return;
    }

    let ctx = context(app);
    // A pending `g` swallows the next key, whether or not it finishes a chord.
    if ctx == GoTo {
        app.end_chord();
    }
    if let Some(binding) = BINDINGS
        .iter()
        .find(|b| b.shown() && b.applies_in(ctx) && b.matches(&key))
    {
        (binding.action)(app);
        return;
    }
    // Anything else typed into a text field is text.
    if TEXT.contains(&ctx)
        && let KeyCode::Char(c) = key.code
        && !ctrl
    {
        edit(app, |input| input.insert(c));
    }
}

/// Keys in a pick-one popup. Until something is typed, the popup keeps its
/// single-key moves (`j`/`k`, `g`, `q`, digits); after that every letter is
/// part of the query, and only arrows, `Ctrl+N`/`Ctrl+P`, Home/End, and Enter
/// move or pick. An upper-case letter always starts a query, since matching
/// ignores case.
fn handle_popup_keys(app: &mut App, key: KeyEvent) {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let typing = !app.view.popup_query.is_empty();
    match key.code {
        KeyCode::Esc => app.popup_escape(),
        KeyCode::Char('q') if !typing && !ctrl => app.popup_escape(),
        KeyCode::Down => app.popup_next(),
        KeyCode::Up => app.popup_prev(),
        KeyCode::Char('n') if ctrl => app.popup_next(),
        KeyCode::Char('p') if ctrl => app.popup_prev(),
        KeyCode::Char('j') if !typing && !ctrl => app.popup_next(),
        KeyCode::Char('k') if !typing && !ctrl => app.popup_prev(),
        KeyCode::Home => app.popup_first(),
        KeyCode::End => app.popup_last(),
        KeyCode::Char('g') if !typing && !ctrl => app.popup_first(),
        KeyCode::Enter => app.apply_popup(),
        KeyCode::Char(c @ '1'..='9') if !typing && !ctrl => {
            app.popup_pick((c as usize) - ('1' as usize))
        }
        KeyCode::Backspace => app.popup_erase(),
        KeyCode::Char('w') if ctrl => app.edit_popup_query(Input::kill_word),
        KeyCode::Char('u') if ctrl => app.edit_popup_query(Input::kill_to_start),
        KeyCode::Char(c) if !ctrl => app.popup_type(c),
        _ => {}
    }
}

// --- Actions that depend on where they run ---

fn down(app: &mut App) {
    if app.view.sidebar.focus {
        app.sidebar_move(1);
    } else if app.nav.screen == Screen::IssueDetail {
        app.scroll_down();
    } else {
        app.move_selection(1);
    }
}

fn up(app: &mut App) {
    if app.view.sidebar.focus {
        app.sidebar_move(-1);
    } else if app.nav.screen == Screen::IssueDetail {
        app.scroll_up();
    } else {
        app.move_selection(-1);
    }
}

fn half_page_down(app: &mut App) {
    if app.view.sidebar.focus {
        app.sidebar_move(app.half_page());
    } else if app.nav.screen == Screen::IssueDetail {
        app.scroll_by(app.frame.detail_viewport as i16 / 2);
    } else {
        app.move_selection(app.half_page());
    }
}

fn half_page_up(app: &mut App) {
    if app.view.sidebar.focus {
        app.sidebar_move(-app.half_page());
    } else if app.nav.screen == Screen::IssueDetail {
        app.scroll_by(-(app.frame.detail_viewport as i16) / 2);
    } else {
        app.move_selection(-app.half_page());
    }
}

fn page_down(app: &mut App) {
    if app.nav.screen == Screen::IssueDetail {
        app.scroll_by(app.frame.detail_viewport as i16);
    } else {
        app.move_selection(app.frame.list_viewport.max(1) as isize);
    }
}

fn page_up(app: &mut App) {
    if app.nav.screen == Screen::IssueDetail {
        app.scroll_by(-(app.frame.detail_viewport as i16));
    } else {
        app.move_selection(-(app.frame.list_viewport.max(1) as isize));
    }
}

fn first(app: &mut App) {
    if app.view.sidebar.focus {
        app.sidebar_move(isize::MIN / 2);
    } else if app.nav.screen == Screen::IssueDetail {
        app.scroll_to_top();
    } else {
        app.select_first();
    }
}

fn last(app: &mut App) {
    if app.view.sidebar.focus {
        app.sidebar_move(isize::MAX / 2);
    } else if app.nav.screen == Screen::IssueDetail {
        app.scroll_to_bottom();
    } else {
        app.select_last();
    }
}

/// Esc: close the issue view; elsewhere drop a search first, and only then
/// leave a project or cycle page.
fn back(app: &mut App) {
    match app.nav.screen {
        Screen::IssueDetail => app.close_detail(),
        Screen::ProjectDetail | Screen::CycleDetail if app.list().search.is_empty() => {
            app.leave_container()
        }
        _ => app.clear_search(),
    }
}

/// `q` on a nested page steps back instead of quitting.
fn leave(app: &mut App) {
    if app.nav.screen == Screen::IssueDetail {
        app.close_detail();
    } else {
        app.leave_container();
    }
}

fn refresh(app: &mut App) {
    if app.nav.screen == Screen::IssueDetail {
        app.refresh_detail();
    } else {
        app.force_reload();
    }
}

fn team_preset(app: &mut App, preset: Preset) {
    app.go_to_team_issues();
    app.set_preset(preset);
}

fn cancel(app: &mut App) {
    match app.view.input_mode {
        InputMode::Search => app.cancel_search(),
        InputMode::Comment => app.cancel_comment(),
        InputMode::Note => app.cancel_note(),
        InputMode::NewIssue => app.cancel_new_issue(),
        InputMode::Normal => {}
    }
}

fn submit(app: &mut App) {
    match app.view.input_mode {
        InputMode::Comment => app.submit_comment(),
        InputMode::Note => app.submit_note(),
        InputMode::NewIssue => app.submit_new_issue(),
        InputMode::Search | InputMode::Normal => {}
    }
}

/// The text field keys are typed into, if any.
fn active_input(app: &mut App) -> Option<&mut Input> {
    match app.view.input_mode {
        InputMode::Search => Some(&mut app.list_mut().search),
        InputMode::Comment => Some(&mut app.view.comment),
        InputMode::Note => Some(&mut app.view.note),
        InputMode::NewIssue => app
            .view
            .new_issue
            .as_mut()
            .and_then(|form| match form.field {
                FormField::Title => Some(&mut form.title),
                FormField::Description => Some(&mut form.description),
                FormField::Priority => None,
            }),
        InputMode::Normal => None,
    }
}

/// Edits the active field. A search filters as you type, so the list stays in
/// sync with the query.
fn edit(app: &mut App, change: impl FnOnce(&mut Input)) {
    if let Some(input) = active_input(app) {
        change(input);
    }
    if app.view.input_mode == InputMode::Search {
        app.apply_search();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::types::Issue;
    use crate::app::{IssueSource, Screen};
    use crate::config::Config;
    use crossterm::event::{KeyEventKind, KeyEventState};

    fn press(app: &mut App, code: KeyCode) {
        handle_key(
            app,
            KeyEvent {
                code,
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: KeyEventState::NONE,
            },
        );
    }

    fn stated(id: &str, state_id: &str, name: &str, kind: &str) -> Issue {
        serde_json::from_str(&format!(
            r#"{{"id":"{id}","identifier":"ENG-{id}","title":"t{id}","priority":0,
                "state":{{"id":"{state_id}","name":"{name}","type":"{kind}","position":1}},
                "assignee":null,"description":null,"comments":null,"project":null,"cycle":null}}"#
        ))
        .unwrap()
    }

    /// The API returns these as Todo, In Progress, Todo; grouping shows In
    /// Progress first, so the second row on screen is raw index 0.
    fn reordered() -> Vec<Issue> {
        vec![
            stated("1", "s-todo", "Todo", "unstarted"),
            stated("2", "s-prog", "In Progress", "started"),
            stated("3", "s-todo", "Todo", "unstarted"),
        ]
    }

    fn app() -> App {
        let mut app = App::new(&Config::default());
        app.outbox.requests.clear();
        app
    }

    /// Regression: Enter on a project's issue opened whichever issue sat at the
    /// cursor's position in the raw API order, not the one highlighted.
    #[test]
    fn enter_on_a_project_issue_opens_the_highlighted_one() {
        let mut app = app();
        app.store.issues[IssueSource::Project].items = reordered();
        app.nav.screen = Screen::ProjectDetail;
        press(&mut app, KeyCode::Char('j'));
        let highlighted = app.focused_issue().unwrap().id.clone();
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.nav.screen, Screen::IssueDetail);
        assert_eq!(app.store.current_issue.as_ref().unwrap().id, highlighted);
        assert_eq!(highlighted, "1");
    }

    #[test]
    fn enter_on_a_cycle_issue_opens_the_highlighted_one() {
        let mut app = app();
        app.store.issues[IssueSource::Cycle].items = reordered();
        app.nav.screen = Screen::CycleDetail;
        press(&mut app, KeyCode::Char('j'));
        press(&mut app, KeyCode::Char('j'));
        let highlighted = app.focused_issue().unwrap().id.clone();
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.store.current_issue.as_ref().unwrap().id, highlighted);
        assert_eq!(highlighted, "3");
    }

    /// Every list screen: keyboard Enter and the highlighted row agree.
    #[test]
    fn enter_on_every_issue_list_opens_the_highlighted_issue() {
        use crate::app::Nav;
        for (screen, nav) in [
            (Screen::IssueList, None),
            (Screen::IssueList, Some(Nav::MyIssues)),
            (Screen::ProjectDetail, None),
            (Screen::CycleDetail, None),
        ] {
            let mut app = app();
            app.store.issues[IssueSource::Team].items = reordered();
            app.store.issues[IssueSource::My].items = reordered();
            app.store.issues[IssueSource::Project].items = reordered();
            app.store.issues[IssueSource::Cycle].items = reordered();
            app.set_preset(crate::grouping::Preset::All);
            app.outbox.requests.clear();
            if let Some(nav) = nav {
                app.nav.dest = nav;
            }
            app.nav.screen = screen;
            for downs in 0..3 {
                app.nav.screen = screen;
                app.set_selected_index(0);
                for _ in 0..downs {
                    press(&mut app, KeyCode::Char('j'));
                }
                let highlighted = app.focused_issue().unwrap().id.clone();
                press(&mut app, KeyCode::Enter);
                assert_eq!(
                    app.store.current_issue.as_ref().unwrap().id,
                    highlighted,
                    "{screen:?} {nav:?} row {downs}"
                );
                app.close_detail();
            }
        }
    }

    fn press_with(app: &mut App, code: KeyCode, modifiers: KeyModifiers) {
        handle_key(
            app,
            KeyEvent {
                code,
                modifiers,
                kind: KeyEventKind::Press,
                state: KeyEventState::NONE,
            },
        );
    }

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

    /// A team with three active issues on its list.
    fn team_app() -> App {
        let mut app = app();
        app.store.teams =
            vec![serde_json::from_str(r#"{"id":"t","name":"Core","key":"ENG"}"#).unwrap()];
        app.store.issues[IssueSource::Team].items = reordered();
        app
    }

    #[test]
    fn a_g_chord_jumps_and_esc_abandons_it() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('g'));
        assert_eq!(app.view.pending_chord, Some('g'));
        press(&mut app, KeyCode::Char('m'));
        assert_eq!(app.nav.dest, Nav::MyIssues);
        assert_eq!(app.view.pending_chord, None);

        press(&mut app, KeyCode::Char('g'));
        press(&mut app, KeyCode::Esc);
        assert_eq!(app.view.pending_chord, None);
        assert_eq!(app.nav.dest, Nav::MyIssues, "Esc only drops the chord");
    }

    #[test]
    fn a_number_key_picks_a_popup_entry() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('p'));
        assert!(matches!(app.view.popup, Popup::PriorityChange(_)));
        // Row 2 of the priority menu is Urgent.
        press(&mut app, KeyCode::Char('2'));
        assert_eq!(app.view.popup, Popup::None);
        assert!(matches!(
            app.outbox.requests.back(),
            Some(crate::message::Request::UpdatePriority {
                priority: Priority::Urgent,
                ..
            })
        ));
    }

    #[test]
    fn search_filters_as_you_type_and_esc_clears_it() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('/'));
        assert_eq!(app.view.input_mode, InputMode::Search);
        typed(&mut app, "t2");
        assert_eq!(app.visible_issues().len(), 1);
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.view.input_mode, InputMode::Normal);
        assert_eq!(app.visible_issues().len(), 1, "Enter keeps the query");

        press(&mut app, KeyCode::Esc);
        assert_eq!(app.visible_issues().len(), 3);
    }

    #[test]
    fn keys_typed_into_search_are_not_commands() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('/'));
        typed(&mut app, "q");
        assert!(!app.should_quit);
        assert_eq!(app.list().search.value, "q");
    }

    #[test]
    fn ctrl_c_quits_from_any_mode() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('/'));
        press_with(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert!(app.should_quit);
    }

    #[test]
    fn linears_ctrl_period_and_its_plain_alias_both_copy_the_id() {
        for (code, modifiers) in [
            (KeyCode::Char('.'), KeyModifiers::CONTROL),
            (KeyCode::Char('y'), KeyModifiers::NONE),
        ] {
            let mut app = team_app();
            press_with(&mut app, code, modifiers);
            assert_eq!(app.outbox.clipboard.as_deref(), Some("ENG-2"), "{code:?}");
        }
    }

    #[test]
    fn shift_digits_set_a_priority_directly() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('!'));
        assert_eq!(app.focused_issue().unwrap().priority, Priority::Urgent);
    }

    #[test]
    fn tab_moves_focus_to_the_sidebar_and_back() {
        let mut app = team_app();
        press(&mut app, KeyCode::Tab);
        assert!(app.view.sidebar.focus);
        press(&mut app, KeyCode::Char('j'));
        assert!(app.view.sidebar.focus, "j moves within the sidebar");
        press(&mut app, KeyCode::Esc);
        assert!(!app.view.sidebar.focus);
    }

    #[test]
    fn q_quits_a_list_but_only_closes_the_detail() {
        let mut app = team_app();
        press(&mut app, KeyCode::Enter);
        assert_eq!(app.nav.screen, Screen::IssueDetail);
        press(&mut app, KeyCode::Char('q'));
        assert_eq!(app.nav.screen, Screen::IssueList);
        assert!(!app.should_quit);
        press(&mut app, KeyCode::Char('q'));
        assert!(app.should_quit);
    }

    #[test]
    fn enter_breaks_a_comment_line_and_ctrl_enter_posts_it() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('m'));
        assert_eq!(app.view.input_mode, InputMode::Comment);
        typed(&mut app, "hi");
        press(&mut app, KeyCode::Enter);
        typed(&mut app, "there");
        assert_eq!(app.view.comment.value, "hi\nthere");
        press_with(&mut app, KeyCode::Enter, KeyModifiers::CONTROL);
        assert_eq!(app.view.input_mode, InputMode::Normal);
        assert!(matches!(
            app.outbox.requests.back(),
            Some(crate::message::Request::CreateComment { body, .. }) if body == "hi\nthere"
        ));
    }

    #[test]
    fn the_help_overlay_closes_on_any_other_key() {
        let mut app = team_app();
        press(&mut app, KeyCode::Char('?'));
        assert!(app.view.show_help);
        press(&mut app, KeyCode::Char('j'));
        assert!(app.view.show_help, "j scrolls the help");
        press(&mut app, KeyCode::Char('x'));
        assert!(!app.view.show_help);
    }
}

#[cfg(test)]
mod table_tests {
    use super::*;
    use crossterm::event::{KeyEventKind, KeyEventState};

    /// The plainest event a key answers to.
    fn sample(key: &Key) -> KeyEvent {
        let modifiers = match key.mods {
            Mods::Any | Mods::NoCtrl | Mods::Bare => KeyModifiers::NONE,
            Mods::Ctrl | Mods::CtrlNoShift | Mods::CtrlOrAlt => KeyModifiers::CONTROL,
            Mods::CtrlShift => KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        };
        KeyEvent {
            code: key.code,
            modifiers,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }
    }

    /// Dispatch takes the first match, so two bindings sharing a key in one
    /// context would leave the second one dead.
    #[test]
    fn no_two_bindings_claim_a_key_in_the_same_context() {
        for (i, a) in BINDINGS.iter().enumerate() {
            for b in &BINDINGS[i + 1..] {
                let Some(ctx) = a.context.iter().find(|c| b.context.contains(c)) else {
                    continue;
                };
                for key in a.keys.iter().chain(b.keys) {
                    let event = sample(key);
                    assert!(
                        !(a.matches(&event) && b.matches(&event)),
                        "{key:?} is bound twice in {ctx:?}"
                    );
                }
            }
        }
    }

    /// A hint must not advertise a key where it does nothing.
    #[test]
    fn hints_show_only_where_their_binding_applies() {
        for binding in BINDINGS {
            if let Some(hint) = &binding.hint {
                for ctx in hint.on {
                    assert!(binding.applies_in(*ctx), "{:?} hint on {ctx:?}", hint.keys);
                }
            }
        }
    }

    /// A keyless row either documents the mouse or is a palette-only command.
    #[test]
    fn every_keyless_binding_is_documented() {
        for binding in BINDINGS.iter().filter(|b| b.keys.is_empty()) {
            if binding.command.is_some() {
                continue;
            }
            let help = binding.help.expect("a keyless binding documents something");
            assert_eq!(help.section, Section::Mouse, "{:?}", help.keys);
        }
    }

    /// Everything the help overlay lists as an action can be run from the
    /// palette, so a new binding cannot be added without an entry. Movement,
    /// scrolling and text editing are exempt, and so are keys that only work
    /// inside a text field, where the palette cannot be opened.
    #[test]
    fn every_documented_action_is_in_the_palette() {
        let exempt = [
            Section::Navigation,
            Section::Mouse,
            Section::Scrolling,
            Section::Editing,
        ];
        for binding in BINDINGS {
            let Some(help) = binding.help else { continue };
            if exempt.contains(&help.section) || binding.context.iter().all(|c| EDITING.contains(c))
            {
                continue;
            }
            assert!(
                binding.command.is_some(),
                "{} ({}) has no palette entry",
                help.text,
                help.keys
            );
        }
    }

    /// Two entries with one title in one place could not be told apart.
    #[test]
    fn no_two_commands_share_a_title_in_a_context() {
        for ctx in NORMAL.iter().chain(&[GoTo]) {
            let titles: Vec<&str> = commands(*ctx)
                .iter()
                .filter_map(|b| b.command.map(|c| c.title))
                .collect();
            for (i, title) in titles.iter().enumerate() {
                assert!(!titles[i + 1..].contains(title), "{title} twice in {ctx:?}");
            }
        }
    }

    /// The palette can only be opened where nothing is being typed.
    #[test]
    fn commands_are_offered_only_outside_text_fields() {
        for binding in BINDINGS {
            if let Some(command) = binding.command {
                assert!(
                    command.on.iter().all(|c| NORMAL.contains(c)),
                    "{} offered in a text field",
                    command.title
                );
            }
        }
    }

    #[test]
    fn keys_are_labelled_plain_alias_first() {
        let comment = BINDINGS
            .iter()
            .find(|b| b.command.is_some_and(|c| c.title == "Add comment"))
            .unwrap();
        assert_eq!(comment.keys_label(), "m / Ctrl+M");
        let url = BINDINGS
            .iter()
            .find(|b| b.command.is_some_and(|c| c.title == "Copy issue URL"))
            .unwrap();
        assert_eq!(url.keys_label(), "Y / Ctrl+Shift+,");
    }
}