gpui-commands 0.1.0

Unified action registration, keybinding, and command palette for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! The command palette: a searchable overlay listing every registered
//! command, opened by a configurable trigger keybinding.

use crate::fuzzy::fuzzy_match;
use crate::{Command, CommandRegistry};
use gpui::{
    actions, point, App, AnyView, Bounds, Context, Entity, FocusHandle, Focusable, KeyBinding,
    KeyDownEvent, MouseButton, Render, SharedString, Window, div, prelude::*, px, rgb, rgba,
};

// The action dispatched when the palette's trigger keybinding is pressed.
actions!(gpui_commands, [ToggleCommandPalette]);

/// A searchable command palette overlay.
///
/// `CommandPalette::install` stores the registry as a GPUI global, binds the
/// trigger keybinding, and replaces each open window's root view with the
/// palette, which keeps the previous root inside itself: while closed it
/// renders the previous root untouched (the palette's wrapper div is in the
/// element tree so the trigger still bubbles to it), and while open it draws
/// a dimmed overlay with the palette card on top. App state is preserved
/// across open/close cycles because the previous root view is never destroyed.
///
/// Call `install` after creating the windows you want the palette to live in.
pub struct CommandPalette {
    previous_root: AnyView,
    previous_focus: Option<FocusHandle>,
    input_focus: FocusHandle,
    open: bool,
    query: SharedString,
    selected_index: usize,
}

impl CommandPalette {
    /// Install the palette with the default trigger (`cmd-shift-p` /
    /// `ctrl-shift-p`) in every open window: stores the registry as a global
    /// and binds the trigger keybinding in the app's keymap.
    pub fn install(registry: CommandRegistry, cx: &mut App) {
        Self::install_with_trigger(registry, "cmd-shift-p", cx);
    }

    /// Like [`CommandPalette::install`], but with a custom trigger
    /// keybinding, e.g. `"cmd-k"`.
    pub fn install_with_trigger(registry: CommandRegistry, trigger: &str, cx: &mut App) {
        cx.set_global(registry);
        cx.bind_keys([KeyBinding::new(trigger, ToggleCommandPalette, None)]);

        let windows = cx.windows();
        for window in windows {
            let _ = window.update(cx, |previous_root, window, cx| {
                window.replace_root(cx, |window, cx| {
                    CommandPalette::new(previous_root, window, cx)
                });
            });
        }
    }

    fn new(previous_root: AnyView, _window: &mut Window, cx: &mut Context<Self>) -> Self {
        Self {
            previous_root,
            previous_focus: None,
            input_focus: cx.focus_handle(),
            open: false,
            query: SharedString::new(""),
            selected_index: 0,
        }
    }

    fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.open = !self.open;
        if self.open {
            self.previous_focus = window.focused(cx);
            self.selected_index = 0;
            window.focus(&self.input_focus);
        } else {
            if let Some(previous) = &self.previous_focus {
                window.focus(previous);
            }
            self.query = SharedString::new("");
            self.selected_index = 0;
        }
        cx.notify();
    }

    fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.open {
            self.open = false;
            if let Some(previous) = &self.previous_focus {
                window.focus(previous);
            }
            self.query = SharedString::new("");
            self.selected_index = 0;
            cx.notify();
        }
    }

    fn move_selection(&mut self, delta: isize, cx: &mut Context<Self>) {
        let count = self.filtered_count(cx);
        if count == 0 {
            return;
        }
        let current = self.selected_index as isize;
        self.selected_index = (current + delta).rem_euclid(count as isize) as usize;
        cx.notify();
    }

    fn filtered_count(&self, cx: &Context<Self>) -> usize {
        let commands = cx.global::<CommandRegistry>().commands().iter().collect::<Vec<_>>();
        filtered_commands(&commands, self.query.as_str()).len()
    }

    fn execute_selected(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let executed = cx.update_global::<CommandRegistry, bool>(|registry, cx| {
            let commands = registry.commands().iter().collect::<Vec<_>>();
            let filtered = filtered_commands(&commands, self.query.as_str());
            match filtered.get(self.selected_index) {
                Some((command, _)) => {
                    command.run(window, cx);
                    true
                }
                None => false,
            }
        });
        if executed {
            self.close(window, cx);
        }
    }

    fn select_and_execute(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        self.selected_index = index;
        self.execute_selected(window, cx);
    }

    fn handle_key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let keystroke = &event.keystroke;
        match keystroke.key.as_str() {
            "escape" => self.close(window, cx),
            "backspace" => {
                if !self.query.is_empty() {
                    let mut text = self.query.to_string();
                    text.pop();
                    self.query = text.into();
                    self.selected_index = 0;
                    cx.notify();
                }
            }
            "up" => self.move_selection(-1, cx),
            "down" => self.move_selection(1, cx),
            "enter" => self.execute_selected(window, cx),
            _ => {
                // Modifier chords are shortcuts, not text input.
                let modifiers = keystroke.modifiers;
                if modifiers.platform || modifiers.control || modifiers.alt {
                    return;
                }
                if let Some(char) = keystroke.key_char.as_ref() {
                    let mut text = self.query.to_string();
                    text.push_str(char);
                    self.query = text.into();
                    self.selected_index = 0;
                    cx.notify();
                }
            }
        }
    }
}

