tui-pages 0.7.5

Core for TUI apps with multiple pages
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
//! Integration helpers for using the `canvas` crate with `tui-pages`.
//!
//! Enable the `canvas` feature and make your application action type implement
//! `From<CanvasAction>`. Then `.canvas_defaults()` on the builder installs the
//! standard `FormEditor` keybindings and typed-character action routing, while
//! [`PageSpec::canvas_editor`] keeps the active mode stack in sync with the
//! editor.

use crate::focus::{FocusIntent, FocusTarget};
use crate::input::{InputPipeline, InputRegistry, KeyChord, KeyMap, PipelineResponse};
use crate::runtime::{
    modes, ActionContext, ActionOutcome, KeyHook, KeyHookKind, KeyHookOutcome, ModeId, PageSpec,
    TuiEffect, TuiPagesBuilder, TuiPagesStatus,
};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::{layout::Rect, Frame};

// The `canvas` feature enables full canvas support — every surface below is
// available unconditionally. We do not split canvas into sub-features.

// --- Base surface ---
pub use ::canvas::{ActionResult, AppMode, CanvasAction, DataProvider, EditorState, FormEditor};
pub use ::canvas::integration::focus_handoff::{
    execute_action_for_host, execute_action_for_host_with_options, BoundaryExit, HostActionOutcome,
};

// --- Keymap-driven host handoff ---
pub use ::canvas::integration::focus_handoff::{
    boundary_from_key_outcome, handle_key_event_for_host, key_outcome_for_vertical_navigation,
    map_key_event_outcome_for_host, HostKeyEventOutcome,
};
pub use ::canvas::{
    default_builtin_action_bindings, default_emacs_action_bindings,
    default_helix_action_bindings, default_vim_action_bindings, preset,
    BuiltinCanvasKeybindingPreset, CanvasActionBinding, CanvasActionKeyBinding,
    CanvasKeyBindings, KeyEventOutcome,
};
pub use ::canvas::keybindings::{CanvasKeyAction, KeyStroke};

// --- Cursor style ---
pub use ::canvas::CursorManager;

// --- Suggestions ---
pub use ::canvas::{
    render_suggestions_dropdown, SuggestionItem, SuggestionQuery, SuggestionTrigger,
};

// --- Validation ---
pub use ::canvas::{
    AppliedValidation, CharacterFilter, CharacterLimits, CustomFormatter, DefaultPositionMapper,
    DisplayMask, FormattingResult, PatternFilters, PositionFilter, PositionMapper, PositionRange,
    ValidationConfig, ValidationConfigBuilder, ValidationError, ValidationResult, ValidationRule,
    ValidationSet, ValidationSettings, ValidationState, ValidationSummary,
};
pub use ::canvas::validation::limits::{CountMode, LimitCheckResult};

// --- Computed fields ---
pub use ::canvas::{ComputedContext, ComputedProvider, ComputedState};

// --- GUI: renderers, themes, display options ---
pub use ::canvas::{
    render_canvas, render_canvas_default, render_canvas_with_options, CanvasDisplayOptions,
    CanvasTheme, DefaultCanvasTheme, FormInputEventOutcome, OverflowMode,
};

// Crossterm terminal-input session helpers (raw mode, bracketed paste, mouse
// capture) — the canvas-side complement to [`crate::terminal`] for apps wiring
// up text widgets that need paste support.
pub use ::canvas::integration::crossterm_input::{
    CrosstermInputGuard, CrosstermInputOptions, CrosstermInputSession,
};

// --- Text area ---
pub use ::canvas::{
    TextArea, TextAreaDataProvider, TextAreaEditor, TextAreaProvider, TextAreaState,
};
pub use ::canvas::textarea::{
    TextAreaCommandLineState, TextAreaEventOutcome, TextAreaLineNumberMode, TextAreaSearchMatch,
    TextOverflowMode,
};

// --- Command line ---
pub use ::canvas::{
    parse_command_args, parse_command_line, CommandLine, CommandLineCommand,
    CommandLineCommandInvocation, CommandLineDispatchError, CommandLineEventOutcome,
    CommandLineMode, CommandLineParseError, CommandLineParsedCommand, CommandLinePlacement,
    CommandLineRegistry, CommandLineRegistrationError, CommandLineState, CommandLineSubmit,
};

// --- Text input ---
pub use ::canvas::{
    TextInput, TextInputDataProvider, TextInputEditor, TextInputEventOutcome, TextInputProvider,
    TextInputState,
};

