pristine-cli 0.1.0

A language-agnostic reclaimable-space finder and cleaner.
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
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
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
//! What a keypress means: one table, and the chain that reads it.
//!
//! # Deliberately close to pua's
//!
//! pua is a rollup tree over processes and this is a rollup tree over directories, so the two
//! should feel like siblings: `j`/`k`, `←`/`→`, `*`, `z`, `g`/`G`, `s`/`S`, `/`, `?`, `q` and
//! `Esc` all mean here exactly what they mean there, and this file is a rewrite of pua's
//! `tui/keymap.rs` rather than an independent invention.
//!
//! It diverges exactly where the verbs do. pua kills one process and needs a key that asks
//! before signalling; pristine **marks a subtree** and then commits a batch, which is two verbs
//! rather than one. `space` marks (npkill's key for the same idea), `a` marks or clears
//! everything, and `x` — pua's one key that writes — commits what is marked. The keys pua
//! spends on sampling (`space` freezes, `r` re-samples) are free here, because a directory tree
//! does not tick.
//!
//! # Why a table rather than a `match`
//!
//! Three things have to agree about the keymap and drift apart the moment any of them is
//! written by hand: the dispatcher, the help overlay and the footer. [`KEYMAP`] is the single
//! statement of what is bound and all three read it, so a key that does something is a key the
//! help page documents by construction.
//!
//! # Routing is a chain of surfaces
//!
//! Overlay first, then the tree, then the globals. Spelled as a list of [`Surface`]s rather
//! than as branches in the dispatcher because of the guarantee attached to it: the tree can
//! never shadow a global key, which is one assertion over the table rather than a property
//! somebody has to keep noticing. An overlay is modal by *omission* — while one is up the
//! chain simply does not contain the tree.
//!
//! # The pointer is a second table, for the same reason
//!
//! [`POINTER`] is to a mouse event what [`KEYMAP`] is to a keystroke, and it is a table for
//! the argument written above rather than by analogy: the dispatcher, the help overlay and
//! the guarantee that no gesture acts undocumented all read it. What it does *not* need is
//! the chain — a press has coordinates, so "which surface is this" is answered by
//! [`super::render::hit`] geometrically, and restating the order here would be two rules that
//! have to agree.

use std::fmt;
use std::sync::LazyLock;

use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};

use super::render::{Spot, Zone};
use crate::rules::Kind;
use crate::tree::Order;

/// Where a motion key wants the cursor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Motion {
    /// One row back.
    Up,
    /// One row on.
    Down,
    /// A screenful back.
    PageUp,
    /// A screenful on.
    PageDown,
    /// The first row.
    Top,
    /// The last row.
    Bottom,
}

/// Which way round a cycle goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Turn {
    /// Forwards.
    Next,
    /// Backwards.
    Prev,
}

/// What a keypress asked for.
///
/// Separated from carrying it out so the keymap can be asserted directly: "`h` collapses" is
/// one assertion here rather than a terminal, a fixture tree and a rendered frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    /// `q` `Ctrl-c` — put the terminal back and go.
    Quit,
    /// A motion key — move the cursor, which moves the viewport with it.
    Cursor(Motion),
    /// `→` `l` `Enter` — open a row, or step into an open one.
    Expand,
    /// `←` `h` — close a row, or step out of a closed one.
    Collapse,
    /// `*` — open or close everything under the cursor at once.
    ToggleSubtree,
    /// `z` — close every open row, back to the roots.
    ///
    /// **Not a toggle**, where [`ToggleSubtree`](Self::ToggleSubtree) is: `*` is ambiguous on
    /// a partly-open subtree and this key is not, so it keeps the one meaning it has. An
    /// "open everything" companion is deliberately absent — one real home directory expands
    /// to 22,765 rows, and that is not a view anybody asked for.
    CollapseAll,
    /// `space` — mark the row's whole subtree, or unmark it.
    ///
    /// The key npkill uses for selecting a row, doing the thing npkill's flat list cannot: a
    /// mark on a collapsed row covers everything beneath it.
    Mark,
    /// `a` — mark everything, or clear the marks.
    ///
    /// Ambiguous on a partial selection in a way `space` is not, and resolved toward
    /// **clearing**: a reader who has marked forty directories and presses an unfamiliar key
    /// can afford to lose the selection and cannot afford to gain thirty more.
    MarkAll,
    /// `x` — remove what is marked. Asks first.
    ///
    /// pua's key for the one thing that writes, and the sentence in the help says that it
    /// asks: a reader scanning the page for a way to free space must not have to press it to
    /// find out whether it is armed. The key **asks** and never deletes; the only thing that
    /// commits is the dialog handing back what it was holding.
    Commit,
    /// `m` — show or hide the treemap pane.
    ///
    /// A key rather than a flag, and the reason is the one every part of [`super::treemap`]
    /// turns on: an enhancement a reader cannot dismiss is not an enhancement. It is on the
    /// tree's surface rather than among the globals because what it changes is how the tree
    /// pane is laid out.
    ToggleMap,
    /// `s` — the next sort key.
    CycleSort,
    /// `S` — the same key, upside down.
    ReverseSort,
    /// `1` `2` `3`, or a click on a column heading — order a level by that key.
    ///
    /// Reverses when it names the order already in force, and starts a *new* column the right
    /// way up: see [`super::state::View::sort_by`].
    SortBy(Order),
    /// A click on a row's name — put the cursor on that directory.
    ///
    /// By [`NodeId`](crate::tree::NodeId) and never by row index; see [`Spot::Row`].
    Select(crate::tree::NodeId),
    /// A click on a row's `▸` — open that row, or close it.
    ///
    /// The one thing `→` and `←` between them do, reached with one gesture and without the
    /// cursor having to be there first.
    OpenRow(crate::tree::NodeId),
    /// A click on a row's `[ ]` — mark that row's subtree, or unmark it.
    ///
    /// `space` for a reader who is pointing. pristine draws a box on every row, and a box
    /// that cannot be pressed is a lie the screen tells about itself.
    MarkRow(crate::tree::NodeId),
    /// A double click on a row — price everything under it that carries no price.
    ///
    /// The expensive thing a reader wants on one specific subtree, which is what
    /// `--breakdown-under` is on the command line. A double click is the gesture for it
    /// because it is the one that says "this one, in particular".
    Price(crate::tree::NodeId),
    /// The wheel over the tree — move the viewport, taking the cursor with it.
    ///
    /// Distinct from [`Cursor`](Self::Cursor), which moves the cursor and lets the viewport
    /// follow: this is the other way round.
    ScrollRows(Motion),
    /// `/` — open the filter prompt.
    OpenFilter,
    /// `f` `F` — the next named view, or the one before.
    ///
    /// A view is the two axes of [`super::lens`] together, and this key walks the presets over
    /// them. Deliberately **not** a key that changes the selection: what is marked is
    /// independent of what is visible, and the whole point of the pair is that a reader can
    /// narrow the screen without narrowing what they are about to delete.
    CyclePreset(Turn),
    /// `t` — move the **tier** axis on its own: named, named + gitignored, gitignored.
    ///
    /// The presets are shortcuts through four points; this and [`ToggleKind`](Self::ToggleKind)
    /// are what make every *other* point reachable. Without them "show me every cache a rule
    /// named" is a combination the model can hold and no reader can ask for, which is not what
    /// "stays expressible" can mean.
    CycleTiers,
    /// `i` — show or hide gitignored **files**, leaving both other axes exactly as they were.
    ///
    /// Its own key rather than a value on the tier axis, for the reason [`super::lens::Lens::files`]
    /// gives: a preset moves one axis per step and `all` would have to move two to reach files.
    /// The request asked for exactly this — includable and excludable independently of ignored
    /// directories — so the key is the feature rather than a convenience over it.
    ToggleFiles,
    /// `u` `d` `b` `c` `n` — turn one **kind** on or off, leaving the others and the tier axis
    /// exactly as they were.
    ///
    /// One key per member rather than a cycle, because a set of five has thirty-two states and
    /// a cycle through thirty-two is a key nobody can aim.
    ToggleKind(Kind),
    /// A printable character, while the prompt has it.
    ///
    /// **Not in [`KEYMAP`]**, and it could not be: it stands for every character a terminal
    /// can report, which is not a list. It is also not a keybinding — typing `v` into a text
    /// field is content, not a command.
    Type(char),
    /// `Backspace` in the prompt.
    Erase,
    /// `Delete` in the prompt.
    EraseAhead,
    /// `Ctrl-u` — throw the prompt's line away.
    Wipe,
    /// `←` `→` `Home` `End` in the prompt.
    Caret(Motion),
    /// `Enter` in the prompt — apply the filter.
    Submit,
    /// `?` — show or hide the help.
    Help,
    /// `Esc` — step back one rung, and never quit.
    Back,
    /// A click on what the footer is saying — take it away, and **nothing else**.
    ///
    /// The rung [`Back`](Self::Back) takes first, reached on its own rather than through the
    /// ladder. That distinction is the whole reason this is not just `Back`: a press is
    /// resolved against the frame the reader aimed at and acted on at the release, so a report
    /// that goes in between would leave a `Back` to fall through onto the rung below — and the
    /// rung below is the reader's filter. A dismissal with nothing to dismiss does nothing.
    Dismiss,
    /// `←` `→` on a confirmation — move the highlight between the two answers.
    ///
    /// Arrows and **not `Tab`**: a modal quietly redefining a key is worst in the one place a
    /// reader is being asked to be careful.
    Highlight(Turn),
    /// `Enter` on a confirmation — answer with whichever one is highlighted.
    ///
    /// It does not say *which* answer: the dialog holds both, so this is only "the one I am
    /// looking at". The highlight starts on cancel, so the key a reader presses to get rid of
    /// what is in front of them is the safe one.
    Answer,
    /// `↑` `↓` inside the help overlay.
    Scroll(Motion),
    /// `↑` `↓` on a confirmation — move down the batch it is listing.
    ///
    /// Distinct from [`Scroll`](Self::Scroll), which moves a document with no cursor in it:
    /// here the line under the cursor is a directory, and [`Spare`](Self::Spare) acts on it.
    Listing(Motion),
    /// `space` on a confirmation — take the highlighted directory out of the batch.
    ///
    /// The tree's own mark key, on the one screen where a reader can see everything they
    /// marked at once. It is what makes the listing an answer to a surprise rather than a
    /// notification of one.
    Spare,
    /// A key with no meaning here, or a resize. Any event redraws, so this is genuinely
    /// nothing — the resize included, which needs only the frame.
    Ignore,
}

