Skip to main content

gpui_material_extras/command_palette/
state.rs

1use gpui::{
2    App, AppContext, Context, Entity, EntityInputHandler, EventEmitter, FocusHandle, Focusable,
3    ScrollHandle, SharedString, Subscription, Window,
4};
5use gpui_material_components::{DialogCloseReason, DialogState, TextFieldEvent, TextFieldState};
6
7use super::CommandItem;
8
9/// Events emitted by [`CommandPaletteState`].
10#[derive(Clone, Debug)]
11pub enum CommandPaletteEvent {
12    /// Emitted when an enabled [`CommandItem`] is executed via keyboard or pointer activation.
13    Execute(CommandItem),
14    /// Emitted when the palette's search query changes.
15    QueryChange(SharedString),
16    /// Emitted when the palette closes due to user dismissal.
17    Close(DialogCloseReason),
18}
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub(super) enum NavStep {
22    Next,
23    Previous,
24    First,
25    Last,
26}
27
28/// Retains modal visibility, search editor, scroll position, and active selection state
29/// for a [`super::CommandPalette`].
30pub struct CommandPaletteState {
31    dialog: Entity<DialogState>,
32    input: Entity<TextFieldState>,
33    scroll: ScrollHandle,
34    query: SharedString,
35    active_id: Option<SharedString>,
36    clear_on_open: bool,
37    _input_sub: Subscription,
38    _dialog_sub: Subscription,
39}
40
41impl EventEmitter<CommandPaletteEvent> for CommandPaletteState {}
42
43impl CommandPaletteState {
44    /// Creates a closed command palette state with an owned [`TextFieldState`] and [`DialogState`].
45    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
46        let input = cx.new(|cx| TextFieldState::new(window, cx));
47        Self::with_editor(&input, window, cx)
48    }
49
50    /// Creates a closed command palette state reusing a caller-owned [`TextFieldState`].
51    pub fn with_editor(
52        input: &Entity<TextFieldState>,
53        window: &mut Window,
54        cx: &mut Context<Self>,
55    ) -> Self {
56        let dialog = cx.new(DialogState::new);
57        let dialog_sub = cx.observe(&dialog, |_, _, cx| cx.notify());
58        let input_sub = cx.subscribe_in(input, window, |state, input, event, window, cx| {
59            if !state.is_open(cx) || !matches!(event, TextFieldEvent::Change) {
60                return;
61            }
62            if input.update(cx, |input, cx| {
63                input.marked_text_range(window, cx).is_some()
64            }) {
65                return;
66            }
67            let value = input.read(cx).value();
68            if value != state.query {
69                state.query = value.clone();
70                state.active_id = None;
71                cx.emit(CommandPaletteEvent::QueryChange(value));
72                cx.notify();
73                window.refresh();
74            }
75        });
76        Self {
77            dialog,
78            input: input.clone(),
79            scroll: ScrollHandle::new(),
80            query: SharedString::default(),
81            active_id: None,
82            clear_on_open: true,
83            _input_sub: input_sub,
84            _dialog_sub: dialog_sub,
85        }
86    }
87
88    /// Configures whether [`Self::open`] clears the previous query text (defaults to `true`).
89    pub fn clear_on_open(mut self, clear: bool) -> Self {
90        self.clear_on_open = clear;
91        self
92    }
93
94    /// Returns `true` while the command palette dialog is open.
95    pub fn is_open(&self, cx: &App) -> bool {
96        self.dialog.read(cx).is_open()
97    }
98
99    /// Returns the latest committed query text.
100    pub fn query(&self) -> &SharedString {
101        &self.query
102    }
103
104    /// Returns the currently highlighted command ID, if explicitly selected.
105    pub fn active_command_id(&self) -> Option<&SharedString> {
106        self.active_id.as_ref()
107    }
108
109    /// Returns the underlying [`DialogState`] entity.
110    pub fn dialog_state(&self) -> &Entity<DialogState> {
111        &self.dialog
112    }
113
114    /// Returns the retained [`TextFieldState`] backing the search input.
115    pub fn editor(&self) -> &Entity<TextFieldState> {
116        &self.input
117    }
118
119    /// Returns the focus handle of the search input editor.
120    pub fn input_focus(&self, cx: &App) -> FocusHandle {
121        self.input.read(cx).focus_handle(cx)
122    }
123
124    /// Returns the retained scroll handle bound to the results list.
125    pub fn scroll_handle(&self) -> &ScrollHandle {
126        &self.scroll
127    }
128
129    /// Opens the command palette, capturing current focus for restoration and focusing the search input.
130    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
131        if self.is_open(cx) {
132            self.input_focus(cx).focus(window, cx);
133            return;
134        }
135        self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
136        if self.clear_on_open {
137            let had_query = !self.query.is_empty() || !self.input.read(cx).value().is_empty();
138            self.query = SharedString::default();
139            self.input.update(cx, |input, cx| {
140                if !input.value().is_empty() {
141                    input.set_value("", window, cx);
142                }
143            });
144            if had_query {
145                cx.emit(CommandPaletteEvent::QueryChange(SharedString::default()));
146            }
147        } else {
148            let value = self.input.read(cx).value();
149            if value != self.query {
150                self.query = value;
151            }
152        }
153        self.active_id = None;
154        self.input_focus(cx).focus(window, cx);
155        cx.notify();
156        window.refresh();
157    }
158
159    /// Closes the command palette programmatically and restores prior focus.
160    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
161        if !self.is_open(cx) {
162            return;
163        }
164        self.dialog
165            .update(cx, |dialog, cx| dialog.close(window, cx));
166        cx.notify();
167        window.refresh();
168    }
169
170    /// Toggles the command palette open or closed (convenient for `Ctrl+K` / `Cmd+K` bindings).
171    pub fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
172        if self.is_open(cx) {
173            self.close(window, cx);
174        } else {
175            self.open(window, cx);
176        }
177    }
178
179    /// Updates the query text programmatically and resets the active command highlight.
180    pub fn set_query(
181        &mut self,
182        query: impl Into<SharedString>,
183        window: &mut Window,
184        cx: &mut Context<Self>,
185    ) {
186        let query = query.into();
187        self.input.update(cx, |input, cx| {
188            if input.value() != query {
189                input.set_value(query.clone(), window, cx);
190            }
191        });
192        if query != self.query {
193            self.query = query.clone();
194            self.active_id = None;
195            cx.emit(CommandPaletteEvent::QueryChange(query));
196            cx.notify();
197            window.refresh();
198        }
199    }
200
201    /// Explicitly highlights a command ID within the filtered list.
202    pub fn set_active_command(&mut self, id: Option<SharedString>, cx: &mut Context<Self>) {
203        if self.active_id != id {
204            self.active_id = id;
205            cx.notify();
206        }
207    }
208
209    pub(super) fn emit_execute(&mut self, item: CommandItem, cx: &mut Context<Self>) {
210        cx.emit(CommandPaletteEvent::Execute(item));
211    }
212
213    pub(super) fn emit_close(&mut self, reason: DialogCloseReason, cx: &mut Context<Self>) {
214        cx.emit(CommandPaletteEvent::Close(reason));
215    }
216}
217
218/// Default case-insensitive multi-token substring matcher across label, supporting text,
219/// group heading, id, and keywords.
220pub(super) fn matches_command(item: &CommandItem, query: &str) -> bool {
221    let trimmed = query.trim();
222    if trimmed.is_empty() {
223        return true;
224    }
225    let label = item.label().to_lowercase();
226    let id = item.id().to_lowercase();
227    let supporting = item.supporting_text().map(|s| s.to_lowercase());
228    let group = item.group_label().map(|s| s.to_lowercase());
229    let keywords: Vec<String> = item
230        .keywords_slice()
231        .iter()
232        .map(|k| k.to_lowercase())
233        .collect();
234
235    trimmed.split_whitespace().all(|token| {
236        let needle = token.to_lowercase();
237        label.contains(&needle)
238            || id.contains(&needle)
239            || supporting.as_deref().is_some_and(|s| s.contains(&needle))
240            || group.as_deref().is_some_and(|g| g.contains(&needle))
241            || keywords.iter().any(|k| k.contains(&needle))
242    })
243}
244
245pub(super) fn resolve_active_id(
246    filtered: &[CommandItem],
247    current: Option<&SharedString>,
248) -> Option<SharedString> {
249    if let Some(current) = current
250        && filtered
251            .iter()
252            .any(|item| !item.is_disabled() && item.id() == current)
253    {
254        return Some(current.clone());
255    }
256    filtered
257        .iter()
258        .find(|item| !item.is_disabled())
259        .map(|item| item.id().clone())
260}
261
262pub(super) fn step_active_id(
263    filtered: &[CommandItem],
264    current: Option<&SharedString>,
265    step: NavStep,
266) -> Option<SharedString> {
267    let enabled: Vec<&CommandItem> = filtered.iter().filter(|item| !item.is_disabled()).collect();
268    if enabled.is_empty() {
269        return None;
270    }
271    let active = resolve_active_id(filtered, current);
272    let current_ix = active
273        .as_ref()
274        .and_then(|id| enabled.iter().position(|item| item.id() == id))
275        .unwrap_or(0);
276    let next_ix = match step {
277        NavStep::First => 0,
278        NavStep::Last => enabled.len() - 1,
279        NavStep::Next => (current_ix + 1) % enabled.len(),
280        NavStep::Previous => (current_ix + enabled.len() - 1) % enabled.len(),
281    };
282    Some(enabled[next_ix].id().clone())
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288
289    #[test]
290    fn default_filter_matches_case_insensitively_across_fields_and_keywords() {
291        let item = CommandItem::new("toggle-dark", "Switch appearance")
292            .group("Theme")
293            .supporting("Toggle between light and dark color schemes")
294            .keywords(["night", "mode"]);
295
296        assert!(matches_command(&item, ""));
297        assert!(matches_command(&item, "   "));
298        assert!(matches_command(&item, "APPEARANCE"));
299        assert!(matches_command(&item, "theme dark"));
300        assert!(matches_command(&item, "night mode"));
301        assert!(!matches_command(&item, "theme export"));
302    }
303
304    #[test]
305    fn navigation_steps_skip_disabled_commands_and_wrap() {
306        let items = vec![
307            CommandItem::new("open", "Open file"),
308            CommandItem::new("locked", "Locked action").disabled(true),
309            CommandItem::new("save", "Save file"),
310            CommandItem::new("close", "Close tab"),
311        ];
312
313        assert_eq!(resolve_active_id(&items, None), Some("open".into()));
314        assert_eq!(
315            step_active_id(&items, Some(&"open".into()), NavStep::Next),
316            Some("save".into())
317        );
318        assert_eq!(
319            step_active_id(&items, Some(&"close".into()), NavStep::Next),
320            Some("open".into())
321        );
322        assert_eq!(
323            step_active_id(&items, Some(&"open".into()), NavStep::Previous),
324            Some("close".into())
325        );
326        assert_eq!(
327            step_active_id(&items, Some(&"save".into()), NavStep::First),
328            Some("open".into())
329        );
330        assert_eq!(
331            step_active_id(&items, Some(&"open".into()), NavStep::Last),
332            Some("close".into())
333        );
334    }
335}