impl Focusable for CommandPalette {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.input_focus.clone()
    }
}

impl Render for CommandPalette {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let entity = cx.entity();

        // The trigger is handled by an element-level on_action on this wrapper
        // div, so it fires during normal action bubbling with direct access to
        // the window — no re-entering the dispatch in progress.
        if self.open {
            let focus = self.input_focus.clone();
            let query = self.query.clone();
            let selected = self.selected_index;
            let commands = cx
                .global::<CommandRegistry>()
                .commands()
                .iter()
                .collect::<Vec<_>>();
            let filtered = filtered_commands(&commands, self.query.as_str());

            let window_bounds = window.bounds();
            let width = f32::from(window_bounds.size.width);
            let card_bounds = Bounds::from_corners(
                point(px((width - 520.0) / 2.0), px(96.0)),
                point(px((width + 520.0) / 2.0), px(96.0 + 320.0)),
            );

            div()
                .id("command-palette")
                .size_full()
                .relative()
                .on_action({
                    let entity = entity.clone();
                    move |_: &ToggleCommandPalette, window, cx| {
                        entity.update(cx, |palette, cx| palette.toggle(window, cx));
                    }
                })
                .child(self.previous_root.clone())
                .child(
                    div()
                        .absolute()
                        .top_0()
                        .right_0()
                        .bottom_0()
                        .left_0()
                        .bg(rgba(0x000000b0))
                        .on_mouse_down(
                            MouseButton::Left,
                            {
                                let entity = entity.clone();
                                move |event, window, cx| {
                                    if !card_bounds.contains(&event.position) {
                                        entity.update(cx, |palette, cx| {
                                            palette.close(window, cx)
                                        });
                                    }
                                }
                            },
                        )
                        .flex()
                        .justify_center()
                        .items_start()
                        .pt(px(96.0))
                        .child(card(&entity, &focus, &query, &filtered, selected)),
                )
                .into_any_element()
        } else {
            div()
                .id("command-palette")
                .size_full()
                .on_action({
                    let entity = entity.clone();
                    move |_: &ToggleCommandPalette, window, cx| {
                        entity.update(cx, |palette, cx| palette.toggle(window, cx));
                    }
                })
                .child(self.previous_root.clone())
                .into_any_element()
        }
    }
}

fn card(
    entity: &Entity<CommandPalette>,
    focus: &FocusHandle,
    query: &SharedString,
    filtered: &[(&Command, i32)],
    selected: usize,
) -> impl IntoElement {
    let entity = entity.clone();
    let key_entity = entity.clone();
    let focus = focus.clone();
    let query = query.clone();
    let query_empty = query.is_empty();
    let empty_query = query.clone();

    div()
        .flex()
        .flex_col()
        .w(px(520.0))
        .h(px(320.0))
        .bg(rgb(0x181825))
        .border_1()
        .border_color(rgb(0x45475a))
        .rounded_lg()
        .shadow_lg()
        .child(
            div()
                .flex()
                .flex_row()
                .items_center()
                .gap_2()
                .px_3()
                .py_2()
                .border_b_1()
                .border_color(rgb(0x313244))
                .child(div().text_color(rgb(0x89b4fa)).child(">"))
                .child(
                    div()
                        .flex_1()
                        .track_focus(&focus)
                        .on_key_down(move |event, window, cx| {
                            key_entity.update(cx, |palette, cx| {
                                palette.handle_key(event, window, cx)
                            });
                        })
                        .child(if query_empty {
                            div()
                                .text_color(rgb(0x6c7086))
                                .child("Search commands…")
                        } else {
                            div().text_color(rgb(0xcdd6f4)).child(query)
                        }),
                ),
        )
        .child(
            div()
                .id("command-list")
                .flex()
                .flex_col()
                .flex_1()
                .overflow_y_scroll()
                .when(filtered.is_empty() && !query_empty, {
                    let query = empty_query;
                    move |this| {
                        this.child(
                            div()
                                .px_3()
                                .py_2()
                                .text_color(rgb(0x6c7086))
                                .child(format!("No commands match \"{query}\"")),
                        )
                    }
                })
                .children(
                    filtered
                        .iter()
                        .enumerate()
                        .map(|(index, (command, _))| command_row(&entity, command, index, selected)),
                ),
        )
}