/// Which layer of the screen a binding belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Surface {
    /// Reserved everywhere. Small on purpose — every key here is one the tree may never take.
    Global,
    /// The rows themselves, which is where every key that acts on a directory lives.
    Tree,
    /// The help overlay's own keys, reachable only while it is up.
    Help,
    /// The filter prompt's, which are the one surface allowed to take a global key: while a
    /// text field has input there is no chain past it. See [`chain`].
    Prompt,
    /// The confirmation dialog's two answers.
    Confirm,
}

impl Surface {
    /// The heading this surface gets in the help overlay.
    #[must_use]
    pub fn title(self) -> &'static str {
        match self {
            Self::Global => "Everywhere",
            Self::Tree => "The tree",
            Self::Help => "This overlay",
            Self::Prompt => "The filter prompt",
            Self::Confirm => "A confirmation",
        }
    }
}

/// One key, with the modifier that distinguishes it from the bare version.
///
/// `Shift` is deliberately absent: a terminal reports `S` as `Char('S')`, so the shifted
/// letter is already a different [`KeyCode`]. Recording it as well would mean matching two
/// spellings of every capital.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Chord {
    /// The key.
    pub code: KeyCode,
    /// Whether Control was held.
    pub ctrl: bool,
}

impl Chord {
    const fn plain(code: KeyCode) -> Self {
        Self { code, ctrl: false }
    }

    const fn ctrl(letter: char) -> Self {
        Self {
            code: KeyCode::Char(letter),
            ctrl: true,
        }
    }

    /// What the reader actually pressed.
    #[must_use]
    pub fn of(key: KeyEvent) -> Self {
        Self {
            code: key.code,
            ctrl: key.modifiers.contains(KeyModifiers::CONTROL),
        }
    }
}

impl fmt::Display for Chord {
    /// How the help overlay spells this key.
    ///
    /// Rendered from the chord rather than written beside it, so a binding cannot advertise a
    /// key it does not answer to — which is the failure a hand-maintained help screen has by
    /// construction.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ctrl {
            f.write_str("Ctrl-")?;
        }
        match self.code {
            KeyCode::Char(' ') => f.write_str("space"),
            KeyCode::Char(letter) => write!(f, "{letter}"),
            KeyCode::Up => f.write_str(""),
            KeyCode::Down => f.write_str(""),
            KeyCode::Left => f.write_str(""),
            KeyCode::Right => f.write_str(""),
            KeyCode::Enter => f.write_str("Enter"),
            KeyCode::Esc => f.write_str("Esc"),
            KeyCode::Home => f.write_str("Home"),
            KeyCode::End => f.write_str("End"),
            KeyCode::PageUp => f.write_str("PgUp"),
            KeyCode::PageDown => f.write_str("PgDn"),
            KeyCode::Backspace => f.write_str("Backspace"),
            KeyCode::Delete => f.write_str("Delete"),
            other => write!(f, "{other:?}"),
        }
    }
}

/// One row of the keymap: the keys that do a thing, and what the thing is.
#[derive(Clone, Debug)]
pub struct Binding {
    /// Which layer of the screen this binding belongs to.
    pub surface: Surface,
    /// Every key that produces this action, in the order the help lists them.
    pub chords: Vec<Chord>,
    /// The sentence the help overlay prints. Lower case and imperative, so the generated page
    /// reads as a list rather than as prose.
    pub what: &'static str,
    /// What the key asks for.
    pub action: Action,
}

