Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
which_key: Unify preparation and rendering for which-key and the pending keystrokes indicator (#64522)
Smit Barmase7fecbb2c4b0c
diff --git a/crates/ui/src/components/keybinding.rs b/crates/ui/src/components/keybinding.rsindex 0d03ddff3c1..cd58c284cb7 100644--- a/crates/ui/src/components/keybinding.rs+++ b/crates/ui/src/components/keybinding.rs@@ -106,7 +106,8 @@ impl KeyBinding {cx.set_global(VimStyle(enabled));}- fn is_vim_mode(cx: &App) -> bool {+ /// Returns whether keybindings use Vim-style notation.+ pub fn is_vim_mode(cx: &App) -> bool {cx.try_global::<VimStyle>().is_some_and(|g| g.0)}diff --git a/crates/which_key/src/pending_bindings.rs b/crates/which_key/src/pending_bindings.rsnew file mode 100644index 00000000000..92ad34cdbc6--- /dev/null+++ b/crates/which_key/src/pending_bindings.rs@@ -0,0 +1,573 @@+use std::{collections::HashMap, rc::Rc};++use gpui::{+ App, AvailableSpace, KeybindingKeystroke, Pixels, RenderOnce, ScrollHandle, Window, size,+};+use ui::{+ Divider, DividerColor, KeyBinding, LabelSize, WithScrollbar, prelude::*,+ text_for_keybinding_keystrokes,+};++use crate::PendingBinding;++#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct PendingBindingRow {+ pub(crate) keystrokes: Rc<[KeybindingKeystroke]>,+ pub(crate) action_name: SharedString,+ pub(crate) is_group: bool,+}++pub(crate) fn prepare_pending_bindings(+ bindings: Vec<PendingBinding>,+ cx: &App,+) -> Vec<PendingBindingRow> {+ let mut rows = group_bindings(bindings)+ .into_iter()+ .map(|row| {+ let formatted_text = text_for_keybinding_keystrokes(&row.keystrokes, cx);+ (row, formatted_text)+ })+ .collect::<Vec<_>>();++ rows.sort_by(|(row_a, text_a), (row_b, text_b)| {+ row_a+ .is_group+ .cmp(&row_b.is_group)+ .then_with(|| row_a.keystrokes.len().cmp(&row_b.keystrokes.len()))+ .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+ for binding in bindings {+ groups+ .entry(binding.remaining_keystrokes.first().cloned())+ .or_default()+ .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+ {+ // Collapse bindings sharing the next keystroke into a single row.+ result.push(PendingBindingRow {+ keystrokes: Rc::from([first_keystroke]),+ action_name: format!("+{} keybinds", bindings.len()).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+}++#[derive(IntoElement)]+pub(crate) struct PendingBindings {+ id: &'static str,+ pending_keystrokes: Rc<[KeybindingKeystroke]>,+ bindings: Rc<[PendingBindingRow]>,+ scroll_handle: ScrollHandle,+ max_content_height: Pixels,+}++impl PendingBindings {+ pub(crate) fn new(+ id: &'static str,+ pending_keystrokes: Rc<[KeybindingKeystroke]>,+ bindings: Rc<[PendingBindingRow]>,+ scroll_handle: ScrollHandle,+ max_content_height: Pixels,+ ) -> Self {+ Self {+ id,+ pending_keystrokes,+ bindings,+ scroll_handle,+ max_content_height,+ }+ }++ fn keybinding(keystrokes: Rc<[KeybindingKeystroke]>, cx: &App) -> KeyBinding {+ KeyBinding::from_keystrokes(keystrokes, KeyBinding::is_vim_mode(cx)).color(Color::Accent)+ }+}++impl RenderOnce for PendingBindings {+ fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {+ let has_bindings = !self.bindings.is_empty();+ // 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+ })+ .fold(px(0.), Pixels::max);+ let content = h_flex()+ .items_start()+ .gap_2()+ .px_2()+ .py_1()+ .child(+ v_flex()+ .w(key_column_width)+ .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))+ })),+ )+ .child(+ v_flex()+ .gap_1()+ .flex_1()+ .min_w_0()+ .children(self.bindings.iter().map(|binding| {+ h_flex().h_6().flex_none().w_full().min_w_0().child(+ Label::new(binding.action_name.clone())+ .size(LabelSize::Small)+ .color(if binding.is_group {+ Color::Success+ } else {+ Color::Default+ })+ .single_line()+ .truncate(),+ )+ })),+ );++ v_flex()+ // Title section+ .child(+ h_flex()+ .gap_2()+ .px_2()+ .py_1()+ .child(+ h_flex()+ .w(key_column_width)+ .flex_shrink_0()+ .justify_end()+ .child(Self::keybinding(self.pending_keystrokes, cx)),+ )+ .child(+ Label::new("is waiting for more keys…")+ .size(LabelSize::Small)+ .color(Color::Muted)+ .single_line()+ .truncate(),+ ),+ )+ .when(has_bindings, |element| {+ element.child(Divider::horizontal().color(DividerColor::BorderFaded))+ })+ .when(has_bindings, |element| {+ element.child(+ div()+ .max_h(self.max_content_height)+ .child(+ div()+ .id(self.id)+ .overflow_y_scroll()+ .track_scroll(&self.scroll_handle)+ .max_h(self.max_content_height)+ .child(content),+ )+ .vertical_scrollbar_for(&self.scroll_handle, window, cx),+ )+ })+ }+}++#[cfg(test)]+mod tests {+ use gpui::{Action as _, KeyBinding, KeyContext, Keymap, Keystroke, TestAppContext};+ use settings::KeybindSource;++ use super::*;++ fn parse_keystrokes(keystrokes: &str) -> Vec<KeybindingKeystroke> {+ keystrokes+ .split_whitespace()+ .map(|keystroke| {+ KeybindingKeystroke::from_keystroke(+ Keystroke::parse(keystroke).expect("valid test keystroke"),+ )+ })+ .collect()+ }++ fn binding(keystrokes: &str, action_name: &str) -> PendingBinding {+ PendingBinding {+ remaining_keystrokes: parse_keystrokes(keystrokes),+ action_name: action_name.into(),+ }+ }++ fn binding_after_first_keystroke(chord: &str, action_name: &str) -> PendingBinding {+ let (_, remaining_keystrokes) = chord.split_once(' ').expect("multi-keystroke binding");+ binding(+ remaining_keystrokes,+ &command_palette::humanize_action_name(action_name),+ )+ }++ fn unparsed_keystrokes(binding: &PendingBindingRow) -> Vec<String> {+ binding+ .keystrokes+ .iter()+ .map(|keystroke| keystroke.inner().unparse())+ .collect()+ }++ #[gpui::test]+ fn test_pending_keybinding_uses_active_vim_style(cx: &mut TestAppContext) {+ let cx = cx.add_empty_window();+ cx.update(|window, cx| {+ // Toggle Vim notation on and back off to catch stale formatting after a mode change.+ for vim_mode in [false, true, false] {+ ui::KeyBinding::set_vim_mode(cx, vim_mode);+ for sequence in ["g", "h", "ctrl-w", "shift-h"] {+ let keystrokes: Rc<[KeybindingKeystroke]> =+ binding(sequence, "Action").remaining_keystrokes.into();+ let expected = text_for_keybinding_keystrokes(&keystrokes, cx);+ let keybinding = PendingBindings::keybinding(keystrokes, cx);+ assert_eq!(+ keybinding+ .keyboard_shortcut_text(window, cx)+ .expect("keybinding label")+ .as_ref(),+ expected,+ "sequence {sequence}, Vim mode {vim_mode}",+ );+ }+ }+ });+ }++ #[gpui::test]+ fn test_prepare_pending_bindings_preserves_keybinding_keystrokes(cx: &mut App) {+ #[cfg(target_os = "windows")]+ let keystroke = KeybindingKeystroke::new(+ Keystroke::parse("ctrl-$").expect("valid keystroke"),+ gpui::Modifiers::control_shift(),+ "4".to_owned(),+ );+ #[cfg(not(target_os = "windows"))]+ let keystroke = KeybindingKeystroke::from_keystroke(+ Keystroke::parse("ctrl-x").expect("valid keystroke"),+ );++ for grouped in [false, true] {+ let bindings = if grouped {+ ["h", "j"]+ .into_iter()+ .map(|key| PendingBinding {+ remaining_keystrokes: vec![+ keystroke.clone(),+ KeybindingKeystroke::from_keystroke(+ Keystroke::parse(key).expect("valid keystroke"),+ ),+ ],+ action_name: key.into(),+ })+ .collect()+ } else {+ vec![PendingBinding {+ remaining_keystrokes: vec![keystroke.clone()],+ action_name: "Action".into(),+ }]+ };+ let rows = prepare_pending_bindings(bindings, cx);+ assert_eq!(rows.len(), 1);+ let row = rows.first().expect("prepared binding");+ assert_eq!(row.keystrokes.as_ref(), std::slice::from_ref(&keystroke));+ assert_eq!(row.is_group, grouped);+ #[cfg(target_os = "windows")]+ assert_eq!(+ text_for_keybinding_keystrokes(&row.keystrokes, cx),+ "Ctrl-Shift-4"+ );+ }+ }++ #[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"),+ ] {+ let bindings = group_bindings(+ sequences+ .into_iter()+ .map(|sequence| binding(sequence, "zed: open settings"))+ .collect(),+ );++ assert_eq!(bindings.len(), 1);+ let group = bindings.first().expect("group");+ assert_eq!(group.action_name.as_ref(), expected_label);+ assert!(group.is_group);+ }+ }++ #[gpui::test]+ fn test_duplicate_selection_preserves_candidate_order(cx: &mut App) {+ let contexts = [+ KeyContext::parse("Workspace").expect("valid context"),+ KeyContext::parse("Editor").expect("valid context"),+ ];+ let input = [+ Keystroke::parse("cmd-k").expect("valid keystroke"),+ Keystroke::parse("cmd-s").expect("valid keystroke"),+ ];+ for bindings in [+ vec![+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenKeymap, Some("Workspace"))+ .with_meta(KeybindSource::User.meta()),+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenSettings, Some("Workspace"))+ .with_meta(KeybindSource::User.meta()),+ ],+ vec![+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenSettings, Some("Editor"))+ .with_meta(KeybindSource::Default.meta()),+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenKeymap, Some("Workspace"))+ .with_meta(KeybindSource::User.meta()),+ ],+ vec![+ KeyBinding::new("cmd-k cmd-s", zed_actions::OpenKeymap, Some("Workspace"))+ .with_meta(KeybindSource::Default.meta()),+ KeyBinding::load(+ "cmd-k cmd-s",+ Box::new(zed_actions::OpenSettings),+ Some(+ gpui::KeyBindingContextPredicate::parse("Workspace")+ .expect("valid context")+ .into(),+ ),+ true,+ None,+ cx.keyboard_mapper().as_ref(),+ )+ .expect("user binding with key equivalents")+ .with_meta(KeybindSource::User.meta()),+ ],+ ] {+ let keymap = Keymap::new(bindings);+ 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()+ );++ 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::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.len(), 1);+ let row = rows.first().expect("remaining binding");+ assert_eq!(+ row.action_name.as_ref(),+ command_palette::humanize_action_name(first_match.action().name())+ );+ }+ }++ #[gpui::test]+ fn test_prepare_pending_bindings_sorts_shorter_chords_first(cx: &mut App) {+ let bindings = prepare_pending_bindings(+ vec![+ binding_after_first_keystroke("cmd-k z a", "zed::OpenSettings"),+ binding_after_first_keystroke("cmd-k cmd-shift-t", "theme::ToggleMode"),+ ],+ cx,+ );++ assert_eq!(+ bindings+ .iter()+ .map(|row| row.keystrokes.to_vec())+ .collect::<Vec<_>>(),+ vec![parse_keystrokes("cmd-shift-t"), parse_keystrokes("z a")],+ );+ }++ #[gpui::test]+ fn test_prepare_pending_bindings_sorts_by_key_label_length(cx: &mut App) {+ ui::KeyBinding::set_vim_mode(cx, false);+ // These default macOS chords both follow cmd-k. Key-label length takes+ // precedence over alphabetical key order: "Z" comes before "Command-Left".+ let rows = prepare_pending_bindings(+ vec![+ binding_after_first_keystroke("cmd-k cmd-left", "workspace::ActivatePaneLeft"),+ binding_after_first_keystroke("cmd-k z", "editor::ToggleSoftWrap"),+ ],+ cx,+ );++ assert_eq!(+ rows.iter()+ .map(|row| row.keystrokes.to_vec())+ .collect::<Vec<_>>(),+ vec![parse_keystrokes("z"), parse_keystrokes("cmd-left")],+ );+ }++ #[gpui::test]+ fn test_prepare_pending_bindings_sorts_equal_length_key_labels(cx: &mut App) {+ ui::KeyBinding::set_vim_mode(cx, false);+ // After cmd-k, language selection (m) precedes encoding selection (n),+ // even though their action names sort in the opposite order.+ let rows = prepare_pending_bindings(+ vec![+ binding_after_first_keystroke("cmd-k n", "encoding_selector::Toggle"),+ binding_after_first_keystroke("cmd-k m", "language_selector::Toggle"),+ ],+ cx,+ );++ assert_eq!(+ rows.iter().map(unparsed_keystrokes).collect::<Vec<_>>(),+ vec![vec!["m"], vec!["n"]],+ );+ }++ #[gpui::test]+ fn test_prepare_pending_bindings_preserves_distinct_actions_with_identical_key_labels(+ cx: &mut App,+ ) {+ ui::KeyBinding::set_vim_mode(cx, false);+ for reverse in [false, true] {+ // Custom bindings are needed to exercise a display collision: é and É+ // are distinct keys, but non-Vim formatting capitalizes both to "É".+ let mut bindings = vec![+ binding_after_first_keystroke("cmd-k é", "zed::OpenSettings"),+ binding_after_first_keystroke("cmd-k É", "zed::OpenKeymap"),+ ];+ let first = bindings.first().expect("first binding");+ let second = bindings.last().expect("second binding");+ assert_ne!(first.remaining_keystrokes, second.remaining_keystrokes);+ assert_eq!(+ text_for_keybinding_keystrokes(&first.remaining_keystrokes, cx),+ text_for_keybinding_keystrokes(&second.remaining_keystrokes, cx),+ );+ if reverse {+ bindings.reverse();+ }++ let rows = prepare_pending_bindings(bindings, cx);+ let mut action_names = rows+ .iter()+ .map(|row| row.action_name.as_ref())+ .collect::<Vec<_>>();+ action_names.sort();+ assert_eq!(action_names, vec!["zed: open keymap", "zed: open settings"]);+ assert!(rows.iter().all(|row| !row.is_group));+ }+ }++ #[gpui::test]+ fn test_prepare_pending_bindings_preserves_distinct_keys_with_identical_display_rows(+ cx: &mut App,+ ) {+ ui::KeyBinding::set_vim_mode(cx, false);+ let rows = prepare_pending_bindings(+ vec![+ binding_after_first_keystroke("cmd-k é", "zed::OpenSettings"),+ binding_after_first_keystroke("cmd-k É", "zed::OpenSettings"),+ ],+ cx,+ );++ let mut keys = rows.iter().map(unparsed_keystrokes).collect::<Vec<_>>();+ keys.sort();+ assert_eq!(keys, vec![vec!["É"], vec!["é"]]);+ for row in rows {+ assert_eq!(text_for_keybinding_keystrokes(&row.keystrokes, cx), "É");+ assert_eq!(row.action_name.as_ref(), "zed: open settings");+ assert!(!row.is_group);+ }+ }++ #[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.+ 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"),+ ],+ cx,+ );++ assert_eq!(+ rows.iter()+ .map(|row| (+ row.keystrokes.to_vec(),+ row.action_name.as_ref(),+ row.is_group,+ ))+ .collect::<Vec<_>>(),+ vec![+ (parse_keystrokes("cmd-t"), "theme selector: toggle", false),+ (parse_keystrokes("cmd-s"), "+2 keybinds", true),+ ],+ );+ }+}diff --git a/crates/which_key/src/pending_keystrokes_indicator.rs b/crates/which_key/src/pending_keystrokes_indicator.rsindex 8259ad5d057..9c4180c3c60 100644--- a/crates/which_key/src/pending_keystrokes_indicator.rs+++ b/crates/which_key/src/pending_keystrokes_indicator.rs@@ -1,22 +1,22 @@use gpui::{Action as _, Anchor, Animation, AnimationExt, App, Context, HoverListenerMode,- KeybindingKeystroke, Render, Subscription, Task, Window, anchored, deferred,+ KeybindingKeystroke, Render, ScrollHandle, Subscription, Task, Window, anchored, deferred,};use settings::{Settings, SettingsStore};use std::{rc::Rc, time::Duration};use ui::{- ButtonLike, CircularProgress, KeyBinding, KeyBindingStyle, prelude::*,- text_for_keybinding_keystrokes, tooltip_container,+ ButtonLike, CircularProgress, KeyBinding, KeyBindingStyle, prelude::*, tooltip_container,};use util::ResultExt;use vim_mode_setting::{HelixModeSetting, VimModeSetting};use workspace::{HideStatusItem, StatusBarSettings, StatusItemView, item::ItemHandle};use crate::{- bindings_for_pending_input, map_pending_keystrokes, which_key_settings::WhichKeySettings,+ bindings_for_pending_input, map_pending_keystrokes,+ pending_bindings::{PendingBindingRow, PendingBindings, prepare_pending_bindings},+ which_key_settings::WhichKeySettings,};-const MAX_TOOLTIP_BINDINGS: usize = 10;const POPOVER_HIDE_DELAY: Duration = Duration::from_millis(300);/// A status bar item shown while pending input can complete a multi-stroke key binding.@@ -24,6 +24,7 @@ pub struct PendingKeystrokesIndicator {render_state: Option<Rc<IndicatorRenderState>>,pending_input_generation: u64,popover: PopoverState,+ popover_scroll_handle: ScrollHandle,_pending_input_subscription: Subscription,_settings_subscription: Subscription,}@@ -45,7 +46,7 @@ impl PopoverState {struct IndicatorRenderState {keystrokes: Rc<[KeybindingKeystroke]>,pending_input_generation: u64,- bindings: Vec<(Rc<[KeybindingKeystroke]>, SharedString)>,+ bindings: Rc<[PendingBindingRow]>,timeout: Option<IndicatorTimeout>,}@@ -92,6 +93,7 @@ impl PendingKeystrokesIndicator {render_state: None,pending_input_generation: 0,popover: PopoverState::default(),+ popover_scroll_handle: ScrollHandle::new(),_pending_input_subscription: pending_input_subscription,_settings_subscription: settings_subscription,}@@ -119,39 +121,19 @@ impl PendingKeystrokesIndicator {};let keystrokes = pending_input.keystrokes();- let mut bindings = bindings_for_pending_input(window, keystrokes)- .into_iter()- .map(|binding| {- let remaining_text =- text_for_keybinding_keystrokes(&binding.remaining_keystrokes, cx);- (- remaining_text,- binding.remaining_keystrokes,- binding.action_name,- )- })- .collect::<Vec<_>>();- bindings.sort_by(|(text_a, keys_a, action_a), (text_b, keys_b, action_b)| {- keys_a- .len()- .cmp(&keys_b.len())- .then_with(|| text_a.cmp(text_b))- .then_with(|| action_a.cmp(action_b))- });- bindings.dedup_by(|(text_a, _, action_a), (text_b, _, action_b)| {- text_a == text_b && action_a == action_b- });+ let bindings = prepare_pending_bindings(bindings_for_pending_input(window, keystrokes), cx);let keystrokes = map_pending_keystrokes(keystrokes, cx.keyboard_mapper().as_ref());+ let pending_keys_changed = self+ .render_state+ .as_ref()+ .is_none_or(|previous| previous.keystrokes.as_ref() != keystrokes.as_slice());+ if pending_keys_changed {+ self.popover_scroll_handle.set_offset(Default::default());+ }// Pausing or resuming the timer also notifies observers.// Only a change in pending keys should close the popover early.- if self.popover.visible- && !self.popover.is_pointer_over()- && self- .render_state- .as_ref()- .is_some_and(|previous| previous.keystrokes.as_ref() != keystrokes.as_slice())- {+ if self.popover.visible && !self.popover.is_pointer_over() && pending_keys_changed {self.popover = PopoverState::default();}@@ -159,10 +141,7 @@ impl PendingKeystrokesIndicator {self.render_state = Some(Rc::new(IndicatorRenderState {keystrokes: keystrokes.into(),pending_input_generation: self.pending_input_generation,- bindings: bindings- .into_iter()- .map(|(_, keystrokes, action)| (Rc::from(keystrokes), action))- .collect(),+ bindings: bindings.into(),timeout: pending_input.timeout().map(|timeout| IndicatorTimeout {timeout_duration: timeout.duration(),remaining_duration: timeout.remaining(cx),@@ -174,6 +153,7 @@ impl PendingKeystrokesIndicator {fn clear_render_state(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {self.popover = PopoverState::default();+ self.popover_scroll_handle.set_offset(Default::default());window.set_pending_input_timeout_paused(&cx.entity(), false, cx);self.render_state.take().is_some()}@@ -295,6 +275,9 @@ impl Render for PendingKeystrokesIndicator {let popover = self.popover.visible.then(|| {let popover_render_state = render_state.clone();+ let viewport_size = window.viewport_size();+ let max_panel_width = px((f32::from(viewport_size.width) * 0.5).min(480.0));+ let max_content_height = px(f32::from(viewport_size.height) * 0.4);let anchored_popover = deferred(anchored().anchor(Anchor::BottomRight)@@ -310,60 +293,14 @@ impl Render for PendingKeystrokesIndicator {})).hover_listener_mode(HoverListenerMode::InputModalityIndependent).child(tooltip_container(cx, |el, _| {- el.child(- v_flex()- .gap_1()- .child(- h_flex()- .gap_1()- .child(- KeyBinding::from_keystrokes(- popover_render_state.keystrokes.clone(),- false,- )- .color(Color::Accent),- )- .child(- Label::new("is waiting for more keys")- .color(Color::Muted),- ),- )- .children(- popover_render_state- .bindings- .iter()- .take(MAX_TOOLTIP_BINDINGS)- .map(|(keystrokes, action)| {- h_flex()- .gap_2()- .child(- KeyBinding::from_keystrokes(- keystrokes.clone(),- false,- )- .color(Color::Accent),- )- .child(- Label::new(action.clone())- .size(LabelSize::Small),- )- }),- )- .when(- popover_render_state.bindings.len()- > MAX_TOOLTIP_BINDINGS,- |el| {- el.child(- Label::new(format!(- "…and {} more",- popover_render_state.bindings.len()- - MAX_TOOLTIP_BINDINGS- ))- .size(LabelSize::Small)- .color(Color::Muted),- )- },- ),+ el.p_0().max_w(max_panel_width).overflow_hidden().child(+ PendingBindings::new(+ "pending-keystrokes-popover-content",+ popover_render_state.keystrokes.clone(),+ popover_render_state.bindings.clone(),+ self.popover_scroll_handle.clone(),+ max_content_height,+ ),)})),),@@ -492,13 +429,14 @@ mod tests {bindings: render_state.bindings.iter()- .map(|(keystrokes, action)| {+ .map(|binding| {(- keystrokes+ binding+ .keystrokes.iter().map(|keystroke| keystroke.inner().unparse()).collect(),- action.to_string(),+ binding.action_name.to_string(),)}).collect(),@@ -631,16 +569,7 @@ mod tests {assert_eq!(first_render_state.keystrokes, vec!["ctrl-b"]);assert_eq!(first_render_state.bindings,- vec![- (- vec!["h".to_string()],- humanize_action_name(LongerBinding.name()),- ),- (- vec!["h".to_string(), "j".to_string()],- humanize_action_name(LongestBinding.name()),- ),- ]+ vec![(vec!["h".to_string()], "+2 keybinds".to_string())]);cx.simulate_keystrokes("h");diff --git a/crates/which_key/src/which_key.rs b/crates/which_key/src/which_key.rsindex 493aefcfe2d..6f2d6d344b5 100644--- a/crates/which_key/src/which_key.rs+++ b/crates/which_key/src/which_key.rs@@ -1,5 +1,6 @@//! Which-key support for Zed.+mod pending_bindings;mod pending_keystrokes_indicator;mod which_key_modal;mod which_key_settings;diff --git a/crates/which_key/src/which_key_modal.rs b/crates/which_key/src/which_key_modal.rsindex 689ce10cc77..9f9d1ac7a33 100644--- a/crates/which_key/src/which_key_modal.rs+++ b/crates/which_key/src/which_key_modal.rs@@ -1,27 +1,26 @@//! Modal implementation for the which-key display.-use gpui::prelude::FluentBuilder;use gpui::{- App, Context, DismissEvent, EventEmitter, FocusHandle, Focusable, FontWeight,- KeybindingKeystroke, ScrollHandle, Subscription, WeakEntity, Window,+ App, Context, DismissEvent, EventEmitter, FocusHandle, Focusable, KeybindingKeystroke,+ ScrollHandle, Subscription, WeakEntity, Window,};use settings::Settings;-use std::collections::HashMap;+use std::rc::Rc;use theme_settings::ThemeSettings;-use ui::{- Divider, DividerColor, DynamicSpacing, LabelSize, WithScrollbar, prelude::*,- text_for_keybinding_keystrokes,-};+use ui::{DynamicSpacing, prelude::*};use workspace::{ModalView, Workspace};-use crate::{bindings_for_which_key, map_pending_keystrokes};+use crate::{+ bindings_for_which_key, map_pending_keystrokes,+ pending_bindings::{PendingBindingRow, PendingBindings, prepare_pending_bindings},+};pub struct WhichKeyModal {_workspace: WeakEntity<Workspace>,focus_handle: FocusHandle,scroll_handle: ScrollHandle,- bindings: Vec<(SharedString, SharedString)>,- pending_keys: SharedString,+ bindings: Rc<[PendingBindingRow]>,+ pending_keys: Rc<[KeybindingKeystroke]>,_pending_input_subscription: Subscription,_focus_out_subscription: Subscription,}@@ -40,8 +39,8 @@ impl WhichKeyModal {_workspace: workspace,focus_handle: focus_handle.clone(),scroll_handle: ScrollHandle::new(),- bindings: Vec::new(),- pending_keys: SharedString::new_static(""),+ bindings: Rc::from([]),+ pending_keys: Rc::from([]),_pending_input_subscription: cx.observe_pending_input(window,|this: &mut Self, window, cx| {@@ -65,59 +64,18 @@ impl WhichKeyModal {cx.emit(DismissEvent);return;};- let mut binding_data = bindings_for_which_key(window, pending_keys)- .into_iter()- .map(|binding| (binding.remaining_keystrokes, binding.action_name))- .collect();-- binding_data = group_bindings(binding_data);-- // Sort bindings from shortest to longest, with groups last- // Using stable sort to preserve relative order of equal elements- binding_data.sort_by(|(keystrokes_a, action_a), (keystrokes_b, action_b)| {- // Groups (actions starting with "+") should go last- let is_group_a = action_a.starts_with('+');- let is_group_b = action_b.starts_with('+');-- // First, separate groups from non-groups- let group_cmp = is_group_a.cmp(&is_group_b);- if group_cmp != std::cmp::Ordering::Equal {- return group_cmp;- }-- // Then sort by keystroke count- let keystroke_cmp = keystrokes_a.len().cmp(&keystrokes_b.len());- if keystroke_cmp != std::cmp::Ordering::Equal {- return keystroke_cmp;- }-- // Finally sort by text length, then lexicographically for full stability- let text_a = text_for_keybinding_keystrokes(keystrokes_a, cx);- let text_b = text_for_keybinding_keystrokes(keystrokes_b, cx);- let text_len_cmp = text_a.len().cmp(&text_b.len());- if text_len_cmp != std::cmp::Ordering::Equal {- return text_len_cmp;- }- text_a.cmp(&text_b)- });- binding_data.dedup();+ self.bindings =+ prepare_pending_bindings(bindings_for_which_key(window, pending_keys), cx).into();let pending_keys = map_pending_keystrokes(pending_keys, cx.keyboard_mapper().as_ref());- self.pending_keys = text_for_keybinding_keystrokes(&pending_keys, cx).into();- self.bindings = binding_data- .into_iter()- .map(|(keystrokes, action)| {- (- text_for_keybinding_keystrokes(&keystrokes, cx).into(),- action,- )- })- .collect();+ if self.pending_keys.as_ref() != pending_keys.as_slice() {+ self.scroll_handle.set_offset(Default::default());+ }+ self.pending_keys = pending_keys.into();}}impl Render for WhichKeyModal {fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {- let has_rows = !self.bindings.is_empty();let viewport_size = window.viewport_size();let max_panel_width = px((f32::from(viewport_size.width) * 0.5).min(480.0));@@ -144,77 +102,6 @@ impl Render for WhichKeyModal {let margin_bottom = px(16.);let bottom_offset = margin_bottom + status_height;- // Title section- let title_section = {- let mut column = v_flex().gap(px(0.)).child(- div()- .child(- Label::new(self.pending_keys.clone())- .size(LabelSize::Default)- .weight(FontWeight::MEDIUM)- .color(Color::Accent),- )- .mb(px(2.)),- );-- if has_rows {- column = column.child(- div()- .child(Divider::horizontal().color(DividerColor::BorderFaded))- .mb(px(2.)),- );- }-- column- };-- let content = h_flex()- .items_start()- .id("which-key-content")- .gap(px(8.))- .overflow_y_scroll()- .track_scroll(&self.scroll_handle)- .h_full()- .max_h(max_content_height)- .child(- // Keystrokes column- v_flex()- .gap(px(4.))- .flex_shrink_0()- .children(self.bindings.iter().map(|(keystrokes, _)| {- div()- .child(- Label::new(keystrokes.clone())- .size(LabelSize::Default)- .color(Color::Accent),- )- .text_align(gpui::TextAlign::Right)- })),- )- .child(- // Actions column- v_flex()- .gap(px(4.))- .flex_1()- .min_w_0()- .children(self.bindings.iter().map(|(_, action_name)| {- let is_group = action_name.starts_with('+');- let label_color = if is_group {- Color::Success- } else {- Color::Default- };-- div().child(- Label::new(action_name.clone())- .size(LabelSize::Default)- .color(label_color)- .single_line()- .truncate(),- )- })),- );-div().id("which-key-buffer-panel-scroll").occlude()@@ -224,15 +111,14 @@ impl Render for WhichKeyModal {.min_w(px(220.)).max_w(max_panel_width).elevation_3(cx)- .px(px(12.))- .child(v_flex().child(title_section).when(has_rows, |el| {- el.child(- div()- .max_h(max_content_height)- .child(content)- .vertical_scrollbar_for(&self.scroll_handle, window, cx),- )- }))+ .overflow_hidden()+ .child(PendingBindings::new(+ "which-key-content",+ self.pending_keys.clone(),+ self.bindings.clone(),+ self.scroll_handle.clone(),+ max_content_height,+ ))}}@@ -249,153 +135,3 @@ impl ModalView for WhichKeyModal {true}}--fn group_bindings(- binding_data: Vec<(Vec<KeybindingKeystroke>, SharedString)>,-) -> Vec<(Vec<KeybindingKeystroke>, SharedString)> {- let mut groups: HashMap<- Option<KeybindingKeystroke>,- Vec<(Vec<KeybindingKeystroke>, SharedString)>,- > = HashMap::new();-- // Group bindings by their first keystroke- for (remaining_keystrokes, action_name) in binding_data {- let first_key = remaining_keystrokes.first().cloned();- groups- .entry(first_key)- .or_default()- .push((remaining_keystrokes, action_name));- }-- let mut result = Vec::new();-- for (first_key, mut group_bindings) in groups {- // Remove duplicates within each group- group_bindings.dedup_by_key(|(keystrokes, _)| keystrokes.clone());-- if let Some(first_key) = first_key- && group_bindings.len() > 1- {- // This is a group - create a single entry with just the first keystroke- let first_keystroke = vec![first_key];- let count = group_bindings.len();- result.push((first_keystroke, format!("+{} keybinds", count).into()));- } else {- // Not a group or empty keystrokes - add all bindings as-is- result.append(&mut group_bindings);- }- }-- result-}--#[cfg(test)]-mod tests {- #[cfg(target_os = "windows")]- use gpui::Modifiers;- use gpui::{- Action as _, Entity, FocusHandle, InvalidKeystrokeError, KeyBinding, Keystroke,- TestAppContext, VisualTestContext, actions,- };-- use super::*;-- actions!(- which_key_modal_test,- [FirstBinding, SecondBinding, ThirdBinding]- );-- struct TestView {- focus_handle: FocusHandle,- }-- impl Render for TestView {- fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {- div()- .key_context("WhichKeyModalTest")- .track_focus(&self.focus_handle)- .on_action(|_: &FirstBinding, _, _| {})- .on_action(|_: &SecondBinding, _, _| {})- .on_action(|_: &ThirdBinding, _, _| {})- }- }-- fn setup_modal_test<'a>(- cx: &'a mut TestAppContext,- bindings: impl IntoIterator<Item = KeyBinding>,- pending_keystrokes: &str,- ) -> (Entity<WhichKeyModal>, &'a mut VisualTestContext) {- cx.update(|cx| cx.bind_keys(bindings));- let (test_view, cx) = cx.add_window_view(|_, cx| TestView {- focus_handle: cx.focus_handle(),- });- let focus_handle = test_view.read_with(cx, |test_view, _| test_view.focus_handle.clone());- cx.update(|window, cx| {- window.focus(&focus_handle, cx);- window.activate_window();- });- cx.simulate_keystrokes(pending_keystrokes);- cx.run_until_parked();- cx.update(|window, _| assert!(window.has_pending_keystrokes()));-- let modal = cx.update(|window, cx| {- cx.new(|cx| WhichKeyModal::new(WeakEntity::new_invalid(), window, cx))- });- (modal, cx)- }-- #[test]- fn test_group_bindings_preserves_keybinding_keystrokes() -> Result<(), InvalidKeystrokeError> {- #[cfg(target_os = "windows")]- let keystroke = KeybindingKeystroke::new(- Keystroke::parse("ctrl-$")?,- Modifiers::control_shift(),- "4".to_owned(),- );- #[cfg(not(target_os = "windows"))]- let keystroke = KeybindingKeystroke::from_keystroke(Keystroke::parse("ctrl-x")?);- let binding_data = vec![(vec![keystroke.clone()], SharedString::from("test action"))];-- let grouped_bindings = group_bindings(binding_data);-- assert_eq!(- grouped_bindings,- vec![(vec![keystroke], SharedString::from("test action"))]- );- Ok(())- }-- #[gpui::test]- fn test_which_key_modal_groups_and_orders_pending_bindings(cx: &mut TestAppContext) {- let (modal, cx) = setup_modal_test(- cx,- [- KeyBinding::new("ctrl-b h", FirstBinding, Some("WhichKeyModalTest")),- KeyBinding::new("ctrl-b h j", SecondBinding, Some("WhichKeyModalTest")),- KeyBinding::new("ctrl-b k", ThirdBinding, Some("WhichKeyModalTest")),- ],- "ctrl-b",- );-- let h = KeybindingKeystroke::from_keystroke(- Keystroke::parse("h").expect("valid test keystroke"),- );- let k = KeybindingKeystroke::from_keystroke(- Keystroke::parse("k").expect("valid test keystroke"),- );- let h_text = cx.update(|_, cx| text_for_keybinding_keystrokes(&[h], cx));- let k_text = cx.update(|_, cx| text_for_keybinding_keystrokes(&[k], cx));- let expected_bindings = vec![- (- k_text.into(),- command_palette::humanize_action_name(ThirdBinding.name()).into(),- ),- (h_text.into(), SharedString::from("+2 keybinds")),- ];-- assert_eq!(- modal.read_with(cx, |modal, _| modal.bindings.clone()),- expected_bindings- );- }-}