kimun-notes 0.23.2

A terminal-based notes application
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
//! The editor screen's input classifier: resolves one raw input event into an
//! **Intent** — what the event *means* under the screen's input precedence —
//! before anything mutates. `classify` is pure over an [`InputCtx`] snapshot,
//! so the precedence (leader → paste intercepts → shortcuts → overlay →
//! mouse → panels) is table-tested here instead of living as statement order
//! inside `EditorScreen::handle_input`. The screen builds the snapshot,
//! classifies, then *executes* the intent.
//!
//! A pending leader sequence owns the input first (spec §8a) — including
//! ahead of the paste intercepts, which in the pre-extraction ladder sat
//! above it (the old quirk let a leader-pending Ctrl+V paste an image and
//! leave the sequence pending). Ctrl-chords and paste payloads cancel the
//! sequence and dispatch normally; every other key feeds it.
//!
//! Two decided collaterals of that reorder, both asserted by tests below:
//! Ctrl+Enter mid-sequence now feeds the leader instead of following the
//! link (Enter is not a `Char` chord, so no exception applies — §8a wins
//! over the old follow-link-first order), and a paste arriving mid-sequence
//! under an open overlay cancels the leader where the old ladder left it
//! pending (the paste rule applies regardless of who receives the paste).

use ratatui::crossterm::event::KeyEvent;

use crate::components::drawer::DrawerView;
use crate::components::events::InputEvent;
use crate::components::overlay::OverlayKind;
use crate::components::panel::PanelKind;
use crate::components::text_editor::EditorClaim;
use crate::keys::action_shortcuts::{ActionShortcuts, TextAction};
use crate::keys::key_strike::KeyStrike;
use crate::keys::{KeyBindings, key_event_to_combo};

/// Snapshot of the screen state the classifier needs. Built per event by
/// `EditorScreen::handle_input`; keep it minimal — every field is a reason
/// the classification can change.
#[derive(Debug, Clone, PartialEq)]
pub struct InputCtx {
    /// The open overlay's kind, `None` when no overlay is open.
    pub overlay: Option<OverlayKind>,
    /// A leader key sequence is pending.
    pub leader_pending: bool,
    /// The focused panel.
    pub focused: PanelKind,
    /// The active drawer view (regardless of drawer visibility).
    pub drawer_view: DrawerView,
    /// Bare Space starts the leader (vim Normal mode, empty pending state).
    pub space_leads: bool,
    /// Which editor-internal surface holds input, if any. Without
    /// this the classifier cannot know the **find bar** is open, and ownership
    /// gets re-decided further down, once per event kind.
    pub claim: EditorClaim,
    /// This mouse press completes a double-click in the editor column — the
    /// mouse's way of following a link (see `click_run`).
    ///
    /// An *input* to classification, not an output: it picks between
    /// [`EditorIntent::Mouse`] and [`EditorIntent::FollowLink`], so no intent
    /// variant has to name the gesture that produced it. The rule itself lives
    /// in [`ClickRun`](crate::app_screen::click_run::ClickRun); the screen
    /// records the press before building this snapshot.
    pub double_click: bool,
}

impl InputCtx {
    /// The editor owns key input: it is focused and no overlay sits over it.
    /// Mirrors `EditorScreen::editor_active`.
    fn editor_active(&self) -> bool {
        self.focused == PanelKind::Editor && self.overlay.is_none()
    }

    fn find_panel_focused(&self) -> bool {
        self.focused == PanelKind::Drawer && self.drawer_view == DrawerView::Find
    }
}

/// The classifier's full verdict: pre-effects plus the intent. The executor
/// applies `flash` and `cancel_leader` first, then runs the intent.
#[derive(Debug, Clone, PartialEq)]
pub struct Classification {
    /// Footer chord flash (F-keys and Ctrl/Alt+letter chords, except the
    /// leader gateway, whose affordance is the pending sequence).
    pub flash: Option<String>,
    /// A pending leader sequence must be cancelled before the intent runs
    /// (an overlay opened underneath, or a Ctrl-chord dispatches normally).
    pub cancel_leader: bool,
    pub intent: EditorIntent,
}

/// What one raw input event means in the editor screen. Execution lives in
/// `EditorScreen`; anything that depends on a runtime outcome (the clipboard
/// image probe, a panel's first crack at a key) carries its fallback as data.
#[derive(Debug, Clone, PartialEq)]
pub enum EditorIntent {
    /// Swallow the event (guarded no-ops, the F-key sink).
    Consume,
    /// Bracketed paste into the editor: try an image paste first, fall
    /// back to pasting the event's text payload when the clipboard holds
    /// no image. Carries nothing — the executor reads the payload back
    /// from the event it already holds, so large pastes are never cloned.
    EditorPaste,
    /// Ctrl+V in the editor: probe the clipboard for an image. When there
    /// is none, the executor reclassifies the tail of the ladder
    /// ([`classify_tail`] with `cancel_leader = false` — the probe
    /// classification already owned any leader cancel) against fresh
    /// screen state. Lazy on purpose: the common with-image press must not
    /// pay for a discarded fallback classification.
    ImageProbe,
    /// Follow the **follow target** under the editor cursor — a link, or a
    /// label whose query is run. Reached two ways, deliberately one intent:
    /// the bound `FollowLink` shortcut, and a double-click, whose first press
    /// put the cursor where the second one asks about (see `click_run`).
    FollowLink,
    /// Feed the key to the pending leader sequence.
    LeaderKey(KeyEvent),
    /// Start a leader sequence and schedule the which-key reveal.
    LeaderStart,
    /// A screen operation with no classification-time policy beyond its
    /// guard (see CONTEXT.md **Intent** — "action" is reserved for
    /// `ActionShortcuts`, the classifier's *input*).
    Op(EditorOp),
    /// Dismiss the overlay when one of `kind` is already open, else `open`.
    ToggleOverlay {
        kind: OverlayKind,
        open: OverlayOpen,
    },
    /// Present the overlay `OverlayOpen` names (the executor builds it from
    /// its seed state). No toggle semantics — see `ToggleOverlay` for those.
    OpenOverlay(OverlayOpen),
    /// Route the event to the open overlay.
    Overlay,
    /// Route the mouse event through the `PanelSet` hit-test path.
    Mouse,
    /// Route the event to the focused panel; on `NotConsumed` apply the
    /// fallback.
    Panel { fallback: PanelFallback },
}

