rok-ui 0.9.2

shadcn/ui-style component system for GPUI desktop apps, with a React-like developer experience.
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
584
585
586
587
588
589
590
591
592
593
//! Command: a searchable list of actions (cmdk), plus [`CommandDialog`] for a
//! ⌘K-style palette. [`super::Combobox`] is built on the same list.

use std::rc::Rc;

use gpui::{
    div, point, prelude::*, px, AnyElement, App, Corner, Div, ElementId, Entity, SharedString,
    StyleRefinement, Window,
};

use super::layer::layer_at;
use super::{
    input::{use_input_state, Input, InputState, Submit},
    interaction::Callback,
    overlay::child_id,
};
use crate::sx::SxStyled;
use crate::{
    hooks::{use_keyed_state, EventHandler},
    icon::{Icon, IconName},
    styles,
    styles::ApplyStyleOverrides,
    theme::ActiveTheme,
};

/// One selectable row in a [`Command`] list.
#[derive(Clone)]
pub struct CommandItem {
    label: SharedString,
    keywords: Vec<SharedString>,
    icon: Option<IconName>,
    shortcut: Option<SharedString>,
    disabled: bool,
    checked: Option<bool>,
    on_select: Option<EventHandler<()>>,
}

impl CommandItem {
    /// Create it with its label.
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            keywords: Vec::new(),
            icon: None,
            shortcut: None,
            disabled: false,
            checked: None,
            on_select: None,
        }
    }

    /// Extra words the search matches besides the label.
    #[must_use]
    pub fn keywords(mut self, keywords: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
        self.keywords = keywords.into_iter().map(Into::into).collect();
        self
    }

    /// An icon shown with the label.
    #[must_use]
    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

    /// A keyboard shortcut hint shown at the end.
    #[must_use]
    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    /// Disable it: it ignores input and renders muted.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Show a check on the right (used by [`super::Combobox`] for the current value).
    #[must_use]
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = Some(checked);
        self
    }

    /// Called when the item is chosen.
    #[must_use]
    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_select = Some(Rc::new(handler));
        self
    }

    fn matches(&self, query: &str) -> bool {
        let query = query.trim().to_lowercase();
        if query.is_empty() {
            return true;
        }
        std::iter::once(&self.label)
            .chain(self.keywords.iter())
            .any(|text| fuzzy_match(&text.to_lowercase(), &query))
    }
}

/// Every query character appears in `text`, in order (cmdk-style loose matching).
fn fuzzy_match(text: &str, query: &str) -> bool {
    let mut text_characters = text.chars();
    query
        .chars()
        .filter(|character| !character.is_whitespace())
        .all(|query_character| text_characters.any(|character| character == query_character))
}

#[derive(Clone)]
#[doc(hidden)]
pub struct CommandGroup {
    heading: Option<SharedString>,
    items: Vec<CommandItem>,
}

impl CommandGroup {
    #[cfg_attr(not(feature = "full"), allow(dead_code))]
    #[doc(hidden)]
    #[must_use]
    pub fn without_heading(items: Vec<CommandItem>) -> Self {
        Self {
            heading: None,
            items,
        }
    }
}

/// Highlighted row, reset whenever the query changes.
struct CommandHighlight {
    query: SharedString,
    index: usize,
}

styles! {
    COMMAND = {
        root: { display: flex, direction: column },
        // The search field sits flush on top, divided from the list by its bottom border.
        search: { height: 10, border: 0, radius: none, border_bottom: 1, border_color: border },
        list: {
            display: flex,
            direction: column,
            max_height: 75,
            padding_x: 1,
            padding_bottom: 1,
        },
        empty: { padding_y: 6, text_align: center, text: sm, color: muted_foreground },
        separator: { height: 0.25, margin_x: -1, background: border },
        group: { display: flex, direction: column, padding_y: 1 },
        heading: {
            padding_x: 2,
            padding_y: 1.5,
            text: xs,
            font: medium,
            color: muted_foreground,
        },
        item: {
            display: flex,
            align: center,
            gap: 2,
            padding_x: 2,
            padding_y: 1.5,
            radius: sm,
            text: sm,
        },
        highlighted: { background: accent, color: accent_foreground },
        interactive: { cursor: pointer },
        inert: { opacity: 0.5 },
        item_label: { flex: 1 },
        shortcut: { text: xs, color: muted_foreground },
        check_slot: { size: 4 },
        frame: {
            width: full,
            overflow: hidden,
            radius: md,
            border: 1,
            border_color: border,
            background: popover,
            color: popover_foreground,
        },
        // Layers lay out apart from the window root, so text alignment is set here.
        dialog_scrim: {
            display: flex,
            direction: column,
            align: center,
            padding_x: 4,
            font_family: sans,
            text: theme,
            text_align: start,
        },
        dialog_panel: { width: full, max_width: 128, shadow: lg },
    }
}

