Skip to main content

ftui_runtime/
pane_keymap.rs

1//! Terminal keyboard bindings for the pane workspace (bd-21pbi.2).
2//!
3//! This is the terminal host's binding layer over the canonical, host-agnostic
4//! command model in `ftui_layout::pane_command` (bd-21pbi.1). It provides:
5//!
6//! - [`key_to_pane_command`]: the default terminal keymap, mapping raw
7//!   `KeyEvent`s to canonical [`PaneCommand`]s. It binds only modifier-qualified
8//!   keys (and `Tab`/`BackTab`) so it coexists with application shortcuts and
9//!   never steals unrelated plain keys.
10//! - [`PaneKeyboardController`]: a reusable host helper that translates a key,
11//!   resolves it against a live `PaneTree`, applies any structural operations,
12//!   and tracks focus/maximize state — so pointer-free pane workflows are fully
13//!   operable from a few lines of host glue.
14//! - [`render_pane_focus_ring`]: a stable focus indicator (a distinct border on
15//!   the active pane), generic over the render target so it works with both a
16//!   `Frame` and a bare `Buffer`.
17//! - [`pane_keyboard_hints`]: discoverable shortcut hints for a help panel.
18//!
19//! The keymap is the terminal half of the cross-host parity guarantee: it emits
20//! the same `PaneCommand` stream a conformant web binding (bd-21pbi.3) would for
21//! equivalent intent, so both hosts reach identical pane state.
22
23use 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/// Translate a raw terminal key event into a canonical [`PaneCommand`].
38///
39/// Returns `None` for key release events and for any key not in the default
40/// pane keymap (so the host passes those through to the application). The
41/// keymap is intentionally modifier-qualified to avoid stealing plain keys:
42///
43/// | Key | Command |
44/// |-----|---------|
45/// | `Tab` / `Shift+Tab` | `FocusNext` / `FocusPrevious` |
46/// | `Ctrl+Arrow` | `FocusDirectional` |
47/// | `Ctrl+Shift+Arrow` | `FocusEdge` |
48/// | `Alt+Arrow` | `MovePane` |
49/// | `Alt++` / `Alt+-` | `ResizeStep` grow / shrink |
50/// | `Alt+s` / `Alt+v` | `Split` horizontal / vertical |
51/// | `Alt+w` | `Close` |
52/// | `Alt+[` / `Alt+]` | `SwapPane` previous / next |
53/// | `Alt+z` / `Alt+r` | `Maximize` / `Restore` |
54///
55/// `resize_units` is the snap-step count for `ResizeStep` (computed by the
56/// caller via [`PaneCommandAcceleration`]); it is ignored for other commands.
57///
58/// The bindings live in a [`KeyMap`] built from one table
59/// ([`pane_keymap`]); this resolves `key` against the shared default map.
60/// Modifiers match exactly (an unexpected Super or Ctrl leaves the key to
61/// the application), and a release never produces a command.
62#[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/// One row of the pane binding table: the key, the command it produces
68/// (`ResizeStep` carries `units: 1` as a template; resolution substitutes
69/// the accelerated unit count), and the help-panel family it belongs to.
70#[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
79/// The pane binding table, in help-panel display order. It is the single
80/// source for the [`KeyMap`] the controller consults and for
81/// [`pane_keyboard_hints`], so behaviour and hints cannot drift. Letter
82/// bindings appear with and without Shift because terminals report `Alt+S`
83/// either way, and `Alt+=` / `Alt+_` stand in for `Alt++` / `Alt+-` on
84/// keyboards where the sign needs Shift.
85fn 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/// The pane [`KeyMap`]: every row of the binding table bound at
229/// [`Priority::Global`] with no context and labelled with its help-panel
230/// action. Hosts that merge pane bindings into an application map start
231/// from this; [`PaneKeyboardController`] owns its own copy.
232#[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
252/// Resolve `key` against `map`: the bound command with `ResizeStep` units
253/// replaced by `resize_units`; `None` for releases and unbound keys.
254fn 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/// Outcome of feeding one key event to a [`PaneKeyboardController`].
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub enum PaneKeyOutcome {
276    /// The key is not a pane binding; the host should handle it normally.
277    Unbound,
278    /// The command was resolved (and any structural operations applied).
279    Handled {
280        /// The command the key mapped to.
281        command: PaneCommand,
282        /// The full resolution (effect + resulting focus state).
283        resolution: PaneCommandResolution,
284    },
285    /// The command resolved to structural operations but one failed to apply
286    /// (e.g. an invalid topology); focus state is left unchanged.
287    Failed {
288        /// The command that failed.
289        command: PaneCommand,
290    },
291}
292
293/// A reusable terminal pane keyboard host: translates keys to commands,
294/// resolves them against a live tree, applies structural operations, and tracks
295/// focus + maximize state. Hosts own the `PaneTree`; this owns the focus state
296/// and a monotonic operation counter.
297#[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    /// Create a controller focused on `active` (or unfocused if `None`),
310    /// bound to the default pane [`KeyMap`] ([`pane_keymap`]).
311    #[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    /// The [`KeyMap`] `handle_key` resolves keys against.
328    #[must_use]
329    pub fn keymap(&self) -> &KeyMap<PaneCommand> {
330        &self.keymap
331    }
332
333    /// Replace the key map (e.g. an application map that merged
334    /// [`pane_keymap`] with its own bindings). Only bindings whose action
335    /// is a [`PaneCommand`] can be expressed here; `ResizeStep` units are
336    /// substituted at resolution time.
337    #[must_use]
338    pub fn with_keymap(mut self, keymap: KeyMap<PaneCommand>) -> Self {
339        self.keymap = keymap;
340        self
341    }
342
343    /// Take the pending accessibility announcement (for a status line / screen
344    /// reader), coalesced and de-duplicated. Call once per render.
345    pub fn take_announcement(&mut self) -> Option<PaneAnnouncement> {
346        self.announcer.take()
347    }
348
349    /// Peek the pending accessibility announcement without consuming it.
350    #[must_use]
351    pub fn pending_announcement(&self) -> Option<&PaneAnnouncement> {
352        self.announcer.pending()
353    }
354
355    /// Override the resize acceleration policy.
356    #[must_use]
357    pub const fn with_acceleration(mut self, acceleration: PaneCommandAcceleration) -> Self {
358        self.acceleration = acceleration;
359        self
360    }
361
362    /// Set the accessibility preferences (reduced-motion / high-contrast /
363    /// large-target) at construction time (bd-21pbi.5).
364    #[must_use]
365    pub const fn with_preferences(mut self, preferences: PaneAccessibilityPreferences) -> Self {
366        self.preferences = preferences;
367        self
368    }
369
370    /// Update the accessibility preferences at runtime (e.g. when the user
371    /// toggles a mode). Never affects focus/command semantics — only the
372    /// presentation helpers below.
373    pub const fn set_preferences(&mut self, preferences: PaneAccessibilityPreferences) {
374        self.preferences = preferences;
375    }
376
377    /// The active accessibility preferences.
378    #[must_use]
379    pub const fn preferences(&self) -> PaneAccessibilityPreferences {
380        self.preferences
381    }
382
383    /// The affordance micro-animation policy implied by the current
384    /// preferences (motion is stepped under reduced-motion).
385    #[must_use]
386    pub fn affordance_motion(&self) -> PaneAffordanceMotion {
387        self.preferences.affordance_motion()
388    }
389
390    /// Build a focus ring for the active pane from `theme`, honoring the
391    /// high-contrast preference. The ring color is contrast-clamped against the
392    /// pane surface (AAA when high-contrast is on, AA otherwise).
393    #[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    /// The current focus context (active + maximized pane).
400    #[must_use]
401    pub const fn focus(&self) -> PaneFocusContext {
402        self.focus
403    }
404
405    /// The currently active (focused) pane.
406    #[must_use]
407    pub const fn active(&self) -> Option<PaneId> {
408        self.focus.active
409    }
410
411    /// The currently maximized pane, if any.
412    #[must_use]
413    pub const fn maximized(&self) -> Option<PaneId> {
414        self.focus.maximized
415    }
416
417    /// Set the active pane (e.g. when a pointer click changes focus).
418    pub const fn set_active(&mut self, active: Option<PaneId>) {
419        self.focus.active = active;
420    }
421
422    /// Translate, resolve, and apply one key event. Structural commands mutate
423    /// `tree`; focus/maximize commands update internal state. The `layout` must
424    /// be the solved layout of `tree` (used for spatial focus + move).
425    pub fn handle_key(
426        &mut self,
427        key: &KeyEvent,
428        tree: &mut PaneTree,
429        layout: &PaneLayout,
430    ) -> PaneKeyOutcome {
431        // Sustained key repeat accelerates resize stepping.
432        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/// A stable focus indicator: a distinct border drawn around the active pane.
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub struct PaneFocusRing {
466    /// Border glyph set (default: double-line, visually distinct from pane
467    /// content borders).
468    pub border: BorderChars,
469    /// Cell whose fg/bg/attrs style the border glyphs.
470    pub cell: Cell,
471}
472
473impl Default for PaneFocusRing {
474    fn default() -> Self {
475        Self {
476            border: BorderChars::DOUBLE,
477            // Gold border: high-contrast and stable across themes. Used when no
478            // theme is wired in; prefer [`PaneFocusRing::themed`] when a theme is
479            // available so the ring respects palette + high-contrast preferences.
480            cell: Cell::from_char(' ').with_fg(PackedRgba::rgb(0xFF, 0xD7, 0x00)),
481        }
482    }
483}
484
485impl PaneFocusRing {
486    /// Build a focus ring whose color is the theme's contrast-guaranteed pane
487    /// focus-ring affordance (bd-3bfbp).
488    ///
489    /// The supplied [`PaneAffordanceTheme`] has already been contrast-clamped
490    /// against the pane surface (AA by default, AAA when built in the
491    /// high-contrast profile), so the ring stays visible across every theme
492    /// without per-call tuning.
493    #[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
503/// Draw a focus ring around `rect` on any render target (`Frame` or `Buffer`).
504///
505/// Visually stable: it draws a deterministic border and never depends on
506/// animation or timing, so the active pane is unambiguous after any command.
507pub 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/// One discoverable keyboard hint for a help panel.
512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
513pub struct PaneKeyHint {
514    /// Human-readable key combination, e.g. `"Ctrl+Arrows"`.
515    pub keys: &'static str,
516    /// What the binding does.
517    pub action: &'static str,
518}
519
520/// The canonical, discoverable pane keyboard shortcut hints, in display
521/// order: one entry per binding family, generated from the same table the
522/// [`KeyMap`] is built from, so a binding cannot exist without its hint or
523/// vice versa.
524#[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    /// Horizontal root: left(2) | vertical(top(4)/bottom(5)). Focus order [2,4,5].
565    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        // Plain letters and plain arrows are left for the application.
670        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        // Ctrl+C (common app binding) is not a pane command.
679        assert_eq!(
680            key_to_pane_command(&key(KeyCode::Char('c'), Modifiers::CTRL), 1),
681            None
682        );
683        // Release events are ignored.
684        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        // A keyboard-only session: focus, split, focus by direction, close,
692        // maximize/restore — no pointer events at all.
693        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            // Tab -> focus next (2 -> 4).
701            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            // Ctrl+Down -> focus bottom (4 -> 5).
708            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            // Alt+s -> split the active leaf (structural; tree grows).
713            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            // Alt+z then Alt+r -> maximize then restore.
719            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        // Active pane must now be a surviving leaf, not the closed one.
755        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        // Make left(2) the active pane so its enclosing split is the root.
779        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        // Drive enough repeats to cross the acceleration threshold (default 3).
784        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        // Double-line top-left corner glyph.
809        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        // The ring's fg must equal the theme's contrast-clamped focus-ring color,
826        // not the hardcoded gold default.
827        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        // Glyph set is unchanged (still the distinct double-line border).
831        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        // Identical key stream, two controllers: one with no a11y modes, one with
850        // all of them. Focus/maximize/topology and announcements must be byte
851        // identical — a11y modes are presentation-only.
852        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        // The controller wires its high-contrast preference straight into the
894        // themed ring: each ring's color matches the affordance for its profile.
895        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        // And high contrast is never less visible than the default profile.
908        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    /// The controller's map, the free function and the binding table agree:
934    /// every row resolves to its command through both paths (with the
935    /// accelerated resize units substituted), and the map has no conflicts.
936    #[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        // Shifted letters resolve the same as unshifted ones.
960        assert_eq!(
961            key_to_pane_command(&key(KeyCode::Char('S'), Modifiers::ALT), 1),
962            Some(PaneCommand::Split(SplitAxis::Horizontal))
963        );
964    }
965
966    /// The hints are the binding table's families in table order, and every
967    /// binding label is one of the hint actions.
968    #[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    /// A host-supplied map replaces the default bindings.
991    #[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        // Tab -> focus next (2 -> 4) announces the newly focused pane.
1025        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        // Nothing pending after taking.
1029        assert!(controller.take_announcement().is_none());
1030    }
1031}