impl Binding {
    /// The keys, spelled as the overlay spells them.
    #[must_use]
    pub fn keys(&self) -> String {
        self.chords
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" ")
    }
}

fn bind(surface: Surface, chords: &[Chord], what: &'static str, action: Action) -> Binding {
    Binding {
        surface,
        chords: chords.to_vec(),
        what,
        action,
    }
}

const fn key(letter: char) -> Chord {
    Chord::plain(KeyCode::Char(letter))
}

/// Every binding pristine has, in help order.
///
/// Built at first use rather than written as a `const`, because the sort digits are *derived*
/// from [`Order::ALL`]: a fourth way to order a level arrives with its key already bound,
/// documented and dispatched.
static KEYMAP: LazyLock<Vec<Binding>> = LazyLock::new(build);

/// The whole keymap, for anything that renders or checks it.
#[must_use]
pub fn bindings() -> &'static [Binding] {
    &KEYMAP
}

fn build() -> Vec<Binding> {
    let mut map = globals();
    map.extend(tree_keys());
    map.extend(overlay_keys());
    map
}

/// The keys no surface may ever take.
fn globals() -> Vec<Binding> {
    use Surface::Global;
    vec![
        bind(Global, &[key('q'), Chord::ctrl('c')], "quit", Action::Quit),
        bind(Global, &[key('?')], "show or hide this help", Action::Help),
        bind(
            Global,
            &[key('/')],
            "filter by a regex over the whole path",
            Action::OpenFilter,
        ),
        // A report in the footer is one of the levels, and the only one a reader cannot see a
        // border around — so the footer says so itself, on the frames that have one to take
        // away, rather than this sentence growing a list the overlay would clip. The order is
        // in [`super::state::View::step_back`].
        bind(
            Global,
            &[Chord::plain(KeyCode::Esc)],
            "step back one level — never quits",
            Action::Back,
        ),
    ]
}

/// The keys that act on a directory. Every one of them belongs to the pane that has a cursor.
fn tree_keys() -> Vec<Binding> {
    let mut map = tree_motion();
    map.extend(tree_verbs());
    // One key per kind, derived rather than listed, so a fourth kind in #623's vocabulary
    // arrives already filterable, already documented and already dispatched. The `match` is
    // what makes that true rather than hopeful: adding a kind stops this compiling.
    for kind in Kind::ALL {
        map.push(bind(
            Surface::Tree,
            &[key(kind_key(kind))],
            match kind {
                Kind::Unrecoverable => "show or hide what nothing brings back",
                Kind::Dependencies => "show or hide installed dependencies",
                Kind::Build => "show or hide compiled output",
                Kind::Cache => "show or hide caches",
                Kind::Noise => "show or hide logs and system cruft",
            },
            Action::ToggleKind(kind),
        ));
    }
    // One digit per order, derived rather than listed, so the key, the help row and the
    // dispatch for a fourth ordering all arrive together.
    for (nth, order) in Order::ALL.iter().enumerate() {
        map.push(bind(
            Surface::Tree,
            &[key(digit_for(nth))],
            // Each sentence says the key turns its own order upside down when pressed again,
            // because it does — the digits and a click on the heading are one door, and a
            // reader who does not know that would press `S` and reverse whatever `s` last
            // left in force instead.
            match order {
                Order::Size => "sort by size, biggest subtree first — again to reverse",
                Order::Path => "sort by path — again to reverse",
                Order::Age => "sort by age, stalest first — again to reverse",
            },
            Action::SortBy(*order),
        ));
    }
    map
}

/// Moving the cursor, and moving the tree's own shape around it.
fn tree_motion() -> Vec<Binding> {
    use Surface::Tree;
    vec![
        bind(
            Tree,
            &[Chord::plain(KeyCode::Up), key('k')],
            "move up",
            Action::Cursor(Motion::Up),
        ),
        bind(
            Tree,
            &[Chord::plain(KeyCode::Down), key('j')],
            "move down",
            Action::Cursor(Motion::Down),
        ),
        bind(
            Tree,
            &[Chord::plain(KeyCode::PageUp), Chord::ctrl('u')],
            "up a page",
            Action::Cursor(Motion::PageUp),
        ),
        bind(
            Tree,
            &[Chord::plain(KeyCode::PageDown), Chord::ctrl('d')],
            "down a page",
            Action::Cursor(Motion::PageDown),
        ),
        bind(
            Tree,
            &[Chord::plain(KeyCode::Home), key('g')],
            "to the top",
            Action::Cursor(Motion::Top),
        ),
        bind(
            Tree,
            &[Chord::plain(KeyCode::End), key('G')],
            "to the bottom",
            Action::Cursor(Motion::Bottom),
        ),
        bind(
            Tree,
            &[
                Chord::plain(KeyCode::Right),
                key('l'),
                Chord::plain(KeyCode::Enter),
            ],
            "open a row, or step into an open one",
            Action::Expand,
        ),
        bind(
            Tree,
            &[Chord::plain(KeyCode::Left), key('h')],
            "close a row, or step out of a closed one",
            Action::Collapse,
        ),
        bind(
            Tree,
            &[key('*')],
            "open or close the whole subtree",
            Action::ToggleSubtree,
        ),
        bind(
            Tree,
            &[key('z')],
            "close every open row, back to the roots",
            Action::CollapseAll,
        ),
    ]
}

/// What a reader does to what they have found.
fn tree_verbs() -> Vec<Binding> {
    use Surface::Tree;
    vec![
        bind(
            Tree,
            &[key(' ')],
            "mark this row's whole subtree, or unmark it",
            Action::Mark,
        ),
        bind(
            Tree,
            &[key('a')],
            "mark everything, or clear the marks",
            Action::MarkAll,
        ),
        // The only key here that writes, and the only sentence that has to say it asks.
        bind(
            Tree,
            &[key('x')],
            "delete what is marked — asks first",
            Action::Commit,
        ),
        bind(
            Tree,
            &[key('m')],
            "show or hide the map beside the tree",
            Action::ToggleMap,
        ),
        bind(
            Tree,
            &[key('f')],
            "the next view: default, dependencies, all-ignored, all",
            Action::CyclePreset(Turn::Next),
        ),
        bind(
            Tree,
            &[key('F')],
            "the view before it",
            Action::CyclePreset(Turn::Prev),
        ),
        bind(
            Tree,
            &[key('t')],
            "which tiers are shown, on its own: named, both, gitignored",
            Action::CycleTiers,
        ),
        bind(
            Tree,
            &[key('i')],
            "show or hide gitignored files, on their own",
            Action::ToggleFiles,
        ),
        bind(Tree, &[key('s')], "the next sort key", Action::CycleSort),
        bind(
            Tree,
            &[key('S')],
            "the same sort, upside down",
            Action::ReverseSort,
        ),
    ]
}

/// The three modal surfaces: the filter prompt, the help page, and a confirmation.
fn overlay_keys() -> Vec<Binding> {
    let mut map = prompt_keys();
    map.extend(help_keys());
    map.extend(confirm_keys());
    map
}

