Skip to main content

gpui_material_extras/
command_palette.rs

1//! Material 3 Expressive modal command palette (`Ctrl+K` / `Cmd+K` style).
2
3mod render;
4mod state;
5
6use std::rc::Rc;
7
8use gpui::{
9    AnyElement, App, ElementId, Entity, Hsla, IntoElement, Pixels, SharedString, Window, px,
10};
11use gpui_material_components::{DialogCloseReason, DialogProperties, IconName};
12use gpui_material_theme::CornerShape;
13
14pub use state::{CommandPaletteEvent, CommandPaletteState};
15
16type FilterPredicate = Rc<dyn Fn(&CommandItem, &str) -> bool>;
17type SelectHandler = Rc<dyn Fn(&CommandItem, &mut Window, &mut App)>;
18type DismissRequestHandler = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
19type ClosedHandler = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
20
21/// One typed command entry rendered in a [`CommandPalette`].
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct CommandItem {
24    id: SharedString,
25    label: SharedString,
26    supporting: Option<SharedString>,
27    group: Option<SharedString>,
28    icon: Option<IconName>,
29    shortcut: Option<SharedString>,
30    keywords: Vec<SharedString>,
31    disabled: bool,
32}
33
34impl CommandItem {
35    /// Creates an enabled command with a stable `id` and primary display `label`.
36    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
37        Self {
38            id: id.into(),
39            label: label.into(),
40            supporting: None,
41            group: None,
42            icon: None,
43            shortcut: None,
44            keywords: Vec::new(),
45            disabled: false,
46        }
47    }
48
49    /// Sets optional secondary description text rendered beneath the command label.
50    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
51        self.supporting = Some(text.into());
52        self
53    }
54
55    /// Assigns this command to a visual group heading.
56    pub fn group(mut self, heading: impl Into<SharedString>) -> Self {
57        self.group = Some(heading.into());
58        self
59    }
60
61    /// Sets an optional leading bundled Material Symbol icon.
62    pub fn icon(mut self, icon: IconName) -> Self {
63        self.icon = Some(icon);
64        self
65    }
66
67    /// Sets an optional keyboard shortcut hint badge (for example `"Ctrl+K"` or `"⌘P"`).
68    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
69        self.shortcut = Some(shortcut.into());
70        self
71    }
72
73    /// Appends one extra search keyword matched by the default command filter.
74    pub fn keyword(mut self, keyword: impl Into<SharedString>) -> Self {
75        self.keywords.push(keyword.into());
76        self
77    }
78
79    /// Appends multiple extra search keywords matched by the default command filter.
80    pub fn keywords<I, S>(mut self, keywords: I) -> Self
81    where
82        I: IntoIterator<Item = S>,
83        S: Into<SharedString>,
84    {
85        self.keywords.extend(keywords.into_iter().map(Into::into));
86        self
87    }
88
89    /// Marks this command as unavailable (greyed out, non-clickable, skipped by keyboard navigation).
90    pub fn disabled(mut self, disabled: bool) -> Self {
91        self.disabled = disabled;
92        self
93    }
94
95    /// Returns the stable command identifier.
96    pub fn id(&self) -> &SharedString {
97        &self.id
98    }
99
100    /// Returns the primary display label.
101    pub fn label(&self) -> &SharedString {
102        &self.label
103    }
104
105    /// Returns the optional supporting description.
106    pub fn supporting_text(&self) -> Option<&SharedString> {
107        self.supporting.as_ref()
108    }
109
110    /// Returns the optional group heading assigned to this command.
111    pub fn group_label(&self) -> Option<&SharedString> {
112        self.group.as_ref()
113    }
114
115    /// Returns the optional leading [`IconName`].
116    pub fn icon_name(&self) -> Option<IconName> {
117        self.icon
118    }
119
120    /// Returns the optional shortcut hint string.
121    pub fn shortcut_label(&self) -> Option<&SharedString> {
122        self.shortcut.as_ref()
123    }
124
125    /// Returns the extra search keywords associated with this command.
126    pub fn keywords_slice(&self) -> &[SharedString] {
127        &self.keywords
128    }
129
130    /// Returns `true` when this command is disabled.
131    pub fn is_disabled(&self) -> bool {
132        self.disabled
133    }
134}
135
136/// A named group of [`CommandItem`] entries for [`CommandPalette::grouped`].
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct CommandGroup {
139    heading: SharedString,
140    items: Vec<CommandItem>,
141}
142
143impl CommandGroup {
144    /// Creates a command group whose `heading` is applied to items without an explicit group.
145    pub fn new(
146        heading: impl Into<SharedString>,
147        items: impl IntoIterator<Item = CommandItem>,
148    ) -> Self {
149        let heading = heading.into();
150        let items = items
151            .into_iter()
152            .map(|item| {
153                if item.group.is_some() {
154                    item
155                } else {
156                    item.group(heading.clone())
157                }
158            })
159            .collect();
160        Self { heading, items }
161    }
162
163    /// Returns the group heading label.
164    pub fn heading(&self) -> &SharedString {
165        &self.heading
166    }
167
168    /// Returns the ordered commands in this group.
169    pub fn items(&self) -> &[CommandItem] {
170        &self.items
171    }
172
173    /// Consumes the group and returns its flattened [`CommandItem`] list.
174    pub fn into_items(self) -> Vec<CommandItem> {
175        self.items
176    }
177}
178
179/// Per-instance color overrides for [`CommandPalette`]. Omitted fields use the window theme.
180#[derive(Clone, Copy, Debug, Default)]
181pub struct CommandPaletteColors {
182    /// Background color for the modal surface (defaults to `SurfaceContainerHigh`).
183    pub container: Option<Hsla>,
184    /// Divider color between the search header, results list, and optional footer.
185    pub divider: Option<Hsla>,
186    /// Foreground color for group headings (defaults to `OnSurfaceVariant`).
187    pub group_heading: Option<Hsla>,
188    /// Background fill for the currently highlighted command row (defaults to `SecondaryContainer`).
189    pub active_item_container: Option<Hsla>,
190    /// Foreground color for the currently highlighted command row (defaults to `OnSecondaryContainer`).
191    pub active_item_content: Option<Hsla>,
192    /// Background fill for shortcut hint badges (defaults to `SurfaceContainerHighest`).
193    pub shortcut_container: Option<Hsla>,
194    /// Foreground color for shortcut hint badges (defaults to `OnSurfaceVariant`).
195    pub shortcut_content: Option<Hsla>,
196    /// Optional override for the modal backdrop scrim tint.
197    pub scrim: Option<Hsla>,
198}
199
200/// Material 3 modal command palette built on `Dialog` and `TextField`.
201///
202/// Retain an [`Entity<CommandPaletteState>`] in your view, mount `CommandPalette` in the
203/// view tree, and call [`CommandPaletteState::open`] or [`CommandPaletteState::toggle`]
204/// from a button or `Ctrl+K` / `Cmd+K` keybinding.
205#[derive(IntoElement)]
206pub struct CommandPalette {
207    id: ElementId,
208    state: Entity<CommandPaletteState>,
209    items: Vec<CommandItem>,
210    accessible_label: Option<SharedString>,
211    placeholder: Option<SharedString>,
212    empty_label: Option<SharedString>,
213    close_label: Option<SharedString>,
214    filter: Option<FilterPredicate>,
215    close_on_select: bool,
216    width: Pixels,
217    max_results_height: Pixels,
218    layer: usize,
219    properties: DialogProperties,
220    shape: Option<CornerShape>,
221    colors: CommandPaletteColors,
222    scrim_opacity: f32,
223    footer: Option<AnyElement>,
224    on_select: Option<SelectHandler>,
225    on_dismiss_request: Option<DismissRequestHandler>,
226    on_closed: Option<ClosedHandler>,
227}
228
229impl CommandPalette {
230    /// Creates a modal command palette bound to `state` with the supplied ordered `items`.
231    pub fn new(
232        id: impl Into<ElementId>,
233        state: &Entity<CommandPaletteState>,
234        items: impl IntoIterator<Item = CommandItem>,
235    ) -> Self {
236        Self {
237            id: id.into(),
238            state: state.clone(),
239            items: items.into_iter().collect(),
240            accessible_label: None,
241            placeholder: None,
242            empty_label: None,
243            close_label: None,
244            filter: None,
245            close_on_select: true,
246            width: px(580.),
247            max_results_height: px(360.),
248            layer: 0,
249            properties: DialogProperties::default(),
250            shape: None,
251            colors: CommandPaletteColors::default(),
252            scrim_opacity: 0.32,
253            footer: None,
254            on_select: None,
255            on_dismiss_request: None,
256            on_closed: None,
257        }
258    }
259
260    /// Creates a modal command palette from grouped [`CommandGroup`] collections.
261    pub fn grouped(
262        id: impl Into<ElementId>,
263        state: &Entity<CommandPaletteState>,
264        groups: impl IntoIterator<Item = CommandGroup>,
265    ) -> Self {
266        let items = groups.into_iter().flat_map(CommandGroup::into_items);
267        Self::new(id, state, items)
268    }
269
270    /// Overrides the accessible dialog name (defaults to `"Command palette"`).
271    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
272        self.accessible_label = Some(label.into());
273        self
274    }
275
276    /// Overrides the search field placeholder (defaults to
277    /// [`gpui_material_theme::MaterialStrings::search_prompt`]).
278    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
279        self.placeholder = Some(placeholder.into());
280        self
281    }
282
283    /// Overrides the empty-results message (defaults to
284    /// [`gpui_material_theme::MaterialStrings::no_results`]).
285    pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
286        self.empty_label = Some(label.into());
287        self
288    }
289
290    /// Overrides the close button's accessible label (defaults to
291    /// [`gpui_material_theme::MaterialStrings::close`]).
292    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
293        self.close_label = Some(label.into());
294        self
295    }
296
297    /// Supplies a custom filtering predicate `(item, query) -> bool` replacing the built-in
298    /// case-insensitive multi-token substring and keyword matcher.
299    pub fn filter(mut self, predicate: impl Fn(&CommandItem, &str) -> bool + 'static) -> Self {
300        self.filter = Some(Rc::new(predicate));
301        self
302    }
303
304    /// Sets whether executing a command automatically closes the palette (defaults to `true`).
305    pub fn close_on_select(mut self, close: bool) -> Self {
306        self.close_on_select = close;
307        self
308    }
309
310    /// Sets the maximum width of the command palette surface in logical pixels (defaults to `580px`).
311    pub fn width(mut self, width: Pixels) -> Self {
312        if f32::from(width).is_finite() {
313            self.width = width.max(px(280.));
314        }
315        self
316    }
317
318    /// Sets the maximum scrollable height of the results region in logical pixels (defaults to `360px`).
319    pub fn max_results_height(mut self, height: Pixels) -> Self {
320        if f32::from(height).is_finite() {
321            self.max_results_height = height.max(px(120.));
322        }
323        self
324    }
325
326    /// Sets the modal z-layer forwarded to the underlying `Dialog`.
327    pub fn layer(mut self, layer: usize) -> Self {
328        self.layer = layer;
329        self
330    }
331
332    /// Configures Escape and outside-click dismissal behavior.
333    pub fn properties(mut self, properties: DialogProperties) -> Self {
334        self.properties = properties;
335        self
336    }
337
338    /// Overrides the corner shape of the command palette surface (defaults to `CornerRole::ExtraLarge`).
339    pub fn shape(mut self, shape: CornerShape) -> Self {
340        self.shape = Some(shape);
341        self
342    }
343
344    /// Overrides container, divider, heading, active row, shortcut badge, and scrim colors.
345    pub fn colors(mut self, colors: CommandPaletteColors) -> Self {
346        self.colors = colors;
347        self
348    }
349
350    /// Sets backdrop scrim opacity clamped to `0.0..=1.0` (defaults to `0.32`).
351    pub fn scrim_opacity(mut self, opacity: f32) -> Self {
352        self.scrim_opacity = if opacity.is_nan() {
353            0.32
354        } else {
355            opacity.clamp(0., 1.)
356        };
357        self
358    }
359
360    /// Renders optional footer content beneath the results list (for example keyboard hints).
361    pub fn footer(mut self, element: impl IntoElement) -> Self {
362        self.footer = Some(element.into_any_element());
363        self
364    }
365
366    /// Invoked when an enabled command is executed via `Enter` or pointer click.
367    pub fn on_select(
368        mut self,
369        handler: impl Fn(&CommandItem, &mut Window, &mut App) + 'static,
370    ) -> Self {
371        self.on_select = Some(Rc::new(handler));
372        self
373    }
374
375    /// Handles Escape and outside-click dismissal requests. Return `false` to keep the palette open.
376    pub fn on_dismiss_request(
377        mut self,
378        handler: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
379    ) -> Self {
380        self.on_dismiss_request = Some(Rc::new(handler));
381        self
382    }
383
384    /// Invoked once when the palette closes due to user dismissal or selection.
385    pub fn on_closed(
386        mut self,
387        handler: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
388    ) -> Self {
389        self.on_closed = Some(Rc::new(handler));
390        self
391    }
392}