/// Every overlay the editor screen can open, as a construction recipe the
/// executor's one `build_overlay` match turns into the live overlay. Distinct
/// from `OverlayKind` (the *presentation* kind): two recipes share
/// `OverlayKind::NoteBrowser` (search browser vs file finder), so the kind
/// alone cannot pick the opener.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OverlayOpen {
    SearchBrowser,
    FileFinder,
    SavedSearches,
    CommandPalette,
    WorkspaceSwitcher,
    ThemePicker,
    /// The flat key-bindings help (F1).
    Help,
    /// The search query syntax reference (F1 over the Find panel).
    QueryHelp,
    /// The full leader-tree cheatsheet (leader `?`).
    Cheatsheet,
    SortQuery,
    SortSidebar,
    QuickNote,
}

/// Fallback applied when the focused panel does not consume the event.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PanelFallback {
    None,
    /// Tab / Shift-Tab cycle panel focus when the panel passes.
    FocusCycle(CycleDir),
    /// The FIND view yields focus back to the editor on an unhandled Esc.
    FocusEditor,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CycleDir {
    Left,
    Right,
}

#[derive(Debug, Clone, PartialEq)]
pub enum EditorOp {
    ToggleDrawer,
    FocusLeft,
    FocusRight,
    OpenJournal,
    ShowFileOps,
    ToggleQueryPanel,
    /// Open (or switch the drawer to) FILES and reveal the open note's
    /// directory — never hides the drawer.
    OpenFileBrowserReveal,
    SaveCurrentQuery,
    FindInBuffer,
    /// Open the find bar with the replace field revealed.
    ReplaceInBuffer,
    ApplyText(TextAction),
    /// Switch to the Ask workspace and focus its composer (F6 and leader
    /// `a a`).
    OpenAsk,
}

/// Resolve one raw input event into its [`Classification`] under the editor
/// screen's input precedence. Pure: same event + bindings + ctx, same verdict.
///
/// Runs the precedence ladder, then applies the **editor claim** filter — an
/// intent the current holder does not allow is rewritten so the event reaches
/// the holder instead. With no claim held the filter is the identity,
/// which is why the ladder's own tests are unaffected by it.
pub fn classify(event: &InputEvent, bindings: &KeyBindings, ctx: &InputCtx) -> Classification {
    let mut classification = classify_unclaimed(event, bindings, ctx);
    // An **editor claim** only holds while the editor is the active panel: the
    // bar is inside it, so a drawer click or an open overlay outranks it.
    // Without this the filter would swallow every click anywhere in the app.
    let claim = if ctx.editor_active() {
        ctx.claim
    } else {
        EditorClaim::None
    };
    let filtered = apply_claim(classification.intent.clone(), event, claim);
    if filtered != classification.intent {
        // The chord did not run, so it must not advertise itself in the footer.
        classification.flash = None;
    }
    classification.intent = filtered;
    classification
}

/// Which intents survive an **editor claim**, and what a blocked one becomes.
///
/// An allow-list, exhaustive over [`EditorIntent`]: a new variant defaults to
/// blocked, so getting it wrong shows up as a key that appears to do nothing
/// rather than one that silently edits the note. A block-list would default the
/// other way — which is how `Ctrl+B` came to embolden the note while the user
/// was typing a find pattern.
///
/// A blocked intent becomes [`EditorIntent::Panel`] — the existing default,
/// which routes to the focused panel, which is the editor, which routes to its
/// holder. The claim decides *ownership*; the holder decides behaviour.
fn apply_claim(intent: EditorIntent, event: &InputEvent, claim: EditorClaim) -> EditorIntent {
    if claim == EditorClaim::None {
        return intent;
    }
    let deliver = EditorIntent::Panel {
        fallback: PanelFallback::None,
    };
    let find_bar = claim == EditorClaim::FindBar;
    match intent {
        // Always allowed. A pending leader sequence outranks a claim (spec
        // §8a); the panel default IS the delivery path; an overlay cannot
        // coexist with a claim (a claim implies the editor is focused and
        // unobscured); the palette stays reachable as a global escape.
        EditorIntent::LeaderKey(_)
        | EditorIntent::Panel { .. }
        | EditorIntent::Overlay
        | EditorIntent::ToggleOverlay { .. }
        | EditorIntent::OpenOverlay(_)
        | EditorIntent::Consume => intent,

        // Buffer-targeting ops lose to any holder — typing a find pattern must
        // not embolden the note. Navigation ops are unaffected.
        EditorIntent::Op(EditorOp::ApplyText(_)) => deliver,
        EditorIntent::Op(_) => intent,

        // The find bar is a text field: a paste belongs in it and an image
        // probe is meaningless there. The popup wants both to behave normally.
        EditorIntent::EditorPaste | EditorIntent::ImageProbe => {
            if find_bar {
                deliver
            } else {
                intent
            }
        }

        // Ctrl+Enter must not follow a link out of the bar, so a key-origin
        // follow is delivered to it. A mouse-origin one carries the same intent
        // but is a *press* wearing a different name, so it degrades to whatever
        // a plain press does under this claim — swallowed by the bar, delivered
        // normally under the popup, which wants the click that dismisses it.
        // Abandoning the follow is the point: a holder is mid-edit, and the
        // link under the pointer is text it is still being typed into.
        EditorIntent::FollowLink => match event {
            InputEvent::Mouse(_) => claimed_mouse(event, find_bar),
            _ if find_bar => deliver,
            _ => intent,
        },

        // Bare Space is a character in a find pattern. The bound leader
        // gateway is not — it opens "in every context, including mid-typing",
        // and blocking it here would also make a pending sequence unreachable.
        EditorIntent::LeaderStart => match event {
            InputEvent::Key(k)
                if find_bar
                    && k.code == ratatui::crossterm::event::KeyCode::Char(' ')
                    && k.modifiers.is_empty() =>
            {
                deliver
            }
            _ => intent,
        },

        EditorIntent::Mouse => claimed_mouse(event, find_bar),
    }
}