/// A text field's keys.
fn prompt_keys() -> Vec<Binding> {
    use Surface::Prompt;
    vec![
        // ---- The filter prompt ---------------------------------------
        //
        // Every key here is one a *text field* needs, which is why this surface is the one
        // place a global may be shadowed: while the prompt is up there is no chain past it,
        // so `Ctrl-c` and `Esc` are re-bound here rather than reached through the globals.
        // Printable characters are not in this list — see [`Action::Type`].
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Enter)],
            "apply the filter",
            Action::Submit,
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Backspace)],
            "rub out the character before the caret",
            Action::Erase,
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Delete)],
            "rub out the character after it",
            Action::EraseAhead,
        ),
        bind(
            Prompt,
            &[Chord::ctrl('u')],
            "throw the line away",
            Action::Wipe,
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Left)],
            "caret left",
            Action::Caret(Motion::Up),
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Right)],
            "caret right",
            Action::Caret(Motion::Down),
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Home)],
            "caret to the start",
            Action::Caret(Motion::Top),
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::End)],
            "caret to the end",
            Action::Caret(Motion::Bottom),
        ),
        bind(
            Prompt,
            &[Chord::plain(KeyCode::Esc)],
            "close the prompt, leaving the filter as it was",
            Action::Back,
        ),
        bind(
            Prompt,
            &[Chord::ctrl('c')],
            "quit — reserved everywhere, this surface included",
            Action::Quit,
        ),
    ]
}

/// Scrolling a document, and nothing else.
fn help_keys() -> Vec<Binding> {
    use Surface::Help;
    vec![
        // ---- The help overlay ----------------------------------------
        //
        // Scrolling only. `Esc` and `?` close it through their global bindings, which is what
        // stops this surface from being a second place those two keys are defined.
        bind(
            Help,
            &[Chord::plain(KeyCode::Up), key('k')],
            "scroll up",
            Action::Scroll(Motion::Up),
        ),
        bind(
            Help,
            &[Chord::plain(KeyCode::Down), key('j')],
            "scroll down",
            Action::Scroll(Motion::Down),
        ),
        bind(
            Help,
            &[Chord::plain(KeyCode::PageUp)],
            "scroll up a page",
            Action::Scroll(Motion::PageUp),
        ),
        bind(
            Help,
            &[Chord::plain(KeyCode::PageDown)],
            "scroll down a page",
            Action::Scroll(Motion::PageDown),
        ),
        bind(
            Help,
            &[Chord::plain(KeyCode::Home), key('g')],
            "to the top",
            Action::Scroll(Motion::Top),
        ),
        bind(
            Help,
            &[Chord::plain(KeyCode::End), key('G')],
            "to the bottom",
            Action::Scroll(Motion::Bottom),
        ),
    ]
}

/// Two answers, chosen rather than named.
fn confirm_keys() -> Vec<Binding> {
    use Surface::Confirm;
    vec![
        // ---- A confirmation ------------------------------------------
        //
        // Two answers, chosen rather than named: `←` and `→` move the highlight and `Enter`
        // takes the highlighted one. `Esc` cancels through its global binding. `y` and `n`
        // are deliberately unbound — a key that acts while being undocumented is the failure
        // this table exists to make impossible, and the box shows the two answers.
        bind(
            Confirm,
            &[Chord::plain(KeyCode::Left)],
            "highlight cancel, the left-hand answer",
            Action::Highlight(Turn::Prev),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::Right)],
            "highlight delete",
            Action::Highlight(Turn::Next),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::Enter)],
            "answer with the highlighted one",
            Action::Answer,
        ),
        // ---- and the batch it is listing -----------------------------
        //
        // `↑`/`↓` rather than `←`/`→`, which are the answers: the two are a list and a pair of
        // buttons, and a modal that made one key mean both would be worst in the one place a
        // reader is being asked to be careful.
        bind(
            Confirm,
            &[Chord::plain(KeyCode::Up), key('k')],
            "up the batch it is listing",
            Action::Listing(Motion::Up),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::Down), key('j')],
            "down the batch",
            Action::Listing(Motion::Down),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::PageUp)],
            "up a page of it",
            Action::Listing(Motion::PageUp),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::PageDown)],
            "down a page",
            Action::Listing(Motion::PageDown),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::Home), key('g')],
            "to the first entry",
            Action::Listing(Motion::Top),
        ),
        bind(
            Confirm,
            &[Chord::plain(KeyCode::End), key('G')],
            "to the last",
            Action::Listing(Motion::Bottom),
        ),
        bind(
            Confirm,
            &[key(' ')],
            "take the highlighted directory out of the batch",
            Action::Spare,
        ),
    ]
}

/// Which letter toggles this kind.
///
/// The initial of the word the help page prints for it, which is the only mnemonic worth having
/// — and a `match` rather than a table, so a fourth kind cannot arrive without one.
const fn kind_key(kind: Kind) -> char {
    match kind {
        Kind::Unrecoverable => 'u',
        Kind::Dependencies => 'd',
        Kind::Build => 'b',
        Kind::Cache => 'c',
        // Not the initial: `n` rather than the `l` of "logs", because `l` is the tree's own
        // right-hand motion and a key cannot be two things.
        Kind::Noise => 'n',
    }
}

/// The digit key for the `nth` member of a positional group, counting from 1.
///
/// Falls back to a key nobody presses rather than wrapping round to `1`, which would silently
/// give a tenth ordering the first one's key.
fn digit_for(nth: usize) -> char {
    u32::try_from(nth)
        .ok()
        .and_then(|nth| char::from_digit(nth + 1, 10))
        .unwrap_or('\0')
}

/// Which overlay is up, if any.
///
/// Named rather than a `bool`, because they differ in the one way routing cares about: help is
/// a document laid over the screen and the globals still reach past it, while the prompt is a
/// **text field** where every printable key belongs to the field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Overlay {
    /// The generated key reference.
    Help,
    /// The filter's text field.
    Prompt,
    /// A confirmation dialog. Modal the way the other two are — by leaving the tree out of the
    /// chain — rather than by a rule of its own: the globals still reach past it, which keeps
    /// `q` and `Ctrl-c` the way out everywhere, and a reader who reached the question by
    /// accident must not have to guess that it took quitting away.
    Confirm,
}

/// The surfaces a key is offered to, in order.
///
/// An overlay is modal by omission: while one is up the tree is simply not in the chain, so no
/// tree key can reach the tree from behind it. The prompt is the one surface that comes
/// *before* the globals, because a text field owns every key it needs — including `Esc`, and
/// including the printable letters that would otherwise be tree commands.
#[must_use]
pub fn chain(overlay: Option<Overlay>) -> Vec<Surface> {
    match overlay {
        Some(Overlay::Prompt) => vec![Surface::Prompt],
        Some(Overlay::Help) => vec![Surface::Help, Surface::Global],
        Some(Overlay::Confirm) => vec![Surface::Confirm, Surface::Global],
        None => vec![Surface::Tree, Surface::Global],
    }
}