/// Filter and rank commands by the palette query, best match first.
fn filtered_commands<'a>(commands: &'a [&'a Command], query: &str) -> Vec<(&'a Command, i32)> {
    if query.is_empty() {
        return commands.iter().map(|command| (*command, 0)).collect();
    }
    let mut scored: Vec<_> = commands
        .iter()
        .filter_map(|command| {
            fuzzy_match(query, command.name().as_str()).map(|score| (*command, score))
        })
        .collect();
    scored.sort_by_key(|(_, score)| std::cmp::Reverse(*score));
    scored
}

fn command_row(
    entity: &Entity<CommandPalette>,
    command: &Command,
    index: usize,
    selected: usize,
) -> impl IntoElement {
    let entity = entity.clone();
    div()
        .flex()
        .flex_row()
        .justify_between()
        .items_center()
        .px_3()
        .py_1()
        .when(index == selected, |this| this.bg(rgb(0x45475a)))
        .hover(|style| style.bg(rgb(0x313244)))
        .on_mouse_down(
            MouseButton::Left,
            move |_, window, cx| {
                entity.update(cx, |palette, cx| {
                    palette.select_and_execute(index, window, cx)
                });
            },
        )
        .child(
            div()
                .flex()
                .flex_row()
                .gap_2()
                .child(div().text_color(rgb(0xcdd6f4)).child(command.name().clone()))
                .child(
                    div()
                        .text_sm()
                        .text_color(rgb(0x6c7086))
                        .child(command.category_name().clone()),
                ),
        )
        .when_some(command.binding(), |this, binding| {
            this.child(
                div()
                    .px_2()
                    .py_1()
                    .bg(rgb(0x313244))
                    .rounded_md()
                    .text_sm()
                    .text_color(rgb(0x89b4fa))
                    .child(binding.clone()),
            )
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Command;
    use gpui::{actions, App, Context, FocusHandle, Focusable, Render, TestAppContext, Window, div};

    actions!([PingPalette, PongPalette]);

    struct Placeholder {
        focus: FocusHandle,
    }

    impl Placeholder {
        fn new(cx: &mut Context<Self>) -> Self {
            Self {
                focus: cx.focus_handle(),
            }
        }
    }

    impl Focusable for Placeholder {
        fn focus_handle(&self, _: &App) -> FocusHandle {
            self.focus.clone()
        }
    }

    impl Render for Placeholder {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            div()
                .size_full()
                .track_focus(&self.focus_handle(cx))
                .child("placeholder")
        }
    }

    fn install_palette(cx: &mut TestAppContext) -> (gpui::AnyWindowHandle, &mut TestAppContext) {
        let window = cx.add_window(|_, cx| Placeholder::new(cx));
        window
            .update(cx, |view, window, cx| {
                window.focus(&view.focus_handle(cx));
            })
            .unwrap();
        let handle: gpui::AnyWindowHandle = window.into();

        cx.update(|cx| {
            let mut registry = CommandRegistry::new();
            registry.register(Command::new("Ping", PingPalette).handler(|_, _| {}));
            registry.register(Command::new("Pong", PongPalette).handler(|_, _| {}));
            CommandPalette::install(registry, cx);
        });

        (handle, cx)
    }

    fn palette_open(cx: &mut TestAppContext, handle: gpui::AnyWindowHandle) -> bool {
        cx.update(|cx| {
            handle
                .update(cx, |root, _, cx| {
                    let palette = root.downcast::<CommandPalette>().unwrap();
                    palette.read(cx).open
                })
                .unwrap()
        })
    }

    fn palette_selection(cx: &mut TestAppContext, handle: gpui::AnyWindowHandle) -> usize {
        cx.update(|cx| {
            handle
                .update(cx, |root, _, cx| {
                    let palette = root.downcast::<CommandPalette>().unwrap();
                    palette.read(cx).selected_index
                })
                .unwrap()
        })
    }

    #[gpui::test]
    fn install_wraps_root_and_trigger_opens_palette(cx: &mut TestAppContext) {
        let (handle, cx) = install_palette(cx);

        cx.update(|cx| {
            let is_palette = handle
                .update(cx, |root, _, _| root.downcast::<CommandPalette>().is_ok())
                .unwrap();
            assert!(is_palette, "install did not wrap the window's root view");
        });

        cx.simulate_keystrokes(handle, "cmd-shift-p");
        assert!(palette_open(cx, handle), "trigger did not open the palette");

        // Toggle again to close, then again to reopen.
        cx.simulate_keystrokes(handle, "cmd-shift-p");
        cx.simulate_keystrokes(handle, "cmd-shift-p");
        assert!(palette_open(cx, handle), "trigger did not reopen the palette");
    }

    #[gpui::test]
    fn arrow_keys_move_selection_with_wraparound(cx: &mut TestAppContext) {
        let (handle, cx) = install_palette(cx);

        cx.simulate_keystrokes(handle, "cmd-shift-p");
        assert_eq!(palette_selection(cx, handle), 0);

        cx.simulate_keystrokes(handle, "down");
        assert_eq!(palette_selection(cx, handle), 1);

        // Wraps back around to the first command.
        cx.simulate_keystrokes(handle, "down");
        assert_eq!(palette_selection(cx, handle), 0);

        cx.simulate_keystrokes(handle, "up");
        assert_eq!(palette_selection(cx, handle), 1);
    }

    #[gpui::test]
    fn enter_executes_selected_command(cx: &mut TestAppContext) {
        let window = cx.add_window(|_, cx| Placeholder::new(cx));
        window
            .update(cx, |view, window, cx| {
                window.focus(&view.focus_handle(cx));
            })
            .unwrap();
        let handle: gpui::AnyWindowHandle = window.into();

        let executed = std::rc::Rc::new(std::cell::RefCell::new(0));
        let counter = executed.clone();

        cx.update(|cx| {
            let mut registry = CommandRegistry::new();
            registry.register(
                Command::new("Increment", PingPalette).handler(move |_, _| {
                    *counter.borrow_mut() += 1;
                }),
            );
            CommandPalette::install(registry, cx);
        });

        cx.simulate_keystrokes(handle, "cmd-shift-p");
        cx.simulate_keystrokes(handle, "enter");

        assert_eq!(
            *executed.borrow(),
            1,
            "enter did not run the selected command's handler"
        );
        assert!(!palette_open(cx, handle), "enter did not close the palette");
    }

    #[gpui::test]
    fn typing_filters_and_enter_executes_match(cx: &mut TestAppContext) {
        let window = cx.add_window(|_, cx| Placeholder::new(cx));
        window
            .update(cx, |view, window, cx| {
                window.focus(&view.focus_handle(cx));
            })
            .unwrap();
        let handle: gpui::AnyWindowHandle = window.into();

        let ping_count = std::rc::Rc::new(std::cell::RefCell::new(0));
        let pong_count = std::rc::Rc::new(std::cell::RefCell::new(0));

        cx.update(|cx| {
            let mut registry = CommandRegistry::new();
            registry.register(Command::new("Ping", PingPalette).handler({
                let counter = ping_count.clone();
                move |_, _| *counter.borrow_mut() += 1
            }));
            registry.register(Command::new("Pong", PongPalette).handler({
                let counter = pong_count.clone();
                move |_, _| *counter.borrow_mut() += 1
            }));
            CommandPalette::install(registry, cx);
        });

        cx.simulate_keystrokes(handle, "cmd-shift-p");
        cx.simulate_keystrokes(handle, "p o n g");
        cx.simulate_keystrokes(handle, "enter");

        assert_eq!(*ping_count.borrow(), 0, "filtered-out command was executed");
        assert_eq!(*pong_count.borrow(), 1, "matching command was not executed");
        assert!(!palette_open(cx, handle), "palette did not close after executing");
    }
}