1use std::sync::OnceLock;
24
25use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
26use ftui_core::keybinding::{Chord, KeyCombo, KeyMap, Priority};
27use ftui_layout::{
28 PaneAccessibilityPreferences, PaneAffordanceMotion, PaneAnnouncement, PaneAnnouncer,
29 PaneCardinalDirection, PaneCommand, PaneCommandAcceleration, PaneCommandEffect,
30 PaneCommandResolution, PaneFocusContext, PaneFocusOrdinal, PaneId, PaneLayout,
31 PaneResizeDirection, PaneTree, Rect, SplitAxis, announce_command, resolve_pane_command,
32};
33use ftui_render::cell::{Cell, PackedRgba};
34use ftui_render::drawing::{BorderChars, Draw};
35use ftui_style::{PaneAffordanceTheme, ResolvedTheme};
36
37#[must_use]
63pub fn key_to_pane_command(key: &KeyEvent, resize_units: u16) -> Option<PaneCommand> {
64 resolve_pane_key(default_pane_keymap(), key, resize_units)
65}
66
67#[derive(Debug, Clone, Copy)]
71struct PaneBindingSpec {
72 code: KeyCode,
73 modifiers: Modifiers,
74 command: PaneCommand,
75 hint_keys: &'static str,
76 hint_action: &'static str,
77}
78
79fn pane_binding_specs() -> Vec<PaneBindingSpec> {
86 use PaneCardinalDirection as Dir;
87
88 let spec = |code, modifiers, command, hint_keys, hint_action| PaneBindingSpec {
89 code,
90 modifiers,
91 command,
92 hint_keys,
93 hint_action,
94 };
95 let arrows = [
96 (KeyCode::Left, Dir::Left),
97 (KeyCode::Right, Dir::Right),
98 (KeyCode::Up, Dir::Up),
99 (KeyCode::Down, Dir::Down),
100 ];
101 let alt = Modifiers::ALT;
102 let alt_shift = Modifiers::ALT | Modifiers::SHIFT;
103 let ctrl_shift = Modifiers::CTRL | Modifiers::SHIFT;
104
105 let mut specs = vec![
106 spec(
107 KeyCode::Tab,
108 Modifiers::NONE,
109 PaneCommand::FocusNext,
110 "Tab / Shift+Tab",
111 "focus next / previous pane",
112 ),
113 spec(
114 KeyCode::BackTab,
115 Modifiers::NONE,
116 PaneCommand::FocusPrevious,
117 "Tab / Shift+Tab",
118 "focus next / previous pane",
119 ),
120 spec(
121 KeyCode::BackTab,
122 Modifiers::SHIFT,
123 PaneCommand::FocusPrevious,
124 "Tab / Shift+Tab",
125 "focus next / previous pane",
126 ),
127 ];
128 for (code, dir) in arrows {
129 specs.push(spec(
130 code,
131 Modifiers::CTRL,
132 PaneCommand::FocusDirectional(dir),
133 "Ctrl+Arrows",
134 "focus pane by direction",
135 ));
136 }
137 for (code, dir) in arrows {
138 specs.push(spec(
139 code,
140 ctrl_shift,
141 PaneCommand::FocusEdge(dir),
142 "Ctrl+Shift+Arrows",
143 "focus pane at edge",
144 ));
145 }
146 for (code, dir) in arrows {
147 for modifiers in [alt, alt_shift] {
148 specs.push(spec(
149 code,
150 modifiers,
151 PaneCommand::MovePane(dir),
152 "Alt+Arrows",
153 "move pane",
154 ));
155 }
156 }
157 let grow = PaneCommand::ResizeStep {
158 direction: PaneResizeDirection::Increase,
159 units: 1,
160 };
161 let shrink = PaneCommand::ResizeStep {
162 direction: PaneResizeDirection::Decrease,
163 units: 1,
164 };
165 for (ch, command) in [('+', grow), ('=', grow), ('-', shrink), ('_', shrink)] {
166 specs.push(spec(
167 KeyCode::Char(ch),
168 alt,
169 command,
170 "Alt++ / Alt+-",
171 "grow / shrink pane",
172 ));
173 }
174 let letters = [
175 (
176 's',
177 PaneCommand::Split(SplitAxis::Horizontal),
178 "Alt+s / Alt+v",
179 "split horizontal / vertical",
180 ),
181 (
182 'v',
183 PaneCommand::Split(SplitAxis::Vertical),
184 "Alt+s / Alt+v",
185 "split horizontal / vertical",
186 ),
187 ('w', PaneCommand::Close, "Alt+w", "close pane"),
188 ];
189 for (ch, command, hint_keys, hint_action) in letters {
190 for modifiers in [alt, alt_shift] {
191 specs.push(spec(
192 KeyCode::Char(ch),
193 modifiers,
194 command,
195 hint_keys,
196 hint_action,
197 ));
198 }
199 }
200 specs.push(spec(
201 KeyCode::Char('['),
202 alt,
203 PaneCommand::SwapPane(PaneFocusOrdinal::Previous),
204 "Alt+[ / Alt+]",
205 "swap with previous / next pane",
206 ));
207 specs.push(spec(
208 KeyCode::Char(']'),
209 alt,
210 PaneCommand::SwapPane(PaneFocusOrdinal::Next),
211 "Alt+[ / Alt+]",
212 "swap with previous / next pane",
213 ));
214 for (ch, command) in [('z', PaneCommand::Maximize), ('r', PaneCommand::Restore)] {
215 for modifiers in [alt, alt_shift] {
216 specs.push(spec(
217 KeyCode::Char(ch),
218 modifiers,
219 command,
220 "Alt+z / Alt+r",
221 "maximize / restore pane",
222 ));
223 }
224 }
225 specs
226}
227
228#[must_use]
233pub fn pane_keymap() -> KeyMap<PaneCommand> {
234 let mut map = KeyMap::new();
235 for spec in pane_binding_specs() {
236 let id = map.bind_in(
237 Chord::single(KeyCombo::new(spec.code, spec.modifiers)),
238 spec.command,
239 Priority::Global,
240 None,
241 );
242 map.set_label(id, spec.hint_action);
243 }
244 map
245}
246
247fn default_pane_keymap() -> &'static KeyMap<PaneCommand> {
248 static MAP: OnceLock<KeyMap<PaneCommand>> = OnceLock::new();
249 MAP.get_or_init(pane_keymap)
250}
251
252fn resolve_pane_key(
255 map: &KeyMap<PaneCommand>,
256 key: &KeyEvent,
257 resize_units: u16,
258) -> Option<PaneCommand> {
259 if key.kind == KeyEventKind::Release {
260 return None;
261 }
262 let chord = Chord::single(KeyCombo::new(key.code, key.modifiers));
263 let command = map.lookup(&chord, &[]).exact?.action;
264 Some(match command {
265 PaneCommand::ResizeStep { direction, .. } => PaneCommand::ResizeStep {
266 direction,
267 units: resize_units,
268 },
269 other => other,
270 })
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
275pub enum PaneKeyOutcome {
276 Unbound,
278 Handled {
280 command: PaneCommand,
282 resolution: PaneCommandResolution,
284 },
285 Failed {
288 command: PaneCommand,
290 },
291}
292
293#[derive(Debug, Clone)]
298pub struct PaneKeyboardController {
299 focus: PaneFocusContext,
300 acceleration: PaneCommandAcceleration,
301 op_seed: u64,
302 repeat_count: u16,
303 announcer: PaneAnnouncer,
304 preferences: PaneAccessibilityPreferences,
305 keymap: KeyMap<PaneCommand>,
306}
307
308impl PaneKeyboardController {
309 #[must_use]
312 pub fn new(active: Option<PaneId>) -> Self {
313 Self {
314 focus: PaneFocusContext {
315 active,
316 maximized: None,
317 },
318 acceleration: PaneCommandAcceleration::default(),
319 op_seed: 0,
320 repeat_count: 0,
321 announcer: PaneAnnouncer::new(),
322 preferences: PaneAccessibilityPreferences::none(),
323 keymap: pane_keymap(),
324 }
325 }
326
327 #[must_use]
329 pub fn keymap(&self) -> &KeyMap<PaneCommand> {
330 &self.keymap
331 }
332
333 #[must_use]
338 pub fn with_keymap(mut self, keymap: KeyMap<PaneCommand>) -> Self {
339 self.keymap = keymap;
340 self
341 }
342
343 pub fn take_announcement(&mut self) -> Option<PaneAnnouncement> {
346 self.announcer.take()
347 }
348
349 #[must_use]
351 pub fn pending_announcement(&self) -> Option<&PaneAnnouncement> {
352 self.announcer.pending()
353 }
354
355 #[must_use]
357 pub const fn with_acceleration(mut self, acceleration: PaneCommandAcceleration) -> Self {
358 self.acceleration = acceleration;
359 self
360 }
361
362 #[must_use]
365 pub const fn with_preferences(mut self, preferences: PaneAccessibilityPreferences) -> Self {
366 self.preferences = preferences;
367 self
368 }
369
370 pub const fn set_preferences(&mut self, preferences: PaneAccessibilityPreferences) {
374 self.preferences = preferences;
375 }
376
377 #[must_use]
379 pub const fn preferences(&self) -> PaneAccessibilityPreferences {
380 self.preferences
381 }
382
383 #[must_use]
386 pub fn affordance_motion(&self) -> PaneAffordanceMotion {
387 self.preferences.affordance_motion()
388 }
389
390 #[must_use]
394 pub fn focus_ring(&self, theme: &ResolvedTheme) -> PaneFocusRing {
395 let affordance = PaneAffordanceTheme::from_resolved(theme, self.preferences.high_contrast);
396 PaneFocusRing::themed(&affordance)
397 }
398
399 #[must_use]
401 pub const fn focus(&self) -> PaneFocusContext {
402 self.focus
403 }
404
405 #[must_use]
407 pub const fn active(&self) -> Option<PaneId> {
408 self.focus.active
409 }
410
411 #[must_use]
413 pub const fn maximized(&self) -> Option<PaneId> {
414 self.focus.maximized
415 }
416
417 pub const fn set_active(&mut self, active: Option<PaneId>) {
419 self.focus.active = active;
420 }
421
422 pub fn handle_key(
426 &mut self,
427 key: &KeyEvent,
428 tree: &mut PaneTree,
429 layout: &PaneLayout,
430 ) -> PaneKeyOutcome {
431 if key.kind == KeyEventKind::Repeat {
433 self.repeat_count = self.repeat_count.saturating_add(1);
434 } else {
435 self.repeat_count = 0;
436 }
437 let resize_units = self.acceleration.units_for(self.repeat_count);
438
439 let Some(command) = resolve_pane_key(&self.keymap, key, resize_units) else {
440 return PaneKeyOutcome::Unbound;
441 };
442
443 let resolution = resolve_pane_command(tree, layout, self.focus, command);
444 if let PaneCommandEffect::Structural(ops) = &resolution.effect {
445 for op in ops {
446 if tree.apply_operation(self.op_seed, op.clone()).is_err() {
447 return PaneKeyOutcome::Failed { command };
448 }
449 self.op_seed += 1;
450 }
451 }
452 self.focus.active = resolution.next_active;
453 self.focus.maximized = resolution.next_maximized;
454 self.announcer
455 .offer(announce_command(command, &resolution, tree));
456 PaneKeyOutcome::Handled {
457 command,
458 resolution,
459 }
460 }
461}
462
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub struct PaneFocusRing {
466 pub border: BorderChars,
469 pub cell: Cell,
471}
472
473impl Default for PaneFocusRing {
474 fn default() -> Self {
475 Self {
476 border: BorderChars::DOUBLE,
477 cell: Cell::from_char(' ').with_fg(PackedRgba::rgb(0xFF, 0xD7, 0x00)),
481 }
482 }
483}
484
485impl PaneFocusRing {
486 #[must_use]
494 pub fn themed(affordance: &PaneAffordanceTheme) -> Self {
495 let rgb = affordance.focus_ring.to_rgb();
496 Self {
497 border: BorderChars::DOUBLE,
498 cell: Cell::from_char(' ').with_fg(PackedRgba::rgb(rgb.r, rgb.g, rgb.b)),
499 }
500 }
501}
502
503pub fn render_pane_focus_ring<T: Draw>(target: &mut T, rect: Rect, ring: &PaneFocusRing) {
508 target.draw_border(rect, ring.border, ring.cell);
509}
510
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
513pub struct PaneKeyHint {
514 pub keys: &'static str,
516 pub action: &'static str,
518}
519
520#[must_use]
525pub fn pane_keyboard_hints() -> &'static [PaneKeyHint] {
526 static HINTS: OnceLock<Vec<PaneKeyHint>> = OnceLock::new();
527 HINTS.get_or_init(|| {
528 let mut hints: Vec<PaneKeyHint> = Vec::new();
529 for spec in pane_binding_specs() {
530 let hint = PaneKeyHint {
531 keys: spec.hint_keys,
532 action: spec.hint_action,
533 };
534 if !hints.contains(&hint) {
535 hints.push(hint);
536 }
537 }
538 hints
539 })
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545 use ftui_layout::{
546 PANE_TREE_SCHEMA_VERSION, PaneLeaf, PaneNodeRecord, PaneSplit, PaneSplitRatio,
547 PaneTreeSnapshot,
548 };
549 use ftui_render::buffer::Buffer;
550 use std::collections::BTreeMap;
551
552 fn pid(raw: u64) -> PaneId {
553 PaneId::new(raw).expect("non-zero id")
554 }
555
556 fn key(code: KeyCode, modifiers: Modifiers) -> KeyEvent {
557 KeyEvent {
558 code,
559 modifiers,
560 kind: KeyEventKind::Press,
561 }
562 }
563
564 fn nested() -> PaneTree {
566 let snapshot = PaneTreeSnapshot {
567 schema_version: PANE_TREE_SCHEMA_VERSION,
568 root: pid(1),
569 next_id: pid(6),
570 nodes: vec![
571 PaneNodeRecord::split(
572 pid(1),
573 None,
574 PaneSplit {
575 axis: SplitAxis::Horizontal,
576 ratio: PaneSplitRatio::new(1, 1).unwrap(),
577 first: pid(2),
578 second: pid(3),
579 },
580 ),
581 PaneNodeRecord::leaf(pid(2), Some(pid(1)), PaneLeaf::new("left")),
582 PaneNodeRecord::split(
583 pid(3),
584 Some(pid(1)),
585 PaneSplit {
586 axis: SplitAxis::Vertical,
587 ratio: PaneSplitRatio::new(1, 1).unwrap(),
588 first: pid(4),
589 second: pid(5),
590 },
591 ),
592 PaneNodeRecord::leaf(pid(4), Some(pid(3)), PaneLeaf::new("right_top")),
593 PaneNodeRecord::leaf(pid(5), Some(pid(3)), PaneLeaf::new("right_bottom")),
594 ],
595 extensions: BTreeMap::new(),
596 };
597 PaneTree::from_snapshot(snapshot).expect("valid tree")
598 }
599
600 #[test]
601 fn keymap_covers_the_full_vocabulary() {
602 let none = Modifiers::NONE;
603 let ctrl = Modifiers::CTRL;
604 let alt = Modifiers::ALT;
605 let ctrl_shift = Modifiers::CTRL | Modifiers::SHIFT;
606
607 assert_eq!(
608 key_to_pane_command(&key(KeyCode::Tab, none), 1),
609 Some(PaneCommand::FocusNext)
610 );
611 assert_eq!(
612 key_to_pane_command(&key(KeyCode::BackTab, Modifiers::SHIFT), 1),
613 Some(PaneCommand::FocusPrevious)
614 );
615 assert_eq!(
616 key_to_pane_command(&key(KeyCode::Left, ctrl), 1),
617 Some(PaneCommand::FocusDirectional(PaneCardinalDirection::Left))
618 );
619 assert_eq!(
620 key_to_pane_command(&key(KeyCode::Down, ctrl_shift), 1),
621 Some(PaneCommand::FocusEdge(PaneCardinalDirection::Down))
622 );
623 assert_eq!(
624 key_to_pane_command(&key(KeyCode::Right, alt), 1),
625 Some(PaneCommand::MovePane(PaneCardinalDirection::Right))
626 );
627 assert_eq!(
628 key_to_pane_command(&key(KeyCode::Char('+'), alt), 4),
629 Some(PaneCommand::ResizeStep {
630 direction: PaneResizeDirection::Increase,
631 units: 4
632 })
633 );
634 assert_eq!(
635 key_to_pane_command(&key(KeyCode::Char('-'), alt), 1),
636 Some(PaneCommand::ResizeStep {
637 direction: PaneResizeDirection::Decrease,
638 units: 1
639 })
640 );
641 assert_eq!(
642 key_to_pane_command(&key(KeyCode::Char('s'), alt), 1),
643 Some(PaneCommand::Split(SplitAxis::Horizontal))
644 );
645 assert_eq!(
646 key_to_pane_command(&key(KeyCode::Char('v'), alt), 1),
647 Some(PaneCommand::Split(SplitAxis::Vertical))
648 );
649 assert_eq!(
650 key_to_pane_command(&key(KeyCode::Char('w'), alt), 1),
651 Some(PaneCommand::Close)
652 );
653 assert_eq!(
654 key_to_pane_command(&key(KeyCode::Char('['), alt), 1),
655 Some(PaneCommand::SwapPane(PaneFocusOrdinal::Previous))
656 );
657 assert_eq!(
658 key_to_pane_command(&key(KeyCode::Char('z'), alt), 1),
659 Some(PaneCommand::Maximize)
660 );
661 assert_eq!(
662 key_to_pane_command(&key(KeyCode::Char('r'), alt), 1),
663 Some(PaneCommand::Restore)
664 );
665 }
666
667 #[test]
668 fn keymap_does_not_steal_plain_or_app_keys() {
669 assert_eq!(
671 key_to_pane_command(&key(KeyCode::Char('a'), Modifiers::NONE), 1),
672 None
673 );
674 assert_eq!(
675 key_to_pane_command(&key(KeyCode::Left, Modifiers::NONE), 1),
676 None
677 );
678 assert_eq!(
680 key_to_pane_command(&key(KeyCode::Char('c'), Modifiers::CTRL), 1),
681 None
682 );
683 let mut release = key(KeyCode::Tab, Modifiers::NONE);
685 release.kind = KeyEventKind::Release;
686 assert_eq!(key_to_pane_command(&release, 1), None);
687 }
688
689 #[test]
690 fn controller_drives_pointer_free_workflow() {
691 fn run() -> (u64, Option<PaneId>, Option<PaneId>) {
694 let mut tree = nested();
695 let mut controller = PaneKeyboardController::new(Some(pid(2)));
696 let area = Rect::new(0, 0, 80, 24);
697
698 let solve = |t: &PaneTree| t.solve_layout(area).expect("solves");
699
700 let layout = solve(&tree);
702 let out =
703 controller.handle_key(&key(KeyCode::Tab, Modifiers::NONE), &mut tree, &layout);
704 assert!(matches!(out, PaneKeyOutcome::Handled { .. }));
705 assert_eq!(controller.active(), Some(pid(4)));
706
707 let layout = solve(&tree);
709 controller.handle_key(&key(KeyCode::Down, Modifiers::CTRL), &mut tree, &layout);
710 assert_eq!(controller.active(), Some(pid(5)));
711
712 let layout = solve(&tree);
714 let before = tree.nodes().count();
715 controller.handle_key(&key(KeyCode::Char('s'), Modifiers::ALT), &mut tree, &layout);
716 assert!(tree.nodes().count() > before, "split must grow the tree");
717
718 let layout = solve(&tree);
720 controller.handle_key(&key(KeyCode::Char('z'), Modifiers::ALT), &mut tree, &layout);
721 assert!(controller.maximized().is_some());
722 let layout = solve(&tree);
723 controller.handle_key(&key(KeyCode::Char('r'), Modifiers::ALT), &mut tree, &layout);
724 assert_eq!(controller.maximized(), None);
725
726 (
727 tree.state_hash(),
728 controller.active(),
729 controller.maximized(),
730 )
731 }
732
733 let first = run();
734 let second = run();
735 assert_eq!(
736 first, second,
737 "keyboard-only workflow must be deterministic"
738 );
739 }
740
741 #[test]
742 fn controller_close_updates_focus_to_survivor() {
743 let mut tree = nested();
744 let mut controller = PaneKeyboardController::new(Some(pid(2)));
745 let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
746 let out =
747 controller.handle_key(&key(KeyCode::Char('w'), Modifiers::ALT), &mut tree, &layout);
748 match out {
749 PaneKeyOutcome::Handled { command, .. } => {
750 assert_eq!(command, PaneCommand::Close);
751 }
752 other => panic!("expected handled close, got {other:?}"),
753 }
754 assert_ne!(controller.active(), Some(pid(2)));
756 assert!(controller.active().is_some());
757 }
758
759 #[test]
760 fn unbound_key_does_not_touch_state() {
761 let mut tree = nested();
762 let mut controller = PaneKeyboardController::new(Some(pid(2)));
763 let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
764 let before = tree.state_hash();
765 let out = controller.handle_key(
766 &key(KeyCode::Char('q'), Modifiers::NONE),
767 &mut tree,
768 &layout,
769 );
770 assert_eq!(out, PaneKeyOutcome::Unbound);
771 assert_eq!(controller.active(), Some(pid(2)));
772 assert_eq!(tree.state_hash(), before);
773 }
774
775 #[test]
776 fn repeat_accelerates_resize_units() {
777 let mut tree = nested();
778 let mut controller = PaneKeyboardController::new(Some(pid(2)));
780 let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
781 let mut repeat = key(KeyCode::Char('+'), Modifiers::ALT);
782 repeat.kind = KeyEventKind::Repeat;
783 let mut last_units = 0u16;
785 for _ in 0..4 {
786 if let PaneKeyOutcome::Handled {
787 command: PaneCommand::ResizeStep { units, .. },
788 ..
789 } = controller.handle_key(&repeat, &mut tree, &layout)
790 {
791 last_units = units;
792 }
793 }
794 assert_eq!(
795 last_units,
796 PaneCommandAcceleration::default().accelerated_units
797 );
798 }
799
800 #[test]
801 fn focus_ring_draws_a_distinct_border() {
802 let mut buffer = Buffer::new(10, 6);
803 render_pane_focus_ring(
804 &mut buffer,
805 Rect::new(0, 0, 6, 4),
806 &PaneFocusRing::default(),
807 );
808 assert_eq!(
810 buffer.get(0, 0).and_then(|c| c.content.as_char()),
811 Some('╔')
812 );
813 assert_eq!(
814 buffer.get(5, 3).and_then(|c| c.content.as_char()),
815 Some('╝')
816 );
817 }
818
819 #[test]
820 fn themed_focus_ring_uses_the_affordance_color() {
821 use ftui_style::theme::themes;
822 let resolved = themes::dark().resolve(true);
823 let affordance = PaneAffordanceTheme::from_resolved(&resolved, false);
824 let ring = PaneFocusRing::themed(&affordance);
825 let want = affordance.focus_ring.to_rgb();
828 assert_eq!(ring.cell.fg, PackedRgba::rgb(want.r, want.g, want.b));
829 assert_ne!(ring.cell.fg, PaneFocusRing::default().cell.fg);
830 assert_eq!(ring.border, BorderChars::DOUBLE);
832 }
833
834 #[test]
835 fn themed_focus_ring_high_contrast_is_at_least_as_visible() {
836 use ftui_style::theme::themes;
837 let resolved = themes::solarized_light().resolve(false);
838 let normal = PaneAffordanceTheme::from_resolved(&resolved, false);
839 let high = PaneAffordanceTheme::from_resolved(&resolved, true);
840 let ratio = |c: ftui_style::color::Color| {
841 ftui_style::color::contrast_ratio(c.to_rgb(), resolved.surface.to_rgb())
842 };
843 assert!(ratio(high.focus_ring) + 1e-9 >= ratio(normal.focus_ring));
844 }
845
846 #[test]
847 fn preferences_do_not_alter_keyboard_semantics() {
848 use ftui_layout::PaneAccessibilityPreferences;
849 fn drive(
853 prefs: PaneAccessibilityPreferences,
854 ) -> (u64, Option<PaneId>, Option<PaneId>, Vec<String>) {
855 let mut tree = nested();
856 let mut controller = PaneKeyboardController::new(Some(pid(2))).with_preferences(prefs);
857 let area = Rect::new(0, 0, 80, 24);
858 let seq = [
859 key(KeyCode::Tab, Modifiers::NONE),
860 key(KeyCode::Down, Modifiers::CTRL),
861 key(KeyCode::Char('s'), Modifiers::ALT),
862 key(KeyCode::Char('z'), Modifiers::ALT),
863 key(KeyCode::Char('r'), Modifiers::ALT),
864 ];
865 let mut announcements = Vec::new();
866 for k in seq {
867 let layout = tree.solve_layout(area).expect("solves");
868 controller.handle_key(&k, &mut tree, &layout);
869 if let Some(a) = controller.take_announcement() {
870 announcements.push(a.text);
871 }
872 }
873 (
874 tree.state_hash(),
875 controller.active(),
876 controller.maximized(),
877 announcements,
878 )
879 }
880 let plain = drive(PaneAccessibilityPreferences::none());
881 let full = drive(PaneAccessibilityPreferences::all());
882 assert_eq!(plain, full, "a11y modes must not change pane semantics");
883 }
884
885 #[test]
886 fn focus_ring_honors_high_contrast_preference() {
887 use ftui_layout::PaneAccessibilityPreferences;
888 use ftui_style::theme::themes;
889 let theme = themes::dark().resolve(true);
890 let normal_aff = PaneAffordanceTheme::from_resolved(&theme, false);
891 let high_aff = PaneAffordanceTheme::from_resolved(&theme, true);
892
893 let normal_ctl = PaneKeyboardController::new(Some(pid(2)));
896 let high_ctl = PaneKeyboardController::new(Some(pid(2)))
897 .with_preferences(PaneAccessibilityPreferences::none().with_high_contrast(true));
898 assert_eq!(
899 normal_ctl.focus_ring(&theme).cell.fg,
900 PaneFocusRing::themed(&normal_aff).cell.fg
901 );
902 assert_eq!(
903 high_ctl.focus_ring(&theme).cell.fg,
904 PaneFocusRing::themed(&high_aff).cell.fg
905 );
906
907 let ratio = |c: ftui_style::color::Color| {
909 ftui_style::color::contrast_ratio(c.to_rgb(), theme.surface.to_rgb())
910 };
911 assert!(ratio(high_aff.focus_ring) + 1e-9 >= ratio(normal_aff.focus_ring));
912 }
913
914 #[test]
915 fn controller_affordance_motion_honors_reduced_motion() {
916 use ftui_layout::PaneAccessibilityPreferences;
917 let reduced = PaneKeyboardController::new(None)
918 .with_preferences(PaneAccessibilityPreferences::none().with_reduced_motion(true));
919 assert!(reduced.affordance_motion().reduced_motion);
920 let plain = PaneKeyboardController::new(None);
921 assert!(!plain.affordance_motion().reduced_motion);
922 }
923
924 #[test]
925 fn hints_cover_every_binding_family() {
926 let hints = pane_keyboard_hints();
927 assert_eq!(hints.len(), 9);
928 assert!(hints.iter().any(|h| h.action.contains("focus next")));
929 assert!(hints.iter().any(|h| h.action.contains("split")));
930 assert!(hints.iter().any(|h| h.action.contains("maximize")));
931 }
932
933 #[test]
937 fn keymap_lookup_agrees_with_binding_table() {
938 let controller = PaneKeyboardController::new(None);
939 let conflicts = controller.keymap().conflicts();
940 assert!(conflicts.is_empty(), "{conflicts:?}");
941 let specs = pane_binding_specs();
942 assert_eq!(pane_keymap().bindings().len(), specs.len());
943 for spec in specs {
944 let event = key(spec.code, spec.modifiers);
945 let expected = match spec.command {
946 PaneCommand::ResizeStep { direction, .. } => PaneCommand::ResizeStep {
947 direction,
948 units: 3,
949 },
950 other => other,
951 };
952 assert_eq!(key_to_pane_command(&event, 3), Some(expected), "{spec:?}");
953 assert_eq!(
954 resolve_pane_key(controller.keymap(), &event, 3),
955 Some(expected),
956 "{spec:?}"
957 );
958 }
959 assert_eq!(
961 key_to_pane_command(&key(KeyCode::Char('S'), Modifiers::ALT), 1),
962 Some(PaneCommand::Split(SplitAxis::Horizontal))
963 );
964 }
965
966 #[test]
969 fn hints_are_generated_from_the_binding_table() {
970 let hints = pane_keyboard_hints();
971 let mut families: Vec<(&str, &str)> = Vec::new();
972 for spec in pane_binding_specs() {
973 if !families.contains(&(spec.hint_keys, spec.hint_action)) {
974 families.push((spec.hint_keys, spec.hint_action));
975 }
976 }
977 let generated: Vec<(&str, &str)> = hints.iter().map(|h| (h.keys, h.action)).collect();
978 assert_eq!(generated, families);
979 assert_eq!(hints[0].keys, "Tab / Shift+Tab");
980 assert_eq!(hints[hints.len() - 1].action, "maximize / restore pane");
981 for binding in pane_keymap().bindings() {
982 let label = binding
983 .label
984 .as_deref()
985 .expect("every pane binding is labelled");
986 assert!(hints.iter().any(|h| h.action == label), "{label}");
987 }
988 }
989
990 #[test]
992 fn controller_with_custom_keymap() {
993 let mut map = KeyMap::new();
994 map.bind(
995 Chord::single(KeyCombo::new(KeyCode::Char('n'), Modifiers::CTRL)),
996 PaneCommand::FocusNext,
997 );
998 let mut controller = PaneKeyboardController::new(Some(pid(1))).with_keymap(map);
999 let mut tree = nested();
1000 let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
1001 assert_eq!(
1002 controller.handle_key(&key(KeyCode::Tab, Modifiers::NONE), &mut tree, &layout),
1003 PaneKeyOutcome::Unbound,
1004 "Tab is not bound in the custom map"
1005 );
1006 assert!(matches!(
1007 controller.handle_key(
1008 &key(KeyCode::Char('n'), Modifiers::CTRL),
1009 &mut tree,
1010 &layout
1011 ),
1012 PaneKeyOutcome::Handled {
1013 command: PaneCommand::FocusNext,
1014 ..
1015 }
1016 ));
1017 }
1018
1019 #[test]
1020 fn controller_surfaces_announcements() {
1021 let mut tree = nested();
1022 let mut controller = PaneKeyboardController::new(Some(pid(2)));
1023 let layout = tree.solve_layout(Rect::new(0, 0, 80, 24)).expect("solves");
1024 controller.handle_key(&key(KeyCode::Tab, Modifiers::NONE), &mut tree, &layout);
1026 let spoken = controller.take_announcement().expect("focus announces");
1027 assert_eq!(spoken.text, "Focused pane right_top");
1028 assert!(controller.take_announcement().is_none());
1030 }
1031}