/// What one terminal event means, here and now.
#[must_use]
pub fn action_for(event: &Event, overlay: Option<Overlay>) -> Action {
    let Event::Key(key) = event else {
        return Action::Ignore;
    };
    // Terminals that speak the kitty protocol report releases as well as presses. Without
    // this every key would fire twice.
    if key.kind == KeyEventKind::Release {
        return Action::Ignore;
    }

    let chord = Chord::of(*key);
    if let Some(action) = chain(overlay)
        .iter()
        .find_map(|&surface| lookup(surface, chord))
    {
        return action;
    }

    // The prompt's catch-all, and the reason it is here rather than in the table: it stands
    // for every character a terminal can report. A modifier rules it out — `Ctrl-x` in a text
    // field is a command nobody bound, not an `x` — which is what keeps the explicit prompt
    // chords above reachable.
    match (overlay, chord) {
        (
            Some(Overlay::Prompt),
            Chord {
                code: KeyCode::Char(character),
                ctrl: false,
            },
        ) => Action::Type(character),
        _ => Action::Ignore,
    }
}

/// What this chord does on this surface, if anything.
fn lookup(surface: Surface, chord: Chord) -> Option<Action> {
    bindings()
        .iter()
        .find(|binding| binding.surface == surface && binding.chords.contains(&chord))
        .map(|binding| binding.action)
}

// ---- the pointer ----------------------------------------------------------------------

/// What the loop has judged one mouse event to be.
///
/// Judgements about *previous* events, which the one in hand cannot see — whether a press has
/// already moved, whether one landed on this spot a moment ago — so they are made by
/// [`super::Pointer`] and handed here. That keeps [`pointer()`] a pure function of one gesture
/// and one spot, which is what makes the whole table assertable without a terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gesture {
    /// A press, or the pointer merely passing over. It **aims and no more**.
    ///
    /// The rule the deferred click forced: at the moment the button goes down there is no way
    /// to tell a click from a drag, so a press that acted would re-sort the tree under a hand
    /// that was about to select from it. See [`finish`].
    Aim,
    /// A press and a release, with no movement between them — the click, at last.
    Click,
    /// Two clicks on one **row**, close enough together to be one gesture.
    Double,
    /// One turn of the wheel.
    ///
    /// The direction belongs to the *action* rather than to the row of the table: the wheel
    /// does the same thing over a spot whichever way it turns, so both turns are one row and
    /// [`Gesture::same`] is what keys them together.
    Wheel(Motion),
}

impl Gesture {
    /// Whether this is the gesture a table row describes.
    ///
    /// By kind rather than by value, which matters for exactly one variant: the two wheel
    /// turns are one row of the table, and the row has to be written with *some* direction
    /// in it.
    fn same(self, row: Self) -> bool {
        std::mem::discriminant(&self) == std::mem::discriminant(&row)
    }

    /// Which way the wheel turned, if it was the wheel.
    fn motion(self) -> Option<Motion> {
        match self {
            Self::Wheel(motion) => Some(motion),
            _ => None,
        }
    }
}

impl fmt::Display for Gesture {
    /// How the help overlay spells this gesture.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Aim => "point at",
            Self::Click => "click",
            Self::Double => "double-click",
            Self::Wheel(_) => "wheel over",
        })
    }
}

/// What a gesture landed on, as the table names it — a [`Spot`] with the identity taken out.
///
/// The identity is what the *action* needs and what the table must not carry: a row of
/// [`POINTER`] says "a click on a name selects", and which directory is a fact about the
/// press rather than about the rule.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Target {
    /// A column heading.
    Heading,
    /// A row's mark box.
    Box,
    /// A row's expand indicator.
    Indicator,
    /// A row's name, and the space around it.
    Name,
    /// A row, whichever part of it — what a gesture that is not a click aims at.
    Row,
    /// The tree pane, past its last row.
    Pane,
    /// The help overlay.
    Help,
    /// One of a confirmation's two answers.
    Answer,
    /// A confirmation, off both of its answers.
    Question,
    /// The filter prompt.
    Prompt,
    /// Outside whichever overlay is up.
    Away,
    /// The footer, while it is saying what just happened.
    Notice,
    /// Chrome, or a frame with nothing on it.
    Elsewhere,
}

impl Target {
    /// Every target there is, for the assertions over the table.
    pub const ALL: [Self; 13] = [
        Self::Heading,
        Self::Box,
        Self::Indicator,
        Self::Name,
        Self::Row,
        Self::Pane,
        Self::Help,
        Self::Answer,
        Self::Question,
        Self::Prompt,
        Self::Away,
        Self::Notice,
        Self::Elsewhere,
    ];

    /// What this gesture, landing here, is aimed at.
    ///
    /// The zones are a **click**'s business and nothing else's. A double click and a wheel
    /// turn are both claims about the row rather than about the cell of it under the hand —
    /// "double-click a row" is what the gesture means everywhere, and a wheel that scrolled
    /// differently over the mark box would be unusable.
    fn of(gesture: Gesture, spot: Spot) -> Self {
        match spot {
            Spot::Heading(_) => Self::Heading,
            Spot::Row { zone, .. } if matches!(gesture, Gesture::Click) => match zone {
                Zone::Mark => Self::Box,
                Zone::Open => Self::Indicator,
                Zone::Name => Self::Name,
            },
            Spot::Row { .. } => Self::Row,
            Spot::Tree => Self::Pane,
            Spot::Help => Self::Help,
            Spot::Answer(_) => Self::Answer,
            Spot::Confirm => Self::Question,
            Spot::Prompt => Self::Prompt,
            Spot::Outside => Self::Away,
            Spot::Notice => Self::Notice,
            Spot::Nowhere => Self::Elsewhere,
        }
    }
}

/// One row of the pointer map: a gesture, where it lands, and what it does there.
#[derive(Clone, Debug)]
pub struct Pointing {
    /// Which gesture.
    pub gesture: Gesture,
    /// Every spot it means this on. Several, exactly as a [`Binding`] has several chords: the
    /// wheel scrolls the tree over the heading, over a row and over the empty pane below.
    pub targets: &'static [Target],
    /// How the help overlay names where it lands, as the object of [`Gesture`]'s verb.
    pub place: &'static str,
    /// The sentence the help overlay prints, in the same lower-case imperative the keymap's
    /// sentences use.
    pub what: &'static str,
    /// What it produces. A function of the spot, because the action carries the identity the
    /// table deliberately does not.
    deed: fn(Gesture, Spot) -> Action,
}

impl Pointing {
    /// The gesture, spelled as the overlay spells it.
    #[must_use]
    pub fn how(&self) -> String {
        format!("{} {}", self.gesture, self.place)
    }
}

const fn point(
    gesture: Gesture,
    targets: &'static [Target],
    place: &'static str,
    what: &'static str,
    deed: fn(Gesture, Spot) -> Action,
) -> Pointing {
    Pointing {
        gesture,
        targets,
        place,
        what,
        deed,
    }
}

