fc_ui/capabilities/navigation/
command_palette.rs1use crate::capabilities::controls::input::Input;
4use crate::capabilities::controls::input_state::InputState;
5use crate::capabilities::foundation::theme::use_theme;
6use crate::capabilities::primitives::icon::Icon;
7use crate::capabilities::primitives::icon_source::IconSource;
8use crate::capabilities::primitives::text::{body, caption, label_small};
9use crate::capabilities::scroll::scrollable::scrollable_vertical;
10use gpui::{prelude::FluentBuilder as _, InteractiveElement, *};
11use std::cmp::Reverse;
12use std::rc::Rc;
13
14actions!(
15 command_palette,
16 [NavigateUp, NavigateDown, SelectCommand, CloseCommand]
17);
18
19#[derive(Clone)]
20pub struct Command {
21 pub id: SharedString,
22 pub name: SharedString,
23 pub description: Option<SharedString>,
24 pub icon: Option<IconSource>,
25 pub category: Option<SharedString>,
26 pub shortcut: Option<SharedString>,
27 pub on_select: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
28 search_text: String,
29}
30
31impl Command {
32 pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
33 let id = id.into();
34 let name = name.into();
35 let search_text = name.to_string().to_lowercase();
36
37 Self {
38 id,
39 name,
40 description: None,
41 icon: None,
42 category: None,
43 shortcut: None,
44 on_select: None,
45 search_text,
46 }
47 }
48
49 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
50 let desc = description.into();
51 self.search_text = format!("{} {}", self.name, desc).to_lowercase();
52 self.description = Some(desc);
53 self
54 }
55
56 pub fn icon(mut self, icon: impl Into<IconSource>) -> Self {
57 self.icon = Some(icon.into());
58 self
59 }
60
61 pub fn category(mut self, category: impl Into<SharedString>) -> Self {
62 self.category = Some(category.into());
63 self
64 }
65
66 pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
67 self.shortcut = Some(shortcut.into());
68 self
69 }
70
71 pub fn on_select<F>(mut self, handler: F) -> Self
72 where
73 F: Fn(&mut Window, &mut App) + 'static,
74 {
75 self.on_select = Some(Rc::new(handler));
76 self
77 }
78
79 pub fn matches(&self, query: &str) -> bool {
80 if query.is_empty() {
81 return true;
82 }
83
84 let query = query.to_lowercase();
85 self.search_text.contains(&query)
86 }
87
88 pub fn match_score(&self, query: &str) -> i32 {
89 if query.is_empty() {
90 return 0;
91 }
92
93 let query = query.to_lowercase();
94 let name_lower = self.name.to_string().to_lowercase();
95
96 if name_lower == query {
97 return 1000;
98 }
99
100 if name_lower.starts_with(&query) {
101 return 500;
102 }
103
104 if name_lower.contains(&query) {
105 return 100;
106 }
107
108 if self.search_text.contains(&query) {
109 return 50;
110 }
111
112 0
113 }
114}
115
116pub struct CommandPaletteState {
117 commands: Vec<Command>,
118 search_query: String,
119 filtered_commands: Vec<Command>,
120 selected_index: usize,
121 recent_commands: Vec<SharedString>,
122}
123
124impl CommandPaletteState {
125 pub fn new(commands: Vec<Command>) -> Self {
126 let filtered_commands = commands.clone();
127
128 Self {
129 commands,
130 search_query: String::new(),
131 filtered_commands,
132 selected_index: 0,
133 recent_commands: Vec::new(),
134 }
135 }
136
137 pub fn update_search(&mut self, query: String) {
138 self.search_query = query.clone();
139
140 if query.is_empty() {
141 self.filtered_commands = self.commands.clone();
142 } else {
143 let mut matches: Vec<(Command, i32)> = self
144 .commands
145 .iter()
146 .filter(|cmd| cmd.matches(&query))
147 .map(|cmd| (cmd.clone(), cmd.match_score(&query)))
148 .collect();
149
150 matches.sort_by_key(|(_, score)| Reverse(*score));
151 self.filtered_commands = matches.into_iter().map(|(cmd, _)| cmd).collect();
152 }
153
154 self.selected_index = 0;
155 }
156
157 pub fn select_previous(&mut self) {
158 if self.selected_index > 0 {
159 self.selected_index -= 1;
160 }
161 }
162
163 pub fn select_next(&mut self) {
164 if self.selected_index < self.filtered_commands.len().saturating_sub(1) {
165 self.selected_index += 1;
166 }
167 }
168
169 pub fn execute_selected(&mut self, window: &mut Window, cx: &mut App) -> bool {
170 if let Some(command) = self.filtered_commands.get(self.selected_index) {
171 if let Some(handler) = &command.on_select {
172 handler(window, cx);
173 self.recent_commands.push(command.id.clone());
174 if self.recent_commands.len() > 10 {
175 self.recent_commands.remove(0);
176 }
177 return true;
178 }
179 }
180 false
181 }
182
183 pub fn filtered_commands(&self) -> &[Command] {
184 &self.filtered_commands
185 }
186
187 pub fn selected_index(&self) -> usize {
188 self.selected_index
189 }
190}
191
192pub struct CommandPalette {
193 state: Entity<CommandPaletteState>,
194 search_input: Entity<InputState>,
195 on_close: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
196 focus_handle: FocusHandle,
197 style: StyleRefinement,
198}
199
200impl CommandPalette {
201 pub fn new(_window: &mut Window, cx: &mut Context<Self>, commands: Vec<Command>) -> Self {
202 let state = cx.new(|_| CommandPaletteState::new(commands));
203 let search_input =
204 cx.new(|cx| InputState::new(cx).placeholder("Type a command or search..."));
205 let focus_handle = cx.focus_handle();
206
207 cx.subscribe(&search_input, |this, _input, event, cx| {
208 use crate::capabilities::controls::input_state::InputEvent;
209 if matches!(event, InputEvent::Change) {
210 let query = this.search_input.read(cx).content().to_string();
211 this.state.update(cx, |state, _cx| {
212 state.update_search(query);
213 });
214 cx.notify();
215 }
216 })
217 .detach();
218
219 Self {
220 state,
221 search_input,
222 on_close: None,
223 focus_handle,
224 style: StyleRefinement::default(),
225 }
226 }
227
228 pub fn on_close<F>(mut self, handler: F) -> Self
229 where
230 F: Fn(&mut Window, &mut App) + 'static,
231 {
232 self.on_close = Some(Rc::new(handler));
233 self
234 }
235}
236
237impl Styled for CommandPalette {
238 fn style(&mut self) -> &mut StyleRefinement {
239 &mut self.style
240 }
241}
242
243impl Focusable for CommandPalette {
244 fn focus_handle(&self, _cx: &App) -> FocusHandle {
245 self.focus_handle.clone()
246 }
247}
248
249impl Render for CommandPalette {
250 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
251 let theme = use_theme(cx);
252 let state = self.state.read(cx);
253 let filtered = state.filtered_commands();
254 let selected_idx = state.selected_index();
255 let user_style = self.style.clone();
256
257 div()
258 .absolute()
259 .inset_0()
260 .flex()
261 .items_center()
262 .justify_center()
263 .bg(gpui::rgba(0x00000088))
264 .on_mouse_down(
265 MouseButton::Left,
266 cx.listener(|this, _event, window, cx| {
267 if let Some(handler) = &this.on_close {
268 handler(window, cx);
269 }
270 }),
271 )
272 .on_scroll_wheel(|_, _, _| {})
273 .key_context("CommandPalette")
274 .track_focus(&self.focus_handle)
275 .on_action(cx.listener(|this, _: &NavigateUp, _window, cx| {
276 this.state.update(cx, |state, _cx| {
277 state.select_previous();
278 });
279 cx.notify();
280 }))
281 .on_action(cx.listener(|this, _: &NavigateDown, _window, cx| {
282 this.state.update(cx, |state, _cx| {
283 state.select_next();
284 });
285 cx.notify();
286 }))
287 .on_action(cx.listener(|this, _: &SelectCommand, window, cx| {
288 let executed = this
289 .state
290 .update(cx, |state, app_cx| state.execute_selected(window, app_cx));
291 if executed {
292 if let Some(handler) = &this.on_close {
293 handler(window, cx);
294 }
295 }
296 }))
297 .on_action(cx.listener(|this, _: &CloseCommand, window, cx| {
298 if let Some(handler) = &this.on_close {
299 handler(window, cx);
300 }
301 }))
302 .child(
303 div()
304 .w(px(600.0))
305 .max_h(px(500.0))
306 .flex()
307 .flex_col()
308 .bg(theme.tokens.card)
309 .border_1()
310 .border_color(theme.tokens.border)
311 .rounded(theme.tokens.radius_lg)
312 .shadow_lg()
313 .overflow_hidden()
314 .on_mouse_down(MouseButton::Left, |_event, _window, cx| {
315 cx.stop_propagation();
316 })
317 .map(|this| {
318 let mut div = this;
319 div.style().refine(&user_style);
320 div
321 })
322 .child(
323 div()
324 .flex()
325 .items_center()
326 .px(px(16.0))
327 .py(px(12.0))
328 .border_b_1()
329 .border_color(theme.tokens.border)
330 .child(
331 Input::new(&self.search_input)
332 .placeholder("Type a command or search..."),
333 ),
334 )
335 .child(
336 div().flex_1().overflow_hidden().child(scrollable_vertical(
337 div()
338 .flex()
339 .flex_col()
340 .p(px(8.0))
341 .children(filtered.is_empty().then(|| {
342 div()
343 .flex()
344 .items_center()
345 .justify_center()
346 .h(px(200.0))
347 .child(
348 caption("No commands found")
349 .color(theme.tokens.muted_foreground),
350 )
351 .into_any_element()
352 }))
353 .children(filtered.iter().enumerate().map(|(idx, command)| {
354 let is_selected = idx == selected_idx;
355 render_command_item(command.clone(), is_selected, cx)
356 })),
357 )),
358 )
359 .child(
360 div()
361 .flex()
362 .items_center()
363 .justify_between()
364 .px(px(16.0))
365 .py(px(8.0))
366 .border_t_1()
367 .border_color(theme.tokens.border)
368 .bg(theme.tokens.muted.opacity(0.3))
369 .child(
370 div()
371 .flex()
372 .gap(px(16.0))
373 .child(
374 label_small("↑↓ Navigate")
375 .color(theme.tokens.muted_foreground),
376 )
377 .child(
378 label_small("↵ Select")
379 .color(theme.tokens.muted_foreground),
380 )
381 .child(
382 label_small("Esc Close")
383 .color(theme.tokens.muted_foreground),
384 ),
385 ),
386 ),
387 )
388 }
389}
390
391fn render_command_item(command: Command, selected: bool, cx: &App) -> impl IntoElement {
392 let theme = use_theme(cx);
393
394 div()
395 .flex()
396 .items_center()
397 .gap(px(12.0))
398 .px(px(12.0))
399 .py(px(10.0))
400 .rounded(theme.tokens.radius_sm)
401 .cursor(CursorStyle::PointingHand)
402 .when(selected, |div| div.bg(theme.tokens.accent))
403 .when(!selected, |div| {
404 div.hover(|style| style.bg(theme.tokens.muted))
405 })
406 .when_some(command.on_select, |div, handler| {
407 div.on_mouse_down(MouseButton::Left, move |_event, window, cx| {
408 handler(window, cx);
409 })
410 })
411 .when_some(command.icon, |div, icon| {
412 div.child(Icon::new(icon).size(px(18.0)).color(if selected {
413 theme.tokens.accent_foreground
414 } else {
415 theme.tokens.foreground
416 }))
417 })
418 .child(
419 div()
420 .flex_1()
421 .flex()
422 .flex_col()
423 .gap(px(2.0))
424 .child(body(command.name).color(if selected {
425 theme.tokens.accent_foreground
426 } else {
427 theme.tokens.foreground
428 }))
429 .when_some(command.description, |div, desc| {
430 div.child(caption(desc).color(if selected {
431 theme.tokens.accent_foreground.opacity(0.8)
432 } else {
433 theme.tokens.muted_foreground
434 }))
435 }),
436 )
437 .children(command.shortcut.map(|shortcut| {
438 div()
439 .px(px(8.0))
440 .py(px(4.0))
441 .rounded(theme.tokens.radius_sm)
442 .bg(if selected {
443 theme.tokens.accent_foreground.opacity(0.2)
444 } else {
445 theme.tokens.muted
446 })
447 .child(caption(shortcut).color(if selected {
448 theme.tokens.accent_foreground
449 } else {
450 theme.tokens.muted_foreground
451 }))
452 .into_any_element()
453 }))
454}