/// Render the search field and the filtered list. `after_select` runs after an
/// item's own handler (Combobox uses it to close its popover).
#[doc(hidden)]
pub fn render_command(
    id: &ElementId,
    search: &Entity<InputState>,
    groups: &[CommandGroup],
    empty_text: SharedString,
    after_select: Option<Callback>,
    window: &mut Window,
    cx: &mut App,
) -> Div {
    let query = search.read(cx).text().clone();
    let highlight = use_keyed_state(child_id(id, "highlight"), window, cx, || CommandHighlight {
        query: SharedString::default(),
        index: 0,
    });
    if highlight.read(cx).query != query {
        highlight.update(cx, |highlight| {
            highlight.query = query.clone();
            highlight.index = 0;
        });
    }
    let highlighted_index = highlight.read(cx).index;
    let muted_foreground = cx.theme().colors.muted_foreground;

    // Flatten the visible items so keyboard navigation can step across groups.
    let mut visible_items: Vec<CommandItem> = Vec::new();
    let mut sections: Vec<AnyElement> = Vec::new();
    for group in groups {
        let matching: Vec<CommandItem> = group
            .items
            .iter()
            .filter(|item| item.matches(&query))
            .cloned()
            .collect();
        if matching.is_empty() {
            continue;
        }
        if !sections.is_empty() {
            sections.push(div().sx(&COMMAND.separator).into_any_element());
        }
        let mut section = div().sx(&COMMAND.group);
        if let Some(heading) = group.heading.clone() {
            section = section.child(
                div()
                    .sx(&COMMAND.heading)
                    .child(crate::components::bidi_text::text(heading)),
            );
        }
        for item in matching {
            let flat_index = visible_items.len();
            let is_highlighted = flat_index == highlighted_index && !item.disabled;
            let hover_highlight = highlight.clone();
            let after_select = after_select.clone();
            let selected_item = item.clone();
            section = section.child(
                div()
                    .id(("command-item", flat_index))
                    .sx((
                        &COMMAND.item,
                        is_highlighted.then_some(&COMMAND.highlighted),
                        if item.disabled {
                            &COMMAND.inert
                        } else {
                            &COMMAND.interactive
                        },
                    ))
                    .when(!item.disabled, |row| {
                        row.on_hover(move |hovered, _, cx| {
                            if *hovered {
                                hover_highlight
                                    .update(cx, |highlight| highlight.index = flat_index);
                            }
                        })
                        .on_click(move |_, window, cx| {
                            select_item(&selected_item, after_select.as_ref(), window, cx);
                        })
                    })
                    .when_some(item.icon, |row, icon| {
                        row.child(Icon::new(icon).size(px(16.)).color(muted_foreground))
                    })
                    .child(
                        div()
                            .sx(&COMMAND.item_label)
                            .child(crate::components::bidi_text::text(item.label.clone())),
                    )
                    .when_some(item.shortcut.clone(), |row, shortcut| {
                        row.child(
                            div()
                                .sx(&COMMAND.shortcut)
                                .child(crate::components::bidi_text::text(shortcut)),
                        )
                    })
                    .when_some(item.checked, |row, checked| {
                        row.child(div().sx(&COMMAND.check_slot).when(checked, |slot| {
                            slot.child(Icon::new(IconName::Check).size(px(16.)))
                        }))
                    }),
            );
            visible_items.push(item);
        }
        sections.push(section.into_any_element());
    }

    let list = div()
        .sx(&COMMAND.list)
        .id(child_id(id, "list"))
        .overflow_y_scroll()
        .when(visible_items.is_empty(), |list| {
            list.child(div().sx(&COMMAND.empty).child(empty_text))
        })
        .children(sections);

    let visible_items = Rc::new(visible_items);
    let key_highlight = highlight.clone();
    let key_items = visible_items.clone();
    let submit_after_select = after_select.clone();
    div()
        .sx(&COMMAND.root)
        .on_key_down(move |event, _, cx| {
            let count = key_items.len();
            if count == 0 {
                return;
            }
            let step = match event.keystroke.key.as_str() {
                "down" => 1,
                "up" => count - 1,
                _ => return,
            };
            cx.stop_propagation();
            key_highlight.update(cx, |highlight| {
                highlight.index = (highlight.index + step) % count;
            });
        })
        // Enter is the input's Submit action; capture it before the input does.
        .capture_action(move |_: &Submit, window, cx| {
            let index = highlight.read(cx).index;
            if let Some(item) = visible_items.get(index).filter(|item| !item.disabled) {
                cx.stop_propagation();
                select_item(item, submit_after_select.as_ref(), window, cx);
            }
        })
        .child(
            Input::new(search)
                .leading_icon(IconName::Search)
                .without_focus_ring()
                .sx(&COMMAND.search),
        )
        .child(list)
}