/// Every pointer gesture pristine has, in help order.
///
/// # Only the left button, and the wheel
///
/// The right and middle are left to the terminal's own menus. A **drag** is deliberately
/// absent from this table and that is not an omission: a press that moved is not a click, and
/// there is nothing else for it to be here — pristine has no text selection of its own, so a
/// drag's only job is to make sure the press it belongs to never becomes one. See
/// [`super::Pointer`].
static POINTER: LazyLock<Vec<Pointing>> = LazyLock::new(|| {
    vec![
        point(
            Gesture::Click,
            &[Target::Heading],
            "a column heading",
            "order the levels by it — again to turn it upside down",
            sort_by,
        ),
        point(
            Gesture::Click,
            &[Target::Box],
            "a row's box",
            "mark this row's whole subtree, or unmark it",
            mark_row,
        ),
        point(
            Gesture::Click,
            &[Target::Indicator],
            "a row's ▸",
            "open the row, or close it",
            open_row,
        ),
        point(
            Gesture::Click,
            &[Target::Name],
            "a row's name",
            "put the cursor on it",
            select,
        ),
        point(
            Gesture::Double,
            &[Target::Row],
            "a row",
            "price this subtree — what --breakdown-under does, on one directory",
            price,
        ),
        point(
            Gesture::Aim,
            &[Target::Answer],
            "a confirmation's answer",
            "highlight it, so the button under the pointer is the one a click takes",
            aim,
        ),
        point(
            Gesture::Click,
            &[Target::Answer],
            "a confirmation's answer",
            "answer with it — the press has to have landed on it too",
            answer,
        ),
        point(
            Gesture::Click,
            &[Target::Away],
            "outside an overlay",
            "close it, exactly as Esc does",
            dismiss,
        ),
        // The same rung `Esc` takes first, reached by hand: a reader who is already pointing
        // should not have to go back to the keyboard to be rid of a line they have finished
        // reading. Why it is not simply `Back` is in [`Action::Dismiss`].
        point(
            Gesture::Click,
            &[Target::Notice],
            "what the footer is saying",
            "dismiss what it says",
            take_away,
        ),
        point(
            Gesture::Wheel(Motion::Down),
            &[Target::Heading, Target::Row, Target::Pane],
            "the tree",
            "scroll the rows",
            scroll_rows,
        ),
        point(
            Gesture::Wheel(Motion::Down),
            &[Target::Help],
            "the help",
            "scroll the page",
            scroll_page,
        ),
        // A confirmation used to be eight static lines, and a wheel over it was rightly
        // nothing: it is not a way past something that swallowed the keyboard. It now lists
        // the whole batch, which is a document with a cursor in it, and a list nothing can
        // scroll while everything beside it scrolls is a list a reader will believe is short.
        point(
            Gesture::Wheel(Motion::Down),
            &[Target::Question, Target::Answer],
            "a confirmation",
            "move down the batch it is listing",
            walk_listing,
        ),
    ]
});

/// The whole pointer map, for anything that renders or checks it.
#[must_use]
pub fn pointing() -> &'static [Pointing] {
    &POINTER
}

/// What one mouse gesture means, given what it landed on.
///
/// There is no chain here, and that is the point. A key is offered to a list of surfaces
/// because a keyboard has no coordinates; a press has them, so the same question is answered
/// by [`super::render::hit`] — an overlay covers what it is over, so a press inside one cannot
/// also be a press on the tree, and one outside is the dismissal.
#[must_use]
pub fn pointer(gesture: Gesture, spot: Spot) -> Action {
    let target = Target::of(gesture, spot);
    pointing()
        .iter()
        .find(|row| row.gesture.same(gesture) && row.targets.contains(&target))
        .map_or(Action::Ignore, |row| (row.deed)(gesture, spot))
}

/// Letting go of a press that never moved — the click.
///
/// It acts on what the **press** landed on rather than on what the release did, which is the
/// only rule that can be right: the press is the aimed half of the gesture, resolved against
/// the frame the reader was looking at when they aimed.
///
/// A confirmation is the exception, and it is the one surface where the worst case is
/// irreversible: there both halves have to land in the same button. That single equality is
/// the whole guard, and it is stronger than it looks — [`Spot::Answer`] exists only on a frame
/// that drew a question, so a press made *before* the box appeared can never equal one, and a
/// box arriving under a held button cannot be answered by the hand that was already down.
#[must_use]
pub fn finish(pressed: Spot, double: bool, released: Spot) -> Action {
    if matches!(pressed, Spot::Answer(_)) && pressed != released {
        return Action::Ignore;
    }
    pointer(
        if double {
            Gesture::Double
        } else {
            Gesture::Click
        },
        pressed,
    )
}

/// A click on a row, with the identity the table left out put back.
fn on_row(spot: Spot, deed: fn(crate::tree::NodeId) -> Action) -> Action {
    match spot {
        Spot::Row { id, .. } => deed(id),
        _ => Action::Ignore,
    }
}

fn select(_: Gesture, spot: Spot) -> Action {
    on_row(spot, Action::Select)
}

fn open_row(_: Gesture, spot: Spot) -> Action {
    on_row(spot, Action::OpenRow)
}

fn mark_row(_: Gesture, spot: Spot) -> Action {
    on_row(spot, Action::MarkRow)
}

fn price(_: Gesture, spot: Spot) -> Action {
    on_row(spot, Action::Price)
}

fn sort_by(_: Gesture, spot: Spot) -> Action {
    match spot {
        Spot::Heading(order) => Action::SortBy(order),
        _ => Action::Ignore,
    }
}

/// Aiming at an answer moves the *keyboard's* highlight, which is what keeps the pointer and
/// the arrow keys driving one selection rather than two.
fn aim(_: Gesture, spot: Spot) -> Action {
    match spot {
        Spot::Answer(answer) => Action::Highlight(answer.turn()),
        _ => Action::Ignore,
    }
}

/// Taking the answer the press aimed at, which the press has already highlighted.
fn answer(_: Gesture, spot: Spot) -> Action {
    match spot {
        Spot::Answer(_) => Action::Answer,
        _ => Action::Ignore,
    }
}

fn dismiss(_: Gesture, _: Spot) -> Action {
    Action::Back
}

fn take_away(_: Gesture, _: Spot) -> Action {
    Action::Dismiss
}

fn scroll_rows(gesture: Gesture, _: Spot) -> Action {
    gesture.motion().map_or(Action::Ignore, Action::ScrollRows)
}

fn scroll_page(gesture: Gesture, _: Spot) -> Action {
    gesture.motion().map_or(Action::Ignore, Action::Scroll)
}

fn walk_listing(gesture: Gesture, _: Spot) -> Action {
    gesture.motion().map_or(Action::Ignore, Action::Listing)
}

