Add a keyboard diagram to TUI shortcut help (#62048)

## What changed

Let users switch from the grouped shortcut list to a US QWERTY keyboard diagram with `Tab`. Highlight keys with unmodified runtime bindings and point users back to the list for keys outside the diagram. Choose an available function key when `Tab` conflicts with configured bindings or chord prefixes.

Fall back to the action list when the diagram does not fit, and size the guide to fit an `80x24` conversation view. Preserve input priority for sidebar navigation and active transcript interactions.

## Testing

Add snapshots and regression tests for keyboard layouts, terminal colors, small-area fallback, remapped bindings, and sidebar and transcript input priority.

GitOrigin-RevId: 606edcc25e9dc98d0548e86d4b7544cb97f2db6f
This commit is contained in:
Benjamin Carlsson
2026-11-17 13:39:08 +00:00
committed by copyberry
parent db9778b73c
commit 49d657aad0
33 changed files with 945 additions and 65 deletions
+18
View File
@@ -871,6 +871,18 @@ impl App {
}
}
fn shortcut_guide_owns_input(&self, tui: &tui::Tui) -> bool {
self.overlay.is_none()
&& self.chat_widget.shortcut_overlay_visible()
&& !self.focused_sidebar_chooser(tui)
&& !(tui.is_owned_screen()
&& (self.backtrack.overlay_preview_active
|| self.transcript_view.has_active_interaction()
|| self
.transcript_view
.owns_interaction_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE))))
}
pub(crate) async fn handle_tui_event(
&mut self,
tui: &mut tui::Tui,
@@ -1121,6 +1133,12 @@ impl App {
let Some(key_event) = self.route_key_chord_event(tui, key_event) else {
return Ok(AppRunControl::Continue);
};
if self.routed_key_activation.is_none()
&& self.shortcut_guide_owns_input(tui)
&& self.chat_widget.handle_shortcut_view_key(key_event)
{
return Ok(AppRunControl::Continue);
}
TuiEvent::Key(key_event)
} else {
event
+1 -1
View File
@@ -236,7 +236,7 @@ impl App {
}
}
fn focused_sidebar_chooser(&self, tui: &tui::Tui) -> bool {
pub(super) fn focused_sidebar_chooser(&self, tui: &tui::Tui) -> bool {
self.conversation_focus_available(tui)
&& self.chooser_focus() == Some(super::sidebar::PaneFocus::Sidebar)
&& self.sidebar_chooser_available()
@@ -327,6 +327,99 @@ async fn recap_spacing_belongs_to_the_transcript_tail() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn shortcut_action_list_leaves_room_for_the_owned_transcript() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
attach_thread(&mut app, ThreadId::new());
app.transcript_cells
.push(Arc::new(crate::history_cell::PlainHistoryCell::new(vec![
"Conversation remains visible".into(),
])));
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
let size = Size::new(/*width*/ 60, /*height*/ 24);
tui.terminal.resize(size)?;
app.chat_widget.handle_key_event(KeyCode::Char('?').into());
app.render_owned_transcript(&mut tui, size)?;
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
let screen = buffer_text(buffer);
let visible_lines = screen
.lines()
.filter(|row| {
row.contains("Conversation remains visible")
|| row.contains("Keyboard shortcuts")
|| row.contains("resize to see all")
|| row.contains("/keymap customize")
|| row.contains("Ask Codex")
|| row.contains("esc close")
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(visible_lines, @"
Conversation remains visible
Keyboard shortcuts
… resize to see all
/keymap customize
› Ask Codex to do anything
? / esc close
");
assert!(
app.chat_widget
.handle_shortcut_view_key(KeyCode::Tab.into())
);
app.render_owned_transcript(&mut tui, size)?;
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
let screen = buffer_text(buffer);
assert!(screen.contains("Conversation remains visible"));
assert!(screen.contains("Keyboard unavailable"));
tui.set_owned_screen(/*owned*/ false)?;
Ok(())
}
#[tokio::test]
async fn shortcut_keyboard_fits_in_owned_transcript_at_80x24() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
attach_thread(&mut app, ThreadId::new());
app.chat_widget.handle_key_event(KeyCode::Char('?').into());
assert!(
app.chat_widget
.handle_shortcut_view_key(KeyCode::Tab.into())
);
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
let size = Size::new(/*width*/ 80, /*height*/ 24);
tui.terminal.resize(size)?;
app.render_owned_transcript(&mut tui, size)?;
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
insta::assert_snapshot!(
"shortcut_keyboard_owned_transcript",
normalize_snapshot_paths(buffer_text(buffer))
);
app.transcript_cells.push(user_cell("needle"));
app.transcript_view.begin_search();
app.transcript_view.paste_search("needle");
app.render_owned_transcript(&mut tui, size)?;
assert!(app.transcript_view.is_search_editing());
assert!(!app.shortcut_guide_owns_input(&tui));
app.transcript_view
.handle_key(KeyCode::Enter.into(), &app.transcript_cells);
assert!(!app.transcript_view.is_search_editing());
assert!(app.transcript_view.has_active_interaction());
assert!(!app.shortcut_guide_owns_input(&tui));
app.transcript_view
.handle_key(KeyCode::Esc.into(), &app.transcript_cells);
assert!(app.shortcut_guide_owns_input(&tui));
tui.set_owned_screen(/*owned*/ false)?;
Ok(())
}
#[tokio::test]
async fn owned_transcript_reserves_a_row_above_the_composer() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
@@ -0,0 +1,28 @@
---
source: tui/src/app/owned_transcript_tests.rs
expression: normalize_snapshot_paths(buffer_text(buffer))
---
Keyboard shortcuts Base · 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 │
│ │
│ 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 ← ↓ → │
│ │
└──────────────────────────────────────────────────────────────────────┘
/keymap customize
› Ask Codex to do anything
gpt-test default · /tmp/project
? / esc close
+43
View File
@@ -1331,6 +1331,49 @@ async fn sidebar_chooser_resize_survives_startup_thread_assignment() -> Result<(
Ok(())
}
#[tokio::test]
async fn focused_sidebar_chooser_keeps_tab_with_shortcut_guide_open() -> Result<()> {
use crate::app::sidebar::PaneFocus;
use crate::app::sidebar::SidebarContent;
let mut app = make_test_app().await;
app.local_settings.tui.keymap = toml::from_str(r#"list.move_down = "tab""#)?;
super::enable_side_retention(&mut app)?;
app.chat_widget
.apply_keymap_update(app.local_settings.tui.keymap.clone(), &app.keymap);
let mut server = start_config_write_test_app_server(&app).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
app.chat_widget.handle_thread_session(test_thread_session(
ThreadId::new(),
app.config.cwd.to_path_buf(),
));
app.chat_widget.replay_thread_turns(
vec![super::test_turn(
"parent-turn",
TurnStatus::Completed,
Vec::new(),
)],
ReplayKind::ResumeInitialMessages,
);
press(&mut app, &mut tui, &mut server, KeyCode::Char('?').into()).await?;
assert!(app.chat_widget.shortcut_overlay_visible());
let second_chat = ThreadId::new();
let pane = app.sidebar_mut();
pane.update_saved_chats(vec![ThreadId::new().into(), second_chat.into()]);
pane.show(SidebarContent::Chooser, PaneFocus::Sidebar);
press(&mut app, &mut tui, &mut server, KeyCode::Tab.into()).await?;
let pane = app.sidebar().expect("open sidebar chooser");
assert_eq!(pane.chat_tabs().choice(pane.choice), Some(second_chat));
assert!(app.chat_widget.shortcut_overlay_visible());
server.shutdown().await?;
tui.set_owned_screen(/*owned*/ false)?;
Ok(())
}
#[tokio::test]
async fn sidebar_chooser_preserves_the_parent_draft_and_starts_a_side_chat() -> Result<()> {
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
+13 -9
View File
@@ -16,8 +16,8 @@
//! loss cancels the pending paste; a late clipboard result cannot overwrite newer input.
//! The live voice strip renders after effort ignition, followed by the Astra sparkle when eligible.
//! Owned transcripts keep persistent status below the composer and hints on a separate final row.
//! Shortcut help expands above the composer, with its close hint replacing the final shortcuts row
//! so input and persistent status stay anchored when help opens or closes.
//! Shortcut help opens a grouped action list above the composer and can switch to a keyboard.
//! Its close hint replaces the final shortcuts row so input and persistent status stay anchored.
//! Escape dismisses visible shortcut help before editing, transcript backtracking, or interruption.
//! Fullscreen limits the composer height; wheel browsing preserves the caret until editor input.
//! Transcript interactions borrow the hint footer through `ComposerRenderOptions`;
@@ -835,6 +835,9 @@ impl ChatComposer {
queue_key: default_keymap.primary_hint(KeymapContext::Composer, "queue"),
toggle_shortcuts_key: default_keymap
.primary_hint(KeymapContext::Composer, "toggle_shortcuts"),
shortcut_guide_keys: super::shortcut_overlay::ShortcutGuideKeys::from_keymap(
&default_keymap,
),
history_search_key: default_keymap
.primary_hint(KeymapContext::Composer, "history_search_previous"),
reasoning_down_key: default_keymap
@@ -1141,6 +1144,8 @@ impl ChatComposer {
self.footer.queue_key = keymap.primary_hint(KeymapContext::Composer, "queue");
self.footer.toggle_shortcuts_key =
keymap.primary_hint(KeymapContext::Composer, "toggle_shortcuts");
self.footer.shortcut_guide_keys =
super::shortcut_overlay::ShortcutGuideKeys::from_keymap(keymap);
self.footer.history_search_key =
keymap.primary_hint(KeymapContext::Composer, "history_search_previous");
self.footer.reasoning_down_key =
@@ -4040,7 +4045,7 @@ impl ChatComposer {
.remove_deleted_local_placeholders(&removed_payloads, &mut self.draft.textarea);
}
/// Handle empty-prompt agents navigation and shortcut-overlay toggling or dismissal.
/// Handle empty-prompt agents navigation and shortcut guide toggling or dismissal.
///
/// This only toggles when the composer is empty and no paste burst is in
/// progress, so typing/pasting `?` still inserts text instead of opening
@@ -6841,7 +6846,7 @@ mod tests {
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
assert_eq!(result, InputResult::None);
assert!(needs_redraw, "toggling overlay should request redraw");
assert_eq!(composer.footer.mode, FooterMode::ShortcutOverlay);
assert!(composer.shortcut_overlay_visible());
// Toggle back to prompt mode so subsequent typing captures characters.
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
@@ -6882,7 +6887,7 @@ mod tests {
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT));
assert_eq!(result, InputResult::None);
assert!(needs_redraw, "toggling overlay should request redraw");
assert_eq!(composer.footer.mode, FooterMode::ShortcutOverlay);
assert!(composer.shortcut_overlay_visible());
}
/// Behavior: while a paste-like burst is being captured, `?` must not toggle the shortcut
@@ -6918,7 +6923,7 @@ mod tests {
let _ = flush_after_paste_burst(&mut composer);
assert_eq!(composer.draft.textarea.text(), "hi?there");
assert_ne!(composer.footer.mode, FooterMode::ShortcutOverlay);
assert!(!composer.shortcut_overlay_visible());
}
#[test]
@@ -8199,12 +8204,11 @@ mod tests {
);
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
assert_eq!(composer.footer.mode, FooterMode::ShortcutOverlay);
assert!(composer.shortcut_overlay_visible());
composer.set_task_running(/*running*/ true);
assert_eq!(composer.footer.mode, FooterMode::ShortcutOverlay);
assert_eq!(composer.footer_mode(), FooterMode::ShortcutOverlay);
assert!(composer.shortcut_overlay_visible());
}
#[test]
@@ -229,7 +229,8 @@ impl ChatComposer {
width: u16,
options: ComposerRenderOptions<'_>,
) -> u16 {
let rows = self.composer_rows(width, options.max_height.unwrap_or(u16::MAX), options);
let height = self.height_budget(width, options);
let rows = self.composer_rows(width, height, options);
[
rows.input,
rows.above_input,
@@ -280,7 +281,7 @@ impl ChatComposer {
|| matches!(
self.footer_mode(),
FooterMode::HistorySearch
| FooterMode::ShortcutOverlay
| FooterMode::ShortcutOverlay(_)
| FooterMode::QuitShortcutReminder
| FooterMode::EscHint
);
@@ -16,6 +16,8 @@ use std::time::Instant;
use super::super::footer::footer_height;
use super::super::footer::reset_mode_after_activity;
use super::super::shortcut_overlay;
use super::super::shortcut_overlay::ShortcutView;
use super::ActivePopup;
use super::warning_notice;
use crate::bottom_pane::StatusLine;
@@ -23,6 +25,7 @@ use crate::bottom_pane::footer::FooterKeyHints;
use crate::bottom_pane::footer::FooterProps;
use crate::key_hint;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Styled;
@@ -35,6 +38,7 @@ use crate::bottom_pane::footer::CollaborationModeIndicator;
use crate::bottom_pane::footer::FooterMode;
use crate::bottom_pane::footer::GoalStatusIndicator;
use crate::key_hint::KeyBinding;
use crate::key_hint::KeyBindingListExt;
use crate::key_hint::ShortcutHint;
use crate::style::secondary_text_style;
use std::time::Duration;
@@ -99,7 +103,8 @@ impl super::ChatComposer {
let is_wsl = {
#[cfg(target_os = "linux")]
{
mode == FooterMode::ShortcutOverlay && crate::clipboard_paste::is_probably_wsl()
matches!(mode, FooterMode::ShortcutOverlay(_))
&& crate::clipboard_paste::is_probably_wsl()
}
#[cfg(not(target_os = "linux"))]
{
@@ -122,6 +127,7 @@ impl super::ChatComposer {
.agents_navigation_available()
.then_some(key_hint::plain(KeyCode::Left).into()),
toggle_shortcuts: self.footer.toggle_shortcuts_key,
shortcut_guide: self.footer.shortcut_guide_keys,
queue: self.footer.queue_key,
insert_newline: self.footer.insert_newline_key,
external_editor: self.footer.external_editor_key,
@@ -161,7 +167,7 @@ impl super::ChatComposer {
match self.footer.mode {
FooterMode::HistorySearch => FooterMode::HistorySearch,
FooterMode::EscHint => FooterMode::EscHint,
FooterMode::ShortcutOverlay => FooterMode::ShortcutOverlay,
mode @ FooterMode::ShortcutOverlay(_) => mode,
FooterMode::QuitShortcutReminder if self.quit_shortcut_hint_visible() => {
FooterMode::QuitShortcutReminder
}
@@ -239,7 +245,7 @@ impl super::ChatComposer {
FooterMode::ComposerHasDraft => Some(ComposerState::Draft),
FooterMode::HistorySearch
| FooterMode::QuitShortcutReminder
| FooterMode::ShortcutOverlay
| FooterMode::ShortcutOverlay(_)
| FooterMode::EscHint => None,
};
match &self.popups.active {
@@ -276,13 +282,39 @@ impl super::ChatComposer {
}
pub(crate) fn shortcut_overlay_visible(&self) -> bool {
self.footer_mode() == FooterMode::ShortcutOverlay
matches!(self.footer_mode(), FooterMode::ShortcutOverlay(_))
&& matches!(self.popups.active, ActivePopup::None)
&& self.custom_footer_height().is_none()
}
pub(in crate::bottom_pane) fn handle_shortcut_view_key(&mut self, key: KeyEvent) -> bool {
let can_switch = self.is_empty() && !self.toggle_shortcuts_keys.is_pressed(key);
let props = self.footer_props();
let FooterMode::ShortcutOverlay(view) = &mut self.footer.mode else {
return false;
};
can_switch && view.handle_key(key, &props)
}
pub(super) fn shortcuts_above_composer(&self, options: ComposerRenderOptions<'_>) -> bool {
self.shortcut_overlay_visible() && options.footer.is_none()
!options.unfocused && self.shortcut_overlay_visible() && options.footer.is_none()
}
pub(in crate::bottom_pane) fn height_budget(
&self,
width: u16,
options: ComposerRenderOptions<'_>,
) -> 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)
&& shortcut_overlay::keyboard_fits_width(guide_width)
{
// A keyboard diagram needs all its rows. The conversation viewport still bounds it.
u16::MAX
} else {
options.max_height.unwrap_or(u16::MAX)
}
}
pub(super) fn footer_hint_height(&self, width: u16, options: ComposerRenderOptions<'_>) -> u16 {
@@ -398,6 +430,7 @@ pub(super) struct FooterState {
pub(super) insert_newline_key: Option<ShortcutHint>,
pub(super) queue_key: Option<ShortcutHint>,
pub(super) toggle_shortcuts_key: Option<ShortcutHint>,
pub(super) shortcut_guide_keys: super::super::shortcut_overlay::ShortcutGuideKeys,
pub(super) history_search_key: Option<ShortcutHint>,
pub(super) reasoning_down_key: Option<ShortcutHint>,
pub(super) reasoning_up_key: Option<ShortcutHint>,
@@ -61,7 +61,7 @@ fn shortcut_footer_displays_configured_chords() {
let keymap = RuntimeKeymap::from_config(&config).expect("valid composer chords");
let (mut composer, _rx) = new_test_composer();
composer.set_keymap_bindings(&keymap);
composer.footer.mode = FooterMode::ShortcutOverlay;
composer.footer.mode = FooterMode::ShortcutOverlay(Default::default());
let hints = composer.footer_props().key_hints;
assert_eq!(
@@ -85,7 +85,7 @@ fn shortcut_footer_displays_configured_chords() {
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_keymap_bindings(&keymap);
composer.footer.mode = FooterMode::ShortcutOverlay;
composer.footer.mode = FooterMode::ShortcutOverlay(Default::default());
},
);
}
@@ -9,7 +9,7 @@ initial:
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
shortcut help:
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session
/ Commands tab Send message
@@ -45,7 +45,7 @@ initial:
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
shortcut help:
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session
/ Commands tab Send message
@@ -3,7 +3,7 @@ source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
shortcut help:
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session
/ Commands tab Send message
@@ -11,7 +11,7 @@ expression: "snapshots.join(\"\\n---\\n\")"
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@@ -39,7 +39,7 @@ expression: "snapshots.join(\"\\n---\\n\")"
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@@ -67,7 +67,7 @@ expression: "snapshots.join(\"\\n---\\n\")"
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@@ -10,7 +10,7 @@ expression: text
Keyboard shortcuts
Keyboard shortcuts · Tab: Keyboard
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@@ -379,7 +379,7 @@ impl ChatComposer {
|| self.is_task_running
|| self.voice_strip.is_some()
|| self.popup_active()
|| self.footer_mode() == FooterMode::ShortcutOverlay
|| matches!(self.footer_mode(), FooterMode::ShortcutOverlay(_))
|| area.height < 3
|| textarea.is_empty()
|| effective_stdout_color_level() != StdoutColorLevel::TrueColor
@@ -295,7 +295,7 @@ fn shortcut_help_preserves_an_unused_sparkle_but_literal_question_marks_do_not()
if scenario == "close" {
super::super::FooterMode::ComposerEmpty
} else {
super::super::FooterMode::ShortcutOverlay
super::super::FooterMode::ShortcutOverlay(Default::default())
},
String::new(),
SparkleDraft::Untouched
@@ -1043,7 +1043,7 @@ fn status_survives_hints_feedback_and_queue() {
composer.set_collaboration_mode_indicator(Some(CollaborationModeIndicator::Plan));
let mut states = Vec::new();
states.push(render(&composer, /*width*/ 64, /*footer*/ None).0);
composer.footer.mode = FooterMode::ShortcutOverlay;
composer.footer.mode = FooterMode::ShortcutOverlay(Default::default());
composer.show_footer_flash("Copied selection".into(), Duration::from_secs(/*secs*/ 3));
states.push(render(&composer, /*width*/ 64, /*footer*/ None).0);
composer.footer.flash = None;
+18 -14
View File
@@ -94,6 +94,7 @@ const FOOTER_CONTEXT_GAP_COLS: u16 = 1;
pub(crate) struct FooterKeyHints {
pub(crate) agents: Option<ShortcutHint>,
pub(crate) toggle_shortcuts: Option<ShortcutHint>,
pub(crate) shortcut_guide: shortcut_overlay::ShortcutGuideKeys,
pub(crate) queue: Option<ShortcutHint>,
pub(crate) insert_newline: Option<ShortcutHint>,
pub(crate) external_editor: Option<ShortcutHint>,
@@ -113,6 +114,9 @@ impl FooterKeyHints {
Self {
agents: None,
toggle_shortcuts: Some(key_hint::plain(KeyCode::Char('?')).into()),
shortcut_guide: shortcut_overlay::ShortcutGuideKeys::from_keymap(
&crate::keymap::RuntimeKeymap::defaults(),
),
queue: Some(key_hint::plain(KeyCode::Tab).into()),
insert_newline: Some(key_hint::ctrl(KeyCode::Char('j')).into()),
external_editor: Some(key_hint::ctrl(KeyCode::Char('g')).into()),
@@ -165,7 +169,7 @@ pub(crate) enum FooterMode {
/// Transient "press again to quit" reminder (Ctrl+C/Ctrl+D).
QuitShortcutReminder,
/// Multi-line shortcut overlay shown after pressing `?`.
ShortcutOverlay,
ShortcutOverlay(shortcut_overlay::ShortcutView),
/// Transient "press Esc again" hint shown after the first Esc while idle.
EscHint,
/// Base single-line footer when the composer is empty.
@@ -193,8 +197,8 @@ pub(crate) fn toggle_shortcut_mode(
};
match current {
FooterMode::ShortcutOverlay | FooterMode::QuitShortcutReminder => base_mode,
_ => FooterMode::ShortcutOverlay,
FooterMode::ShortcutOverlay(_) | FooterMode::QuitShortcutReminder => base_mode,
_ => FooterMode::ShortcutOverlay(Default::default()),
}
}
@@ -209,7 +213,7 @@ pub(crate) fn esc_hint_mode(current: FooterMode, is_task_running: bool) -> Foote
pub(crate) fn reset_mode_after_activity(current: FooterMode) -> FooterMode {
match current {
FooterMode::EscHint
| FooterMode::ShortcutOverlay
| FooterMode::ShortcutOverlay(_)
| FooterMode::QuitShortcutReminder
| FooterMode::HistorySearch
| FooterMode::ComposerHasDraft => FooterMode::ComposerEmpty,
@@ -219,7 +223,7 @@ pub(crate) fn reset_mode_after_activity(current: FooterMode) -> FooterMode {
pub(crate) fn footer_height(props: &FooterProps, width: u16) -> u16 {
match props.mode {
FooterMode::ShortcutOverlay => {
FooterMode::ShortcutOverlay(_) => {
shortcut_overlay::lines(props, width.saturating_sub(FOOTER_INDENT_COLS as u16)).len()
as u16
}
@@ -257,7 +261,7 @@ pub(crate) fn render_footer_from_props(
show_shortcuts_hint: bool,
show_queue_hint: bool,
) {
if props.mode == FooterMode::ShortcutOverlay {
if matches!(props.mode, FooterMode::ShortcutOverlay(_)) {
shortcut_overlay::render(props, inset_footer_hint_area(area), buf);
return;
}
@@ -767,7 +771,7 @@ fn footer_from_props_lines(
key_hints,
)]
}
FooterMode::ShortcutOverlay => shortcut_overlay::lines(props, u16::MAX),
FooterMode::ShortcutOverlay(_) => shortcut_overlay::lines(props, u16::MAX),
FooterMode::EscHint => vec![esc_hint_line(props.esc_backtrack_hint)],
FooterMode::ComposerHasDraft => {
let state = LeftSideState {
@@ -849,7 +853,7 @@ impl FooterMode {
Self::ComposerHasDraft => !is_task_running,
Self::HistorySearch
| Self::QuitShortcutReminder
| Self::ShortcutOverlay
| Self::ShortcutOverlay(_)
| Self::EscHint => false,
}
}
@@ -1028,7 +1032,7 @@ mod tests {
FooterMode::ComposerHasDraft => false,
FooterMode::HistorySearch
| FooterMode::QuitShortcutReminder
| FooterMode::ShortcutOverlay
| FooterMode::ShortcutOverlay(_)
| FooterMode::EscHint => false,
};
let show_queue_hint = match props.mode {
@@ -1036,7 +1040,7 @@ mod tests {
FooterMode::HistorySearch
| FooterMode::QuitShortcutReminder
| FooterMode::ComposerEmpty
| FooterMode::ShortcutOverlay
| FooterMode::ShortcutOverlay(_)
| FooterMode::EscHint => false,
};
let status_line_active = props.status_line_enabled
@@ -1179,7 +1183,7 @@ mod tests {
FooterMode::EscHint
| FooterMode::HistorySearch
| FooterMode::QuitShortcutReminder
| FooterMode::ShortcutOverlay
| FooterMode::ShortcutOverlay(_)
);
if show_context && let Some(line) = &right_line {
render_context_right(area, f.buffer_mut(), line);
@@ -1285,7 +1289,7 @@ mod tests {
snapshot_footer(
"footer_shortcuts_shift_and_esc",
FooterProps {
mode: FooterMode::ShortcutOverlay,
mode: FooterMode::ShortcutOverlay(Default::default()),
esc_backtrack_hint: true,
is_task_running: false,
queue_submissions: false,
@@ -1305,7 +1309,7 @@ mod tests {
snapshot_footer(
"footer_shortcuts_collaboration_modes_enabled",
FooterProps {
mode: FooterMode::ShortcutOverlay,
mode: FooterMode::ShortcutOverlay(Default::default()),
esc_backtrack_hint: false,
is_task_running: false,
queue_submissions: false,
@@ -1322,7 +1326,7 @@ mod tests {
snapshot_footer(
"footer_shortcuts_running",
FooterProps {
mode: FooterMode::ShortcutOverlay,
mode: FooterMode::ShortcutOverlay(Default::default()),
esc_backtrack_hint: false,
is_task_running: true,
queue_submissions: false,
+9 -1
View File
@@ -1953,6 +1953,14 @@ impl BottomPane {
self.no_modal_or_popup_active() && self.composer.shortcut_overlay_visible()
}
pub(crate) fn handle_shortcut_view_key(&mut self, key: KeyEvent) -> bool {
let handled = self.composer.handle_shortcut_view_key(key);
if handled {
self.request_redraw();
}
handled
}
/// Return true when no popups or modal views are active, regardless of task state.
pub(crate) fn can_launch_external_editor(&self) -> bool {
self.completion_can_yield_focus() && !self.composer.popup_active()
@@ -2695,7 +2703,7 @@ impl Renderable for ChatComposerPresentation<'_> {
fn desired_height(&self, width: u16) -> u16 {
self.composer
.desired_height_with_options(width, self.options)
.min(self.options.max_height.unwrap_or(u16::MAX))
.min(self.composer.height_budget(width, self.options))
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+163 -12
View File
@@ -1,13 +1,18 @@
//! A compact shortcut reference with shared width-aware measurement and rendering.
//!
//! Groups flow into three, two, or one column without changing key routing. Runtime hints
//! remain authoritative for remapped, chorded, and disabled bindings. A clipped reference
//! keeps customization visible; the composer reserves a separate bottom row for the close hint.
//! 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.
mod keyboard;
use super::footer::FooterMode;
use super::footer::FooterProps;
use crate::key_hint;
use crate::key_hint::KeyBinding;
use crate::key_hint::ShortcutHint;
use crate::keymap::KeymapContext;
use crate::keymap::RuntimeKeymap;
use crate::keymap::bindings_for_action;
use crate::multi_agents::next_agent_shortcut;
use crate::multi_agents::previous_agent_shortcut;
use crate::shortcut_help::Group;
@@ -16,14 +21,75 @@ use crate::style::accent_color;
use crate::style::secondary_text_style;
use crate::wrapping::word_wrap_lines;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
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;
/// The view switch takes the first free key.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ShortcutGuideKeys {
view: Option<KeyCode>,
}
impl ShortcutGuideKeys {
pub(super) fn from_keymap(keymap: &RuntimeKeymap) -> Self {
let conflicts = |context: KeymapContext| {
context == KeymapContext::Pager || context.overlaps(KeymapContext::Composer)
};
let view =
std::iter::once(KeyCode::Tab)
.chain((1..=12).map(KeyCode::F))
.find(|&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| {
conflicts(id.context)
&& (id.context != KeymapContext::Composer || id.action != "queue")
&& bindings_for_action(keymap, id.context.config_name(), id.action)
.is_some_and(|bindings| bindings.contains(&key))
}) && !keymap.chords.bindings.iter().any(|binding| {
conflicts(binding.action.context) && binding.chord.prefix == key
})
});
Self { view }
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum ShortcutView {
#[default]
List,
Keyboard,
}
impl ShortcutView {
pub(super) fn handle_key(&mut self, event: KeyEvent, props: &FooterProps) -> bool {
if !props
.key_hints
.shortcut_guide
.view
.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,
};
}
true
}
}
struct Entry {
keys: [Option<ShortcutHint>; 2],
@@ -140,8 +206,73 @@ fn bindings(props: &FooterProps) -> [(&'static str, Vec<Entry>); 3] {
]
}
// Map runtime shortcuts to US QWERTY key positions. Chords use their prefix.
fn key_position(hint: ShortcutHint) -> (KeyCode, KeyModifiers) {
let binding = match hint {
ShortcutHint::Single(key) | ShortcutHint::Chord { prefix: key, .. } => key,
};
let (code, modifiers) = binding.parts();
let (code, modifiers) = key_hint::normalize_key_parts(code, modifiers);
match code {
KeyCode::BackTab => (KeyCode::Tab, modifiers | KeyModifiers::SHIFT),
KeyCode::Char(ch) => keyboard::unshift(ch).map_or((code, modifiers), |base| {
(KeyCode::Char(base), modifiers | KeyModifiers::SHIFT)
}),
_ => (code, modifiers),
}
}
pub(super) fn keyboard_fits_width(width: u16) -> bool {
width >= keyboard::WIDTH
}
pub(super) fn lines(props: &FooterProps, width: u16) -> Vec<Line<'static>> {
let groups = bindings(props).map(|(title, entries)| {
guide_lines(props, width, usize::MAX)
}
fn guide_lines(props: &FooterProps, width: u16, height: usize) -> Vec<Line<'static>> {
let FooterMode::ShortcutOverlay(view) = props.mode else {
return Vec::new();
};
let width_usize = usize::from(width.max(1));
let 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())),
);
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;
}
}
let groups = groups.map(|(title, entries)| {
let entries = entries
.into_iter()
.filter_map(|entry| {
@@ -165,12 +296,32 @@ pub(super) fn lines(props: &FooterProps, width: u16) -> Vec<Line<'static>> {
.collect();
Group { title, entries }
});
let mut result = vec![Line::from("Keyboard shortcuts").bold(), Line::default()];
result.extend(crate::shortcut_help::group_lines(groups, width));
let width = usize::from(width.max(/*other*/ 1));
let mut heading = heading;
match view {
ShortcutView::List if keyboard_fits_width(width) => {
heading.extend(
keys.view
.map(|key| format!(" · {key}: Keyboard").set_style(secondary_text_style())),
);
}
ShortcutView::Keyboard => {
heading.push_span(" · Keyboard unavailable".set_style(secondary_text_style()));
heading.extend(
keys.view
.map(|key| format!(" · {key}: List").set_style(secondary_text_style())),
);
}
ShortcutView::List => {}
}
let mut result = word_wrap_lines([heading], width_usize);
result.push(Line::default());
result.extend(footer_lines(width));
word_wrap_lines(&result, width)
result.extend(word_wrap_lines(
crate::shortcut_help::group_lines(groups, width),
width_usize,
));
result.push(Line::default());
result.extend(footer);
result
}
pub(super) fn close_hint(props: &FooterProps, width: u16) -> Line<'static> {
@@ -199,7 +350,7 @@ fn footer_lines(width: usize) -> Vec<Line<'static>> {
}
pub(super) fn render(props: &FooterProps, area: Rect, buf: &mut Buffer) {
let mut lines = lines(props, area.width);
let mut lines = guide_lines(props, area.width, usize::from(area.height));
let height = usize::from(area.height);
if lines.len() > height && height > 0 {
let mut footer = footer_lines(usize::from(area.width.max(/*other*/ 1)));
@@ -0,0 +1,293 @@
//! Draws a US QWERTY tenkeyless keyboard with highlighted shortcut keys.
use crate::color::blend;
use crate::color::is_light;
use crate::style::readable_color_on;
use crate::style::selection_style;
use crate::terminal_palette::best_color;
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::ModifierKeyCode::*;
use ratatui::style::Color;
use ratatui::style::Style;
use ratatui::style::Styled;
use ratatui::text::Line;
use std::collections::HashSet;
const ROWS: usize = 6;
const NAV_START: usize = 52;
const INNER_WIDTH: usize = NAV_START + 16;
pub(super) const WIDTH: u16 = INNER_WIDTH as u16 + 4;
const ROOMY_WIDTH: u16 = 92;
#[derive(Clone, Copy)]
enum Geometry {
Compact,
Roomy,
}
impl Geometry {
fn for_width(width: u16) -> Self {
if width >= ROOMY_WIDTH {
Self::Roomy
} else {
Self::Compact
}
}
fn inner_width(self) -> usize {
match self {
Self::Compact => INNER_WIDTH,
Self::Roomy => usize::from(ROOMY_WIDTH) - 4,
}
}
fn nav_start(self) -> usize {
match self {
Self::Compact => NAV_START,
Self::Roomy => 69,
}
}
}
const UNSHIFTED: &str = r"`1234567890-=[]\;',./";
const SHIFTED: &str = r#"~!@#$%^&*()_+{}|:"<>?"#;
pub(super) fn unshift(ch: char) -> Option<char> {
SHIFTED
.find(ch)
.map(|index| char::from(UNSHIFTED.as_bytes()[index]))
}
#[derive(Clone, Copy)]
struct Cap<'a>(KeyCode, &'a str, usize);
const fn key(code: KeyCode, label: &'static str) -> Cap<'static> {
Cap(code, label, label.len() + 2)
}
fn keyboard_styles() -> [Style; 4] {
let terminal_default = Style::default().bg(Color::Reset);
let fallback = [
terminal_default,
terminal_default,
terminal_default,
selection_style(),
];
let (Some(background), Some(foreground)) = (default_bg(), default_fg()) else {
return fallback;
};
let panel_rgb = blend(foreground, background, /*alpha*/ 0.07);
let (panel_fill, cap_fill, bound_fill) = match best_color(panel_rgb) {
Color::Reset => {
return fallback;
}
Color::Indexed(_) => {
// Use distinct xterm swatches so palette reduction cannot merge the surfaces.
let (panel, alternate, cap, bound) = if is_light(background) {
(
(228, 228, 228),
(218, 218, 218),
(198, 198, 198),
(175, 215, 255),
)
} else {
((48, 48, 48), (58, 58, 58), (78, 78, 78), (0, 95, 135))
};
let panel = best_color(panel);
let panel = if panel == best_color(background) {
best_color(alternate)
} else {
panel
};
(panel, best_color(cap), best_color(bound))
}
panel => (
panel,
best_color(blend(foreground, background, /*alpha*/ 0.22)),
best_color(blend((35, 100, 140), panel_rgb, /*alpha*/ 0.63)),
),
};
let panel = Style::default().bg(panel_fill);
let border = panel.fg(readable_color_on(
rgb_color(blend(foreground, background, /*alpha*/ 0.60)),
Some(panel_fill),
));
let cap = Style::default()
.bg(cap_fill)
.fg(readable_color_on(rgb_color(foreground), Some(cap_fill)));
let bound = if [panel_fill, cap_fill].contains(&bound_fill) {
selection_style()
} else {
Style::default()
.bg(bound_fill)
.fg(readable_color_on(
rgb_color((190, 228, 255)),
Some(bound_fill),
))
.bold()
};
[panel, border, cap, bound]
}
fn cap(
row: &mut Line<'static>,
Cap(code, label, width): Cap<'_>,
actions: &mut HashSet<KeyCode>,
styles: &[Style; 4],
geometry: Geometry,
) {
let style = if actions.remove(&code) {
styles[3]
} else {
styles[2]
};
let width = match geometry {
Geometry::Compact => width,
Geometry::Roomy => match code {
KeyCode::Char(' ') => 12,
KeyCode::F(1..=4) => label.len() + 2,
KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right => 6,
_ => label.chars().count() + 3,
},
};
let face_width = width - 1;
row.push_span(format!("{label:^face_width$}").set_style(style));
row.push_span(" ");
}
fn framed(content: Line<'static>, panel: Style, frame: Style, geometry: Geometry) -> Line<'static> {
let padding = geometry.inner_width() - content.width();
let mut line = Line::from("│ ".set_style(frame)).style(panel);
line.extend(content.spans);
line.push_span(" ".repeat(padding));
line.push_span(" │".set_style(frame));
line
}
// 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);
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))];
for index in 0..ROWS {
let mut row = Line::default();
let (left, letters, right): (&[Cap<'_>], &str, &[Cap<'_>]) = match index {
0 => (&[], "", &[]),
1 => (&[], "`1234567890-=", &[Cap(KeyCode::Backspace, "Bksp", 9)]),
2 => (&[Cap(KeyCode::Tab, "Tab", 6)], "qwertyuiop[]\\", &[]),
3 => (
&[Cap(KeyCode::CapsLock, "Caps", 7)],
"asdfghjkl;'",
&[Cap(KeyCode::Enter, "Enter", 8)],
),
4 => (
&[Cap(KeyCode::Modifier(LeftShift), "Shift", 8)],
"zxcvbnm,./",
&[Cap(KeyCode::Modifier(RightShift), "Shift", 10)],
),
_ => (
&[
Cap(KeyCode::Modifier(LeftControl), "Ctrl", 5),
Cap(KeyCode::Modifier(LeftSuper), "Super", 6),
key(KeyCode::Modifier(LeftAlt), "Alt"),
Cap(KeyCode::Char(' '), "Space", 11),
key(KeyCode::Modifier(RightAlt), "Alt"),
Cap(KeyCode::Modifier(RightSuper), "Super", 6),
Cap(KeyCode::Menu, "Menu", 5),
Cap(KeyCode::Modifier(RightControl), "Ctrl", 5),
],
"",
&[],
),
};
if index == 0 {
cap(
&mut row,
key(KeyCode::Esc, "Esc"),
actions,
&styles,
geometry,
);
for (first, gap) in [(1, " "), (5, " "), (9, " ")] {
if matches!(geometry, Geometry::Compact) {
row.push_span(gap);
}
for number in first..first + 4 {
let label = format!("F{number}");
cap(
&mut row,
Cap(KeyCode::F(number), &label, label.len() + 1),
actions,
&styles,
geometry,
);
}
}
}
for &key in left {
cap(&mut row, key, actions, &styles, geometry);
}
for letter in letters.chars() {
let mut label = [0; 4];
let label = letter.to_ascii_uppercase().encode_utf8(&mut label);
let width = if letter == '\\' { 6 } else { 3 };
cap(
&mut row,
Cap(KeyCode::Char(letter), label, width),
actions,
&styles,
geometry,
);
}
for &key in right {
cap(&mut row, key, actions, &styles, geometry);
}
let nav: &[Cap<'_>] = match index {
0 => &[
Cap(KeyCode::PrintScreen, "PrtSc", 6),
Cap(KeyCode::ScrollLock, "ScrLk", 6),
Cap(KeyCode::Pause, "Pau", 4),
],
1 => &[
key(KeyCode::Insert, "Ins"),
key(KeyCode::Home, "Home"),
key(KeyCode::PageUp, "PgU"),
],
2 => &[
key(KeyCode::Delete, "Del"),
Cap(KeyCode::End, "End", 6),
key(KeyCode::PageDown, "PgD"),
],
4 => &[Cap(KeyCode::Up, "↑", 6)],
5 => &[
Cap(KeyCode::Left, "←", 5),
Cap(KeyCode::Down, "↓", 6),
Cap(KeyCode::Right, "→", 5),
],
_ => &[],
};
if !nav.is_empty() {
let nav_start = match (geometry, index) {
(Geometry::Roomy, 0) => 66,
(Geometry::Compact, 4) => geometry.nav_start() + 5,
(Geometry::Roomy, 4) => geometry.nav_start() + 6,
_ => geometry.nav_start(),
};
row.push_span(" ".repeat(nav_start - row.width()));
for &key in nav {
cap(&mut row, key, actions, &styles, geometry);
}
}
lines.push(framed(row, panel, frame, geometry));
lines.push(framed(Line::default(), panel, frame, geometry));
if index == 0 {
lines.push(Line::from(format!("├{rail}┤").set_style(frame)));
}
}
lines.push(Line::from(format!("└{rail}┘").set_style(frame)));
lines
}
@@ -1,3 +1,7 @@
#![cfg(test)]
use super::ShortcutGuideKeys;
use super::ShortcutView;
use super::lines;
use crate::bottom_pane::footer::FooterKeyHints;
use crate::bottom_pane::footer::FooterMode;
@@ -14,7 +18,7 @@ use ratatui::backend::TestBackend;
fn props() -> FooterProps {
FooterProps {
mode: FooterMode::ShortcutOverlay,
mode: FooterMode::ShortcutOverlay(Default::default()),
esc_backtrack_hint: false,
is_task_running: true,
queue_submissions: false,
@@ -92,6 +96,139 @@ fn shortcut_overlay_uses_runtime_bindings_and_wsl_paste() {
);
}
#[test]
fn shortcut_overlay_leaves_remapped_tab_and_function_keys_available() {
let config = toml::from_str(
r#"
global.open_transcript = "tab"
vim_search.forward = "f1"
composer.queue = []
"#,
)
.unwrap();
let keymap = crate::keymap::RuntimeKeymap::from_config(&config).unwrap();
let mut props = props();
props.key_hints.shortcut_guide = ShortcutGuideKeys::from_keymap(&keymap);
let mut view = ShortcutView::List;
let keys = props.key_hints.shortcut_guide;
assert_eq!(keys.view, Some(KeyCode::F(5)));
assert!(!view.handle_key(KeyCode::Tab.into(), &props));
assert!(!view.handle_key(KeyCode::F(1).into(), &props));
assert!(view.handle_key(KeyCode::F(5).into(), &props));
assert_eq!(view, ShortcutView::Keyboard);
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() {
let mut props = props();
let all = ratatui::text::Text::from(lines(&props, /*width*/ 80)).to_string();
assert!(
all.lines()
.any(|row| row.contains("Paste image") && row.contains("⌃v"))
);
let mut view = ShortcutView::List;
assert!(view.handle_key(KeyCode::Tab.into(), &props));
props.mode = FooterMode::ShortcutOverlay(view);
snapshot(
"shortcut_keyboard_base",
/*width*/ 80,
/*height*/ None,
&props,
);
snapshot(
"shortcut_keyboard_roomy",
/*width*/ 96,
/*height*/ None,
&props,
);
for (width, height) in [(68, usize::MAX), (80, 12)] {
let fallback =
ratatui::text::Text::from(super::guide_lines(&props, width, height)).to_string();
assert!(fallback.contains("Paste image") && fallback.contains("Change mode"));
}
}
#[test]
fn shortcut_keyboard_adapts_to_probed_and_unknown_terminal_colors() {
let mut props = props();
props.mode = FooterMode::ShortcutOverlay(ShortcutView::Keyboard);
for colors in [
Some(crate::terminal_probe::DefaultColors {
fg: (230, 230, 230),
bg: (20, 20, 20),
}),
Some(crate::terminal_probe::DefaultColors {
fg: (20, 20, 20),
bg: (245, 245, 245),
}),
None,
] {
crate::terminal_palette::with_test_default_colors(colors, || {
let rendered = lines(&props, /*width*/ 78);
let panel = rendered[2].style.bg;
let cap = rendered
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content.trim() == "Q")
.unwrap()
.style;
let bound = rendered
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content.trim() == "Esc")
.unwrap()
.style;
if colors.is_some() {
assert_ne!(panel, cap.bg);
assert_ne!(cap.bg, bound.bg);
assert_ne!(panel, bound.bg);
} else {
assert_eq!(panel, Some(ratatui::style::Color::Reset));
assert_eq!(cap.bg, panel);
assert_ne!(cap, bound);
}
});
}
}
#[test]
fn shortcut_keyboard_keeps_diagram_for_keys_outside_us_layout() {
let mut props = props();
props.key_hints.agents = Some(key_hint::plain(KeyCode::F(13)).into());
props.key_hints.show_transcript = Some(key_hint::plain(KeyCode::Char('é')).into());
let mut view = ShortcutView::List;
assert!(view.handle_key(KeyCode::Tab.into(), &props));
props.mode = FooterMode::ShortcutOverlay(view);
snapshot(
"shortcut_keyboard_off_diagram_keys",
/*width*/ 80,
/*height*/ None,
&props,
);
// Keep the diagram within its original height on an 80-column terminal.
assert_eq!(
super::guide_lines(&props, /*width*/ 78, /*height*/ 17),
lines(&props, /*width*/ 78),
);
// Switching back keeps off-diagram bindings discoverable with their actions.
assert!(view.handle_key(KeyCode::Tab.into(), &props));
props.mode = FooterMode::ShortcutOverlay(view);
let list = ratatui::text::Text::from(lines(&props, /*width*/ 80)).to_string();
assert!(
list.lines()
.any(|row| row.contains("f13") && row.contains("Agents"))
);
assert!(
list.lines()
.any(|row| row.contains('é') && row.contains("Open transcript"))
);
}
#[test]
fn shortcut_overlay_clipping_preserves_customization_in_small_areas() {
snapshot(
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session "
" / Commands tab Send message "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session Transcript (open first) "
" / Commands tab Send message ⌃t Open transcript "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session Transcript (open first) "
" / Commands tab Send message ⌃t Open transcript "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session Transcript (open first) "
" / Commands tab Queue message ⌃t Open transcript "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/footer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session "
" / Commands tab Send message "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/footer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session "
" / Commands tab Queue message "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/footer.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session "
" / Commands tab Send message "
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Base · 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 │ "
" │ │ "
" │ 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 ← ↓ → │ "
" │ │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Base · More keys in list · 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 │ "
" │ │ "
" │ 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 ← ↓ → │ "
" │ │ "
" └──────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -0,0 +1,21 @@
---
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts Base · 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 │ "
" │ │ "
" │ 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 ← ↓ → │ "
" │ │ "
" └──────────────────────────────────────────────────────────────────────────────────────────┘ "
" /keymap customize "
@@ -2,7 +2,7 @@
source: tui/src/bottom_pane/shortcut_overlay_tests.rs
expression: terminal.backend()
---
" Keyboard shortcuts "
" Keyboard shortcuts · Tab: Keyboard "
" "
" Compose Session "
" / Commands tab Send message "
@@ -480,6 +480,10 @@ impl ChatWidget {
self.bottom_pane.shortcut_overlay_visible()
}
pub(crate) fn handle_shortcut_view_key(&mut self, key: KeyEvent) -> bool {
self.bottom_pane.handle_shortcut_view_key(key)
}
pub(crate) fn no_modal_or_popup_active(&self) -> bool {
self.bottom_pane.no_modal_or_popup_active()
}