Show modifier layers and action labels in the TUI shortcut guide (#65112)

## Why

The keyboard view only highlighted unmodified shortcuts, so users had to
switch to the list to find modified bindings or see what a highlighted
key did.

## What changed

- Let users cycle through modifier combinations from the active bindings
  with a free key shown in the guide header. Leave existing bindings
  available.
- Label keys with their actions and show the full binding for two-key
  chords beside the first key.
- Try a compact keyboard when the roomy layout does not fit, then fall
  back to the shortcut list while keeping modifier navigation available.

## Testing

Add snapshots and assertions for Ctrl and Shift layers, remapped chords,
layout fallback, and keyboard help above the prompt in an 80×24 terminal.

GitOrigin-RevId: 0b37579c145fa5176ab83de392d9eb4905d06b81
This commit is contained in:
Benjamin Carlsson
2026-12-01 23:59:56 +00:00
committed by copyberry
parent a1deffb5b2
commit 98e240bbf7
15 changed files with 589 additions and 151 deletions
@@ -4,21 +4,21 @@ expression: normalize_snapshot_paths(buffer_text(buffer))
---
Keyboard shortcuts Base · Tab: List
Keyboard shortcuts Modifiers: None · F1: Change · Tab: List
┌──────────────────────────────────────────────────────────────────────┐
│ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │
│ │
│ │ Find text ──┘ └── Inspect activity │
│ └── Edit last message (esc esc) │
├──────────────────────────────────────────────────────────────────────┤
│ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │
│ │
│ Transcript page up ──┘ │
│ Tab Q W E R T Y U I O P [ ] \ Del End PgD │
│ │
│ └── Send message Transcript page down ──┘ │
│ Caps A S D F G H J K L ; ' Enter │
│ │
│ Shift Z X C V B N M , . / Shift ↑ │
│ │
│ └── Commands │
│ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │
│ │
└──────────────────────────────────────────────────────────────────────┘
/keymap customize
@@ -311,7 +311,10 @@ impl super::ChatComposer {
) -> u16 {
let guide_width = width.saturating_sub(crate::ui_consts::FOOTER_INDENT_COLS as u16);
if self.shortcuts_above_composer(options)
&& self.footer_mode() == FooterMode::ShortcutOverlay(ShortcutView::Keyboard)
&& matches!(
self.footer_mode(),
FooterMode::ShortcutOverlay(ShortcutView::Keyboard(_))
)
&& shortcut_overlay::keyboard_fits_width(guide_width)
{
// A keyboard diagram needs all its rows. The conversation viewport still bounds it.
@@ -0,0 +1,36 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: text
---
Keyboard shortcuts Modifiers: None · F1: Change · Tab: List
┌──────────────────────────────────────────────────────────────────────┐
│ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │
│ │ Find text ──┘ └── Inspect activity │
│ └── Edit last message (esc esc) │
├──────────────────────────────────────────────────────────────────────┤
│ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │
│ Transcript page up ──┘ │
│ Tab Q W E R T Y U I O P [ ] \ Del End PgD │
│ └── Send message Transcript page down ──┘ │
│ Caps A S D F G H J K L ; ' Enter │
│ │
│ Shift Z X C V B N M , . / Shift ↑ │
│ └── Commands │
│ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │
└──────────────────────────────────────────────────────────────────────┘
/keymap customize
› Ask Codex
MODEL · ~/project · Context 20% used
? / esc close
@@ -914,12 +914,15 @@ fn oversized_goal_yields_to_an_eligible_whole_hint_with_status_disabled() {
fn shortcut_help_stays_above_the_prompt_and_bottom_status() {
let mut composer = composer();
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
for (width, height, snapshot) in [
(130, None, Some("shortcut_help_above_wide")),
(80, None, None),
(40, None, Some("shortcut_help_above_narrow")),
(80, Some(12), None),
for (width, height, extra_prompt_rows, snapshot) in [
(130, None, 0, Some("shortcut_help_above_wide")),
(40, None, 0, Some("shortcut_help_above_narrow")),
(80, Some(24), 2, Some("shortcut_help_above_80x24")),
(80, Some(12), 0, None),
] {
if height == Some(24) {
assert!(composer.handle_shortcut_view_key(KeyCode::Tab.into()));
}
let (text, cursor) = render_with_height(&composer, width, /*footer*/ None, height);
let rows: Vec<_> = text.lines().collect();
let help_row = rows
@@ -949,7 +952,7 @@ fn shortcut_help_stays_above_the_prompt_and_bottom_status() {
Some((2, prompt_row as u16))
),
);
assert_eq!(prompt_row + 3, rows.len() - 1);
assert_eq!(prompt_row + 3 + extra_prompt_rows, rows.len() - 1);
if let Some(name) = snapshot {
insta::assert_snapshot!(name, text);
}
+206 -72
View File
@@ -1,7 +1,7 @@
//! A shortcut guide built from runtime bindings. It opens as a grouped action list.
//! The optional tenkeyless keyboard highlights keys with unmodified bindings.
//! Keys outside the diagram remain available in the list. If space is too small,
//! the guide shows the full action list.
//! The optional tenkeyless keyboard highlights a modifier layer with action callouts.
//! Keys outside the diagram remain available in the list. If the keyboard cannot
//! be drawn, the guide shows the full action list.
mod keyboard;
@@ -24,20 +24,21 @@ use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use crossterm::event::ModifierKeyCode;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Styled;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use std::collections::HashSet;
use std::collections::HashMap;
/// The view switch takes the first free key.
/// The view switch takes the first free key. Layer browsing uses the next one.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ShortcutGuideKeys {
view: Option<KeyCode>,
layer: Option<KeyCode>,
}
impl ShortcutGuideKeys {
@@ -45,10 +46,10 @@ impl ShortcutGuideKeys {
let conflicts = |context: KeymapContext| {
context == KeymapContext::Pager || context.overlaps(KeymapContext::Composer)
};
let view =
let mut free =
std::iter::once(KeyCode::Tab)
.chain((1..=12).map(KeyCode::F))
.find(|&code| {
.filter(|&code| {
let key = key_hint::plain(code);
// The guide opens on an empty draft, so queue has nothing to send.
!crate::keymap::keymap_action_ids().any(|id| {
@@ -60,7 +61,10 @@ impl ShortcutGuideKeys {
conflicts(binding.action.context) && binding.chord.prefix == key
})
});
Self { view }
Self {
view: free.next(),
layer: free.next(),
}
}
}
@@ -68,24 +72,82 @@ impl ShortcutGuideKeys {
pub(crate) enum ShortcutView {
#[default]
List,
Keyboard,
Keyboard(ModifierLayers),
}
impl ShortcutView {
pub(super) fn handle_key(&mut self, event: KeyEvent, props: &FooterProps) -> bool {
if !props
if props
.key_hints
.shortcut_guide
.view
.is_some_and(|key| key_hint::plain(key).is_press(event))
{
if event.kind == KeyEventKind::Press {
*self = match self {
Self::List => Self::Keyboard(ModifierLayers::default()),
Self::Keyboard(_) => Self::List,
};
}
return true;
}
match self {
Self::List => false,
Self::Keyboard(layers) => layers.handle_key(event, props),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ModifierLayers {
selected: KeyModifiers,
}
impl Default for ModifierLayers {
fn default() -> Self {
Self {
selected: KeyModifiers::NONE,
}
}
}
impl ModifierLayers {
fn active(self) -> KeyModifiers {
self.selected
}
fn lights(self, key: ModifierKeyCode) -> bool {
use KeyModifiers as M;
use ModifierKeyCode::*;
self.selected.contains(match key {
LeftShift | RightShift => M::SHIFT,
LeftControl | RightControl => M::CONTROL,
LeftAlt | RightAlt => M::ALT,
LeftSuper | RightSuper => M::SUPER,
LeftHyper | RightHyper => M::HYPER,
LeftMeta | RightMeta => M::META,
IsoLevel3Shift | IsoLevel5Shift => return false,
})
}
pub(super) fn handle_key(&mut self, event: KeyEvent, props: &FooterProps) -> bool {
if !props
.key_hints
.shortcut_guide
.layer
.is_some_and(|key| key_hint::plain(key).is_press(event))
{
return false;
}
if event.kind == KeyEventKind::Press {
*self = match self {
Self::List => Self::Keyboard,
Self::Keyboard => Self::List,
};
self.selected = bindings(props)
.into_iter()
.flat_map(|(_, entries)| entries)
.flat_map(|entry| entry.keys.into_iter().flatten())
.map(|key| key_position(key).1)
.filter(|layer| layer.bits() > self.selected.bits())
.min_by_key(KeyModifiers::bits)
.unwrap_or(KeyModifiers::NONE);
}
true
}
@@ -94,7 +156,7 @@ impl ShortcutView {
struct Entry {
keys: [Option<ShortcutHint>; 2],
action: &'static str,
repeat_label: bool,
callouts: [&'static str; 2],
}
impl Entry {
@@ -102,7 +164,7 @@ impl Entry {
Self {
keys: [key, None],
action,
repeat_label: false,
callouts: [action; 2],
}
}
@@ -110,11 +172,11 @@ impl Entry {
Self::hint(Some(key.into()), action)
}
fn pair(action: &'static str, keys: [KeyBinding; 2]) -> Self {
fn pair(action: &'static str, keys: [(KeyBinding, &'static str); 2]) -> Self {
Self {
keys: keys.map(|key| Some(key.into())),
keys: keys.map(|(key, _)| Some(key.into())),
action,
repeat_label: false,
callouts: keys.map(|(_, callout)| callout),
}
}
}
@@ -127,6 +189,13 @@ fn bindings(props: &FooterProps) -> [(&'static str, Vec<Entry>); 3] {
} else {
key_hint::ctrl(K::Char('v'))
};
let edit_previous = match hints.edit_previous {
Some(ShortcutHint::Single(key)) if !props.esc_backtrack_hint => Some(ShortcutHint::Chord {
prefix: key,
completion: key,
}),
hint => hint,
};
let compose = vec![
Entry::key(key_hint::plain(K::Char('/')), "Commands"),
Entry::key(key_hint::plain(K::Char('@')), "Mention files"),
@@ -135,11 +204,7 @@ fn bindings(props: &FooterProps) -> [(&'static str, Vec<Entry>); 3] {
Entry::key(paste, "Paste image"),
Entry::hint(hints.external_editor, "External editor"),
Entry::hint(hints.history_search, "Search history"),
Entry {
keys: [hints.edit_previous, None],
action: "Edit last message",
repeat_label: !props.esc_backtrack_hint,
},
Entry::hint(edit_previous, "Edit last message"),
];
let session = vec![
@@ -163,7 +228,10 @@ fn bindings(props: &FooterProps) -> [(&'static str, Vec<Entry>); 3] {
Entry::hint(hints.agents, "Agents (empty prompt)"),
Entry::pair(
"Subagents (empty prompt)",
[previous_agent_shortcut(), next_agent_shortcut()],
[
(previous_agent_shortcut(), "Previous subagent"),
(next_agent_shortcut(), "Next subagent"),
],
),
Entry::hint(hints.focus_activity, "Inspect activity"),
Entry::key(
@@ -182,19 +250,31 @@ fn bindings(props: &FooterProps) -> [(&'static str, Vec<Entry>); 3] {
Entry::hint(hints.find_transcript, "Find text"),
Entry::pair(
"Scroll",
[key_hint::plain(K::PageUp), key_hint::plain(K::PageDown)],
[
(key_hint::plain(K::PageUp), "Transcript page up"),
(key_hint::plain(K::PageDown), "Transcript page down"),
],
),
Entry::key(key_hint::ctrl(K::Char(' ')), "Start selection"),
Entry::pair(
"Top / latest",
[key_hint::ctrl(K::Home), key_hint::ctrl(K::End)],
[
(key_hint::ctrl(K::Home), "Top of transcript"),
(key_hint::ctrl(K::End), "Latest in transcript"),
],
),
// Keep both jump alternatives: the terminal may be on another OS over SSH.
Entry::pair(
"Top / latest",
[
KeyBinding::new(K::Char(','), alt_shift),
KeyBinding::new(K::Char('.'), alt_shift),
(
KeyBinding::new(K::Char(','), alt_shift),
"Top of transcript",
),
(
KeyBinding::new(K::Char('.'), alt_shift),
"Latest in transcript",
),
],
),
];
@@ -206,12 +286,18 @@ fn bindings(props: &FooterProps) -> [(&'static str, Vec<Entry>); 3] {
]
}
// Map runtime shortcuts to US QWERTY key positions. Chords use their prefix.
// The visual layout uses US QWERTY positions. Bindings with two strokes attach
// to the prefix, and the action callout shows the complete chord.
fn key_position(hint: ShortcutHint) -> (KeyCode, KeyModifiers) {
let binding = match hint {
ShortcutHint::Single(key) | ShortcutHint::Chord { prefix: key, .. } => key,
};
let (code, modifiers) = binding.parts();
// Input matching aliases Ctrl+5 to Ctrl+], but the diagram points to the
// configured key.
if (code, modifiers) == (KeyCode::Char('5'), KeyModifiers::CONTROL) {
return (code, modifiers);
}
let (code, modifiers) = key_hint::normalize_key_parts(code, modifiers);
match code {
KeyCode::BackTab => (KeyCode::Tab, modifiers | KeyModifiers::SHIFT),
@@ -235,40 +321,95 @@ fn guide_lines(props: &FooterProps, width: u16, height: usize) -> Vec<Line<'stat
return Vec::new();
};
let width_usize = usize::from(width.max(1));
let heading = Line::from("Keyboard shortcuts".bold());
let mut heading = Line::from("Keyboard shortcuts".bold());
let footer = footer_lines(width_usize);
let groups = bindings(props);
let keys = props.key_hints.shortcut_guide;
if view == ShortcutView::Keyboard && keyboard_fits_width(width) {
let mut actions: HashSet<_> = groups
.iter()
.flat_map(|(_, entries)| entries)
.flat_map(|entry| entry.keys.into_iter().flatten())
.map(key_position)
.filter_map(|(code, modifiers)| modifiers.is_empty().then_some(code))
.collect();
let empty = actions.is_empty();
let diagram = keyboard::lines(&mut actions, width);
let mut title = heading.clone();
title.extend([Span::raw(" "), "Base".fg(accent_color())]);
if !actions.is_empty() {
title.push_span(" · More keys in list".set_style(secondary_text_style()));
}
title.extend(
keys.view
.map(|key| format!(" · {key}: List").set_style(secondary_text_style())),
if let ShortcutView::Keyboard(layers) = view {
let layer = layers.active();
let layer_label = if layer.is_empty() {
"None".into()
} else {
[
("Shift", KeyModifiers::SHIFT),
("Ctrl", KeyModifiers::CONTROL),
("Alt", KeyModifiers::ALT),
("Super", KeyModifiers::SUPER),
("Hyper", KeyModifiers::HYPER),
("Meta", KeyModifiers::META),
]
.into_iter()
.filter_map(|(label, modifier)| layer.contains(modifier).then_some(label))
.collect::<Vec<_>>()
.join("+")
};
heading.extend([" Modifiers: ".into(), layer_label.fg(accent_color())]);
heading.extend(
keys.layer
.map(|key| format!(" · {key}: Change").set_style(secondary_text_style())),
);
let mut result = word_wrap_lines([title], width_usize);
result.extend(diagram);
if empty {
result.push(Line::from(
"No shortcuts in this layer".set_style(secondary_text_style()),
));
}
if let ShortcutView::Keyboard(layers) = view
&& keyboard_fits_width(width)
{
let layer = layers.active();
let mut actions = HashMap::<KeyCode, String>::new();
for entry in groups.iter().flat_map(|(_, entries)| entries) {
for (hint, action) in entry.keys.into_iter().zip(entry.callouts) {
let Some(hint) = hint else { continue };
let (code, modifiers) = key_position(hint);
if modifiers != layer {
continue;
}
let action = match hint {
ShortcutHint::Single(_) => action.to_owned(),
ShortcutHint::Chord { .. } => format!("{action} ({})", hint.display_label()),
};
actions
.entry(code)
.and_modify(|label| {
label.push_str(" / ");
label.push_str(&action);
})
.or_insert(action);
}
}
if result.len() + footer.len() <= height {
result.extend(footer);
return result;
let empty = actions.is_empty();
let geometry = keyboard::Geometry::for_width(width);
let geometries = [
Some(geometry),
matches!(geometry, keyboard::Geometry::Roomy).then_some(keyboard::Geometry::Compact),
];
for geometry in geometries.into_iter().flatten() {
let mut actions = actions.clone();
let Some(diagram) = keyboard::lines(&mut actions, layers, geometry) else {
continue;
};
let mut title = heading.clone();
title.extend(keys.view.map(|key| {
let extra = if actions.is_empty() {
""
} else {
" (more keys)"
};
format!(" · {key}: List{extra}").set_style(secondary_text_style())
}));
if !actions.is_empty() && keys.view.is_none() {
title.push_span(" · More keys in list".set_style(secondary_text_style()));
}
let mut result = word_wrap_lines([title], width_usize);
result.extend(diagram);
if empty {
result.push(Line::from(
"No shortcuts in this layer".set_style(secondary_text_style()),
));
}
if result.len() + footer.len() <= height {
result.extend(footer);
return result;
}
}
}
@@ -276,27 +417,20 @@ fn guide_lines(props: &FooterProps, width: u16, height: usize) -> Vec<Line<'stat
let entries = entries
.into_iter()
.filter_map(|entry| {
let mut keys = entry
let keys = entry
.keys
.into_iter()
.flatten()
.map(ShortcutHint::display_label);
let key = keys.next()?;
Some(Shortcut {
key: if entry.repeat_label {
format!("{key} {key}")
} else if let Some(alternative) = keys.next() {
format!("{key} / {alternative}")
} else {
key
},
.map(ShortcutHint::display_label)
.collect::<Vec<_>>();
(!keys.is_empty()).then(|| Shortcut {
key: keys.join(" / "),
action: entry.action,
})
})
.collect();
Group { title, entries }
});
let mut heading = heading;
match view {
ShortcutView::List if keyboard_fits_width(width) => {
heading.extend(
@@ -304,7 +438,7 @@ fn guide_lines(props: &FooterProps, width: u16, height: usize) -> Vec<Line<'stat
.map(|key| format!(" · {key}: Keyboard").set_style(secondary_text_style())),
);
}
ShortcutView::Keyboard => {
ShortcutView::Keyboard(_) => {
heading.push_span(" · Keyboard unavailable".set_style(secondary_text_style()));
heading.extend(
keys.view
@@ -1,7 +1,11 @@
//! Draws a US QWERTY tenkeyless keyboard with highlighted shortcut keys.
//! Draws a US QWERTY tenkeyless keyboard and routes box-drawing leaders from the
//! rendered key faces to their actions. Leaders reserve each other's columns
//! so adjacent shortcuts can share a row without crossing.
use super::ModifierLayers;
use crate::color::blend;
use crate::color::is_light;
use crate::style::accent_color_on;
use crate::style::readable_color_on;
use crate::style::selection_style;
use crate::terminal_palette::best_color;
@@ -9,12 +13,15 @@ use crate::terminal_palette::default_bg;
use crate::terminal_palette::default_fg;
use crate::terminal_palette::rgb_color;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use crossterm::event::ModifierKeyCode::*;
use ratatui::style::Color;
use ratatui::style::Style;
use ratatui::style::Styled;
use ratatui::style::Stylize;
use ratatui::text::Line;
use std::collections::HashSet;
use ratatui::text::Span;
use std::collections::HashMap;
const ROWS: usize = 6;
const NAV_START: usize = 52;
@@ -23,13 +30,13 @@ pub(super) const WIDTH: u16 = INNER_WIDTH as u16 + 4;
const ROOMY_WIDTH: u16 = 92;
#[derive(Clone, Copy)]
enum Geometry {
pub(super) enum Geometry {
Compact,
Roomy,
}
impl Geometry {
fn for_width(width: u16) -> Self {
pub(super) fn for_width(width: u16) -> Self {
if width >= ROOMY_WIDTH {
Self::Roomy
} else {
@@ -130,14 +137,24 @@ fn keyboard_styles() -> [Style; 4] {
};
[panel, border, cap, bound]
}
#[derive(Default)]
struct Row {
faces: Line<'static>,
labels: Vec<(usize, String)>,
}
fn cap(
row: &mut Line<'static>,
row: &mut Row,
Cap(code, label, width): Cap<'_>,
actions: &mut HashSet<KeyCode>,
actions: &mut HashMap<KeyCode, String>,
layers: ModifierLayers,
styles: &[Style; 4],
geometry: Geometry,
) {
let style = if actions.remove(&code) {
let action = actions.remove(&code);
let pressed = matches!(code, KeyCode::Modifier(key) if layers.lights(key));
let style = if pressed || action.is_some() {
styles[3]
} else {
styles[2]
@@ -152,8 +169,14 @@ fn cap(
},
};
let face_width = width - 1;
row.push_span(format!("{label:^face_width$}").set_style(style));
row.push_span(" ");
if let Some(action) = action {
let label_width = label.chars().count();
let anchor = row.faces.width() + (face_width - label_width) / 2 + label_width / 2;
row.labels.push((anchor, action));
}
row.faces
.push_span(format!("{label:^face_width$}").set_style(style));
row.faces.push_span(" ");
}
fn framed(content: Line<'static>, panel: Style, frame: Style, geometry: Geometry) -> Line<'static> {
@@ -165,15 +188,74 @@ fn framed(content: Line<'static>, panel: Style, frame: Style, geometry: Geometry
line
}
fn leaders(
mut pending: Vec<(usize, String)>,
panel: Style,
frame: Style,
geometry: Geometry,
) -> Option<Vec<Line<'static>>> {
let inner_width = geometry.inner_width();
let accent = accent_color_on(panel.bg);
let mut lines = Vec::new();
while !pending.is_empty() {
// Anchors are in keycap order. Leave a cell between each label and
// its neighbors, including the stems of labels deferred to the next row.
let count = pending.len();
let mut anchors = pending.into_iter().peekable();
let mut remaining = Vec::new();
let mut lane = Line::default();
while let Some((anchor, label)) = anchors.next() {
let width = Span::raw(&label).width() + 4;
let previous_end = lane.width();
let start = [Some(anchor), anchor.checked_sub(width - 1)]
.into_iter()
.flatten()
.find(|&start| {
let end = start + width;
(previous_end == 0 || start > previous_end)
&& end <= inner_width
&& anchors.peek().is_none_or(|(next, _)| end < *next)
});
lane.push_span(" ".repeat(start.unwrap_or(anchor) - previous_end));
if let Some(start) = start {
let spans = if start == anchor {
["└── ".fg(accent), label.into()]
} else {
[label.into(), " ──┘".fg(accent)]
};
lane.extend(spans);
} else {
lane.push_span("│".fg(accent));
remaining.push((anchor, label));
}
}
if remaining.len() == count {
return None;
}
lines.push(framed(lane, panel, frame, geometry));
pending = remaining;
}
if lines.is_empty() {
lines.push(framed(Line::default(), panel, frame, geometry));
}
Some(lines)
}
// Leaves keys without a keycap in actions so the guide can point to its list.
pub(super) fn lines(actions: &mut HashSet<KeyCode>, width: u16) -> Vec<Line<'static>> {
let geometry = Geometry::for_width(width);
pub(super) fn lines(
actions: &mut HashMap<KeyCode, String>,
layers: ModifierLayers,
geometry: Geometry,
) -> Option<Vec<Line<'static>>> {
let styles = keyboard_styles();
let [panel, frame, _, _] = styles;
let rail = "─".repeat(geometry.inner_width() + 2);
let mut lines = vec![Line::from(format!("┌{rail}┐").set_style(frame))];
let shifted = layers.active().contains(KeyModifiers::SHIFT);
let mut spacers = Vec::new();
let mut extra_lanes = 0;
for index in 0..ROWS {
let mut row = Line::default();
let mut row = Row::default();
let (left, letters, right): (&[Cap<'_>], &str, &[Cap<'_>]) = match index {
0 => (&[], "", &[]),
1 => (&[], "`1234567890-=", &[Cap(KeyCode::Backspace, "Bksp", 9)]),
@@ -208,12 +290,13 @@ pub(super) fn lines(actions: &mut HashSet<KeyCode>, width: u16) -> Vec<Line<'sta
&mut row,
key(KeyCode::Esc, "Esc"),
actions,
layers,
&styles,
geometry,
);
for (first, gap) in [(1, " "), (5, " "), (9, " ")] {
if matches!(geometry, Geometry::Compact) {
row.push_span(gap);
row.faces.push_span(gap);
}
for number in first..first + 4 {
let label = format!("F{number}");
@@ -221,6 +304,7 @@ pub(super) fn lines(actions: &mut HashSet<KeyCode>, width: u16) -> Vec<Line<'sta
&mut row,
Cap(KeyCode::F(number), &label, label.len() + 1),
actions,
layers,
&styles,
geometry,
);
@@ -228,22 +312,28 @@ pub(super) fn lines(actions: &mut HashSet<KeyCode>, width: u16) -> Vec<Line<'sta
}
}
for &key in left {
cap(&mut row, key, actions, &styles, geometry);
cap(&mut row, key, actions, layers, &styles, geometry);
}
for letter in letters.chars() {
let mut label = [0; 4];
let label = letter.to_ascii_uppercase().encode_utf8(&mut label);
let legend = if shifted && let Some(index) = UNSHIFTED.find(letter) {
char::from(SHIFTED.as_bytes()[index])
} else {
letter.to_ascii_uppercase()
};
let label = legend.encode_utf8(&mut label);
let width = if letter == '\\' { 6 } else { 3 };
cap(
&mut row,
Cap(KeyCode::Char(letter), label, width),
actions,
layers,
&styles,
geometry,
);
}
for &key in right {
cap(&mut row, key, actions, &styles, geometry);
cap(&mut row, key, actions, layers, &styles, geometry);
}
let nav: &[Cap<'_>] = match index {
@@ -277,17 +367,28 @@ pub(super) fn lines(actions: &mut HashSet<KeyCode>, width: u16) -> Vec<Line<'sta
(Geometry::Roomy, 4) => geometry.nav_start() + 6,
_ => geometry.nav_start(),
};
row.push_span(" ".repeat(nav_start - row.width()));
row.faces
.push_span(" ".repeat(nav_start - row.faces.width()));
for &key in nav {
cap(&mut row, key, actions, &styles, geometry);
cap(&mut row, key, actions, layers, &styles, geometry);
}
}
lines.push(framed(row, panel, frame, geometry));
lines.push(framed(Line::default(), panel, frame, geometry));
lines.push(framed(row.faces, panel, frame, geometry));
let empty = row.labels.is_empty();
let lanes = leaders(row.labels, panel, frame, geometry)?;
extra_lanes += lanes.len().saturating_sub(1);
if empty {
spacers.push(lines.len());
}
lines.extend(lanes);
if index == 0 {
lines.push(Line::from(format!("├{rail}┤").set_style(frame)));
}
}
// Reuse otherwise empty key-row spacing when callouts need extra lanes.
for index in spacers.into_iter().rev().take(extra_lanes) {
lines.remove(index);
}
lines.push(Line::from(format!("└{rail}┘").set_style(frame)));
lines
Some(lines)
}
@@ -1,5 +1,6 @@
#![cfg(test)]
use super::ModifierLayers;
use super::ShortcutGuideKeys;
use super::ShortcutView;
use super::lines;
@@ -12,6 +13,7 @@ use crate::key_hint;
use crate::key_hint::ShortcutHint;
use crate::ui_consts::FOOTER_INDENT_COLS;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
@@ -86,10 +88,20 @@ fn shortcut_overlay_uses_runtime_bindings_and_wsl_paste() {
completion: key_hint::plain(KeyCode::Char('h')),
});
props.key_hints.insert_newline = Some(key_hint::shift(KeyCode::Enter).into());
props.key_hints.focus_activity = Some(key_hint::ctrl(KeyCode::Char('5')).into());
props.key_hints.history_search = None;
props.key_hints.reasoning_down = None;
snapshot(
"shortcut_overlay_customized_wsl",
/*width*/ 68,
/*height*/ None,
&props,
);
props.mode = FooterMode::ShortcutOverlay(ShortcutView::Keyboard(ModifierLayers {
selected: KeyModifiers::CONTROL,
}));
snapshot(
"shortcut_keyboard_remapped_chord",
/*width*/ 80,
/*height*/ None,
&props,
@@ -113,16 +125,25 @@ fn shortcut_overlay_leaves_remapped_tab_and_function_keys_available() {
let keys = props.key_hints.shortcut_guide;
assert_eq!(keys.view, Some(KeyCode::F(5)));
assert_ne!(keys.view, keys.layer);
assert!(!view.handle_key(KeyCode::Tab.into(), &props));
assert!(!view.handle_key(KeyCode::F(1).into(), &props));
assert!(!view.handle_key(keys.layer.unwrap().into(), &props));
assert!(view.handle_key(KeyCode::F(5).into(), &props));
assert_eq!(view, ShortcutView::Keyboard);
assert_eq!(view, ShortcutView::Keyboard(ModifierLayers::default()));
assert!(view.handle_key(keys.layer.unwrap().into(), &props));
assert_eq!(
view,
ShortcutView::Keyboard(ModifierLayers {
selected: KeyModifiers::SHIFT,
})
);
assert!(view.handle_key(KeyCode::F(5).into(), &props));
assert_eq!(view, ShortcutView::List);
}
#[test]
fn shortcut_overlay_draws_base_keyboard_and_falls_back_to_the_list() {
fn shortcut_overlay_keyboard_follows_selected_layer() {
let mut props = props();
let all = ratatui::text::Text::from(lines(&props, /*width*/ 80)).to_string();
assert!(
@@ -144,6 +165,33 @@ fn shortcut_overlay_draws_base_keyboard_and_falls_back_to_the_list() {
/*height*/ None,
&props,
);
for (name, selected) in [
("shortcut_keyboard_ctrl", KeyModifiers::CONTROL),
("shortcut_keyboard_shift", KeyModifiers::SHIFT),
(
"shortcut_keyboard_no_bindings",
KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::SUPER,
),
] {
props.mode =
FooterMode::ShortcutOverlay(ShortcutView::Keyboard(ModifierLayers { selected }));
snapshot(name, /*width*/ 80, /*height*/ None, &props);
}
props.mode = FooterMode::ShortcutOverlay(ShortcutView::Keyboard(ModifierLayers::default()));
for width in [91, 92] {
let rendered = super::guide_lines(&props, width, /*height*/ 18);
let text = ratatui::text::Text::from(rendered.clone()).to_string();
assert!(rendered.len() <= 18);
assert!(text.contains("Esc") && text.contains("F1: Change"));
}
assert_eq!(
super::guide_lines(&props, /*width*/ 92, /*height*/ 18),
super::guide_lines(&props, /*width*/ 91, /*height*/ 18),
);
assert_ne!(
super::guide_lines(&props, /*width*/ 92, /*height*/ usize::MAX),
super::guide_lines(&props, /*width*/ 92, /*height*/ 18),
);
for (width, height) in [(68, usize::MAX), (80, 12)] {
let fallback =
ratatui::text::Text::from(super::guide_lines(&props, width, height)).to_string();
@@ -151,10 +199,35 @@ fn shortcut_overlay_draws_base_keyboard_and_falls_back_to_the_list() {
}
}
#[test]
fn shortcut_keyboard_fallback_keeps_modifier_navigation_visible() {
let mut props = props();
let prefix = key_hint::ctrl(KeyCode::Char('8'));
props.key_hints.external_editor = Some(ShortcutHint::Chord {
prefix,
completion: key_hint::plain(KeyCode::Char('e')),
});
props.key_hints.history_search = Some(ShortcutHint::Chord {
prefix,
completion: key_hint::plain(KeyCode::Char('r')),
});
let mut view = ShortcutView::Keyboard(ModifierLayers {
selected: KeyModifiers::CONTROL,
});
props.mode = FooterMode::ShortcutOverlay(view);
let text = ratatui::text::Text::from(lines(&props, /*width*/ 78)).to_string();
assert!(text.contains("Keyboard unavailable"));
assert!(text.contains("Modifiers: Ctrl · F1: Change"));
assert!(view.handle_key(KeyCode::F(1).into(), &props));
props.mode = FooterMode::ShortcutOverlay(view);
let text = ratatui::text::Text::from(lines(&props, /*width*/ 78)).to_string();
assert!(!text.contains("Modifiers: Ctrl ·"));
}
#[test]
fn shortcut_keyboard_adapts_to_probed_and_unknown_terminal_colors() {
let mut props = props();
props.mode = FooterMode::ShortcutOverlay(ShortcutView::Keyboard);
props.mode = FooterMode::ShortcutOverlay(ShortcutView::Keyboard(ModifierLayers::default()));
for colors in [
Some(crate::terminal_probe::DefaultColors {
fg: (230, 230, 230),
@@ -2,20 +2,21 @@
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Base · Tab: List "
" Keyboard shortcuts Modifiers: None · F1: Change · Tab: List "
" ┌──────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" │ │ "
" │ │ Find text ──┘ │ └── Voice │ "
" │ │ └── Inspect activity │ "
" │ └── Edit last message (esc esc) │ "
" ├──────────────────────────────────────────────────────────────────────┤ "
" │ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │ "
" │ │ "
" │ Transcript page up ──┘ │ "
" │ Tab Q W E R T Y U I O P [ ] \ Del End PgD │ "
" │ │ "
" │ └── Queue message Transcript page down ──┘ │ "
" │ Caps A S D F G H J K L ; ' Enter │ "
" │ │ "
" │ Shift Z X C V B N M , . / Shift ↑ │ "
" │ │ "
" │ └── Commands │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" │ │ "
" │ Agents (empty prompt) ──┘ │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Modifiers: Ctrl · F1: Change · Tab: List "
" ┌──────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" ├──────────────────────────────────────────────────────────────────────┤ "
" │ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │ "
" │ Top of transcript ──┘ │ "
" │ Tab Q W E R T Y U I O P [ ] \ Del End PgD │ "
" │ │ └── Open transcript │ │ "
" │ └── Search history Latest in transcript ──┘ │ "
" │ Caps A S D F G H J K L ; ' Enter │ "
" │ External editor ──┘ └── New line │ "
" │ Shift Z X C V B N M , . / Shift ↑ │ "
" │ Interrupt ──┘ └── Paste image │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" │ └── Start selection │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -0,0 +1,22 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Modifiers: Shift+Ctrl+Super · F1: Change · Tab: List "
" ┌──────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" │ │ "
" ├──────────────────────────────────────────────────────────────────────┤ "
" │ ~ ! @ # $ % ^ & * ( ) _ + Bksp Ins Home PgU │ "
" │ │ "
" │ Tab Q W E R T Y U I O P { } | Del End PgD │ "
" │ │ "
" │ Caps A S D F G H J K L : " Enter │ "
" │ │ "
" │ Shift Z X C V B N M < > ? Shift ↑ │ "
" │ │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" │ │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" No shortcuts in this layer "
" /keymap customize "
@@ -2,20 +2,20 @@
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Base · More keys in list · Tab: List "
" Keyboard shortcuts Modifiers: None · F1: Change · Tab: List (more keys) "
" ┌──────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" │ │ "
" │ │ Find text ──┘ │ └── Voice │ "
" │ │ └── Inspect activity │ "
" │ └── Edit last message (esc esc) │ "
" ├──────────────────────────────────────────────────────────────────────┤ "
" │ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │ "
" │ │ "
" │ Transcript page up ──┘ │ "
" │ Tab Q W E R T Y U I O P [ ] \ Del End PgD │ "
" │ │ "
" │ └── Queue message Transcript page down ──┘ │ "
" │ Caps A S D F G H J K L ; ' Enter │ "
" │ │ "
" │ Shift Z X C V B N M , . / Shift ↑ │ "
" │ │ "
" │ └── Commands │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" │ │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Modifiers: Ctrl · F1: Change · Tab: List "
" ┌──────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" ├──────────────────────────────────────────────────────────────────────┤ "
" │ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │ "
" │ └── Inspect activity Top of transcript ──┘ │ "
" │ Tab Q W E R T Y U I O P [ ] \ Del End PgD │ "
" │ └── Open transcript │ │ "
" │ Latest in transcript ──┘ │ "
" │ Caps A S D F G H J K L ; ' Enter │ "
" │ Shift Z X C V B N M , . / Shift ↑ │ "
" │ │ └── Quit │ "
" │ └── External editor (⌃x ⌃e) │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" │ └── Start selection │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -2,20 +2,22 @@
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Base · Tab: List "
" Keyboard shortcuts Modifiers: None · F1: Change · Tab: List "
" ┌──────────────────────────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" │ │ "
" │ │ │ │ └── Voice │ "
" │ │ │ └── Inspect activity │ "
" │ │ └── Find text │ "
" │ └── Edit last message (esc esc) │ "
" ├──────────────────────────────────────────────────────────────────────────────────────────┤ "
" │ ` 1 2 3 4 5 6 7 8 9 0 - = Bksp Ins Home PgU │ "
" │ │ "
" │ Transcript page up ──┘ │ "
" │ Tab Q W E R T Y U I O P [ ] \ Del End PgD │ "
" │ │ "
" │ └── Queue message Transcript page down ──┘ │ "
" │ Caps A S D F G H J K L ; ' Enter │ "
" │ │ "
" │ Shift Z X C V B N M , . / Shift ↑ │ "
" │ │ "
" │ └── Commands │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" │ │ "
" │ Agents (empty prompt) ──┘ │ "
" └──────────────────────────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Modifiers: Shift · F1: Change · Tab: List "
" ┌──────────────────────────────────────────────────────────────────────┐ "
" │ Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 PrtSc ScrLk Pau │ "
" │ │ "
" ├──────────────────────────────────────────────────────────────────────┤ "
" │ ~ ! @ # $ % ^ & * ( ) _ + Bksp Ins Home PgU │ "
" │ │ └── Mention files │ "
" │ └── Shell command │ "
" │ Tab Q W E R T Y U I O P { } | Del End PgD │ "
" │ └── Change mode │ "
" │ Caps A S D F G H J K L : " Enter │ "
" │ │ "
" │ Shift Z X C V B N M < > ? Shift ↑ │ "
" │ │ "
" │ Ctrl Super Alt Space Alt Super Menu Ctrl ← ↓ → │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -2,24 +2,24 @@
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session "
" / Commands tab Send message "
" @ Mention files ⇧tab Change mode "
" ! Shell command ⌥. More reasoning "
" ⇧enter New line f8 Voice "
" ⌃⌥v Paste image ← Agents (empty prompt) "
" ⌃x ⌃e External editor ⌥← / ⌥→ Subagents (empty prompt) "
" esc Edit last message f4 Inspect activity "
" ⌃c Quit "
" "
" Transcript (open first) "
" ⌃t Open transcript "
" f3 Find text "
" pgup / pgdn Scroll "
" ⌃space Start selection "
" ⌃home / ⌃end Top / latest "
" ⇧⌥, / ⇧⌥. Top / latest "
" "
" /keymap customize "
" Keyboard shortcuts "
" "
" Compose Session "
" / Commands tab Send message "
" @ Mention files ⇧tab Change mode "
" ! Shell command ⌥. More reasoning "
" ⇧enter New line f8 Voice "
" ⌃⌥v Paste image ← Agents (empty prompt) "
" ⌃x ⌃e External editor ⌥← / ⌥→ Subagents (empty prompt) "
" esc Edit last message ⌃5 Inspect activity "
" ⌃c Quit "
" "
" Transcript (open first) "
" ⌃t Open transcript "
" f3 Find text "
" pgup / pgdn Scroll "
" ⌃space Start selection "
" ⌃home / ⌃end Top / latest "
" ⇧⌥, / ⇧⌥. Top / latest "
" "
" /keymap customize "