/// The help page, as headed groups of `(keys, sentence)`.
///
/// Generated from the tables rather than written, which is what keeps it honest: a binding
/// added without a sentence does not compile, and a sentence with no binding cannot exist.
/// The pointer's rows are generated the same way and for the same reason — a gesture that
/// acts while being undocumented is exactly the failure these tables exist to make
/// impossible.
#[must_use]
pub fn help() -> Vec<(&'static str, Vec<(String, &'static str)>)> {
    let surfaces = [
        Surface::Global,
        Surface::Tree,
        Surface::Prompt,
        Surface::Confirm,
        Surface::Help,
    ];
    let mut page: Vec<(&'static str, Vec<(String, &'static str)>)> = surfaces
        .into_iter()
        .map(|surface| {
            let rows = bindings()
                .iter()
                .filter(|binding| binding.surface == surface)
                .map(|binding| (binding.keys(), binding.what))
                .collect();
            (surface.title(), rows)
        })
        .collect();
    page.push((
        "The pointer",
        pointing().iter().map(|row| (row.how(), row.what)).collect(),
    ));
    page
}

#[cfg(test)]
mod tests {
    use super::{
        Action, Chord, Gesture, Motion, Overlay, Spot, Surface, Target, Turn, Zone, action_for,
        bindings, finish, help, lookup, pointer, pointing,
    };
    use crate::rules::Kind;
    use crate::tree::{NodeId, Order};
    use crate::tui::state::Answer;
    use ratatui::crossterm::event::{
        Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers,
    };

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

    fn letter(letter: char) -> Event {
        press(KeyCode::Char(letter))
    }

    /// A spot of each kind, for the assertions that sweep the whole pointer map.
    ///
    /// One per [`Target`], in the same order, so a target added without a spot to reach it
    /// with does not compile.
    fn spot(target: Target) -> Spot {
        const ROW: NodeId = 7;
        match target {
            Target::Heading => Spot::Heading(Order::Size),
            Target::Box => Spot::Row {
                id: ROW,
                zone: Zone::Mark,
            },
            Target::Indicator => Spot::Row {
                id: ROW,
                zone: Zone::Open,
            },
            // A row aimed at by something other than a click resolves to `Target::Row`
            // whichever zone it names, so the name is as good a stand-in as any.
            Target::Name | Target::Row => Spot::Row {
                id: ROW,
                zone: Zone::Name,
            },
            Target::Pane => Spot::Tree,
            Target::Help => Spot::Help,
            Target::Answer => Spot::Answer(Answer::Delete),
            Target::Question => Spot::Confirm,
            Target::Prompt => Spot::Prompt,
            Target::Away => Spot::Outside,
            Target::Notice => Spot::Notice,
            Target::Elsewhere => Spot::Nowhere,
        }
    }

    #[test]
    fn the_tree_never_shadows_a_global_key() {
        // The guarantee behind the chain being a list of surfaces rather than a pile of
        // conditions: `q` means quit wherever a reader presses it, and no future binding can
        // quietly take it away on one screen.
        for binding in bindings() {
            if binding.surface == Surface::Global {
                continue;
            }
            for chord in &binding.chords {
                let shadowed =
                    binding.surface != Surface::Prompt && lookup(Surface::Global, *chord).is_some();
                assert!(
                    !shadowed,
                    "{:?} takes {chord}, which is global",
                    binding.surface
                );
            }
        }
    }

    #[test]
    fn every_binding_has_a_sentence_and_at_least_one_key() {
        for binding in bindings() {
            assert!(!binding.chords.is_empty(), "{binding:?} binds nothing");
            assert!(!binding.what.is_empty(), "{binding:?} says nothing");
            assert!(
                binding.what.starts_with(|c: char| c.is_lowercase()),
                "{:?} is not a lower-case imperative",
                binding.what
            );
        }
    }

    #[test]
    fn no_surface_binds_one_key_to_two_things() {
        for binding in bindings() {
            for chord in &binding.chords {
                let claimants = bindings()
                    .iter()
                    .filter(|other| {
                        other.surface == binding.surface && other.chords.contains(chord)
                    })
                    .count();
                assert_eq!(
                    claimants, 1,
                    "{chord} is bound twice on {:?}",
                    binding.surface
                );
            }
        }
    }

    #[test]
    fn the_help_page_lists_every_binding_and_every_gesture_there_is() {
        let listed: usize = help().iter().map(|(_, rows)| rows.len()).sum();
        assert_eq!(listed, bindings().len() + pointing().len());
    }

    #[test]
    fn a_tree_key_cannot_reach_the_tree_from_behind_an_overlay() {
        assert_eq!(action_for(&letter('x'), None), Action::Commit);
        // The dangerous key, in particular: a reader reading the help page must not be able
        // to delete their marked batch by pressing the key their eye is on.
        assert_eq!(
            action_for(&letter('x'), Some(Overlay::Help)),
            Action::Ignore
        );
        assert_eq!(
            action_for(&letter('x'), Some(Overlay::Confirm)),
            Action::Ignore
        );
    }