/// What a claim does to a press. The one policy, so a follow that arrived as a
/// click cannot drift away from the click it is.
///
/// Scrolling moves the viewport, not the cursor, so reading elsewhere
/// mid-search stays available. Clicks and drags would move the cursor off the
/// current match and overwrite the selection marking it — the find bar has no
/// way to represent either. Every other holder takes the press normally.
fn claimed_mouse(event: &InputEvent, find_bar: bool) -> EditorIntent {
    use ratatui::crossterm::event::MouseEventKind;

    match event {
        InputEvent::Mouse(m)
            if find_bar
                && !matches!(
                    m.kind,
                    MouseEventKind::ScrollUp
                        | MouseEventKind::ScrollDown
                        | MouseEventKind::ScrollLeft
                        | MouseEventKind::ScrollRight
                ) =>
        {
            EditorIntent::Consume
        }
        _ => EditorIntent::Mouse,
    }
}

fn classify_unclaimed(
    event: &InputEvent,
    bindings: &KeyBindings,
    ctx: &InputCtx,
) -> Classification {
    use ratatui::crossterm::event::{KeyCode, KeyModifiers};

    // A pending leader sequence owns the input ahead of everything else
    // (spec §8a), including the paste intercepts below. Exceptions: an
    // overlay that opened underneath wins, a Ctrl-chord cancels the sequence
    // then dispatches normally, and a paste payload — not a key the sequence
    // can consume — gets the same cancel-then-dispatch treatment.
    let mut cancel_leader = false;
    if ctx.leader_pending {
        match event {
            InputEvent::Key(key) => {
                if ctx.overlay.is_some() {
                    cancel_leader = true;
                } else if matches!(key.code, KeyCode::Char(_))
                    && key.modifiers.contains(KeyModifiers::CONTROL)
                {
                    cancel_leader = true;
                    // fall through to normal dispatch below
                } else {
                    return Classification {
                        flash: None,
                        cancel_leader: false,
                        intent: EditorIntent::LeaderKey(*key),
                    };
                }
            }
            InputEvent::Paste(_) => cancel_leader = true,
            // Mouse input never fed the sequence; it routes below unchanged.
            InputEvent::Mouse(_) => {}
        }
    }

    // Bracketed paste (terminal-level). The executor tries an image paste
    // first and falls back to the text payload.
    if ctx.editor_active() && matches!(event, InputEvent::Paste(_)) {
        return Classification {
            flash: None,
            cancel_leader,
            intent: EditorIntent::EditorPaste,
        };
    }

    // Ctrl+V: probe the clipboard for an image ahead of the editor's own
    // text paste. No image → the executor reclassifies the tail against
    // fresh state. The leader cancel rides on this classification: the
    // sequence dies whether or not the clipboard holds an image.
    if ctx.editor_active()
        && let InputEvent::Key(key) = event
        && key.modifiers == KeyModifiers::CONTROL
        && key.code == KeyCode::Char('v')
    {
        return Classification {
            flash: None,
            cancel_leader,
            intent: EditorIntent::ImageProbe,
        };
    }

    classify_tail(event, bindings, ctx, cancel_leader)
}