fn select_item(
    item: &CommandItem,
    after_select: Option<&Callback>,
    window: &mut Window,
    cx: &mut App,
) {
    if let Some(handler) = item.on_select.as_ref() {
        handler(&(), window, cx);
    }
    if let Some(after_select) = after_select {
        after_select(window, cx);
    }
}

/// shadcn/ui's `<Command>`: a search field over grouped items, filtered as you
/// type. Up / Down move the highlight and Enter runs the highlighted item.
///
/// ```no_run
/// # use rok_ui::prelude::*;
/// # fn example(window: &mut Window, cx: &mut App) {
/// let command = Command::new("command")
///     .placeholder("Type a command or search...")
///     .group("Suggestions", [
///         CommandItem::new("Calendar").icon(IconName::Calendar),
///         CommandItem::new("Search emoji").icon(IconName::Smile),
///     ])
///     .group("Settings", [CommandItem::new("Profile").shortcut("Cmd-P")]);
/// # }
/// ```
#[derive(IntoElement)]
pub struct Command {
    id: ElementId,
    placeholder: SharedString,
    empty_text: SharedString,
    groups: Vec<CommandGroup>,
    sx: crate::sx::Sx,
    style_overrides: StyleRefinement,
}

crate::implement_style_overrides!(Command);

impl Command {
    /// Create the component. `id` must be unique among its siblings; it keys the component's state.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            placeholder: "Type a command or search…".into(),
            empty_text: "No results found.".into(),
            groups: Vec::new(),
            sx: crate::sx::Sx::new(),
            style_overrides: StyleRefinement::default(),
        }
    }

    /// Text shown while nothing is entered or selected.
    #[must_use]
    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Text shown when nothing matches the search.
    #[must_use]
    pub fn empty_text(mut self, empty_text: impl Into<SharedString>) -> Self {
        self.empty_text = empty_text.into();
        self
    }

    /// A headed group of items.
    #[must_use]
    pub fn group(
        mut self,
        heading: impl Into<SharedString>,
        items: impl IntoIterator<Item = CommandItem>,
    ) -> Self {
        self.groups.push(CommandGroup {
            heading: Some(heading.into()),
            items: items.into_iter().collect(),
        });
        self
    }

    /// Items without a group heading.
    #[must_use]
    pub fn items(mut self, items: impl IntoIterator<Item = CommandItem>) -> Self {
        self.groups.push(CommandGroup {
            heading: None,
            items: items.into_iter().collect(),
        });
        self
    }

    fn render_body(self, after_select: Option<Callback>, window: &mut Window, cx: &mut App) -> Div {
        let placeholder = self.placeholder.clone();
        let search = use_input_state(child_id(&self.id, "search"), window, cx, |state| {
            state.with_placeholder(placeholder)
        });
        render_command(
            &self.id,
            &search,
            &self.groups,
            self.empty_text,
            after_select,
            window,
            cx,
        )
        .sx((&COMMAND.frame, &self.sx))
        .apply_style_overrides(&self.style_overrides)
    }
}