    #[test]
    fn a_printable_key_is_content_while_the_prompt_is_up() {
        assert_eq!(
            action_for(&letter('x'), Some(Overlay::Prompt)),
            Action::Type('x')
        );
        assert_eq!(
            action_for(&letter(' '), Some(Overlay::Prompt)),
            Action::Type(' ')
        );
        // …and a chord is not content, so the prompt's own editing keys stay reachable.
        assert_eq!(
            action_for(
                &Event::Key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)),
                Some(Overlay::Prompt)
            ),
            Action::Wipe
        );
    }

    #[test]
    fn quitting_is_reachable_from_every_surface_including_the_text_field() {
        for overlay in [
            None,
            Some(Overlay::Help),
            Some(Overlay::Confirm),
            Some(Overlay::Prompt),
        ] {
            let ctrl_c = Event::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
            assert_eq!(action_for(&ctrl_c, overlay), Action::Quit, "{overlay:?}");
        }
    }

    #[test]
    fn a_ctrl_chord_is_not_the_bare_letter() {
        // `Ctrl-d` is half a page and `d` is nothing at all; matching on the code alone
        // would make those the same key, recoverable only by checking the modifier first.
        assert_eq!(
            action_for(
                &Event::Key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)),
                None
            ),
            Action::Cursor(Motion::PageDown)
        );
        // …and the bare letter is its own binding, which is exactly why the modifier has to
        // be checked first: `d` toggles a kind and `Ctrl-d` moves half a page.
        assert_eq!(
            action_for(&letter('d'), None),
            Action::ToggleKind(Kind::Dependencies)
        );
    }

    #[test]
    fn a_key_release_is_not_a_second_press() {
        let release = Event::Key(KeyEvent::new_with_kind_and_state(
            KeyCode::Char('x'),
            KeyModifiers::NONE,
            KeyEventKind::Release,
            KeyEventState::NONE,
        ));
        assert_eq!(action_for(&release, None), Action::Ignore);
    }

    #[test]
    fn a_chord_spells_itself_the_way_the_help_page_prints_it() {
        assert_eq!(Chord::plain(KeyCode::Char(' ')).to_string(), "space");
        assert_eq!(Chord::ctrl('u').to_string(), "Ctrl-u");
        assert_eq!(Chord::plain(KeyCode::Up).to_string(), "");
    }

    // ---- the pointer ------------------------------------------------------------------

    #[test]
    fn no_row_of_the_pointer_map_is_dead() {
        // The table *is* the dispatcher, so "a gesture that acts is a gesture the help page
        // lists" holds by construction. What does not is the other direction: a row wired to
        // the wrong shape of spot — `sort_by` under a `Row` target — would document a
        // gesture that quietly does nothing. Each row is asked for its own gesture on each
        // of its own targets, which is exactly the sentence the help page prints.
        for row in pointing() {
            for &target in row.targets {
                assert_ne!(
                    pointer(row.gesture, spot(target)),
                    Action::Ignore,
                    "{:?} does nothing, and the help page says {:?}",
                    row.how(),
                    row.what
                );
            }
        }
    }

    #[test]
    fn no_spot_gives_one_gesture_two_meanings() {
        for gesture in [
            Gesture::Aim,
            Gesture::Click,
            Gesture::Double,
            Gesture::Wheel(Motion::Down),
        ] {
            for target in Target::ALL {
                let claimants = pointing()
                    .iter()
                    .filter(|row| row.gesture.same(gesture) && row.targets.contains(&target))
                    .count();
                assert!(claimants <= 1, "{gesture} {target:?} is bound twice");
            }
        }
    }

    #[test]
    fn a_row_is_named_by_its_directory_and_never_by_where_it_is_on_the_screen() {
        // The rule the whole model turns on. The action a press produces carries the
        // `NodeId`, so the row it acts on is the one that was pressed even after a price
        // lands and re-sorts the level under the hand.
        let spot = Spot::Row {
            id: 42,
            zone: Zone::Name,
        };
        assert_eq!(pointer(Gesture::Click, spot), Action::Select(42));
        assert_eq!(pointer(Gesture::Double, spot), Action::Price(42));
    }

    #[test]
    fn the_zones_of_a_row_are_a_clicks_business_and_nothing_elses() {
        // Each part of a row does its own thing under a click…
        for (zone, action) in [
            (Zone::Mark, Action::MarkRow(3)),
            (Zone::Open, Action::OpenRow(3)),
            (Zone::Name, Action::Select(3)),
        ] {
            assert_eq!(
                pointer(Gesture::Click, Spot::Row { id: 3, zone }),
                action,
                "{zone:?}"
            );
            // …and every part of it is the same row to a double click and to the wheel. A
            // wheel that scrolled differently over the mark box would be unusable, and
            // "double-click a row" is what the gesture means everywhere.
            assert_eq!(
                pointer(Gesture::Double, Spot::Row { id: 3, zone }),
                Action::Price(3),
                "{zone:?}"
            );
            assert_eq!(
                pointer(Gesture::Wheel(Motion::Down), Spot::Row { id: 3, zone }),
                Action::ScrollRows(Motion::Down),
                "{zone:?}"
            );
        }
    }

    #[test]
    fn a_press_aims_and_does_no_more_than_aim() {
        // The rule the deferred click exists for: at the moment the button goes down there
        // is no telling a click from a drag, so a press that acted would re-sort the tree
        // under the hand that was about to select from it.
        for target in Target::ALL {
            let aimed = pointer(Gesture::Aim, spot(target));
            let expected = match target {
                // The one exception, and it is not really one: highlighting the button under
                // the pointer moves a selection, which a hover would have moved too.
                Target::Answer => Action::Highlight(Turn::Next),
                _ => Action::Ignore,
            };
            assert_eq!(aimed, expected, "{target:?}");
        }
    }

    #[test]
    fn the_click_acts_on_what_the_press_was_aimed_at() {
        // The release's own spot is not the target: a hand that lets go a cell off the
        // heading it pressed has still clicked that heading, and the press is the aimed half
        // of the gesture.
        assert_eq!(
            finish(Spot::Heading(Order::Age), false, Spot::Nowhere),
            Action::SortBy(Order::Age)
        );
    }

    #[test]
    fn a_confirmation_is_the_one_surface_that_needs_both_halves_in_the_same_button() {
        let delete = Spot::Answer(Answer::Delete);
        assert_eq!(finish(delete, false, delete), Action::Answer);

        // Landing near an answer, or on the other one, is a miss — and so is a press made
        // *before* the box appeared, which is the case that matters: `Spot::Answer` exists
        // only on a frame that drew a question, so such a press can never equal one, and a
        // box arriving under a held button cannot be answered by the hand already down.
        assert_eq!(finish(delete, false, Spot::Confirm), Action::Ignore);
        assert_eq!(
            finish(delete, false, Spot::Answer(Answer::Cancel)),
            Action::Ignore
        );
        assert_eq!(finish(Spot::Tree, false, delete), Action::Ignore);
    }

    #[test]
    fn a_press_inside_an_overlay_that_lands_on_nothing_does_nothing() {
        // Deliberately not a dismissal: a press on a caveat line or on the prompt's own text
        // is a miss, and closing the thing being read is the one response that loses work.
        for spot in [Spot::Help, Spot::Prompt, Spot::Confirm, Spot::Nowhere] {
            assert_eq!(pointer(Gesture::Click, spot), Action::Ignore, "{spot:?}");
        }
        // Outside it is the dismissal, which is `Esc`'s own action rather than a second one.
        assert_eq!(pointer(Gesture::Click, Spot::Outside), Action::Back);
    }

    #[test]
    fn the_wheel_means_the_nearest_thing_to_scrolling_each_surface_has() {
        // Over the tree it moves the viewport; over the help overlay it moves a document.
        // Those are genuinely different verbs, and over a question it is neither — a wheel
        // is not a way past something that swallowed the keyboard.
        assert_eq!(
            pointer(Gesture::Wheel(Motion::Up), Spot::Tree),
            Action::ScrollRows(Motion::Up)
        );
        assert_eq!(
            pointer(Gesture::Wheel(Motion::Down), Spot::Help),
            Action::Scroll(Motion::Down)
        );
        // Over a confirmation it moves down the batch the box is listing. That is not a way
        // past something that swallowed the keyboard — the answers are untouched — it is the
        // one verb a list of eight thousand directories has, and a list nothing can scroll
        // while everything beside it scrolls is a list a reader will believe is short.
        for spot in [Spot::Confirm, Spot::Answer(Answer::Delete)] {
            assert_eq!(
                pointer(Gesture::Wheel(Motion::Down), spot),
                Action::Listing(Motion::Down),
                "{spot:?}"
            );
        }
        assert_eq!(
            pointer(Gesture::Wheel(Motion::Down), Spot::Nowhere),
            Action::Ignore
        );
    }

    #[test]
    fn the_help_page_spells_a_gesture_the_way_a_reader_would_say_it() {
        let page = help();
        let (title, rows) = page.last().unwrap();
        assert_eq!(*title, "The pointer");
        let said: Vec<&str> = rows.iter().map(|(how, _)| how.as_str()).collect();
        assert!(said.contains(&"double-click a row"), "{said:?}");
        assert!(said.contains(&"wheel over the tree"), "{said:?}");
        assert!(said.contains(&"click a column heading"), "{said:?}");
    }
}