#[derive(Debug, Clone)]
pub enum CanvasDispatchOutcome<O = (), M = ()> {
    Applied(::canvas::ActionResult),
    Focus(FocusIntent<O, M>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CanvasKeyDispatchOutcome<O = (), M = ()> {
    Consumed(Option<String>),
    PendingSequence,
    NotHandled,
    Focus(FocusIntent<O, M>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CanvasTextWidgetOutcome<O = (), M = ()> {
    Handled,
    Submitted,
    NotHandled,
    Focus(FocusIntent<O, M>),
}

impl<O, M> CanvasDispatchOutcome<O, M> {
    pub fn into_focus_intent(self) -> Option<FocusIntent<O, M>> {
        match self {
            CanvasDispatchOutcome::Applied(_) => None,
            CanvasDispatchOutcome::Focus(intent) => Some(intent),
        }
    }
}

impl<O, M> CanvasKeyDispatchOutcome<O, M> {
    pub fn into_focus_intent(self) -> Option<FocusIntent<O, M>> {
        match self {
            CanvasKeyDispatchOutcome::Focus(intent) => Some(intent),
            _ => None,
        }
    }
}

impl<O, M> CanvasTextWidgetOutcome<O, M> {
    pub fn into_focus_intent(self) -> Option<FocusIntent<O, M>> {
        match self {
            CanvasTextWidgetOutcome::Focus(intent) => Some(intent),
            _ => None,
        }
    }
}

pub trait CanvasFormEditorHost {
    fn mode(&self) -> AppMode;
    fn dispatch_canvas_action(&mut self, action: CanvasAction) -> CanvasDispatchOutcome;
}

impl<D> CanvasFormEditorHost for FormEditor<D>
where
    D: DataProvider,
{
    fn mode(&self) -> AppMode {
        FormEditor::mode(self)
    }

    fn dispatch_canvas_action(&mut self, action: CanvasAction) -> CanvasDispatchOutcome {
        dispatch_action(self, action)
    }
}

pub trait CanvasTextAreaHost {
    fn mode(&self) -> AppMode;
    fn commandline_enabled(&self) -> bool {
        false
    }
    fn boundary_for_key(&self, key: &KeyEvent) -> Option<BoundaryExit>;
    fn input_key(&mut self, key: KeyEvent) -> TextAreaEventOutcome;
    fn exit_edit_mode(&mut self);
    fn dispatch_canvas_action(&mut self, action: CanvasAction) -> HostActionOutcome;
}

impl<P> CanvasTextAreaHost for TextAreaState<P>
where
    P: TextAreaDataProvider,
{
    fn mode(&self) -> AppMode {
        self.editor().mode()
    }

    fn commandline_enabled(&self) -> bool {
        self.commandline().is_some()
    }

    fn boundary_for_key(&self, key: &KeyEvent) -> Option<BoundaryExit> {
        text_area_boundary_for_key(self, key)
    }

    fn input_key(&mut self, key: KeyEvent) -> TextAreaEventOutcome {
        if self.commandline_enabled() {
            match self.handle_key_event(key) {
                KeyEventOutcome::Consumed(_)
                | KeyEventOutcome::Pending
                | KeyEventOutcome::ExitTop
                | KeyEventOutcome::ExitBottom => TextAreaEventOutcome::Handled,
                KeyEventOutcome::NotMatched => TextAreaEventOutcome::Ignored,
            }
        } else {
            self.input(key)
        }
    }

    fn exit_edit_mode(&mut self) {
        let _ = self.editor_mut().exit_edit_mode();
    }

    fn dispatch_canvas_action(&mut self, action: CanvasAction) -> HostActionOutcome {
        execute_action_for_host_with_options(self.editor_mut(), action, false)
    }
}

pub trait CanvasTextInputHost {
    fn mode(&self) -> AppMode;
    fn text(&self) -> String;
    fn input_key(&mut self, key: KeyEvent) -> CanvasTextWidgetOutcome;
    fn set_suggestion_suffix(&mut self, suffix: String);
    fn clear_suggestion_suffix(&mut self);
    fn exit_edit_mode(&mut self);
    fn dispatch_canvas_action(&mut self, action: CanvasAction) -> HostActionOutcome;
}

impl<P> CanvasTextInputHost for TextInputState<P>
where
    P: TextInputDataProvider,
{
    fn mode(&self) -> AppMode {
        self.editor().mode()
    }

    fn text(&self) -> String {
        TextInputState::text(self)
    }

    fn input_key(&mut self, key: KeyEvent) -> CanvasTextWidgetOutcome {
        dispatch_text_input_key(self, key)
    }

    fn set_suggestion_suffix(&mut self, suffix: String) {
        TextInputState::set_suggestion_suffix(self, suffix);
    }

    fn clear_suggestion_suffix(&mut self) {
        TextInputState::clear_suggestion_suffix(self);
    }

    fn exit_edit_mode(&mut self) {
        let _ = self.editor_mut().exit_edit_mode();
    }

    fn dispatch_canvas_action(&mut self, action: CanvasAction) -> HostActionOutcome {
        execute_action_for_host_with_options(self.editor_mut(), action, false)
    }
}

pub trait CanvasWidgetState {
    fn canvas_form_editor(&mut self, _id: usize) -> Option<&mut dyn CanvasFormEditorHost> {
        None
    }

    fn canvas_textarea(&mut self, _focus_index: usize) -> Option<&mut dyn CanvasTextAreaHost> {
        None
    }

    fn canvas_textarea_entered(&mut self, _focus_index: usize) -> Option<&mut bool> {
        None
    }

    fn canvas_textinput(&mut self, _focus_index: usize) -> Option<&mut dyn CanvasTextInputHost> {
        None
    }

    fn canvas_textinput_entered(&mut self, _focus_index: usize) -> Option<&mut bool> {
        None
    }

    fn canvas_textinput_suggestion_suffix(
        &mut self,
        _focus_index: usize,
        _text: &str,
    ) -> Option<String> {
        None
    }
}

pub fn mode_for_app_mode(mode: AppMode) -> ModeId {
    match mode {
        AppMode::Ins => modes::INSERT,
        AppMode::Sel => modes::SELECT,
        AppMode::Command => modes::COMMAND,
        AppMode::General => modes::GENERAL,
        AppMode::Nor => modes::NORMAL,
    }
}

pub fn modes_for_app_mode(mode: AppMode) -> Vec<ModeId> {
    match mode {
        AppMode::Command => vec![modes::COMMAND],
        AppMode::General => vec![modes::GENERAL, modes::GLOBAL],
        mode => vec![mode_for_app_mode(mode), modes::COMMON, modes::GLOBAL],
    }
}

pub fn accepts_text_input(mode: AppMode) -> bool {
    matches!(mode, AppMode::Ins | AppMode::Command)
}

pub fn text_chord_to_canvas_action(chord: KeyChord) -> Option<CanvasAction> {
    let is_plain_char =
        chord.modifiers.is_empty() || chord.modifiers == KeyModifiers::SHIFT;
    match chord.code {
        KeyCode::Char(c) if is_plain_char => Some(CanvasAction::InsertChar(c)),
        _ => None,
    }
}

pub fn text_chord_to_action<A>(chord: KeyChord) -> Option<A>
where
    A: From<CanvasAction>,
{
    text_chord_to_canvas_action(chord).map(A::from)
}

pub fn focus_intent_for_boundary<O, M>(boundary: BoundaryExit) -> FocusIntent<O, M> {
    match boundary {
        BoundaryExit::Top => FocusIntent::ExitCanvasBackward,
        BoundaryExit::Bottom => FocusIntent::ExitCanvasForward,
    }
}

pub fn dispatch_action<D, O, M>(
    editor: &mut FormEditor<D>,
    action: CanvasAction,
) -> CanvasDispatchOutcome<O, M>
where
    D: DataProvider,
{
    let before_field = editor.current_field();
    let at_boundary = action_boundary(editor, &action).is_some();
    match execute_action_for_host(editor, action) {
        HostActionOutcome::Applied(result) => {
            CanvasDispatchOutcome::Applied(validation_aware_action_result(
                editor,
                before_field,
                at_boundary,
                result,
            ))
        }
        HostActionOutcome::ExitCanvas(boundary) => {
            CanvasDispatchOutcome::Focus(focus_intent_for_boundary(boundary))
        }
    }
}

pub fn render_canvas_with_suggestions<T, D>(
    frame: &mut Frame,
    frame_area: Rect,
    canvas_area: Rect,
    editor: &FormEditor<D>,
    theme: &T,
) -> Option<Rect>
where
    T: CanvasTheme,
    D: DataProvider,
{
    let opts = CanvasDisplayOptions::default();
    render_canvas_with_suggestions_with_options(frame, frame_area, canvas_area, editor, theme, opts)
}

pub fn render_canvas_with_suggestions_with_options<T, D>(
    frame: &mut Frame,
    frame_area: Rect,
    canvas_area: Rect,
    editor: &FormEditor<D>,
    theme: &T,
    opts: CanvasDisplayOptions,
) -> Option<Rect>
where
    T: CanvasTheme,
    D: DataProvider,
{
    let input_rect = render_canvas_with_options(frame, canvas_area, editor, theme, opts);
    if let Some(input_rect) = input_rect {
        render_suggestions_dropdown(frame, frame_area, input_rect, theme, editor);
    }
    input_rect
}

pub fn render_canvas_with_suggestions_default<D>(
    frame: &mut Frame,
    frame_area: Rect,
    canvas_area: Rect,
    editor: &FormEditor<D>,
) -> Option<Rect>
where
    D: DataProvider,
{
    let theme = DefaultCanvasTheme;
    render_canvas_with_suggestions(frame, frame_area, canvas_area, editor, &theme)
}

pub fn render_canvas_with_suggestions_default_options<D>(
    frame: &mut Frame,
    frame_area: Rect,
    canvas_area: Rect,
    editor: &FormEditor<D>,
    opts: CanvasDisplayOptions,
) -> Option<Rect>
where
    D: DataProvider,
{
    let theme = DefaultCanvasTheme;
    render_canvas_with_suggestions_with_options(
        frame,
        frame_area,
        canvas_area,
        editor,
        &theme,
        opts,
    )
}

pub fn update_cursor_style_for_mode(mode: AppMode) -> std::io::Result<()> {
    CursorManager::update_for_mode(mode)
}

pub fn update_cursor_style_for_editor<D>(editor: &FormEditor<D>) -> std::io::Result<()>
where
    D: DataProvider,
{
    update_cursor_style_for_mode(editor.mode())
}

pub fn dispatch_key_event<D, O, M>(
    editor: &mut FormEditor<D>,
    event: KeyEvent,
) -> CanvasKeyDispatchOutcome<O, M>
where
    D: DataProvider,
{
    let before_field = editor.current_field();
    let before_boundary = key_boundary(editor, &event);
    let outcome = handle_key_event_for_host(editor, event);
    host_key_event_outcome(validation_aware_key_event_outcome(
        editor,
        before_field,
        before_boundary,
        outcome,
    ))
}

pub fn host_key_event_outcome<O, M>(
    outcome: HostKeyEventOutcome,
) -> CanvasKeyDispatchOutcome<O, M> {
    match outcome {
        HostKeyEventOutcome::Consumed(message) => CanvasKeyDispatchOutcome::Consumed(message),
        HostKeyEventOutcome::PendingSequence => CanvasKeyDispatchOutcome::PendingSequence,
        HostKeyEventOutcome::NotHandled => CanvasKeyDispatchOutcome::NotHandled,
        HostKeyEventOutcome::ExitCanvas(boundary) => {
            CanvasKeyDispatchOutcome::Focus(focus_intent_for_boundary(boundary))
        }
    }
}

fn validation_aware_action_result<D>(
    editor: &FormEditor<D>,
    before_field: usize,
    at_boundary: bool,
    result: ActionResult,
) -> ActionResult
where
    D: DataProvider,
{
    if editor.current_field() == before_field && !at_boundary {
        if let Some(reason) = editor.last_switch_block() {
            return ActionResult::Error(reason.to_string());
        }
    }
    result
}

fn validation_aware_key_event_outcome<D>(
    editor: &FormEditor<D>,
    before_field: usize,
    before_boundary: Option<BoundaryExit>,
    outcome: HostKeyEventOutcome,
) -> HostKeyEventOutcome
where
    D: DataProvider,
{
    if matches!(outcome, HostKeyEventOutcome::ExitCanvas(_))
        && editor.current_field() == before_field
        && before_boundary.is_none()
    {
        if let Some(reason) = editor.last_switch_block() {
            return HostKeyEventOutcome::Consumed(Some(reason.to_string()));
        }
    }
    outcome
}

fn action_boundary<D>(editor: &FormEditor<D>, action: &CanvasAction) -> Option<BoundaryExit>
where
    D: DataProvider,
{
    match action {
        CanvasAction::MoveUp | CanvasAction::PrevField if editor.current_field() == 0 => {
            Some(BoundaryExit::Top)
        }
        CanvasAction::MoveDown | CanvasAction::NextField
            if editor.current_field()
                >= editor.data_provider().field_count().saturating_sub(1) =>
        {
            Some(BoundaryExit::Bottom)
        }
        _ => None,
    }
}

fn key_boundary<D>(editor: &FormEditor<D>, event: &KeyEvent) -> Option<BoundaryExit>
where
    D: DataProvider,
{
    match event.code {
        KeyCode::Up | KeyCode::BackTab if editor.current_field() == 0 => Some(BoundaryExit::Top),
        KeyCode::Down | KeyCode::Tab
            if editor.current_field()
                >= editor.data_provider().field_count().saturating_sub(1) =>
        {
            Some(BoundaryExit::Bottom)
        }
        _ => None,
    }
}

pub fn key_dispatch_status<A, O, M>(
    outcome: &CanvasKeyDispatchOutcome<O, M>,
) -> Option<TuiPagesStatus<A>> {
    match outcome {
        CanvasKeyDispatchOutcome::Consumed(_) | CanvasKeyDispatchOutcome::Focus(_) => {
            Some(TuiPagesStatus::ActionHandled)
        }
        CanvasKeyDispatchOutcome::PendingSequence => Some(TuiPagesStatus::Waiting(Vec::new())),
        CanvasKeyDispatchOutcome::NotHandled => None,
    }
}

pub fn dispatch_text_input_key<P, O, M>(
    input: &mut TextInputState<P>,
    event: KeyEvent,
) -> CanvasTextWidgetOutcome<O, M>
where
    P: TextInputDataProvider,
{
    let boundary = text_input_boundary_for_key(&event);
    match input.input(event) {
        TextInputEventOutcome::Handled => CanvasTextWidgetOutcome::Handled,
        TextInputEventOutcome::Submitted => CanvasTextWidgetOutcome::Submitted,
        TextInputEventOutcome::Ignored => boundary
            .map(|boundary| CanvasTextWidgetOutcome::Focus(focus_intent_for_boundary(boundary)))
            .unwrap_or(CanvasTextWidgetOutcome::NotHandled),
    }
}

pub fn dispatch_text_area_key<P, O, M>(
    textarea: &mut TextAreaState<P>,
    event: KeyEvent,
) -> CanvasTextWidgetOutcome<O, M>
where
    P: TextAreaDataProvider,
{
    if let Some(boundary) = text_area_boundary_for_key(textarea, &event) {
        return CanvasTextWidgetOutcome::Focus(focus_intent_for_boundary(boundary));
    }

    if textarea.commandline().is_some() {
        match textarea.handle_key_event(event) {
            KeyEventOutcome::Consumed(_) | KeyEventOutcome::Pending => {
                CanvasTextWidgetOutcome::Handled
            }
            KeyEventOutcome::ExitTop => {
                CanvasTextWidgetOutcome::Focus(focus_intent_for_boundary(BoundaryExit::Top))
            }
            KeyEventOutcome::ExitBottom => {
                CanvasTextWidgetOutcome::Focus(focus_intent_for_boundary(BoundaryExit::Bottom))
            }
            KeyEventOutcome::NotMatched => CanvasTextWidgetOutcome::NotHandled,
        }
    } else {
        match textarea.input(event) {
            TextAreaEventOutcome::Handled => CanvasTextWidgetOutcome::Handled,
            TextAreaEventOutcome::Ignored => CanvasTextWidgetOutcome::NotHandled,
        }
    }
}

pub fn text_input_boundary_for_key(event: &KeyEvent) -> Option<BoundaryExit> {
    if event.kind != KeyEventKind::Press {
        return None;
    }

    match (event.code, event.modifiers) {
        (KeyCode::Up | KeyCode::BackTab, _) => Some(BoundaryExit::Top),
        (KeyCode::Down, _) => Some(BoundaryExit::Bottom),
        (KeyCode::Tab, modifiers) if modifiers.is_empty() => Some(BoundaryExit::Bottom),
        _ => None,
    }
}

pub fn text_area_boundary_for_key<P>(
    textarea: &TextAreaState<P>,
    event: &KeyEvent,
) -> Option<BoundaryExit>
where
    P: TextAreaDataProvider,
{
    if event.kind != KeyEventKind::Press {
        return None;
    }

    let current = textarea.current_field();
    let last = textarea.data_provider().field_count().saturating_sub(1);

    match event.code {
        KeyCode::Up | KeyCode::BackTab if current == 0 => Some(BoundaryExit::Top),
        KeyCode::Down if current >= last => Some(BoundaryExit::Bottom),
        _ => None,
    }
}

pub fn bind_default_keymaps<A>(
    normal: &mut KeyMap<A>,
    insert: &mut KeyMap<A>,
    select: &mut KeyMap<A>,
)
where
    A: From<CanvasAction>,
{
    bind_normal_defaults(normal);
    bind_insert_defaults(insert);
    bind_select_defaults(select);
}

pub fn bind_normal_defaults<A>(map: &mut KeyMap<A>)
where
    A: From<CanvasAction>,
{
    bind_canvas_crate_defaults_for_mode(map, AppMode::Nor);
}

pub fn bind_insert_defaults<A>(map: &mut KeyMap<A>)
where
    A: From<CanvasAction>,
{
    bind_canvas_crate_defaults_for_mode(map, AppMode::Ins);
    bind_suggestion_defaults(map);
}

pub fn bind_select_defaults<A>(map: &mut KeyMap<A>)
where
    A: From<CanvasAction>,
{
    bind_canvas_crate_defaults_for_mode(map, AppMode::Sel);
    bind_suggestion_defaults(map);
}

fn bind_canvas_crate_defaults_for_mode<A>(map: &mut KeyMap<A>, mode: AppMode)
where
    A: From<CanvasAction>,
{
    for binding in default_vim_action_bindings()
        .into_iter()
        .filter(|binding| binding.mode == mode)
    {
        let sequence = binding
            .sequence
            .into_iter()
            .map(|stroke| KeyChord::new(stroke.code, stroke.modifiers))
            .collect::<Vec<_>>();
        map.bind(sequence, A::from(binding.action));
    }
}

fn canvas_action_pipeline(timeout_ms: u64) -> InputPipeline<CanvasAction> {
    let mut registry = InputRegistry::empty();
    bind_normal_defaults(registry.map_mut(modes::NORMAL.as_str()));
    bind_insert_defaults(registry.map_mut(modes::INSERT.as_str()));
    bind_select_defaults(registry.map_mut(modes::SELECT.as_str()));
    InputPipeline::new(registry, timeout_ms)
}

fn normalize_shift(mut key: KeyEvent) -> KeyEvent {
    if matches!(key.code, KeyCode::Char(_)) && key.modifiers == KeyModifiers::SHIFT {
        key.modifiers = KeyModifiers::NONE;
    }
    key
}

fn focused_canvas_field<V, O>(ctx: &ActionContext<V, O>, index: usize) -> bool {
    matches!(
        ctx.focus.as_ref(),
        Some(FocusTarget::CanvasField(field) | FocusTarget::InternalCanvasField(field))
            if *field == index
    )
}

fn focus_intent_for_top_level_key<O, M>(key: KeyEvent) -> Option<FocusIntent<O, M>> {
    match (key.code, key.modifiers) {
        (KeyCode::Down | KeyCode::Tab, _) => Some(FocusIntent::ExitCanvasForward),
        (KeyCode::Char('j') | KeyCode::Char('l'), modifiers)
            if modifiers.is_empty() || modifiers == KeyModifiers::SHIFT =>
        {
            Some(FocusIntent::ExitCanvasForward)
        }
        (KeyCode::Up | KeyCode::BackTab, _) => Some(FocusIntent::ExitCanvasBackward),
        (KeyCode::Char('k') | KeyCode::Char('h'), modifiers)
            if modifiers.is_empty() || modifiers == KeyModifiers::SHIFT =>
        {
            Some(FocusIntent::ExitCanvasBackward)
        }
        _ => None,
    }
}

fn hook_outcome<V, A, O, M>(
    status: TuiPagesStatus<A>,
    outcome: ActionOutcome<V, O, M>,
) -> Option<KeyHookOutcome<V, A, O, M>> {
    Some(KeyHookOutcome { status, outcome })
}

fn hook_focus_outcome<V, A, O, M>(
    intent: FocusIntent<O, M>,
) -> Option<KeyHookOutcome<V, A, O, M>> {
    hook_outcome(
        TuiPagesStatus::ActionHandled,
        ActionOutcome::effect(TuiEffect::Focus(intent)),
    )
}

fn hook_status_outcome<V, A, O, M>(
    status: TuiPagesStatus<A>,
) -> Option<KeyHookOutcome<V, A, O, M>> {
    hook_outcome(status, ActionOutcome::none())
}

fn form_host_dispatch_hook_outcome<V, A, O, M>(
    outcome: CanvasDispatchOutcome,
) -> Option<KeyHookOutcome<V, A, O, M>> {
    match outcome {
        CanvasDispatchOutcome::Applied(_) => {
            hook_status_outcome(TuiPagesStatus::ActionHandled)
        }
        CanvasDispatchOutcome::Focus(FocusIntent::ExitCanvasForward) => {
            hook_focus_outcome(FocusIntent::ExitCanvasForward)
        }
        CanvasDispatchOutcome::Focus(FocusIntent::ExitCanvasBackward) => {
            hook_focus_outcome(FocusIntent::ExitCanvasBackward)
        }
        CanvasDispatchOutcome::Focus(_) => hook_status_outcome(TuiPagesStatus::ActionHandled),
    }
}

fn widget_action_hook_outcome<V, A, O, M>(
    outcome: HostActionOutcome,
) -> Option<KeyHookOutcome<V, A, O, M>> {
    match outcome {
        HostActionOutcome::Applied(_) => hook_status_outcome(TuiPagesStatus::ActionHandled),
        HostActionOutcome::ExitCanvas(boundary) => {
            hook_focus_outcome(focus_intent_for_boundary(boundary))
        }
    }
}

fn pipeline_hook_outcome<V, A, O, M>(
    response: PipelineResponse<CanvasAction>,
) -> Option<KeyHookOutcome<V, A, O, M>> {
    match response {
        PipelineResponse::Wait(_) => hook_status_outcome(TuiPagesStatus::Waiting(Vec::new())),
        PipelineResponse::Cancel => hook_status_outcome(TuiPagesStatus::Cancelled),
        PipelineResponse::Execute(_) | PipelineResponse::Type(_) => None,
    }
}

fn refresh_textinput_suggestion_suffix<S>(state: &mut S, focus_index: usize)
where
    S: CanvasWidgetState,
{
    let Some(text) = state.canvas_textinput(focus_index).map(|input| input.text()) else {
        return;
    };
    let suffix = state.canvas_textinput_suggestion_suffix(focus_index, &text);
    let Some(input) = state.canvas_textinput(focus_index) else {
        return;
    };
    if let Some(suffix) = suffix {
        input.set_suggestion_suffix(suffix);
    } else {
        input.clear_suggestion_suffix();
    }
}

pub(crate) fn dispatch_canvas_key_hook<V, A, S, O, M>(
    kind: &mut KeyHookKind,
    key: KeyEvent,
    ctx: ActionContext<V, O>,
    state: &mut S,
) -> Option<KeyHookOutcome<V, A, O, M>>
where
    S: CanvasWidgetState,
{
    match kind {
        KeyHookKind::CanvasFormEditor { id, pipeline } => {
            if !ctx.focus.as_ref().is_some_and(FocusTarget::is_canvas) {
                return None;
            }

            let editor = state.canvas_form_editor(*id)?;
            let mode = editor.mode();
            let modes = modes_for_app_mode(mode);
            match pipeline.process(key, &modes, accepts_text_input(mode)) {
                PipelineResponse::Execute(action) => {
                    form_host_dispatch_hook_outcome(editor.dispatch_canvas_action(action))
                }
                PipelineResponse::Type(chord) if accepts_text_input(mode) => {
                    text_chord_to_canvas_action(chord).and_then(|action| {
                        form_host_dispatch_hook_outcome(editor.dispatch_canvas_action(action))
                    })
                }
                response => pipeline_hook_outcome(response),
            }
        }
        KeyHookKind::CanvasTextArea {
            focus_index,
            pipeline,
        } => {
            if !focused_canvas_field(&ctx, *focus_index) {
                if let Some(entered) = state.canvas_textarea_entered(*focus_index) {
                    *entered = false;
                }
                return None;
            }

            let is_entered = state
                .canvas_textarea_entered(*focus_index)
                .is_some_and(|entered| *entered);
            if !is_entered {
                if key.kind != KeyEventKind::Press {
                    return None;
                }
                if matches!(key.code, KeyCode::Enter) {
                    if let Some(entered) = state.canvas_textarea_entered(*focus_index) {
                        *entered = true;
                    }
                    if let Some(textarea) = state.canvas_textarea(*focus_index) {
                        textarea.exit_edit_mode();
                    }
                    return hook_status_outcome(TuiPagesStatus::ActionHandled);
                }
                return focus_intent_for_top_level_key(key).and_then(hook_focus_outcome);
            }

            let mode = state.canvas_textarea(*focus_index)?.mode();
            if mode == AppMode::Ins {
                return match (key.code, key.modifiers) {
                    (KeyCode::Char('c'), KeyModifiers::CONTROL) => None,
                    (KeyCode::Esc, _) => {
                        state.canvas_textarea(*focus_index)?.exit_edit_mode();
                        hook_status_outcome(TuiPagesStatus::ActionHandled)
                    }
                    _ => match state
                        .canvas_textarea(*focus_index)?
                        .input_key(normalize_shift(key))
                    {
                        TextAreaEventOutcome::Handled => {
                            hook_status_outcome(TuiPagesStatus::TextHandled)
                        }
                        TextAreaEventOutcome::Ignored => None,
                    },
                };
            }

            if matches!(key.code, KeyCode::Esc) && key.kind == KeyEventKind::Press {
                if let Some(entered) = state.canvas_textarea_entered(*focus_index) {
                    *entered = false;
                }
                return hook_status_outcome(TuiPagesStatus::ActionHandled);
            }

            if let Some(boundary) = state.canvas_textarea(*focus_index)?.boundary_for_key(&key) {
                return hook_focus_outcome(focus_intent_for_boundary(boundary));
            }

            match state
                .canvas_textarea(*focus_index)?
                .input_key(normalize_shift(key))
            {
                TextAreaEventOutcome::Handled => {
                    return hook_status_outcome(TuiPagesStatus::TextHandled);
                }
                TextAreaEventOutcome::Ignored => {}
            }

            let modes = modes_for_app_mode(mode);
            match pipeline.process(key, &modes, accepts_text_input(mode)) {
                PipelineResponse::Execute(action) => widget_action_hook_outcome(
                    state.canvas_textarea(*focus_index)?.dispatch_canvas_action(action),
                ),
                response => pipeline_hook_outcome(response),
            }
        }
        KeyHookKind::CanvasTextInput {
            focus_index,
            pipeline,
        } => {
            if !focused_canvas_field(&ctx, *focus_index) {
                if let Some(entered) = state.canvas_textinput_entered(*focus_index) {
                    *entered = false;
                }
                return None;
            }

            let is_entered = state
                .canvas_textinput_entered(*focus_index)
                .is_some_and(|entered| *entered);
            if !is_entered {
                if key.kind != KeyEventKind::Press {
                    return None;
                }
                if matches!(key.code, KeyCode::Enter) {
                    if let Some(entered) = state.canvas_textinput_entered(*focus_index) {
                        *entered = true;
                    }
                    return hook_status_outcome(TuiPagesStatus::ActionHandled);
                }
                return focus_intent_for_top_level_key(key).and_then(hook_focus_outcome);
            }

            let mode = state.canvas_textinput(*focus_index)?.mode();
            if mode == AppMode::Ins {
                return match (key.code, key.modifiers) {
                    (KeyCode::Char('c'), KeyModifiers::CONTROL) => None,
                    (KeyCode::Esc, _) => {
                        state.canvas_textinput(*focus_index)?.exit_edit_mode();
                        hook_status_outcome(TuiPagesStatus::ActionHandled)
                    }
                    _ => match state
                        .canvas_textinput(*focus_index)?
                        .input_key(normalize_shift(key))
                    {
                        CanvasTextWidgetOutcome::Handled => {
                            refresh_textinput_suggestion_suffix(state, *focus_index);
                            hook_status_outcome(TuiPagesStatus::TextHandled)
                        }
                        CanvasTextWidgetOutcome::Submitted => {
                            if let Some(entered) = state.canvas_textinput_entered(*focus_index) {
                                *entered = false;
                            }
                            hook_focus_outcome(FocusIntent::ExitCanvasForward)
                        }
                        CanvasTextWidgetOutcome::Focus(intent) => {
                            if let Some(entered) = state.canvas_textinput_entered(*focus_index) {
                                *entered = false;
                            }
                            match intent {
                                FocusIntent::ExitCanvasForward => {
                                    hook_focus_outcome(FocusIntent::ExitCanvasForward)
                                }
                                FocusIntent::ExitCanvasBackward => {
                                    hook_focus_outcome(FocusIntent::ExitCanvasBackward)
                                }
                                _ => hook_status_outcome(TuiPagesStatus::ActionHandled),
                            }
                        }
                        CanvasTextWidgetOutcome::NotHandled => None,
                    },
                };
            }

            if matches!(key.code, KeyCode::Esc) && key.kind == KeyEventKind::Press {
                if let Some(entered) = state.canvas_textinput_entered(*focus_index) {
                    *entered = false;
                }
                return hook_status_outcome(TuiPagesStatus::ActionHandled);
            }

            let modes = modes_for_app_mode(mode);
            match pipeline.process(key, &modes, accepts_text_input(mode)) {
                PipelineResponse::Execute(action) => widget_action_hook_outcome(
                    state.canvas_textinput(*focus_index)?.dispatch_canvas_action(action),
                ),
                response => pipeline_hook_outcome(response),
            }
        }
    }
}

impl<O> PageSpec<O> {
    pub fn canvas_mode(mut self, mode: AppMode) -> Self {
        self.modes = modes_for_app_mode(mode);
        self.accepts_text_input = accepts_text_input(mode);
        self
    }

    pub fn canvas_editor<D>(self, editor: &FormEditor<D>) -> Self
    where
        D: DataProvider,
    {
        self.canvas_mode(editor.mode())
    }
}

impl<V, A, S, O, M, Pages, Handler> TuiPagesBuilder<V, A, S, O, M, Pages, Handler>
where
    A: From<CanvasAction>,
{
    pub fn canvas_defaults(self) -> Self {
        self.canvas_keybindings().canvas_text_actions()
    }

    pub fn canvas_keybindings(mut self) -> Self {
        bind_normal_defaults(self.input_registry.map_mut(modes::NORMAL.as_str()));
        bind_insert_defaults(self.input_registry.map_mut(modes::INSERT.as_str()));
        bind_select_defaults(self.input_registry.map_mut(modes::SELECT.as_str()));
        self
    }

    pub fn canvas_text_actions(mut self) -> Self {
        self.text_input_mapper = Some(text_chord_to_action::<A>);
        self
    }
}

impl<V, A, S, O, M, Pages, Handler> TuiPagesBuilder<V, A, S, O, M, Pages, Handler>
where
    S: CanvasWidgetState,
{
    pub fn canvas_form_editor(mut self, id: usize) -> Self {
        self.key_hooks.push(KeyHook {
            kind: KeyHookKind::CanvasFormEditor {
                id,
                pipeline: canvas_action_pipeline(self.input_timeout_ms),
            },
            dispatch: dispatch_canvas_key_hook::<V, A, S, O, M>,
        });
        self
    }

    pub fn canvas_textarea_widget(mut self, focus_index: usize) -> Self {
        self.key_hooks.push(KeyHook {
            kind: KeyHookKind::CanvasTextArea {
                focus_index,
                pipeline: canvas_action_pipeline(self.input_timeout_ms),
            },
            dispatch: dispatch_canvas_key_hook::<V, A, S, O, M>,
        });
        self
    }

    pub fn canvas_textinput_widget(mut self, focus_index: usize) -> Self {
        self.key_hooks.push(KeyHook {
            kind: KeyHookKind::CanvasTextInput {
                focus_index,
                pipeline: canvas_action_pipeline(self.input_timeout_ms),
            },
            dispatch: dispatch_canvas_key_hook::<V, A, S, O, M>,
        });
        self
    }
}

fn bind_suggestion_defaults<A>(map: &mut KeyMap<A>)
where
    A: From<CanvasAction>,
{
    bind_key_with_modifiers(
        map,
        KeyCode::Char(' '),
        KeyModifiers::CONTROL,
        CanvasAction::TriggerSuggestions,
    );
    bind_key_with_modifiers(
        map,
        KeyCode::Char('n'),
        KeyModifiers::CONTROL,
        CanvasAction::SuggestionDown,
    );
    bind_key_with_modifiers(
        map,
        KeyCode::Char('p'),
        KeyModifiers::CONTROL,
        CanvasAction::SuggestionUp,
    );
    bind_key_with_modifiers(
        map,
        KeyCode::Char('y'),
        KeyModifiers::CONTROL,
        CanvasAction::SelectSuggestion,
    );
    bind_key_with_modifiers(
        map,
        KeyCode::Char('g'),
        KeyModifiers::CONTROL,
        CanvasAction::ExitSuggestions,
    );
}

fn bind_key_with_modifiers<A>(
    map: &mut KeyMap<A>,
    code: KeyCode,
    modifiers: KeyModifiers,
    action: CanvasAction,
)
where
    A: From<CanvasAction>,
{
    map.bind(vec![KeyChord::new(code, modifiers)], A::from(action));
}