Skip to main content

gpui_material_extras/command_palette/
render.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, App, ElementId, Entity, EntityInputHandler, InteractiveElement, IntoElement,
5    ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window, div,
6    prelude::FluentBuilder, px, transparent_black,
7};
8use gpui_base::{
9    Button as BaseButton, TestSupportExt,
10    input::{Enter as InputEnter, MoveDown, MoveEnd, MoveHome, MoveUp},
11};
12use gpui_material_components::{
13    ControlSize, Dialog, Divider, Icon, IconButton, IconName, Text, TextField,
14    TextFieldColorOverrides, TextFieldColors,
15};
16use gpui_material_foundation::{
17    Surface, color, current_material_strings, current_material_theme, isolated_scroll,
18};
19use gpui_material_theme::{ColorRole, CornerRole, Direction, Elevation, TypeRole};
20
21use super::{
22    CommandItem, CommandPalette, CommandPaletteState, SelectHandler,
23    state::{NavStep, matches_command, resolve_active_id, step_active_id},
24};
25
26fn execute_command(
27    item: CommandItem,
28    state: &Entity<CommandPaletteState>,
29    on_select: Option<&SelectHandler>,
30    close_on_select: bool,
31    window: &mut Window,
32    cx: &mut App,
33) {
34    if item.is_disabled() {
35        return;
36    }
37    if close_on_select {
38        state.update(cx, |state, cx| state.close(window, cx));
39    }
40    state.update(cx, |state, cx| state.emit_execute(item.clone(), cx));
41    if let Some(on_select) = on_select {
42        on_select(&item, window, cx);
43    }
44}
45
46impl RenderOnce for CommandPalette {
47    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
48        let theme = current_material_theme(window, cx);
49        let direction = theme.layout.direction;
50        let rtl = direction == Direction::Rtl;
51        let density = theme.layout.density;
52
53        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
54        let on_surface_variant = color(theme.colors.color(ColorRole::OnSurfaceVariant));
55        let outline_variant = color(theme.colors.color(ColorRole::OutlineVariant));
56        let secondary_container = color(theme.colors.color(ColorRole::SecondaryContainer));
57        let on_secondary_container = color(theme.colors.color(ColorRole::OnSecondaryContainer));
58        let surface_highest = color(theme.colors.color(ColorRole::SurfaceContainerHighest));
59        let disabled_fg = on_surface.opacity(0.38);
60
61        let divider_color = self.colors.divider.unwrap_or(outline_variant);
62        let group_heading_color = self.colors.group_heading.unwrap_or(on_surface_variant);
63        let active_bg = self
64            .colors
65            .active_item_container
66            .unwrap_or(secondary_container);
67        let active_fg = self
68            .colors
69            .active_item_content
70            .unwrap_or(on_secondary_container);
71        let shortcut_bg = self.colors.shortcut_container.unwrap_or(surface_highest);
72        let shortcut_fg = self.colors.shortcut_content.unwrap_or(on_surface_variant);
73        let surface_shape = self.shape.unwrap_or_else(|| CornerRole::ExtraLarge.shape());
74
75        let strings = current_material_strings(window, cx);
76        let placeholder = self
77            .placeholder
78            .unwrap_or_else(|| SharedString::from(strings.search_prompt.clone()));
79        let empty_label = self
80            .empty_label
81            .unwrap_or_else(|| SharedString::from(strings.no_results.clone()));
82        let close_label = self
83            .close_label
84            .unwrap_or_else(|| SharedString::from(strings.close.clone()));
85        let accessible_label = self
86            .accessible_label
87            .unwrap_or_else(|| SharedString::from("Command palette"));
88        drop(strings);
89
90        let (dialog_state, editor, scroll, stored_query, stored_active) = {
91            let model = self.state.read(cx);
92            (
93                model.dialog_state().clone(),
94                model.editor().clone(),
95                model.scroll_handle().clone(),
96                model.query().clone(),
97                model.active_command_id().cloned(),
98            )
99        };
100        let query = if editor.update(cx, |input, cx| {
101            input.marked_text_range(window, cx).is_none()
102        }) {
103            editor.read(cx).value()
104        } else {
105            stored_query
106        };
107
108        let filtered: Vec<CommandItem> = self
109            .items
110            .into_iter()
111            .filter(|item| match &self.filter {
112                Some(predicate) => predicate(item, query.as_ref()),
113                None => matches_command(item, query.as_ref()),
114            })
115            .collect();
116        let active_id = resolve_active_id(&filtered, stored_active.as_ref());
117
118        let palette_id = self.id.clone();
119        let state_for_keys = self.state.clone();
120        let state_for_close = self.state.clone();
121        let filtered_for_keys = Rc::new(filtered.clone());
122        let on_select = self.on_select;
123        let on_select_for_keys = on_select.clone();
124        let close_on_select = self.close_on_select;
125        let max_results_height = self.max_results_height;
126        let container_override = self.colors.container;
127        let footer = self.footer;
128        let row_min_h = px(density.interactive_size(48.0));
129        let row_radius = CornerRole::Medium.shape().radii(48., 48., direction)[0];
130        let badge_radius = CornerRole::Small.shape().radii(24., 24., direction)[0];
131        let input_colors = TextFieldColors {
132            unfocused: TextFieldColorOverrides {
133                container: Some(transparent_black()),
134                indicator: Some(transparent_black()),
135                ..Default::default()
136            },
137            focused: TextFieldColorOverrides {
138                container: Some(transparent_black()),
139                indicator: Some(transparent_black()),
140                ..Default::default()
141            },
142            hovered_indicator: Some(transparent_black()),
143            ..Default::default()
144        };
145
146        let mut dialog =
147            Dialog::unstructured(self.id.clone(), &dialog_state, accessible_label.clone())
148                .width(self.width)
149                .layer(self.layer)
150                .properties(self.properties)
151                .scrim_opacity(self.scrim_opacity)
152                .when_some(self.colors.scrim, Dialog::scrim_color);
153
154        if let Some(on_dismiss_request) = self.on_dismiss_request {
155            dialog = dialog.on_dismiss_request(move |reason, window, cx| {
156                on_dismiss_request(reason, window, cx)
157            });
158        }
159
160        let caller_on_closed = self.on_closed;
161        dialog = dialog.on_closed(move |reason, window, cx| {
162            state_for_close.update(cx, |state, cx| state.emit_close(reason, cx));
163            if let Some(on_closed) = &caller_on_closed {
164                on_closed(reason, window, cx);
165            }
166        });
167
168        let state_for_rows = self.state.clone();
169        dialog.body_content(move |_, dismiss| {
170            let input_id = ElementId::from((palette_id.clone(), "input"));
171            let close_id = ElementId::from((palette_id.clone(), "close"));
172            let results_id = ElementId::from((palette_id.clone(), "results"));
173            let empty_id = ElementId::from((palette_id.clone(), "empty"));
174
175            let header = div()
176                .id((palette_id.clone(), "header"))
177                .test_support()
178                .w_full()
179                .flex()
180                .flex_row()
181                .items_center()
182                .gap(px(8.))
183                .px(px(12.))
184                .py(px(6.))
185                .when(rtl, Styled::flex_row_reverse)
186                .child(
187                    div()
188                        .flex_none()
189                        .flex()
190                        .items_center()
191                        .justify_center()
192                        .pl(px(4.))
193                        .text_color(on_surface_variant)
194                        .child(Icon::new(IconName::Search).size(px(20.))),
195                )
196                .child(
197                    div().flex_1().min_w_0().child(
198                        TextField::new(input_id, accessible_label.clone(), &editor)
199                            .show_label(false)
200                            .placeholder_content(
201                                placeholder.clone(),
202                                Text::new(placeholder)
203                                    .role(TypeRole::BodyLarge)
204                                    .color_override(on_surface_variant),
205                            )
206                            .clearable(true)
207                            .indicator_width(px(0.), px(0.))
208                            .colors(input_colors),
209                    ),
210                )
211                .child(
212                    IconButton::standard(close_id, close_label, Icon::new(IconName::Close))
213                        .size(ControlSize::ExtraSmall)
214                        .on_activate(move |window, cx| dismiss.activate(window, cx)),
215                );
216
217            let results_body = if filtered.is_empty() {
218                div()
219                    .id(empty_id)
220                    .test_support()
221                    .role(Role::Status)
222                    .aria_label(empty_label.clone())
223                    .w_full()
224                    .py(px(32.))
225                    .px(px(16.))
226                    .flex()
227                    .items_center()
228                    .justify_center()
229                    .child(
230                        Text::new(empty_label)
231                            .role(TypeRole::BodyMedium)
232                            .color_override(on_surface_variant),
233                    )
234                    .into_any_element()
235            } else {
236                let mut list = div()
237                    .id((palette_id.clone(), "list"))
238                    .test_support()
239                    .role(Role::ListBox)
240                    .w_full()
241                    .p(px(8.))
242                    .flex()
243                    .flex_col()
244                    .gap(px(2.));
245
246                let mut last_group: Option<SharedString> = None;
247                for item in filtered {
248                    if let Some(group) = item.group_label()
249                        && last_group.as_ref() != Some(group)
250                    {
251                        last_group = Some(group.clone());
252                        list = list.child(
253                            div()
254                                .w_full()
255                                .px(px(12.))
256                                .pt(px(8.))
257                                .pb(px(4.))
258                                .flex()
259                                .when(rtl, Styled::justify_end)
260                                .child(
261                                    Text::new(group.clone())
262                                        .role(TypeRole::LabelMedium)
263                                        .color_override(group_heading_color),
264                                ),
265                        );
266                    }
267
268                    let disabled = item.is_disabled();
269                    let is_active = !disabled && active_id.as_ref() == Some(item.id());
270                    let row_id = ElementId::from((palette_id.clone(), item.id().clone()));
271                    let fg = if disabled {
272                        disabled_fg
273                    } else if is_active {
274                        active_fg
275                    } else {
276                        on_surface
277                    };
278                    let sub_fg = if disabled {
279                        disabled_fg
280                    } else if is_active {
281                        active_fg.opacity(0.84)
282                    } else {
283                        on_surface_variant
284                    };
285                    let icon_fg = if disabled {
286                        disabled_fg
287                    } else if is_active {
288                        active_fg
289                    } else {
290                        on_surface_variant
291                    };
292
293                    let mut row = BaseButton::new(row_id)
294                        .role(Role::ListBoxOption)
295                        .accessibility_label(item.label().clone())
296                        .disabled(disabled)
297                        .focusable(false)
298                        .aria_selected(is_active)
299                        .w_full()
300                        .min_h(row_min_h)
301                        .px(px(12.))
302                        .py(px(8.))
303                        .rounded(px(row_radius))
304                        .flex()
305                        .flex_row()
306                        .items_center()
307                        .justify_start()
308                        .gap(px(12.))
309                        .when(rtl, Styled::flex_row_reverse)
310                        .when(is_active, |this| this.bg(active_bg))
311                        .when(!disabled && !is_active, |this| {
312                            this.cursor_pointer()
313                                .hover(|style| style.bg(on_surface.opacity(0.08)))
314                        })
315                        .when(!disabled && is_active, Styled::cursor_pointer)
316                        .children(item.icon_name().map(|icon| {
317                            div()
318                                .flex_none()
319                                .flex()
320                                .items_center()
321                                .justify_center()
322                                .text_color(icon_fg)
323                                .child(Icon::new(icon).size(px(20.)))
324                        }))
325                        .child(
326                            div()
327                                .flex_1()
328                                .min_w_0()
329                                .flex()
330                                .flex_col()
331                                .gap(px(2.))
332                                .when(rtl, Styled::items_end)
333                                .child(
334                                    Text::new(item.label().clone())
335                                        .role(TypeRole::BodyLarge)
336                                        .emphasized(is_active)
337                                        .color_override(fg)
338                                        .wrap(),
339                                )
340                                .children(item.supporting_text().map(|supporting| {
341                                    Text::new(supporting.clone())
342                                        .role(TypeRole::BodySmall)
343                                        .color_override(sub_fg)
344                                        .wrap()
345                                })),
346                        )
347                        .children(item.shortcut_label().map(|shortcut| {
348                            div()
349                                .flex_none()
350                                .px(px(8.))
351                                .py(px(3.))
352                                .rounded(px(badge_radius))
353                                .bg(shortcut_bg)
354                                .border_1()
355                                .border_color(outline_variant)
356                                .child(
357                                    Text::new(shortcut.clone())
358                                        .role(TypeRole::LabelSmall)
359                                        .color_override(if disabled {
360                                            disabled_fg
361                                        } else {
362                                            shortcut_fg
363                                        }),
364                                )
365                        }));
366
367                    if !disabled {
368                        let click_item = item.clone();
369                        let click_state = state_for_rows.clone();
370                        let click_select = on_select.clone();
371                        let a11y_item = item;
372                        let a11y_state = state_for_rows.clone();
373                        let a11y_select = on_select.clone();
374                        row = row
375                            .on_click(move |_, window, cx| {
376                                execute_command(
377                                    click_item.clone(),
378                                    &click_state,
379                                    click_select.as_ref(),
380                                    close_on_select,
381                                    window,
382                                    cx,
383                                );
384                                cx.stop_propagation();
385                            })
386                            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
387                                execute_command(
388                                    a11y_item.clone(),
389                                    &a11y_state,
390                                    a11y_select.as_ref(),
391                                    close_on_select,
392                                    window,
393                                    cx,
394                                );
395                            });
396                    }
397
398                    list = list.child(row);
399                }
400
401                isolated_scroll(results_id, &scroll)
402                    .test_support()
403                    .w_full()
404                    .max_h(max_results_height)
405                    .child(list)
406                    .into_any_element()
407            };
408
409            let mut surface = Surface::new(ColorRole::SurfaceContainerHigh)
410                .w_full()
411                .flex()
412                .flex_col()
413                .shape(surface_shape)
414                .shadow_elevation(Elevation::Level3)
415                .child(header)
416                .child(Divider::horizontal().color_override(divider_color))
417                .child(results_body)
418                .children(footer.map(|footer| {
419                    div()
420                        .w_full()
421                        .flex()
422                        .flex_col()
423                        .child(Divider::horizontal().color_override(divider_color))
424                        .child(div().w_full().px(px(16.)).py(px(8.)).child(footer))
425                }));
426            if let Some(container) = container_override {
427                surface = surface.container_color(container);
428            }
429
430            let step_action = {
431                let editor = editor.clone();
432                let filtered = filtered_for_keys.clone();
433                let state = state_for_keys.clone();
434                move |step: NavStep, window: &mut Window, cx: &mut App| -> bool {
435                    if editor.update(cx, |input, cx| {
436                        input.marked_text_range(window, cx).is_some()
437                    }) {
438                        return false;
439                    }
440                    let next = step_active_id(&filtered, state.read(cx).active_command_id(), step);
441                    state.update(cx, |state, cx| {
442                        state.set_active_command(next, cx);
443                    });
444                    window.refresh();
445                    true
446                }
447            };
448            let execute_active = {
449                let editor = editor.clone();
450                let filtered = filtered_for_keys.clone();
451                let state = state_for_keys.clone();
452                let on_select = on_select_for_keys.clone();
453                move |window: &mut Window, cx: &mut App| -> bool {
454                    if editor.update(cx, |input, cx| {
455                        input.marked_text_range(window, cx).is_some()
456                    }) {
457                        return false;
458                    }
459                    let active = resolve_active_id(&filtered, state.read(cx).active_command_id());
460                    if let Some(active) = active
461                        && let Some(item) = filtered
462                            .iter()
463                            .find(|item| !item.is_disabled() && item.id() == &active)
464                            .cloned()
465                    {
466                        execute_command(
467                            item,
468                            &state,
469                            on_select.as_ref(),
470                            close_on_select,
471                            window,
472                            cx,
473                        );
474                    }
475                    true
476                }
477            };
478
479            let step_down = step_action.clone();
480            let step_up = step_action.clone();
481            let step_home = step_action.clone();
482            let step_end = step_action.clone();
483            let exec_action = execute_active.clone();
484
485            div()
486                .id((palette_id, "shell"))
487                .test_support()
488                .w_full()
489                .capture_action(move |_: &MoveDown, window, cx| {
490                    if step_down(NavStep::Next, window, cx) {
491                        cx.stop_propagation();
492                    }
493                })
494                .capture_action(move |_: &MoveUp, window, cx| {
495                    if step_up(NavStep::Previous, window, cx) {
496                        cx.stop_propagation();
497                    }
498                })
499                .capture_action(move |_: &MoveHome, window, cx| {
500                    if step_home(NavStep::First, window, cx) {
501                        cx.stop_propagation();
502                    }
503                })
504                .capture_action(move |_: &MoveEnd, window, cx| {
505                    if step_end(NavStep::Last, window, cx) {
506                        cx.stop_propagation();
507                    }
508                })
509                .capture_action(move |_: &InputEnter, window, cx| {
510                    if exec_action(window, cx) {
511                        cx.stop_propagation();
512                    }
513                })
514                .capture_key_down(move |event, window, cx| {
515                    if event.keystroke.modifiers.modified() {
516                        return;
517                    }
518                    let handled = match event.keystroke.key.as_str() {
519                        "down" => step_action(NavStep::Next, window, cx),
520                        "up" => step_action(NavStep::Previous, window, cx),
521                        "home" => step_action(NavStep::First, window, cx),
522                        "end" => step_action(NavStep::Last, window, cx),
523                        "enter" => execute_active(window, cx),
524                        _ => false,
525                    };
526                    if handled {
527                        cx.stop_propagation();
528                    }
529                })
530                .child(surface)
531        })
532    }
533}