Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
which_key: Stop grouped rows from hiding keybindings that complete on the next keystroke (#64942)
Smit Barmaseeba636502559
diff --git a/crates/which_key/src/pending_bindings.rs b/crates/which_key/src/pending_bindings.rsindex 92ad34cdbc6..ceb421e40d1 100644--- a/crates/which_key/src/pending_bindings.rs+++ b/crates/which_key/src/pending_bindings.rs@@ -1,10 +1,10 @@-use std::{collections::HashMap, rc::Rc};+use std::rc::Rc;use gpui::{App, AvailableSpace, KeybindingKeystroke, Pixels, RenderOnce, ScrollHandle, Window, size,};use ui::{- Divider, DividerColor, KeyBinding, LabelSize, WithScrollbar, prelude::*,+ Divider, DividerColor, GradientFade, KeyBinding, LabelSize, WithScrollbar, prelude::*,text_for_keybinding_keystrokes,};@@ -37,58 +37,91 @@ pub(crate) fn prepare_pending_bindings(.then_with(|| text_a.len().cmp(&text_b.len())).then_with(|| text_a.cmp(text_b))});- rows.dedup_by(|(row_a, _), (row_b, _)| {- row_a.keystrokes == row_b.keystrokes && row_a.action_name == row_b.action_name- });rows.into_iter().map(|(row, _)| row).collect()}fn group_bindings(bindings: Vec<PendingBinding>) -> Vec<PendingBindingRow> {- let mut groups: HashMap<Option<KeybindingKeystroke>, Vec<PendingBinding>> = HashMap::new();- // Group bindings by their first keystroke+ let mut groups: Vec<Vec<PendingBinding>> = Vec::new();for binding in bindings {- groups- .entry(binding.remaining_keystrokes.first().cloned())- .or_default()- .push(binding);+ let first_keystroke = binding.remaining_keystrokes.first();+ let group = groups.iter_mut().find(|group| {+ group+ .first()+ .is_some_and(|existing| existing.remaining_keystrokes.first() == first_keystroke)+ });+ let Some(group) = group else {+ groups.push(vec![binding]);+ continue;+ };+ // Candidates come in precedence order, so the first binding for a sequence is the one+ // dispatch tries first. Dispatch only moves on to the next binding when nothing on the+ // focus path handles the first action. Like GPUI's shortcut display, the popup treats the+ // later bindings as shadowed and shows only the first. Bindings for the same sequence+ // share a first keystroke, so checking the group is enough.+ if group+ .iter()+ .any(|existing| existing.remaining_keystrokes == binding.remaining_keystrokes)+ {+ continue;+ }+ group.push(binding);}let mut result = Vec::new();- for (first_keystroke, mut bindings) in groups {- // Preserve which-key's adjacent-only deduplication and candidate order.- bindings.dedup_by(|binding_a, binding_b| {- binding_a.remaining_keystrokes == binding_b.remaining_keystrokes- });-- if let Some(first_keystroke) = first_keystroke- && bindings.len() > 1+ for bindings in groups {+ // A group row would hide what the next keystroke runs, so a binding that completes on it+ // gets its own row and only the longer bindings collapse. Sorting moves the group row+ // down with the other groups, away from that row.+ let longer_count = bindings+ .iter()+ .filter(|binding| binding.remaining_keystrokes.len() > 1)+ .count();++ if longer_count > 1+ && let Some(first_keystroke) = bindings+ .first()+ .and_then(|binding| binding.remaining_keystrokes.first())+ .cloned(){- // Collapse bindings sharing the next keystroke into a single row.+ result.extend(+ bindings+ .into_iter()+ .filter(|binding| binding.remaining_keystrokes.len() <= 1)+ .map(binding_row),+ );result.push(PendingBindingRow {keystrokes: Rc::from([first_keystroke]),- action_name: format!("+{} keybinds", bindings.len()).into(),+ action_name: format!("+{longer_count} keybinds").into(),is_group: true,});} else {- // Keep individual bindings as-is when there is nothing to collapse.- result.extend(bindings.into_iter().map(|binding| PendingBindingRow {- keystrokes: binding.remaining_keystrokes.into(),- action_name: binding.action_name,- is_group: false,- }));+ result.extend(bindings.into_iter().map(binding_row));}}result}+fn binding_row(binding: PendingBinding) -> PendingBindingRow {+ PendingBindingRow {+ keystrokes: binding.remaining_keystrokes.into(),+ action_name: binding.action_name,+ is_group: false,+ }+}++const MAX_KEY_COLUMN_WIDTH: Rems = rems(12.5);+const MIN_KEY_COLUMN_WIDTH: Rems = rems(3.);+const HEADER_LABEL: &str = "is waiting for more keys…";+#[derive(IntoElement)]pub(crate) struct PendingBindings {id: &'static str,pending_keystrokes: Rc<[KeybindingKeystroke]>,bindings: Rc<[PendingBindingRow]>,scroll_handle: ScrollHandle,+ max_width: Pixels,max_content_height: Pixels,}@@ -98,6 +131,7 @@ impl PendingBindings {pending_keystrokes: Rc<[KeybindingKeystroke]>,bindings: Rc<[PendingBindingRow]>,scroll_handle: ScrollHandle,+ max_width: Pixels,max_content_height: Pixels,) -> Self {Self {@@ -105,6 +139,7 @@ impl PendingBindings {pending_keystrokes,bindings,scroll_handle,+ max_width,max_content_height,}}@@ -112,30 +147,87 @@ impl PendingBindings {fn keybinding(keystrokes: Rc<[KeybindingKeystroke]>, cx: &App) -> KeyBinding {KeyBinding::from_keystrokes(keystrokes, KeyBinding::is_vim_mode(cx)).color(Color::Accent)}++ fn keybinding_width(+ keystrokes: Rc<[KeybindingKeystroke]>,+ window: &mut Window,+ cx: &mut App,+ ) -> Pixels {+ Self::keybinding(keystrokes, cx)+ .into_any_element()+ .layout_as_root(+ size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),+ window,+ cx,+ )+ .width+ }++ fn label_width(text: SharedString, window: &mut Window, cx: &mut App) -> Pixels {+ Label::new(text)+ .size(LabelSize::Small)+ .single_line()+ .into_any_element()+ .layout_as_root(+ size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),+ window,+ cx,+ )+ .width+ }++ fn key_cell(+ keystrokes: Rc<[KeybindingKeystroke]>,+ keybinding_width: Pixels,+ key_column_width: Pixels,+ cx: &App,+ ) -> AnyElement {+ let keybinding = Self::keybinding(keystrokes, cx);+ if keybinding_width <= key_column_width {+ return keybinding.into_any_element();+ }+ let background = cx.theme().colors().elevated_surface_background;+ h_flex()+ .relative()+ .w(key_column_width)+ .overflow_hidden()+ .child(keybinding)+ .child(GradientFade::new(background, background, background))+ .into_any_element()+ }}impl RenderOnce for PendingBindings {fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {let has_bindings = !self.bindings.is_empty();+ let rem_size = window.rem_size();// Measure the actual key components so the fixed header and scrolling rows- // share a column width.- let key_column_width = std::iter::once(self.pending_keystrokes.clone())- .chain(- self.bindings- .iter()- .map(|binding| binding.keystrokes.clone()),- )- .map(|keystrokes| {- Self::keybinding(keystrokes, cx)- .into_any_element()- .layout_as_root(- size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),- window,- cx,- )- .width- })+ // share a column width. Labels get their full width first and the key column takes+ // what's left of the panel, so a long sequence fades out instead of cropping labels.+ let pending_keystrokes_width =+ Self::keybinding_width(self.pending_keystrokes.clone(), window, cx);+ let binding_widths = self+ .bindings+ .iter()+ .map(|binding| Self::keybinding_width(binding.keystrokes.clone(), window, cx))+ .collect::<Vec<_>>();+ let widest_label = self+ .bindings+ .iter()+ .map(|binding| binding.action_name.clone())+ .chain([SharedString::from(HEADER_LABEL)])+ .map(|text| Self::label_width(text, window, cx)).fold(px(0.), Pixels::max);+ // `px_2` on both sides, the `gap_2` between columns, and the panel's 1px borders.+ let horizontal_chrome = rems(1.5).to_pixels(rem_size) + px(2.);+ let key_column_limit = (self.max_width - horizontal_chrome - widest_label)+ .max(MIN_KEY_COLUMN_WIDTH.to_pixels(rem_size))+ .min(MAX_KEY_COLUMN_WIDTH.to_pixels(rem_size));+ let key_column_width = binding_widths+ .iter()+ .copied()+ .fold(pending_keystrokes_width, Pixels::max)+ .min(key_column_limit);let content = h_flex().items_start().gap_2()@@ -147,12 +239,16 @@ impl RenderOnce for PendingBindings {.gap_1().items_end().flex_shrink_0()- .children(self.bindings.iter().map(|binding| {- h_flex()- .h_6()- .flex_none()- .child(Self::keybinding(binding.keystrokes.clone(), cx))- })),+ .children(self.bindings.iter().zip(&binding_widths).map(+ |(binding, keybinding_width)| {+ h_flex().h_6().flex_none().child(Self::key_cell(+ binding.keystrokes.clone(),+ *keybinding_width,+ key_column_width,+ cx,+ ))+ },+ )),).child(v_flex()@@ -186,10 +282,15 @@ impl RenderOnce for PendingBindings {.w(key_column_width).flex_shrink_0().justify_end()- .child(Self::keybinding(self.pending_keystrokes, cx)),+ .child(Self::key_cell(+ self.pending_keystrokes,+ pending_keystrokes_width,+ key_column_width,+ cx,+ )),).child(- Label::new("is waiting for more keys…")+ Label::new(HEADER_LABEL).size(LabelSize::Small).color(Color::Muted).single_line()@@ -330,11 +431,8 @@ mod tests {}#[test]- fn test_group_bindings_only_deduplicates_adjacent_sequences() {- for (sequences, expected_label) in [- (["g h", "g h", "g l"], "+2 keybinds"),- (["g h", "g l", "g h"], "+3 keybinds"),- ] {+ fn test_group_bindings_counts_distinct_sequences() {+ for sequences in [["g h", "g h", "g l"], ["g h", "g l", "g h"]] {let bindings = group_bindings(sequences.into_iter()@@ -344,7 +442,7 @@ mod tests {assert_eq!(bindings.len(), 1);let group = bindings.first().expect("group");- assert_eq!(group.action_name.as_ref(), expected_label);+ assert_eq!(group.action_name.as_ref(), "+2 keybinds");assert!(group.is_group);}}@@ -545,13 +643,18 @@ mod tests {}#[gpui::test]- fn test_prepare_pending_bindings_groups_complete_chord_with_continuation(cx: &mut App) {- // A custom keymap can keep Open Keymap on cmd-k cmd-s and add a longer chord.+ fn test_group_bindings_always_shows_completing_bindings(cx: &mut App) {+ ui::KeyBinding::set_vim_mode(cx, false);+ // A user keymap can extend the default cmd-k cmd-s binding with longer chords.let rows = prepare_pending_bindings(vec![binding_after_first_keystroke("cmd-k cmd-s", "zed::OpenKeymap"),binding_after_first_keystroke("cmd-k cmd-s cmd-,", "zed::OpenSettings"),- binding_after_first_keystroke("cmd-k cmd-t", "theme_selector::Toggle"),+ binding_after_first_keystroke("cmd-k cmd-s cmd-.", "zed::OpenKeymapFile"),+ binding_after_first_keystroke("cmd-k cmd-o", "workspace::Open"),+ binding_after_first_keystroke("cmd-k cmd-o cmd-p", "workspace::ReopenLastPicker"),+ binding_after_first_keystroke("cmd-k z a", "theme::ToggleMode"),+ binding_after_first_keystroke("cmd-k z b", "theme_selector::Toggle"),],cx,);@@ -565,9 +668,110 @@ mod tests {)).collect::<Vec<_>>(),vec![- (parse_keystrokes("cmd-t"), "theme selector: toggle", false),+ (parse_keystrokes("cmd-o"), "workspace: open", false),+ (parse_keystrokes("cmd-s"), "zed: open keymap", false),+ (+ parse_keystrokes("cmd-o cmd-p"),+ "workspace: reopen last picker",+ false+ ),+ (parse_keystrokes("z"), "+2 keybinds", true),(parse_keystrokes("cmd-s"), "+2 keybinds", true),],);}++ #[test]+ fn test_group_bindings_keeps_first_binding_per_sequence() {+ // A longer chord can sit between two bindings for the same keys, so duplicates aren't+ // always adjacent.+ let rows = group_bindings(vec![+ binding("a", "zed: open keymap"),+ binding("a b", "zed: open settings"),+ binding("a", "theme selector: toggle"),+ ]);++ assert_eq!(+ rows.iter()+ .map(|row| (row.keystrokes.to_vec(), row.action_name.as_ref()))+ .collect::<Vec<_>>(),+ vec![+ (parse_keystrokes("a"), "zed: open keymap"),+ (parse_keystrokes("a b"), "zed: open settings"),+ ],+ );+ assert!(rows.iter().all(|row| !row.is_group));+ }++ #[gpui::test]+ fn test_completing_row_matches_dispatch_with_continuation(cx: &mut App) {+ let contexts = [+ KeyContext::parse("Workspace").expect("valid context"),+ KeyContext::parse("Editor").expect("valid context"),+ ];+ let keymap = Keymap::new(vec![+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenKeymap, Some("Workspace")),+ KeyBinding::new(+ "cmd-k cmd-s cmd-,",+ zed_actions::OpenKeymapFile,+ Some("Workspace"),+ ),+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenSettings, Some("Editor")),+ ]);+ let input = [+ Keystroke::parse("cmd-k").expect("valid keystroke"),+ Keystroke::parse("cmd-s").expect("valid keystroke"),+ ];++ let (matches, _) = keymap.bindings_for_input(&input, &contexts);+ let first_match = matches.first().expect("matching binding");+ assert_eq!(+ first_match.action().name(),+ zed_actions::OpenSettings.name()+ );++ // The longer chord comes between the two cmd-k cmd-s bindings, so they aren't adjacent.+ let candidates = keymap.possible_next_bindings_for_input(&input[..1], &contexts);+ assert_eq!(+ candidates+ .iter()+ .map(|binding| binding.action().name())+ .collect::<Vec<_>>(),+ vec![+ zed_actions::OpenSettings.name(),+ zed_actions::OpenKeymapFile.name(),+ zed_actions::OpenKeymap.name(),+ ],+ );++ let pending = candidates+ .into_iter()+ .map(|binding| PendingBinding {+ remaining_keystrokes: binding.keystrokes().iter().skip(1).cloned().collect(),+ action_name: command_palette::humanize_action_name(binding.action().name()).into(),+ })+ .collect();+ let rows = prepare_pending_bindings(pending, cx);+ assert_eq!(+ rows.iter()+ .map(|row| (+ row.keystrokes.to_vec(),+ row.action_name.to_string(),+ row.is_group,+ ))+ .collect::<Vec<_>>(),+ vec![+ (+ parse_keystrokes("cmd-s"),+ command_palette::humanize_action_name(first_match.action().name()),+ false,+ ),+ (+ parse_keystrokes("cmd-s cmd-,"),+ command_palette::humanize_action_name(zed_actions::OpenKeymapFile.name()),+ false,+ ),+ ],+ );+ }}diff --git a/crates/which_key/src/pending_keystrokes_indicator.rs b/crates/which_key/src/pending_keystrokes_indicator.rsindex 49597b8275b..65d591e7ffa 100644--- a/crates/which_key/src/pending_keystrokes_indicator.rs+++ b/crates/which_key/src/pending_keystrokes_indicator.rs@@ -354,6 +354,7 @@ impl Render for PendingKeystrokesIndicator {popover_render_state.keystrokes.clone(),popover_render_state.bindings.clone(),self.popover_scroll_handle.clone(),+ max_panel_width,max_content_height,),)@@ -1175,7 +1176,16 @@ mod tests {assert_eq!(first_render_state.keystrokes, vec!["ctrl-b"]);assert_eq!(first_render_state.bindings,- vec![(vec!["h".to_string()], "+2 keybinds".to_string())]+ vec![+ (+ vec!["h".to_string()],+ humanize_action_name(LongerBinding.name()),+ ),+ (+ vec!["h".to_string(), "j".to_string()],+ humanize_action_name(LongestBinding.name()),+ ),+ ]);cx.simulate_keystrokes("h");diff --git a/crates/which_key/src/which_key.rs b/crates/which_key/src/which_key.rsindex eff17ad7811..11605431870 100644--- a/crates/which_key/src/which_key.rs+++ b/crates/which_key/src/which_key.rs@@ -69,6 +69,9 @@ fn collect_bindings_for_pending_input(pending_keystrokes: &[Keystroke],mut include_binding: impl FnMut(&gpui::KeyBinding) -> bool,) -> Vec<PendingBinding> {+ // Which-key uses GPUI's candidate list as is, on purpose, instead of repeating dispatch rules.+ // The list can include a longer chord that can't be typed because a shorter binding for its+ // prefix comes later in the keymap. GPUI's shortcut display shows those chords too.window.possible_bindings_for_input(pending_keystrokes).into_iter()diff --git a/crates/which_key/src/which_key_modal.rs b/crates/which_key/src/which_key_modal.rsindex 9f9d1ac7a33..dcc545e769f 100644--- a/crates/which_key/src/which_key_modal.rs+++ b/crates/which_key/src/which_key_modal.rs@@ -117,6 +117,7 @@ impl Render for WhichKeyModal {self.pending_keys.clone(),self.bindings.clone(),self.scroll_handle.clone(),+ max_panel_width,max_content_height,))}