impl RenderOnce for Command {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        self.render_body(None, window, cx)
    }
}

/// A [`Command`] in a modal, the ⌘K palette. Controlled like [`super::Dialog`];
/// it closes on Escape, on a backdrop click and after an item runs.
///
/// ```no_run
/// # use rok_ui::prelude::*;
/// # fn example(window: &mut Window, cx: &mut App) {
/// # let palette_open = true;
/// # fn set_palette_open(_: bool, _: &mut App) {}
/// let palette = CommandDialog::new(
///     "palette",
///     Command::new("palette-command").group("Pages", [CommandItem::new("Home")]),
/// )
/// .open(palette_open)
/// .on_close(move |_, _, cx| set_palette_open(false, cx));
/// # }
/// ```
#[derive(IntoElement)]
pub struct CommandDialog {
    id: ElementId,
    command: Command,
    open: bool,
    on_close: Option<EventHandler<()>>,
}

impl CommandDialog {
    /// Create the component. `id` must be unique among its siblings; it keys the component's state.
    pub fn new(id: impl Into<ElementId>, command: Command) -> Self {
        Self {
            id: id.into(),
            command,
            open: false,
            on_close: None,
        }
    }

    /// Whether it is open (controlled).
    #[must_use]
    pub fn open(mut self, open: bool) -> Self {
        self.open = open;
        self
    }

    /// Called when the dialog asks to close (Escape, outside click).
    #[must_use]
    pub fn on_close(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_close = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for CommandDialog {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let presence =
            crate::components::interaction::modal_presence(&self.id, self.open, window, cx);
        if !presence.is_mounted() {
            return div().into_any_element();
        }
        let progress = presence.progress();
        let close: Callback = {
            let on_close = self.on_close.clone();
            Rc::new(move |window, cx| {
                if let Some(handler) = on_close.as_ref() {
                    handler(&(), window, cx);
                }
            })
        };

        // Focus the search field when the palette opens.
        let search_focus = window
            .use_keyed_state(child_id(&self.command.id, "search"), cx, |_, cx| {
                InputState::new(cx).with_placeholder(self.command.placeholder.clone())
            })
            .read(cx)
            .focus_handle_ref()
            .clone();
        // Only when it opens; see `render_modal` for why not on every frame.
        let (focus_container, focus_pending) = window
            .use_keyed_state(child_id(&self.id, "focus"), cx, |_, cx| {
                (
                    cx.focus_handle(),
                    std::rc::Rc::new(std::cell::Cell::new(true)),
                )
            })
            .read(cx)
            .clone();
        if focus_pending.replace(false) {
            window.defer(cx, move |window, _| window.focus(&search_focus));
        }

        let theme = cx.theme();
        let overlay = theme.colors.overlay;
        let viewport_size = window.viewport_size();
        let escape_close = close.clone();
        let backdrop_close = close.clone();
        let panel = super::interaction::trap_focus(div(), &focus_container)
            .track_focus(&focus_container)
            .sx(&COMMAND.dialog_panel)
            .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
            .on_key_down(move |event, window, cx| {
                if event.keystroke.key == "escape" {
                    cx.stop_propagation();
                    escape_close(window, cx);
                }
            })
            .child(self.command.render_body(Some(close), window, cx));

        let scrim = div()
            .id(self.id)
            .occlude()
            .w(viewport_size.width)
            .h(viewport_size.height)
            .sx(&COMMAND.dialog_scrim)
            .pt(viewport_size.height * 0.2)
            .bg(overlay.opacity(progress))
            .on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| {
                backdrop_close(window, cx);
            })
            .child(
                panel
                    .relative()
                    .top(px(8. * (1. - progress)))
                    .opacity(progress),
            );
        layer_at(point(px(0.), px(0.)), Corner::TopLeft, px(0.), scrim, 1, cx)
    }
}