/// The ladder below the leader tier and the paste intercepts: shortcuts →
/// overlay → mouse → vim Space leader → Tab cycle → FIND Esc → focused
/// panel. `cancel_leader` carries the leader tier's verdict into the
/// returned classification. `pub(crate)` for one caller besides
/// [`classify`]: the executor's no-image [`EditorIntent::ImageProbe`]
/// path, which runs the tail against post-probe state.
pub(crate) fn classify_tail(
    event: &InputEvent,
    bindings: &KeyBindings,
    ctx: &InputCtx,
    cancel_leader: bool,
) -> Classification {
    use ratatui::crossterm::event::{KeyCode, KeyModifiers};

    // Ctrl+Enter follows the link under the cursor on kitty-protocol
    // terminals (legacy terminals can't tell it from Enter).
    if ctx.editor_active()
        && let InputEvent::Key(key) = event
        && key.code == KeyCode::Enter
        && key.modifiers.contains(KeyModifiers::CONTROL)
    {
        return Classification {
            flash: None,
            cancel_leader,
            intent: EditorIntent::FollowLink,
        };
    }

    // Shortcut tier: resolve the bound action (if any) to an intent, and
    // compute the footer chord flash. The match *yields* instead of
    // returning so `flash` has a single owner: the one `done` constructor
    // below moves it into whichever classification wins.
    let mut flash = None;
    let mut shortcut_intent = None;
    if let InputEvent::Key(key) = event
        && let Some(combo) = key_event_to_combo(key)
    {
        let is_fkey = combo.key.is_fkey();
        let action = bindings.get_action(&combo);
        // Name the action when the chord resolves to one; fall back to the raw
        // chord when it does not. A bare "Ctrl&K" only answers "what did I
        // press"; "Search notes" answers "what did it do", and the raw chord was
        // never the interesting half for a binding the user chose. Unbound
        // chords keep the echo — there is nothing else to say about them.
        //
        // Handlers that report their own outcome (a yank's "path copied", a
        // paste's "pasted") overwrite this: the tier's flash is applied first,
        // then the intent runs.
        //
        // The leader gateway is exempt either way — its affordance is the
        // pending sequence and the which-key overlay.
        if action != Some(ActionShortcuts::Leader) && (is_fkey || combo.is_letter_chord()) {
            flash = Some(match &action {
                Some(a) => a.label(),
                None => combo.to_string(),
            });
        }
        shortcut_intent = match action {
            Some(ActionShortcuts::OpenCommandPalette) => Some(EditorIntent::ToggleOverlay {
                kind: OverlayKind::CommandPalette,
                open: OverlayOpen::CommandPalette,
            }),
            Some(ActionShortcuts::Leader) => {
                // The gateway works in every context, including mid-typing —
                // but not while an overlay owns input.
                Some(if ctx.overlay.is_none() {
                    EditorIntent::LeaderStart
                } else {
                    EditorIntent::Consume
                })
            }
            Some(ActionShortcuts::ToggleSidebar) => Some(EditorIntent::Op(EditorOp::ToggleDrawer)),
            Some(ActionShortcuts::FocusSidebar) => {
                // No-op while an overlay owns input, but still consume the key.
                Some(if ctx.overlay.is_none() {
                    EditorIntent::Op(EditorOp::FocusLeft)
                } else {
                    EditorIntent::Consume
                })
            }
            Some(ActionShortcuts::FocusEditor) => Some(if ctx.overlay.is_none() {
                EditorIntent::Op(EditorOp::FocusRight)
            } else {
                EditorIntent::Consume
            }),
            Some(ActionShortcuts::NewJournal) => Some(EditorIntent::Op(EditorOp::OpenJournal)),
            Some(ActionShortcuts::SearchNotes) => Some(EditorIntent::ToggleOverlay {
                kind: OverlayKind::NoteBrowser,
                open: OverlayOpen::SearchBrowser,
            }),
            Some(ActionShortcuts::OpenNote) => Some(EditorIntent::ToggleOverlay {
                kind: OverlayKind::NoteBrowser,
                open: OverlayOpen::FileFinder,
            }),
            Some(ActionShortcuts::FileOperations) if ctx.editor_active() => {
                Some(EditorIntent::Op(EditorOp::ShowFileOps))
            }
            Some(ActionShortcuts::FollowLink) if ctx.editor_active() => {
                Some(EditorIntent::FollowLink)
            }
            Some(ActionShortcuts::ToggleQueryPanel) => {
                Some(EditorIntent::Op(EditorOp::ToggleQueryPanel))
            }
            Some(ActionShortcuts::OpenFileBrowser) => {
                // Open (or switch to) the FILES view — never hides the drawer;
                // ToggleSidebar is the on/off switch. Always reveal: with FILES
                // already open this is the "where is my note" gesture.
                Some(EditorIntent::Op(EditorOp::OpenFileBrowserReveal))
            }
            Some(ActionShortcuts::OpenSavedSearches) => Some(EditorIntent::ToggleOverlay {
                kind: OverlayKind::SavedSearches,
                open: OverlayOpen::SavedSearches,
            }),
            Some(ActionShortcuts::OpenAsk) => Some(EditorIntent::Op(EditorOp::OpenAsk)),
            // Deliberately produces NO intent, so the chord is never consumed
            // here and always reaches whatever has focus. A list surface claims
            // it inside `SearchList` and yanks the selected row's target; the
            // editor claims it as redo. The binding exists for the other two
            // things a hand-rolled pre-check could never give it — rebinding and
            // a help-dialog entry.
            Some(ActionShortcuts::YankRow) => None,
            Some(ActionShortcuts::OpenSortDialog) => {
                // Sort applies only when a list is focused (the drawer's
                // Find / Files views). When the editor is focused, do NOT
                // consume — fall through (`None`) so the key reaches it
                // (e.g. Ctrl+R is redo in the nvim editor).
                if ctx.focused == PanelKind::Drawer && ctx.overlay.is_none() {
                    Some(match ctx.drawer_view {
                        DrawerView::Find => EditorIntent::OpenOverlay(OverlayOpen::SortQuery),
                        DrawerView::Files => EditorIntent::OpenOverlay(OverlayOpen::SortSidebar),
                        _ => EditorIntent::Consume,
                    })
                } else {
                    None
                }
            }
            Some(ActionShortcuts::SaveCurrentQuery) => {
                // Whether there is anything to save is executor state (the
                // live query text); the key is consumed either way.
                Some(EditorIntent::Op(EditorOp::SaveCurrentQuery))
            }
            Some(ActionShortcuts::SwitchWorkspace) => {
                Some(EditorIntent::OpenOverlay(OverlayOpen::WorkspaceSwitcher))
            }
            Some(ActionShortcuts::QuickNote) => Some(if ctx.overlay.is_none() {
                EditorIntent::OpenOverlay(OverlayOpen::QuickNote)
            } else {
                EditorIntent::Consume
            }),
            Some(ActionShortcuts::FindInBuffer) if ctx.editor_active() => {
                Some(EditorIntent::Op(EditorOp::FindInBuffer))
            }
            Some(ActionShortcuts::ReplaceInBuffer) if ctx.editor_active() => {
                Some(EditorIntent::Op(EditorOp::ReplaceInBuffer))
            }
            Some(ActionShortcuts::Text(
                action @ (TextAction::Bold | TextAction::Italic | TextAction::Strikethrough),
            )) if ctx.editor_active() => Some(EditorIntent::Op(EditorOp::ApplyText(action))),
            _ => {
                if is_fkey {
                    // F1 opens the help modal. Over the Find panel it surfaces
                    // query syntax instead of the flat key-bindings help. All
                    // F-keys are consumed and never forwarded to the editor.
                    if combo.key == KeyStrike::F1 && combo.modifiers.is_empty() {
                        Some(EditorIntent::OpenOverlay(if ctx.find_panel_focused() {
                            OverlayOpen::QueryHelp
                        } else {
                            OverlayOpen::Help
                        }))
                    } else {
                        Some(EditorIntent::Consume)
                    }
                } else {
                    None
                }
            }
        };
    }

    // Single constructor: moves `flash` into the winning classification.
    // Every call site diverges, so the FnOnce closure is used at most once.
    let done = move |intent| Classification {
        flash,
        cancel_leader,
        intent,
    };

    if let Some(intent) = shortcut_intent {
        return done(intent);
    }

    // An open overlay intercepts all remaining input ahead of the panels.
    if ctx.overlay.is_some() {
        return done(EditorIntent::Overlay);
    }

    if matches!(event, InputEvent::Mouse(_)) {
        // A double-click in the editor follows the link under it, exactly as
        // Ctrl+N does — same intent, same executor, one follow path. The
        // classifier cannot hit-test panels (that is `PanelSet`'s job, and why
        // `Mouse` exists at all), so it leans on focus: the first press of the
        // pair already focused whatever column it landed in.
        if ctx.double_click && ctx.editor_active() {
            return done(EditorIntent::FollowLink);
        }
        return done(EditorIntent::Mouse);
    }

    // Vim Normal mode: bare Space is a second leader gateway, but only with
    // an empty pending state so it never shadows Space as a motion/operator
    // argument. Insert/Visual and the other backends keep Space typing a
    // space (`space_leads` is false for those states).
    if ctx.editor_active()
        && (!ctx.leader_pending || cancel_leader)
        && let InputEvent::Key(key) = event
        && key.code == KeyCode::Char(' ')
        && key.modifiers.is_empty()
        && ctx.space_leads
    {
        return done(EditorIntent::LeaderStart);
    }

    // Tab / Shift-Tab cycle panel focus (spec §2). The focused panel gets
    // first crack — the Query panel's autocomplete accepts on Tab — and the
    // editor keeps Tab for indentation.
    if ctx.focused != PanelKind::Editor
        && let InputEvent::Key(key) = event
        && matches!(key.code, KeyCode::Tab | KeyCode::BackTab)
    {
        return done(EditorIntent::Panel {
            fallback: PanelFallback::FocusCycle(if key.code == KeyCode::Tab {
                CycleDir::Right
            } else {
                CycleDir::Left
            }),
        });
    }

    // The drawer's FIND view gets first crack (its autocomplete popup may
    // consume Esc); on an unhandled Esc it yields focus back to the editor.
    if ctx.find_panel_focused()
        && let InputEvent::Key(key) = event
        && key.code == KeyCode::Esc
    {
        return done(EditorIntent::Panel {
            fallback: PanelFallback::FocusEditor,
        });
    }

    done(EditorIntent::Panel {
        fallback: PanelFallback::None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};

    fn bindings() -> KeyBindings {
        let mut kb = KeyBindings::empty();
        kb.batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyP, ActionShortcuts::OpenCommandPalette)
            .add(KeyStrike::KeyK, ActionShortcuts::SearchNotes)
            .add(KeyStrike::KeyG, ActionShortcuts::Leader)
            .add(KeyStrike::KeyT, ActionShortcuts::ToggleSidebar)
            .add(KeyStrike::KeyR, ActionShortcuts::OpenSortDialog)
            .add(KeyStrike::KeyH, ActionShortcuts::FocusSidebar)
            .add(KeyStrike::KeyB, ActionShortcuts::Text(TextAction::Bold))
            .add(KeyStrike::KeyN, ActionShortcuts::FollowLink)
            .add(KeyStrike::KeyW, ActionShortcuts::QuickNote);
        kb.batch_add()
            .add(KeyStrike::F2, ActionShortcuts::FileOperations);
        kb
    }

    /// Editor focused, nothing pending — the common ctx.
    fn ctx() -> InputCtx {
        InputCtx {
            overlay: None,
            leader_pending: false,
            focused: PanelKind::Editor,
            drawer_view: DrawerView::Files,
            space_leads: false,
            claim: EditorClaim::None,
            double_click: false,
        }
    }

    /// The common ctx with the find bar holding the **editor claim**.
    fn ctx_find_bar() -> InputCtx {
        InputCtx {
            claim: EditorClaim::FindBar,
            ..ctx()
        }
    }

    /// The common ctx with the press completing a double-click. Whether it
    /// *is* one is `ClickRun`'s question, answered before this snapshot.
    fn ctx_double() -> InputCtx {
        InputCtx {
            double_click: true,
            ..ctx()
        }
    }

    /// A left press. Coordinates are irrelevant to the classifier — it never
    /// hit-tests; the screen decided the cell was the editor's before it fed
    /// the click run.
    fn press() -> InputEvent {
        use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
        InputEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 1,
            row: 1,
            modifiers: KeyModifiers::NONE,
        })
    }

    fn key(code: KeyCode, mods: KeyModifiers) -> InputEvent {
        InputEvent::Key(KeyEvent::new(code, mods))
    }

    fn ctrl(c: char) -> InputEvent {
        key(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    fn plain(c: char) -> InputEvent {
        key(KeyCode::Char(c), KeyModifiers::NONE)
    }

    fn classify_it(event: &InputEvent, ctx: &InputCtx) -> Classification {
        classify(event, &bindings(), ctx)
    }

    // ---- editor claim -----------------------------------------

    /// The bug that motivated the claim: with the editor focused — which is
    /// exactly the state when the find bar is open — a formatting chord
    /// classified as a buffer edit and the bar never saw the key. Typing a
    /// find pattern and pressing Ctrl+B emboldened the note.
    #[test]
    fn a_claim_blocks_a_buffer_edit() {
        let ev = key(KeyCode::Char('b'), KeyModifiers::CONTROL);
        assert_eq!(
            classify_it(&ev, &ctx()).intent,
            EditorIntent::Op(EditorOp::ApplyText(TextAction::Bold)),
            "without a claim the chord still bolds"
        );
        assert_eq!(
            classify_it(&ev, &ctx_find_bar()).intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            },
            "under a claim it is delivered to the holder instead"
        );
    }

    /// Navigation is not a buffer edit — the drawer, panel focus and the
    /// palette stay reachable while searching.
    #[test]
    fn a_claim_leaves_navigation_alone() {
        for ev in [
            key(KeyCode::Char('t'), KeyModifiers::CONTROL),
            key(KeyCode::Char('p'), KeyModifiers::CONTROL),
        ] {
            assert_eq!(
                classify_it(&ev, &ctx_find_bar()).intent,
                classify_it(&ev, &ctx()).intent,
                "a claim must not swallow navigation"
            );
        }
    }

    /// A paste aimed at the replace field used to land in the buffer behind
    /// the bar; the fix lived inside `paste_text`. It is a classification now.
    #[test]
    fn a_find_bar_claim_blocks_the_paste_tiers() {
        for ev in [
            InputEvent::Paste("hi".into()),
            key(KeyCode::Char('v'), KeyModifiers::CONTROL),
            key(KeyCode::Enter, KeyModifiers::CONTROL),
        ] {
            assert_eq!(
                classify_it(&ev, &ctx_find_bar()).intent,
                EditorIntent::Panel {
                    fallback: PanelFallback::None
                },
                "paste, image probe and follow-link all belong to the bar"
            );
        }
    }

    /// Space is a character in a find pattern, not the leader gateway. This
    /// used to be enforced by making `space_leads()` lie while the bar was
    /// open — the smuggled fact the claim replaces.
    #[test]
    fn a_find_bar_claim_blocks_the_space_leader() {
        let ev = key(KeyCode::Char(' '), KeyModifiers::NONE);
        let vim_ctx = InputCtx {
            space_leads: true,
            ..ctx()
        };
        assert_eq!(classify_it(&ev, &vim_ctx).intent, EditorIntent::LeaderStart);
        let vim_bar = InputCtx {
            space_leads: true,
            ..ctx_find_bar()
        };
        assert_eq!(
            classify_it(&ev, &vim_bar).intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }

    /// A click would move the cursor off the current match and overwrite the
    /// selection marking it — reachable as a panic before this. Scrolling is
    /// allowed: it moves the viewport, not the cursor.
    #[test]
    fn a_find_bar_claim_blocks_clicks_but_not_scrolling() {
        use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
        let at = |kind| {
            InputEvent::Mouse(MouseEvent {
                kind,
                column: 1,
                row: 1,
                modifiers: KeyModifiers::NONE,
            })
        };
        assert_eq!(
            classify_it(
                &at(MouseEventKind::Down(MouseButton::Left)),
                &ctx_find_bar()
            )
            .intent,
            EditorIntent::Consume,
            "a click reaches nothing while the bar holds the claim"
        );
        assert_eq!(
            classify_it(&at(MouseEventKind::ScrollUp), &ctx_find_bar()).intent,
            EditorIntent::Mouse,
            "scrolling still works"
        );
    }

    // ── Following a link with the mouse (see `click_run`) ───────────────────

    /// A press classifies as an ordinary mouse event whatever it lands on.
    /// Following is the *second* press of a pair, never the first — this is
    /// the regression that a stray click can no longer navigate.
    #[test]
    fn a_single_press_only_reaches_the_editor() {
        assert_eq!(classify_it(&press(), &ctx()).intent, EditorIntent::Mouse);
    }

    /// The whole point: a double-click means the same thing as Ctrl+N, so it
    /// produces the same intent and runs through the same executor.
    #[test]
    fn a_double_click_follows_the_link_under_it() {
        assert_eq!(
            classify_it(&press(), &ctx_double()).intent,
            EditorIntent::FollowLink,
            "the same intent Ctrl+N produces"
        );
        assert_eq!(
            classify_it(&key(KeyCode::Char('n'), KeyModifiers::CONTROL), &ctx()).intent,
            EditorIntent::FollowLink,
            "and Ctrl+N still produces it"
        );
    }

    /// The classifier cannot hit-test panels, so it leans on focus — which the
    /// *first* press of the pair set. Double-clicking a row in the drawer must
    /// not follow whatever the editor's cursor happens to sit on.
    #[test]
    fn a_double_click_outside_the_editor_is_an_ordinary_click() {
        let drawer = InputCtx {
            focused: PanelKind::Drawer,
            ..ctx_double()
        };
        assert_eq!(classify_it(&press(), &drawer).intent, EditorIntent::Mouse);
    }

    /// An overlay owns the input ahead of the panels, so a double-click under
    /// one is the overlay's, not a follow against the buffer behind it.
    #[test]
    fn an_overlay_outranks_a_double_click() {
        let covered = InputCtx {
            overlay: Some(OverlayKind::NoteBrowser),
            ..ctx_double()
        };
        assert_eq!(
            classify_it(&press(), &covered).intent,
            EditorIntent::Overlay
        );
    }

    /// Same intent, different origin, different answer. Ctrl+Enter belongs to
    /// the bar (it is a text field); the press underneath a double-click does
    /// not, and the bar has no way to represent the cursor move it implies.
    #[test]
    fn a_find_bar_claim_swallows_a_double_click_but_takes_ctrl_enter() {
        let bar_double = InputCtx {
            double_click: true,
            ..ctx_find_bar()
        };
        assert_eq!(
            classify_it(&press(), &bar_double).intent,
            EditorIntent::Consume,
            "a follow that arrived as a click is still a click"
        );
        assert_eq!(
            classify_it(&key(KeyCode::Enter, KeyModifiers::CONTROL), &ctx_find_bar()).intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            },
            "but a follow that arrived as a key is delivered to the bar"
        );
    }

    /// The claim filter has three holders, not two. A mouse-origin follow
    /// degrades to whatever a plain press does under the holder — which for the
    /// popup means being delivered, so it can dismiss itself and place the
    /// cursor. Consuming it instead left the popup open over a note that had
    /// navigated away.
    #[test]
    fn an_autocomplete_claim_turns_a_double_click_back_into_a_press() {
        let popup = InputCtx {
            claim: EditorClaim::Autocomplete,
            double_click: true,
            ..ctx()
        };
        assert_eq!(classify_it(&press(), &popup).intent, EditorIntent::Mouse);
        assert_eq!(
            classify_it(&key(KeyCode::Char('n'), KeyModifiers::CONTROL), &popup).intent,
            EditorIntent::FollowLink,
            "the popup does not own the keyboard follow"
        );
    }

    /// The asymmetry that makes the claim an enum rather than a bool: the
    /// popup wants the events the bar blocks. A click should dismiss it and
    /// place the cursor.
    #[test]
    fn an_autocomplete_claim_blocks_only_buffer_edits() {
        let popup = InputCtx {
            claim: EditorClaim::Autocomplete,
            ..ctx()
        };
        assert_eq!(
            classify_it(&InputEvent::Paste("hi".into()), &popup).intent,
            EditorIntent::EditorPaste,
            "the popup does not own pastes"
        );
        assert_eq!(
            classify_it(&key(KeyCode::Char('b'), KeyModifiers::CONTROL), &popup).intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            },
            "but a buffer edit still loses to any holder"
        );
    }

    /// A pending leader sequence outranks a claim (spec §8a).
    #[test]
    fn the_leader_outranks_a_claim() {
        let ev = key(KeyCode::Char('x'), KeyModifiers::NONE);
        let pending = InputCtx {
            leader_pending: true,
            ..ctx_find_bar()
        };
        assert!(matches!(
            classify_it(&ev, &pending).intent,
            EditorIntent::LeaderKey(_)
        ));
    }

    // ---- paste tiers -----------------------------------------------------

    #[test]
    fn bracketed_paste_in_editor_is_editor_paste() {
        let c = classify_it(&InputEvent::Paste("hi".into()), &ctx());
        assert_eq!(c.intent, EditorIntent::EditorPaste);
    }

    #[test]
    fn bracketed_paste_with_overlay_routes_to_overlay() {
        let mut cx = ctx();
        cx.overlay = Some(OverlayKind::NoteBrowser);
        let c = classify_it(&InputEvent::Paste("hi".into()), &cx);
        assert_eq!(c.intent, EditorIntent::Overlay);
    }

    #[test]
    fn bracketed_paste_drawer_focused_goes_to_panel() {
        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        let c = classify_it(&InputEvent::Paste("hi".into()), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }

    #[test]
    fn ctrl_v_in_editor_is_a_bare_image_probe() {
        // The probe carries no precomputed fallback: the executor
        // reclassifies the tail only when the clipboard holds no image.
        let c = classify_it(&ctrl('v'), &ctx());
        assert_eq!(c.intent, EditorIntent::ImageProbe);
        assert_eq!(c.flash, None, "flash belongs to the no-image tail only");
    }

    #[test]
    fn ctrl_v_no_image_tail_reaches_panel_with_a_flash() {
        // The executor's no-image path: classify_tail against post-probe
        // state (leader already cancelled → cancel_leader = false). Ctrl+V
        // is unbound, so it reaches the focused panel (the editor's own
        // paste), flashing the chord on the way through the shortcut tier.
        let c = classify_tail(&ctrl('v'), &bindings(), &ctx(), false);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
        assert!(c.flash.is_some());
        assert!(!c.cancel_leader, "the outer probe already owned the cancel");
    }

    #[test]
    fn leader_pending_ctrl_v_cancels_leader_then_probes_image() {
        // §8a ctrl-chord exception: the chord cancels the pending sequence
        // and dispatches normally — for Ctrl+V that is the image probe, so
        // the cancel rides on the probe classification (the leader must die
        // whether or not the clipboard holds an image), and exactly once:
        // the no-image reclassification must not re-cancel.
        let mut cx = ctx();
        cx.leader_pending = true;
        let c = classify_it(&ctrl('v'), &cx);
        assert!(c.cancel_leader);
        assert_eq!(c.intent, EditorIntent::ImageProbe);
    }

    #[test]
    fn leader_pending_bracketed_paste_cancels_leader_then_pastes() {
        // A paste payload is not a key the sequence can consume: the
        // ctrl-chord rule applied to a non-key event — cancel, then paste.
        let mut cx = ctx();
        cx.leader_pending = true;
        let c = classify_it(&InputEvent::Paste("hi".into()), &cx);
        assert!(c.cancel_leader);
        assert_eq!(c.intent, EditorIntent::EditorPaste);
    }

    #[test]
    fn leader_pending_ctrl_enter_feeds_leader() {
        // Enter is not a Char ctrl-chord, so no exception applies: the
        // pending sequence owns the key (§8a) ahead of follow-link.
        let mut cx = ctx();
        cx.leader_pending = true;
        let c = classify_it(&key(KeyCode::Enter, KeyModifiers::CONTROL), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::LeaderKey(KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL))
        );
        assert!(!c.cancel_leader);
    }

    #[test]
    fn ctrl_enter_in_editor_follows_link() {
        let c = classify_it(&key(KeyCode::Enter, KeyModifiers::CONTROL), &ctx());
        assert_eq!(c.intent, EditorIntent::FollowLink);
    }

    // ---- leader tier -----------------------------------------------------

    #[test]
    fn leader_pending_plain_key_feeds_leader() {
        let mut cx = ctx();
        cx.leader_pending = true;
        let c = classify_it(&plain('f'), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::LeaderKey(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::NONE))
        );
        assert!(!c.cancel_leader);
    }

    #[test]
    fn leader_pending_with_overlay_cancels_and_routes_to_overlay() {
        let mut cx = ctx();
        cx.leader_pending = true;
        cx.overlay = Some(OverlayKind::Dialog);
        let c = classify_it(&plain('f'), &cx);
        assert!(c.cancel_leader);
        assert_eq!(c.intent, EditorIntent::Overlay);
    }

    #[test]
    fn leader_pending_ctrl_chord_cancels_then_dispatches() {
        let mut cx = ctx();
        cx.leader_pending = true;
        let c = classify_it(&ctrl('p'), &cx);
        assert!(c.cancel_leader);
        assert_eq!(
            c.intent,
            EditorIntent::ToggleOverlay {
                kind: OverlayKind::CommandPalette,
                open: OverlayOpen::CommandPalette
            }
        );
    }

    // ---- shortcut tier ---------------------------------------------------

    #[test]
    fn command_palette_chord_toggles_regardless_of_open_state() {
        // Same intent open or closed — the executor dismisses when the kind
        // is already active.
        let c = classify_it(&ctrl('p'), &ctx());
        assert_eq!(
            c.intent,
            EditorIntent::ToggleOverlay {
                kind: OverlayKind::CommandPalette,
                open: OverlayOpen::CommandPalette
            }
        );
        assert!(c.flash.is_some());

        let mut cx = ctx();
        cx.overlay = Some(OverlayKind::CommandPalette);
        let c = classify_it(&ctrl('p'), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::ToggleOverlay {
                kind: OverlayKind::CommandPalette,
                open: OverlayOpen::CommandPalette
            }
        );
    }

    #[test]
    fn leader_gateway_starts_sequence_without_flash() {
        let c = classify_it(&ctrl('g'), &ctx());
        assert_eq!(c.intent, EditorIntent::LeaderStart);
        assert_eq!(c.flash, None);
    }

    #[test]
    fn leader_gateway_with_overlay_is_consumed_noop() {
        let mut cx = ctx();
        cx.overlay = Some(OverlayKind::NoteBrowser);
        let c = classify_it(&ctrl('g'), &cx);
        assert_eq!(c.intent, EditorIntent::Consume);
    }

    #[test]
    fn focus_sidebar_with_overlay_is_consumed_noop() {
        let mut cx = ctx();
        cx.overlay = Some(OverlayKind::NoteBrowser);
        let c = classify_it(&ctrl('h'), &cx);
        assert_eq!(c.intent, EditorIntent::Consume);
    }

    #[test]
    fn toggle_drawer_chord_is_action() {
        let c = classify_it(&ctrl('t'), &ctx());
        assert_eq!(c.intent, EditorIntent::Op(EditorOp::ToggleDrawer));
    }

    #[test]
    fn quick_note_opens_dialog_only_without_overlay() {
        let c = classify_it(&ctrl('w'), &ctx());
        assert_eq!(c.intent, EditorIntent::OpenOverlay(OverlayOpen::QuickNote));

        let mut cx = ctx();
        cx.overlay = Some(OverlayKind::Dialog);
        let c = classify_it(&ctrl('w'), &cx);
        assert_eq!(c.intent, EditorIntent::Consume);
    }

    #[test]
    fn text_style_chord_needs_active_editor() {
        let c = classify_it(&ctrl('b'), &ctx());
        assert_eq!(
            c.intent,
            EditorIntent::Op(EditorOp::ApplyText(TextAction::Bold))
        );

        // Drawer focused: the guard fails and the chord falls through the
        // match to the focused panel.
        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        let c = classify_it(&ctrl('b'), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }

    #[test]
    fn sort_dialog_targets_the_focused_drawer_view() {
        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        cx.drawer_view = DrawerView::Find;
        let c = classify_it(&ctrl('r'), &cx);
        assert_eq!(c.intent, EditorIntent::OpenOverlay(OverlayOpen::SortQuery));

        cx.drawer_view = DrawerView::Files;
        let c = classify_it(&ctrl('r'), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::OpenOverlay(OverlayOpen::SortSidebar)
        );

        // A drawer view without a sortable list consumes the chord.
        cx.drawer_view = DrawerView::Tags;
        let c = classify_it(&ctrl('r'), &cx);
        assert_eq!(c.intent, EditorIntent::Consume);
    }

    #[test]
    fn sort_dialog_chord_falls_through_when_editor_focused() {
        // Ctrl+R must reach the editor (redo in the nvim backend).
        let c = classify_it(&ctrl('r'), &ctx());
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }

    #[test]
    fn f1_opens_help_or_query_help_by_focus() {
        let c = classify_it(&key(KeyCode::F(1), KeyModifiers::NONE), &ctx());
        assert_eq!(c.intent, EditorIntent::OpenOverlay(OverlayOpen::Help));

        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        cx.drawer_view = DrawerView::Find;
        let c = classify_it(&key(KeyCode::F(1), KeyModifiers::NONE), &cx);
        assert_eq!(c.intent, EditorIntent::OpenOverlay(OverlayOpen::QueryHelp));
    }

    #[test]
    fn unbound_fkeys_are_sunk_with_a_flash() {
        let c = classify_it(&key(KeyCode::F(9), KeyModifiers::NONE), &ctx());
        assert_eq!(c.intent, EditorIntent::Consume);
        assert!(c.flash.is_some());
    }

    /// A bound chord flashes what it *does*, not which keys were pressed — the
    /// user chose the binding, so the chord is the half they already know.
    #[test]
    fn a_bound_chord_flashes_the_action_label() {
        let c = classify_it(&ctrl('k'), &ctx());
        assert_eq!(
            c.flash.as_deref(),
            Some(ActionShortcuts::SearchNotes.label().as_str())
        );
    }

    /// An unbound chord has no action to name, so the echo stays — it is the
    /// only answer available to "what did I just press?".
    #[test]
    fn an_unbound_chord_still_flashes_the_raw_chord() {
        // Ctrl+Y is deliberately absent from this test's bindings.
        let c = classify_it(&ctrl('y'), &ctx());
        let combo =
            key_event_to_combo(&KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)).unwrap();
        assert_eq!(c.flash.as_deref(), Some(combo.to_string().as_str()));
    }

    #[test]
    fn high_fkeys_are_sunk_like_the_rest() {
        // "All F-keys are consumed and never forwarded to the editor" —
        // including F13+ (KeyStrike defines up to F25); the shared
        // KeyStrike::is_fkey predicate keeps this in step with the
        // binding validator.
        let c = classify_it(&key(KeyCode::F(13), KeyModifiers::NONE), &ctx());
        assert_eq!(c.intent, EditorIntent::Consume);
    }

    #[test]
    fn bound_fkey_dispatches_when_guard_holds_and_sinks_when_not() {
        // F2 = FileOperations, guarded on the active editor.
        let c = classify_it(&key(KeyCode::F(2), KeyModifiers::NONE), &ctx());
        assert_eq!(c.intent, EditorIntent::Op(EditorOp::ShowFileOps));

        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        let c = classify_it(&key(KeyCode::F(2), KeyModifiers::NONE), &cx);
        assert_eq!(c.intent, EditorIntent::Consume);
    }

    // ---- lower tiers -----------------------------------------------------

    #[test]
    fn overlay_intercepts_unbound_keys() {
        let mut cx = ctx();
        cx.overlay = Some(OverlayKind::SavedSearches);
        let c = classify_it(&plain('x'), &cx);
        assert_eq!(c.intent, EditorIntent::Overlay);
    }

    #[test]
    fn mouse_events_take_the_hit_test_path() {
        let ev = InputEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            column: 3,
            row: 4,
            modifiers: KeyModifiers::NONE,
        });
        let c = classify_it(&ev, &ctx());
        assert_eq!(c.intent, EditorIntent::Mouse);
    }

    #[test]
    fn vim_space_starts_leader_only_when_it_leads() {
        let mut cx = ctx();
        cx.space_leads = true;
        let c = classify_it(&plain(' '), &cx);
        assert_eq!(c.intent, EditorIntent::LeaderStart);

        cx.space_leads = false;
        let c = classify_it(&plain(' '), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }

    #[test]
    fn tab_cycles_focus_when_a_non_editor_panel_passes() {
        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        let c = classify_it(&key(KeyCode::Tab, KeyModifiers::NONE), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::FocusCycle(CycleDir::Right)
            }
        );

        let c = classify_it(&key(KeyCode::BackTab, KeyModifiers::SHIFT), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::FocusCycle(CycleDir::Left)
            }
        );
    }

    #[test]
    fn editor_keeps_tab_for_indentation() {
        let c = classify_it(&key(KeyCode::Tab, KeyModifiers::NONE), &ctx());
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }

    #[test]
    fn find_view_yields_focus_to_editor_on_unhandled_esc() {
        let mut cx = ctx();
        cx.focused = PanelKind::Drawer;
        cx.drawer_view = DrawerView::Find;
        let c = classify_it(&key(KeyCode::Esc, KeyModifiers::NONE), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::FocusEditor
            }
        );

        // Any other unhandled key propagates as-is.
        let c = classify_it(&plain('x'), &cx);
        assert_eq!(
            c.intent,
            EditorIntent::Panel {
                fallback: PanelFallback::None
            }
        );
    }
}