Skip to main content

gpui_component/command/
command.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString,
5    StyleRefinement, Styled, Window, rems,
6};
7
8use crate::IndexPath;
9use crate::command::{
10    item::{CommandEntry, CommandGroup, CommandItem},
11    state::{CommandModel, CommandState, OnCancel, OnIndex, OnQuery},
12};
13
14pub(crate) type CommandSlot = dyn Fn(&CommandState, &mut Window, &mut App) -> AnyElement;
15
16/// Presentation of a [`Command`], pushed into its state on every render.
17#[derive(Clone)]
18pub(crate) struct CommandOptions {
19    pub(crate) style: StyleRefinement,
20    pub(crate) placeholder: Option<SharedString>,
21    pub(crate) empty: Option<Rc<CommandSlot>>,
22    pub(crate) max_h: DefiniteLength,
23    pub(crate) scroll_bounce: Option<bool>,
24    pub(crate) bordered: bool,
25    pub(crate) header: Option<Rc<CommandSlot>>,
26    pub(crate) footer: Option<Rc<CommandSlot>>,
27}
28
29impl Default for CommandOptions {
30    fn default() -> Self {
31        Self {
32            style: StyleRefinement::default(),
33            placeholder: None,
34            empty: None,
35            max_h: rems(18.75).into(),
36            scroll_bounce: None,
37            bordered: true,
38            header: None,
39            footer: None,
40        }
41    }
42}
43
44/// A command palette: a search field over a filtered list of commands.
45///
46/// Entries and rendering policy are configured on each `Command`; interaction
47/// state such as the query and highlighted item lives in [`CommandState`].
48///
49/// ```ignore
50/// let state = cx.new(|cx| CommandState::new(window, cx));
51///
52/// Command::new(&state)
53///     .group(
54///         CommandGroup::new().label("Suggestions")
55///             .item(CommandItem::new().label("Calendar").icon(IconName::Calendar)),
56///     )
57///     .placeholder("Type a command or search...")
58/// ```
59#[derive(IntoElement)]
60pub struct Command {
61    state: Entity<CommandState>,
62    entries: Vec<CommandEntry>,
63    searchable: bool,
64    filterable: bool,
65    highlight_matches: bool,
66    on_query: Option<Rc<OnQuery>>,
67    on_select: Option<Rc<OnIndex>>,
68    on_confirm: Option<Rc<OnIndex>>,
69    on_cancel: Option<Rc<OnCancel>>,
70    options: CommandOptions,
71}
72
73impl Command {
74    /// Render the palette held by `state`.
75    pub fn new(state: &Entity<CommandState>) -> Self {
76        Self {
77            state: state.clone(),
78            entries: Vec::new(),
79            searchable: true,
80            filterable: true,
81            highlight_matches: false,
82            on_query: None,
83            on_select: None,
84            on_confirm: None,
85            on_cancel: None,
86            options: CommandOptions::default(),
87        }
88    }
89
90    /// Add an ungrouped command item.
91    pub fn item(mut self, item: CommandItem) -> Self {
92        self.entries.push(CommandEntry::Item(item));
93        self
94    }
95
96    /// Add multiple ungrouped command items.
97    pub fn items(mut self, items: impl IntoIterator<Item = CommandItem>) -> Self {
98        self.entries
99            .extend(items.into_iter().map(CommandEntry::Item));
100        self
101    }
102
103    /// Add a group of command items.
104    pub fn group(mut self, group: CommandGroup) -> Self {
105        self.entries.push(CommandEntry::Group(group));
106        self
107    }
108
109    /// Add a separator between the preceding and following entries.
110    pub fn separator(mut self) -> Self {
111        self.entries.push(CommandEntry::Separator);
112        self
113    }
114
115    /// Show or hide the query field and local filtering.
116    pub fn searchable(mut self, searchable: bool) -> Self {
117        self.searchable = searchable;
118        self
119    }
120
121    /// Keep the query field but toggle the local filtering, default: `true`.
122    ///
123    /// Turn it off when an external source already answers the query, such as
124    /// an async search: every supplied item stays visible, the query still
125    /// reports through [`Self::on_query`], and a query change hands the
126    /// highlight back to the first item instead of a local textual match.
127    pub fn filterable(mut self, filterable: bool) -> Self {
128        self.filterable = filterable;
129        self
130    }
131
132    /// Highlight the part of each item's label that matches the query, default
133    /// is `false`. Has no effect with `filterable(false)` or on rows built with
134    /// `child`.
135    pub fn highlight_matches(mut self, highlight: bool) -> Self {
136        self.highlight_matches = highlight;
137        self
138    }
139
140    /// Run a callback after a searchable query actually changes and the
141    /// current [`CommandState`] update releases its lease.
142    pub fn on_query<F>(mut self, callback: F) -> Self
143    where
144        F: Fn(&str, &mut Window, &mut App) + 'static,
145    {
146        self.on_query = Some(Rc::new(callback));
147        self
148    }
149
150    /// Run a callback after the highlighted item's original index path changes and the current
151    /// [`CommandState`] update releases its lease.
152    ///
153    /// For [`Self::items`], `section` is 0 and `row` is the item's position in
154    /// the supplied iterator. Explicit groups use their group and item
155    /// positions and follow the implicit ungrouped section when both forms are
156    /// mixed. Local filtering never changes these coordinates.
157    pub fn on_select<F>(mut self, callback: F) -> Self
158    where
159        F: Fn(IndexPath, &mut Window, &mut App) + 'static,
160    {
161        self.on_select = Some(Rc::new(callback));
162        self
163    }
164
165    /// Run a callback with the confirmed item's original index path after its Action is dispatched,
166    /// provided the source window remains live. The callback runs after the
167    /// current [`CommandState`] update releases its lease.
168    /// The path follows the same input-model coordinates as [`Self::on_select`].
169    pub fn on_confirm<F>(mut self, callback: F) -> Self
170    where
171        F: Fn(IndexPath, &mut Window, &mut App) + 'static,
172    {
173        self.on_confirm = Some(Rc::new(callback));
174        self
175    }
176
177    /// Run a callback synchronously before an empty-query Cancel action
178    /// propagates. A hosting Dialog should perform the dismissal after this
179    /// callback instead of being closed by the callback itself.
180    pub fn on_cancel<F>(mut self, callback: F) -> Self
181    where
182        F: Fn(&mut Window, &mut App) + 'static,
183    {
184        self.on_cancel = Some(Rc::new(callback));
185        self
186    }
187
188    /// Set the placeholder of the search field.
189    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
190        self.options.placeholder = Some(placeholder.into());
191        self
192    }
193
194    /// Render custom content when no command matches the query.
195    pub fn empty<F, E>(mut self, f: F) -> Self
196    where
197        F: Fn(&CommandState, &mut Window, &mut App) -> E + 'static,
198        E: IntoElement,
199    {
200        self.options.empty = Some(Rc::new(move |state, window, cx| {
201            f(state, window, cx).into_any_element()
202        }));
203        self
204    }
205
206    /// Set the max height of the list, default: 18.75rem (300px).
207    pub fn max_h(mut self, height: impl Into<DefiniteLength>) -> Self {
208        self.options.max_h = height.into();
209        self
210    }
211
212    /// Bounce the command list at its vertical boundaries. On by default on iOS,
213    /// Android and macOS, off elsewhere; reduced motion disables displacement.
214    pub fn scroll_bounce(mut self, enabled: bool) -> Self {
215        self.options.scroll_bounce = Some(enabled);
216        self
217    }
218
219    /// Set whether to draw the surrounding border and rounding, default: `true`.
220    ///
221    /// Turn it off when the palette already sits inside a frame of its own,
222    /// such as a [`crate::Dialog`].
223    pub fn bordered(mut self, bordered: bool) -> Self {
224        self.options.bordered = bordered;
225        self
226    }
227
228    /// Render a custom element above the search field and command list.
229    pub fn header<F, E>(mut self, f: F) -> Self
230    where
231        F: Fn(&CommandState, &mut Window, &mut App) -> E + 'static,
232        E: IntoElement,
233    {
234        self.options.header = Some(Rc::new(move |state, window, cx| {
235            f(state, window, cx).into_any_element()
236        }));
237        self
238    }
239
240    /// Render a custom element below the command list.
241    pub fn footer<F, E>(mut self, f: F) -> Self
242    where
243        F: Fn(&CommandState, &mut Window, &mut App) -> E + 'static,
244        E: IntoElement,
245    {
246        self.options.footer = Some(Rc::new(move |state, window, cx| {
247            f(state, window, cx).into_any_element()
248        }));
249        self
250    }
251}
252
253impl Styled for Command {
254    fn style(&mut self) -> &mut StyleRefinement {
255        &mut self.options.style
256    }
257}
258
259impl RenderOnce for Command {
260    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
261        let options = self.options;
262        let model = CommandModel {
263            entries: self.entries,
264            searchable: self.searchable,
265            filterable: self.filterable,
266            highlight_matches: self.highlight_matches,
267            on_query: self.on_query,
268            on_select: self.on_select,
269            on_confirm: self.on_confirm,
270            on_cancel: self.on_cancel,
271        };
272        self.state.update(cx, |state, cx| {
273            state.set_options(options);
274            state.install_model(model, cx);
275        });
276
277        self.state
278    }
279}