Skip to main content

ui/
palette.rs

1//! [`CommandPalette`] — a filtered command list over a [`input::TextField`].
2//!
3//! Stateful for the same reason the text field is: it owns a query, a filtered
4//! view of the items and an active row. It reports outcomes as gpui events
5//! rather than taking a callback, so the host decides what a selection *means*
6//! and the palette never knows about the app's actions.
7//!
8//! The state underneath is [`popover::Filter`], shared with
9//! [`crate::combobox::Combobox`] and tested there.
10//!
11//! ```ignore
12//! ui::palette::init(cx);   // once, at startup (with input::init)
13//! let palette = cx.new(|cx| CommandPalette::new(vec!["Open File".into()], cx));
14//! cx.subscribe(&palette, |_, _, event, _| match event {
15//!     PaletteEvent::Selected(index) => { /* run command `index` */ }
16//!     PaletteEvent::Dismissed => { /* unmount */ }
17//! })
18//! .detach();
19//! ```
20
21use gpui::{
22    App, Context, EventEmitter, FocusHandle, Focusable, KeyBinding, SharedString, Window, actions,
23    div, prelude::*, px,
24};
25
26use theme::Theme;
27
28use crate::{input, popover, search::SearchList, surface::Surfaced as _};
29
30actions!(
31    bezel_command_palette,
32    [SelectNext, SelectPrevious, Confirm, Dismiss]
33);
34
35/// The key context the palette claims. It wraps the field's own context, so
36/// typing goes to the field while navigation keys fall through to here.
37pub const KEY_CONTEXT: &str = "CommandPalette";
38
39/// Install the bindings — [`bindings`], bound. Call once, alongside
40/// [`crate::input::init`].
41pub fn init(cx: &mut App) {
42    cx.bind_keys(bindings());
43}
44
45/// The palette's navigation keymap, as data, so an app can have it without having to
46/// take it — see [`crate::keys`] for layering over it or taking a chord
47/// away.
48pub fn bindings() -> Vec<KeyBinding> {
49    let mut bindings = Vec::new();
50    let ctx = Some(KEY_CONTEXT);
51    bindings.extend([
52        KeyBinding::new("down", SelectNext, ctx),
53        KeyBinding::new("up", SelectPrevious, ctx),
54        KeyBinding::new("enter", Confirm, ctx),
55        KeyBinding::new("escape", Dismiss, ctx),
56        // The emacs pair, for the same reason the field honours ctrl-b/f.
57        KeyBinding::new("ctrl-n", SelectNext, ctx),
58        KeyBinding::new("ctrl-p", SelectPrevious, ctx),
59    ]);
60
61    bindings
62}
63
64/// What the palette reports. Indices are into the ORIGINAL item list, never
65/// into the filtered view — a caller matching on a filtered index would run
66/// the wrong command the moment a query is typed.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub enum PaletteEvent {
69    Selected(usize),
70    Dismissed,
71}
72
73pub struct CommandPalette {
74    search: SearchList,
75    focus_handle: FocusHandle,
76}
77
78impl EventEmitter<PaletteEvent> for CommandPalette {}
79
80impl CommandPalette {
81    pub fn new(items: Vec<SharedString>, cx: &mut Context<Self>) -> Self {
82        Self {
83            search: SearchList::new(
84                items,
85                "Type a command…",
86                |view: &mut Self| &mut view.search,
87                cx,
88            ),
89            focus_handle: cx.focus_handle(),
90        }
91    }
92
93    /// Focus the query field — call after mounting, or the palette swallows
94    /// keys without showing a caret.
95    pub fn focus(&self, window: &mut Window, cx: &mut App) {
96        window.focus(&self.search.query.focus_handle(cx), cx);
97    }
98
99    pub fn query_text(&self, cx: &App) -> SharedString {
100        self.search.query.read(cx).content().clone()
101    }
102
103    /// The item the user would get by confirming right now.
104    pub fn active_item(&self) -> Option<usize> {
105        self.search.filter.active_item()
106    }
107
108    fn choose(&mut self, item: usize, _: &mut Window, cx: &mut Context<Self>) {
109        cx.emit(PaletteEvent::Selected(item));
110    }
111
112    fn select_next(&mut self, _: &SelectNext, _: &mut Window, cx: &mut Context<Self>) {
113        self.search.filter.step(1);
114        cx.notify();
115    }
116
117    fn select_previous(&mut self, _: &SelectPrevious, _: &mut Window, cx: &mut Context<Self>) {
118        self.search.filter.step(-1);
119        cx.notify();
120    }
121
122    fn confirm(&mut self, _: &Confirm, _: &mut Window, cx: &mut Context<Self>) {
123        if let Some(item) = self.active_item() {
124            cx.emit(PaletteEvent::Selected(item));
125        }
126    }
127
128    fn dismiss(&mut self, _: &Dismiss, _: &mut Window, cx: &mut Context<Self>) {
129        cx.emit(PaletteEvent::Dismissed);
130    }
131}
132
133impl Focusable for CommandPalette {
134    /// The field holds focus; the palette is the context around it.
135    fn focus_handle(&self, _: &App) -> FocusHandle {
136        self.focus_handle.clone()
137    }
138}
139
140impl Render for CommandPalette {
141    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
142        let theme = Theme::of(cx).clone();
143        let card = popover::popover_card(&theme)
144            .w(px(420.0))
145            .child(
146                self.search
147                    .body(&theme, None, |view| &mut view.search, Self::choose, cx),
148            );
149
150        // The actions live on a wrapper, not the card, because the card is
151        // handed to `material` — which frosts the backdrop so the content
152        // behind the palette blurs instead of reading through it.
153        div()
154            .key_context(KEY_CONTEXT)
155            .track_focus(&self.focus_handle)
156            .on_action(cx.listener(Self::select_next))
157            .on_action(cx.listener(Self::select_previous))
158            .on_action(cx.listener(Self::confirm))
159            .on_action(cx.listener(Self::dismiss))
160            .child(card.surface(&theme, theme.popover_surface))
161    }
162}
163
164/// Re-exported so a host can bind its own "open palette" chord without
165/// depending on gpui's action macros directly.
166pub use input::KEY_CONTEXT as FIELD_KEY_CONTEXT;