Skip to main content

gpui_deck/
command.rs

1//! Searchable actions composed from the existing text input and GPUI scrolling.
2//! GPUI Deck owns matching and the highlighted action; applications own the
3//! surrounding surface, item presentation, and the action's effects.
4
5use gpui::{
6    AnyElement, App, AppContext as _, Bounds, Context, ElementId, Entity, EntityId,
7    EntityInputHandler as _, EventEmitter, FocusHandle, Focusable as _, InteractiveElement,
8    Interactivity, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, ScrollHandle,
9    SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Window, div,
10    prelude::FluentBuilder as _, px,
11};
12
13use crate::{
14    ElementExt as _, Input, InputAccessibility, InputBase, InputState, InputStyles,
15    TestSupportExt as _,
16    a11y_disabled::A11yDisabledExt as _,
17    input::{InputEvent, MoveDown, MoveUp},
18};
19
20/// One value, label, and searchable aliases in a fixed collection. Values must be unique.
21#[derive(Clone, Debug)]
22pub struct SearchItem {
23    value: SharedString,
24    label: SharedString,
25    search_text: String,
26    disabled: bool,
27    group: Option<SharedString>,
28}
29
30impl SearchItem {
31    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
32        let value = value.into();
33        let label = label.into();
34        Self {
35            search_text: format!("{value} {label}").to_lowercase(),
36            value,
37            label,
38            disabled: false,
39            group: None,
40        }
41    }
42
43    /// Adds searchable aliases without changing the visible or accessible label.
44    pub fn keywords<S: AsRef<str>>(mut self, keywords: impl IntoIterator<Item = S>) -> Self {
45        for keyword in keywords {
46            self.search_text.push(' ');
47            self.search_text.push_str(&keyword.as_ref().to_lowercase());
48        }
49        self
50    }
51
52    pub fn disabled(mut self, disabled: bool) -> Self {
53        self.disabled = disabled;
54        self
55    }
56
57    /// Names the result group. Group labels do not change matching or item order.
58    pub fn group(mut self, label: impl Into<SharedString>) -> Self {
59        self.group = Some(label.into());
60        self
61    }
62
63    pub fn group_label(&self) -> Option<&SharedString> {
64        self.group.as_ref()
65    }
66
67    pub fn value(&self) -> &SharedString {
68        &self.value
69    }
70
71    pub fn label(&self) -> &SharedString {
72        &self.label
73    }
74
75    pub fn is_disabled(&self) -> bool {
76        self.disabled
77    }
78}
79
80fn collect_items(items: impl IntoIterator<Item = SearchItem>) -> Vec<SearchItem> {
81    let items: Vec<_> = items.into_iter().collect();
82    for (index, item) in items.iter().enumerate() {
83        assert!(
84            items[..index].iter().all(|other| other.value != item.value),
85            "SearchItem values must be unique"
86        );
87        if index > 0 && items[index - 1].group != item.group {
88            assert!(
89                items[..index].iter().all(|other| other.group != item.group),
90                "SearchItem groups must be contiguous"
91            );
92        }
93    }
94    items
95}
96
97/// Ranks one lowercase query term against an item's lowercase search text, or
98/// `None` when the term's characters do not appear in order. A match at a word
99/// start ranks above any other substring, which ranks above a subsequence; a
100/// tighter subsequence ranks above a looser one.
101fn term_score(text: &str, term: &str) -> Option<u32> {
102    if term.is_empty() {
103        return Some(0);
104    }
105    let mut substring = None;
106    for (start, _) in text.match_indices(term) {
107        let word_start = text[..start]
108            .chars()
109            .next_back()
110            .is_none_or(|previous| !previous.is_alphanumeric());
111        if word_start {
112            return Some(300);
113        }
114        substring = Some(200);
115    }
116    if substring.is_some() {
117        return substring;
118    }
119    let length = term.chars().count();
120    // The shortest window containing the term's characters in order.
121    let chars: Vec<char> = text.chars().collect();
122    let pattern: Vec<char> = term.chars().collect();
123    let mut shortest: Option<usize> = None;
124    for start in 0..chars.len() {
125        if chars[start] != pattern[0] {
126            continue;
127        }
128        let mut matched = 1;
129        let mut end = start;
130        while matched < pattern.len() {
131            end += 1;
132            if end >= chars.len() {
133                break;
134            }
135            if chars[end] == pattern[matched] {
136                matched += 1;
137            }
138        }
139        if matched == pattern.len() {
140            let span = end - start + 1;
141            shortest = Some(shortest.map_or(span, |current| current.min(span)));
142        }
143    }
144    shortest.map(|span| 1 + (99 * length / span) as u32)
145}
146
147/// An explicit command activation. The application decides what it does.
148#[derive(Clone, Debug, Eq, PartialEq)]
149pub enum CommandEvent {
150    Action(SharedString),
151}
152
153/// A query input and its fixed collection of searchable actions in one window.
154///
155/// InputState is the query's source of truth. The characters of each
156/// whitespace-separated query term must appear in order, case-insensitively, in
157/// the value, label, or keywords. Results rank word-start matches above other
158/// substrings and those above looser in-order matches, summed over terms. Groups
159/// stay contiguous, ordered by their best result; equal scores and an empty
160/// query keep collection order.
161/// Query changes highlight the first enabled result. Arrows move that highlight
162/// without committing a value, and Enter or a pointer click emits an action.
163///
164/// Keep this entity in the application and observe it to render its results.
165/// The command has no open/close lifecycle; compose it inside Dialog when needed.
166pub struct CommandState {
167    items: Vec<SearchItem>,
168    input: Entity<InputState>,
169    focus: FocusHandle,
170    // Only the last text processed by the derived filter, never a second value.
171    filtered_query: SharedString,
172    visible: Vec<usize>,
173    // Inverse of the ranked result order, indexed by the source item.
174    visible_positions: Vec<Option<usize>>,
175    highlighted: Option<usize>,
176    scroll: ScrollHandle,
177    option_bounds: Vec<Option<Bounds<Pixels>>>,
178    _input_observation: Subscription,
179    _input_events: Subscription,
180}
181
182impl CommandState {
183    pub fn new(
184        items: impl IntoIterator<Item = SearchItem>,
185        window: &mut Window,
186        cx: &mut Context<Self>,
187    ) -> Self {
188        let items = collect_items(items);
189        let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search commands..."));
190        let focus = input.focus_handle(cx);
191        let input_observation = cx.observe(&input, |state, _, cx| {
192            state.sync_query(cx);
193            // Focus and disabled changes also affect the application-owned frame.
194            cx.notify();
195        });
196        let input_events = cx.subscribe_in(&input, window, |state, _, event, window, cx| {
197            if matches!(
198                event,
199                InputEvent::PressEnter {
200                    secondary: false,
201                    shift: false
202                }
203            ) && state.focus.is_focused(window)
204            {
205                state.activate_highlighted(window, cx);
206            }
207        });
208        Self {
209            option_bounds: vec![None; items.len()],
210            visible: (0..items.len()).collect(),
211            visible_positions: (0..items.len()).map(Some).collect(),
212            highlighted: items.iter().position(|item| !item.disabled),
213            items,
214            input,
215            focus,
216            filtered_query: SharedString::default(),
217            scroll: ScrollHandle::new(),
218            _input_observation: input_observation,
219            _input_events: input_events,
220        }
221    }
222
223    /// The native query input, also available for application text styling.
224    pub fn input(&self) -> &Entity<InputState> {
225        &self.input
226    }
227
228    /// The only ordinary Tab stop supplied by this component.
229    pub fn focus_handle(&self) -> &FocusHandle {
230        &self.focus
231    }
232
233    pub fn items(&self) -> &[SearchItem] {
234        &self.items
235    }
236
237    /// Replaces available actions and refilters the existing native query without
238    /// changing input focus, selection, composition, or editing history.
239    /// Keeps the highlighted value when it remains enabled and visible.
240    pub fn set_items(
241        &mut self,
242        items: impl IntoIterator<Item = SearchItem>,
243        window: &mut Window,
244        cx: &mut Context<Self>,
245    ) {
246        let highlighted = self
247            .highlighted
248            .map(|index| self.items[index].value.clone());
249        let items = collect_items(items);
250        self.option_bounds = vec![None; items.len()];
251        self.items = items;
252        self.filter_query(self.input.read(cx).value());
253        if let Some(value) = highlighted {
254            self.highlighted = self
255                .visible
256                .iter()
257                .copied()
258                .find(|&index| !self.items[index].disabled && self.items[index].value == value)
259                .or(self.highlighted);
260        }
261        cx.notify();
262        window.refresh();
263    }
264
265    /// Original item indices in display order, including matching disabled items.
266    pub fn visible_indices(&self) -> &[usize] {
267        &self.visible
268    }
269
270    /// Nonempty named groups in first-result order. Render each group's options
271    /// in [`Self::visible_group_indices`] order; ungrouped options use None.
272    pub fn visible_groups(&self) -> Vec<SharedString> {
273        let mut groups = Vec::new();
274        for &index in &self.visible {
275            if let Some(group) = &self.items[index].group
276                && !groups.contains(group)
277            {
278                groups.push(group.clone());
279            }
280        }
281        groups
282    }
283
284    pub fn visible_group_indices(&self, group: Option<&str>) -> Vec<usize> {
285        self.visible
286            .iter()
287            .copied()
288            .filter(|&index| self.items[index].group.as_deref() == group)
289            .collect()
290    }
291
292    pub fn highlighted_index(&self) -> Option<usize> {
293        self.highlighted
294    }
295
296    /// Changes the native input and immediately refreshes its derived results.
297    /// Like InputState::set_value, this resets the query's editing history.
298    pub fn set_query(
299        &mut self,
300        query: impl Into<SharedString>,
301        window: &mut Window,
302        cx: &mut Context<Self>,
303    ) {
304        let query: SharedString = query.into();
305        self.input.update(cx, |input, cx| {
306            input.set_value(query.to_string(), window, cx)
307        });
308        self.sync_query(cx);
309        cx.notify();
310    }
311
312    pub(crate) fn activate_highlighted(&mut self, window: &mut Window, cx: &mut Context<Self>) {
313        self.sync_query(cx);
314        if let Some(index) = self.highlighted {
315            self.activate(index, window, cx);
316        }
317    }
318
319    pub(crate) fn sync_query(&mut self, cx: &mut Context<Self>) {
320        let query = self.input.read(cx).value();
321        if query == self.filtered_query {
322            return;
323        }
324        self.filter_query(query);
325    }
326
327    fn filter_query(&mut self, query: SharedString) {
328        let terms: Vec<_> = query.split_whitespace().map(str::to_lowercase).collect();
329        let scored: Vec<(usize, u32)> = self
330            .items
331            .iter()
332            .enumerate()
333            .filter_map(|(index, item)| {
334                terms
335                    .iter()
336                    .map(|term| term_score(&item.search_text, term))
337                    .sum::<Option<u32>>()
338                    .map(|score| (index, score))
339            })
340            .collect();
341        // Groups stay contiguous: they order by their best item, and items by
342        // score within their group. Equal scores keep collection order.
343        let best = |group: &Option<SharedString>| {
344            scored
345                .iter()
346                .filter(|(index, _)| &self.items[*index].group == group)
347                .map(|(_, score)| *score)
348                .max()
349                .unwrap_or(0)
350        };
351        let mut ranked: Vec<(u32, usize, u32, usize)> = scored
352            .iter()
353            .map(|&(index, score)| {
354                let group = &self.items[index].group;
355                let first = self
356                    .items
357                    .iter()
358                    .position(|item| &item.group == group)
359                    .unwrap_or(index);
360                (best(group), first, score, index)
361            })
362            .collect();
363        ranked.sort_by(|a, b| {
364            b.0.cmp(&a.0)
365                .then(a.1.cmp(&b.1))
366                .then(b.2.cmp(&a.2))
367                .then(a.3.cmp(&b.3))
368        });
369        self.visible = ranked.into_iter().map(|(_, _, _, index)| index).collect();
370        self.visible_positions.clear();
371        self.visible_positions.resize(self.items.len(), None);
372        for (position, &index) in self.visible.iter().enumerate() {
373            self.visible_positions[index] = Some(position);
374        }
375        self.highlighted = self
376            .visible
377            .iter()
378            .copied()
379            .find(|&index| !self.items[index].disabled);
380        self.filtered_query = query;
381        self.option_bounds.fill(None);
382        self.scroll.set_offset(Default::default());
383        self.scroll_to_highlight();
384    }
385
386    pub(crate) fn is_composing(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
387        self.input.update(cx, |input, cx| {
388            input.marked_text_range(window, cx).is_some()
389        })
390    }
391
392    fn visible_position(&self, index: usize) -> Option<usize> {
393        self.visible_positions.get(index).copied().flatten()
394    }
395
396    fn scroll_to_highlight(&self) {
397        let Some(bounds) = self.highlighted.and_then(|index| self.option_bounds[index]) else {
398            return;
399        };
400        let viewport = self.scroll.bounds();
401        let mut offset = self.scroll.offset();
402        // Bounds are stored without the viewport's scroll offset, so nested
403        // group wrappers do not change which exact option must be revealed.
404        let top = bounds.top() + offset.y;
405        let bottom = bounds.bottom() + offset.y;
406        if top < viewport.top() {
407            offset.y += viewport.top() - top;
408        } else if bottom > viewport.bottom() {
409            offset.y -= bottom - viewport.bottom();
410        }
411        offset.y = offset.y.clamp(-self.scroll.max_offset().y, px(0.));
412        self.scroll.set_offset(offset);
413    }
414
415    pub(crate) fn move_cursor(
416        &mut self,
417        forward: bool,
418        window: &mut Window,
419        cx: &mut Context<Self>,
420    ) {
421        if !self.focus.is_focused(window)
422            || self.input.read(cx).presentation().is_disabled()
423            || self.is_composing(window, cx)
424        {
425            cx.propagate();
426            return;
427        }
428        self.sync_query(cx);
429        let count = self.visible.len();
430        if count == 0 {
431            return;
432        }
433        let start = self
434            .highlighted
435            .and_then(|index| self.visible_position(index))
436            .unwrap_or(if forward { count - 1 } else { 0 });
437        for distance in 1..=count {
438            let position = if forward {
439                (start + distance) % count
440            } else {
441                (start + count - distance) % count
442            };
443            let index = self.visible[position];
444            if !self.items[index].disabled {
445                self.highlight(index, window, cx);
446                break;
447            }
448        }
449    }
450
451    pub(crate) fn highlight(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
452        if self.highlighted == Some(index)
453            || self.visible_position(index).is_none()
454            || self.items[index].disabled
455            || self.input.read(cx).presentation().is_disabled()
456            || self.is_composing(window, cx)
457        {
458            return;
459        }
460        self.highlighted = Some(index);
461        self.scroll_to_highlight();
462        cx.notify();
463        window.refresh();
464    }
465
466    fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
467        if self.visible_position(index).is_none()
468            || self.items[index].disabled
469            || self.input.read(cx).presentation().is_disabled()
470            || self.is_composing(window, cx)
471        {
472            return;
473        }
474        self.highlight(index, window, cx);
475        self.focus.focus(window, cx);
476        cx.emit(CommandEvent::Action(self.items[index].value.clone()));
477    }
478}
479
480impl EventEmitter<CommandEvent> for CommandState {}
481
482/// An unstyled command root containing a query input and a result list.
483///
484/// Only Input's unmodified Up/Down actions move the command cursor. Home/End,
485/// Space, selection, clipboard, and IME input remain owned by the text engine.
486#[derive(IntoElement)]
487pub struct Command {
488    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
489    state: Entity<CommandState>,
490    label: Option<SharedString>,
491}
492
493impl Command {
494    pub fn new(id: impl Into<ElementId>, state: &Entity<CommandState>) -> Self {
495        Self {
496            base: div().id(id).test_support(),
497            state: state.clone(),
498            label: None,
499        }
500    }
501
502    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
503        self.label = Some(label.into());
504        self
505    }
506}
507
508impl Styled for Command {
509    fn style(&mut self) -> &mut StyleRefinement {
510        self.base.style()
511    }
512}
513
514impl ParentElement for Command {
515    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
516        self.base.extend(elements);
517    }
518}
519
520impl InteractiveElement for Command {
521    fn interactivity(&mut self) -> &mut Interactivity {
522        self.base.interactivity()
523    }
524}
525
526impl StatefulInteractiveElement for Command {}
527
528impl RenderOnce for Command {
529    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
530        let up = self.state.clone();
531        let down = self.state;
532        self.base
533            .role(Role::Group)
534            .when_some(self.label, |this, label| this.aria_label(label))
535            .on_action(move |_: &MoveUp, window, cx| {
536                up.update(cx, |state, cx| state.move_cursor(false, window, cx));
537            })
538            .on_action(move |_: &MoveDown, window, cx| {
539                down.update(cx, |state, cx| state.move_cursor(true, window, cx));
540            })
541    }
542}
543
544/// The query's application-styled InputBase frame and existing native Input.
545#[derive(IntoElement)]
546pub struct CommandInput {
547    base: InputBase,
548    state: Entity<CommandState>,
549    label: Option<SharedString>,
550    placeholder: SharedString,
551}
552
553impl CommandInput {
554    pub fn new(id: impl Into<ElementId>, state: &Entity<CommandState>) -> Self {
555        Self {
556            base: InputBase::new(id).role(None::<Role>),
557            state: state.clone(),
558            label: None,
559            placeholder: "Search commands...".into(),
560        }
561    }
562
563    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
564        self.label = Some(label.into());
565        self
566    }
567
568    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
569        self.placeholder = placeholder.into();
570        self
571    }
572
573    pub fn styles(mut self, build: impl FnOnce(InputStyles) -> InputStyles) -> Self {
574        self.base = self.base.styles(build);
575        self
576    }
577}
578
579impl Styled for CommandInput {
580    fn style(&mut self) -> &mut StyleRefinement {
581        self.base.style()
582    }
583}
584
585impl InteractiveElement for CommandInput {
586    fn interactivity(&mut self) -> &mut Interactivity {
587        self.base.interactivity()
588    }
589}
590
591impl StatefulInteractiveElement for CommandInput {}
592
593impl RenderOnce for CommandInput {
594    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
595        let input = self.state.read(cx).input.clone();
596        input.update(cx, |input, cx| {
597            if input.presentation().placeholder() != &self.placeholder {
598                input.set_placeholder(self.placeholder.clone(), window, cx);
599            }
600            let accessibility = input
601                .accessibility()
602                .cloned()
603                .unwrap_or_else(|| InputAccessibility::new(Some(Role::TextInput)));
604            let label = self
605                .label
606                .or_else(|| accessibility.label().cloned())
607                .unwrap_or_else(|| "Search commands".into());
608            input.set_accessibility(
609                accessibility
610                    .with_role(Some(Role::TextInput))
611                    .with_label(Some(label))
612                    .with_placeholder(Some(self.placeholder)),
613            );
614        });
615        let presentation = input.read(cx).presentation();
616        self.base
617            .semantic_owner::<Input>(input.entity_id())
618            .focused(presentation.focus_handle().is_focused(window))
619            .disabled(presentation.is_disabled())
620            .child(Input::new(&input))
621    }
622}
623
624/// A named, vertically scrolling result list with no independent Tab stop.
625///
626/// Render CommandOption children for `visible_indices()` in that exact order,
627/// optionally inside CommandGroup wrappers. Keep extra controls and empty-result
628/// text outside this list; group headings never participate in navigation.
629/// Applications supply its height limit, spacing, and item presentation.
630#[derive(IntoElement)]
631pub struct CommandList {
632    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
633    state: Entity<CommandState>,
634    label: Option<SharedString>,
635    multiple: bool,
636}
637
638impl CommandList {
639    pub fn new(id: impl Into<ElementId>, state: &Entity<CommandState>) -> Self {
640        Self {
641            base: div().id(id).test_support().flex().flex_col().min_h_0(),
642            state: state.clone(),
643            label: None,
644            multiple: false,
645        }
646    }
647
648    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
649        self.label = Some(label.into());
650        self
651    }
652
653    pub(crate) fn from_base(
654        base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
655        state: &Entity<CommandState>,
656        label: Option<SharedString>,
657        multiple: bool,
658    ) -> Self {
659        Self {
660            base,
661            state: state.clone(),
662            label,
663            multiple,
664        }
665    }
666}
667
668impl Styled for CommandList {
669    fn style(&mut self) -> &mut StyleRefinement {
670        self.base.style()
671    }
672}
673
674impl ParentElement for CommandList {
675    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
676        self.base.extend(elements);
677    }
678}
679
680impl InteractiveElement for CommandList {
681    fn interactivity(&mut self) -> &mut Interactivity {
682        self.base.interactivity()
683    }
684}
685
686impl StatefulInteractiveElement for CommandList {}
687
688impl RenderOnce for CommandList {
689    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
690        self.base
691            .role(Role::ListBox)
692            .when_some(self.label, |this, label| this.aria_label(label))
693            .overflow_y_scroll()
694            .track_scroll(&self.state.read(cx).scroll)
695            .a11y_selection(false, self.multiple)
696    }
697}
698
699/// A named, non-focusable result group with an application-styled heading.
700/// Render only the matching [`CommandState::visible_group_indices`] options.
701/// A group without visible matching items contributes no layout or native nodes.
702#[derive(IntoElement)]
703pub struct CommandGroup {
704    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
705    state: Entity<CommandState>,
706    label: SharedString,
707    heading: gpui::Div,
708    children: Vec<AnyElement>,
709}
710
711impl CommandGroup {
712    pub fn new(
713        id: impl Into<ElementId>,
714        state: &Entity<CommandState>,
715        label: impl Into<SharedString>,
716    ) -> Self {
717        let id = id.into();
718        let label = label.into();
719        Self::from_base(
720            div().id(id).test_support(),
721            state,
722            label.clone(),
723            div().child(label),
724        )
725    }
726
727    pub(crate) fn from_base(
728        base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
729        state: &Entity<CommandState>,
730        label: SharedString,
731        heading: gpui::Div,
732    ) -> Self {
733        Self {
734            base,
735            state: state.clone(),
736            label,
737            heading,
738            children: Vec::new(),
739        }
740    }
741
742    pub fn heading(mut self, build: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
743        self.heading = build(self.heading);
744        self
745    }
746}
747
748impl Styled for CommandGroup {
749    fn style(&mut self) -> &mut StyleRefinement {
750        self.base.style()
751    }
752}
753
754impl ParentElement for CommandGroup {
755    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
756        self.children.extend(elements);
757    }
758}
759
760impl RenderOnce for CommandGroup {
761    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
762        if self
763            .state
764            .read(cx)
765            .visible_group_indices(Some(&self.label))
766            .is_empty()
767        {
768            return gpui::Empty.into_any_element();
769        }
770        // The heading precedes options while the group's accessible name stays
771        // independent of its decorative presentation.
772        self.base
773            .role(Role::Group)
774            .aria_label(self.label.clone())
775            .flex()
776            .flex_col()
777            .flex_shrink_0()
778            .child(
779                self.heading
780                    .id("heading")
781                    .test_support()
782                    .role(Role::Heading)
783                    .aria_level(3)
784                    .aria_label(self.label),
785            )
786            .children(self.children)
787            .into_any_element()
788    }
789}
790
791fn option_id(state: EntityId, index: usize) -> ElementId {
792    (
793        ElementId::from(("command-option", state)),
794        index.to_string(),
795    )
796        .into()
797}
798
799/// One action row. The native text input keeps keyboard focus during navigation.
800///
801/// The highlighted row exposes selected metadata but is not a committed value.
802/// The pinned GPUI API cannot link an input to a sibling list's active descendant;
803/// this component does not claim that unsupported relationship.
804#[derive(IntoElement)]
805pub struct CommandOption {
806    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
807    state: Entity<CommandState>,
808    index: usize,
809    selected: Option<bool>,
810}
811
812impl CommandOption {
813    pub fn new(state: &Entity<CommandState>, index: usize) -> Self {
814        Self {
815            base: div()
816                .id(option_id(state.entity_id(), index))
817                .test_support()
818                .flex_shrink_0(),
819            state: state.clone(),
820            index,
821            selected: None,
822        }
823    }
824
825    pub(crate) fn from_base(
826        base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
827        state: &Entity<CommandState>,
828        index: usize,
829        selected: bool,
830    ) -> Self {
831        Self {
832            base,
833            state: state.clone(),
834            index,
835            selected: Some(selected),
836        }
837    }
838}
839
840impl Styled for CommandOption {
841    fn style(&mut self) -> &mut StyleRefinement {
842        self.base.style()
843    }
844}
845
846impl ParentElement for CommandOption {
847    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
848        self.base.extend(elements);
849    }
850}
851
852impl InteractiveElement for CommandOption {
853    fn interactivity(&mut self) -> &mut Interactivity {
854        self.base.interactivity()
855    }
856}
857
858impl StatefulInteractiveElement for CommandOption {}
859
860impl RenderOnce for CommandOption {
861    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
862        let state = self.state.read(cx);
863        let item = state
864            .items
865            .get(self.index)
866            .expect("CommandOption index must identify an item");
867        if state.visible_position(self.index).is_none() {
868            return gpui::Empty.into_any_element();
869        }
870        let disabled = item.disabled || state.input.read(cx).presentation().is_disabled();
871        let selected = self
872            .selected
873            .unwrap_or(state.highlighted == Some(self.index));
874        let label = item.label.clone();
875        let index = self.index;
876        let focus = state.focus.clone();
877        let hover = self.state.clone();
878        let activate = self.state;
879        let geometry = activate.clone();
880        self.base
881            .role(Role::ListBoxOption)
882            .aria_label(label)
883            .aria_selected(selected)
884            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
885                cx.stop_propagation();
886                if !disabled {
887                    focus.focus(window, cx);
888                }
889            })
890            .when(!disabled, |this| {
891                this.on_hover(move |hovered, window, cx| {
892                    if *hovered {
893                        hover.update(cx, |state, cx| state.highlight(index, window, cx));
894                    }
895                })
896                .on_click(move |_, window, cx| {
897                    activate.update(cx, |state, cx| state.activate(index, window, cx));
898                })
899            })
900            .on_prepaint(move |bounds, window, cx| {
901                geometry.update(cx, |state, _| {
902                    let first = state.option_bounds[index].is_none();
903                    state.option_bounds[index] = Some(Bounds::new(
904                        bounds.origin - state.scroll.offset(),
905                        bounds.size,
906                    ));
907                    if first && state.highlighted == Some(index) {
908                        let previous = state.scroll.offset();
909                        state.scroll_to_highlight();
910                        if state.scroll.offset() != previous {
911                            window.request_animation_frame();
912                        }
913                    }
914                });
915            })
916            .a11y_disabled(disabled)
917            .into_any_element()
918    }
919}
920
921#[cfg(test)]
922mod tests {
923    use std::{cell::RefCell, rc::Rc};
924
925    use gpui::{
926        KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext, VisualTestContext,
927        px,
928    };
929
930    use super::*;
931    use crate::{Button, Root};
932
933    struct Harness {
934        command: Entity<CommandState>,
935        after: FocusHandle,
936        _observation: Subscription,
937    }
938
939    impl Render for Harness {
940        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
941            let state = self.command.read(cx);
942            div()
943                .w(px(320.))
944                .flex()
945                .flex_col()
946                .child(
947                    Command::new("commands", &self.command)
948                        .accessibility_label("Session commands")
949                        .flex()
950                        .flex_col()
951                        .child(CommandInput::new("query", &self.command).h(px(32.)))
952                        .child(
953                            CommandList::new("results", &self.command)
954                                .accessibility_label("Results")
955                                .h(px(64.))
956                                .children(state.visible_indices().iter().map(|&index| {
957                                    CommandOption::new(&self.command, index)
958                                        .debug_selector(move || format!("option-{index}").into())
959                                        .h(px(32.))
960                                        .child(state.items()[index].label().clone())
961                                })),
962                        ),
963                )
964                .child(
965                    Button::new("after")
966                        .track_focus(&self.after)
967                        .h(px(32.))
968                        .child("After"),
969                )
970        }
971    }
972
973    type Actions = Rc<RefCell<Vec<SharedString>>>;
974
975    fn items() -> Vec<SearchItem> {
976        vec![
977            SearchItem::new("edit", "Edit session").keywords(["preferences", "settings"]),
978            SearchItem::new("share", "Share").disabled(true),
979            SearchItem::new("cursor", "Toggle cursor").keywords(["pointer"]),
980            SearchItem::new("toolbar", "Toggle toolbar pin"),
981            SearchItem::new("notes", "메모").keywords(["memo"]),
982        ]
983    }
984
985    fn harness(
986        cx: &mut TestAppContext,
987        items: Vec<SearchItem>,
988    ) -> (&mut VisualTestContext, Entity<Harness>, Actions) {
989        cx.update(crate::init);
990        let (root, cx) = cx.add_window_view(move |window, cx| {
991            let view = cx.new(|cx| {
992                let command = cx.new(|cx| CommandState::new(items, window, cx));
993                let observation = cx.observe(&command, |_, _, cx| cx.notify());
994                Harness {
995                    command,
996                    after: cx.focus_handle(),
997                    _observation: observation,
998                }
999            });
1000            Root::new(view, window, cx)
1001        });
1002        let view = root
1003            .read_with(cx, |root, _| root.view().clone())
1004            .downcast::<Harness>()
1005            .unwrap();
1006        let actions = Rc::new(RefCell::new(Vec::new()));
1007        cx.update(|window, cx| {
1008            let command = view.read(cx).command.clone();
1009            let actions = actions.clone();
1010            cx.subscribe(&command, move |_, event: &CommandEvent, _| {
1011                let CommandEvent::Action(value) = event;
1012                actions.borrow_mut().push(value.clone());
1013            })
1014            .detach();
1015            window.activate_window();
1016            let focus = command.read(cx).focus_handle().clone();
1017            focus.focus(window, cx);
1018            window.draw(cx).clear(cx);
1019        });
1020        cx.run_until_parked();
1021        (cx, view, actions)
1022    }
1023
1024    fn draw(cx: &mut VisualTestContext) {
1025        cx.update(|window, cx| window.draw(cx).clear(cx));
1026    }
1027
1028    fn press(cx: &mut VisualTestContext, key: &str) {
1029        let keystroke =
1030            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
1031        cx.simulate_event(KeyDownEvent {
1032            keystroke: keystroke.clone(),
1033            is_held: false,
1034            prefer_character_input: false,
1035        });
1036        cx.simulate_event(KeyUpEvent { keystroke });
1037        draw(cx);
1038    }
1039
1040    fn set_query(cx: &mut VisualTestContext, view: &Entity<Harness>, query: &str) {
1041        cx.update(|window, cx| {
1042            let command = view.read(cx).command.clone();
1043            command.update(cx, |state, cx| {
1044                state.set_query(query.to_owned(), window, cx)
1045            });
1046        });
1047        draw(cx);
1048    }
1049
1050    #[gpui::test]
1051    fn filtering_uses_native_query_and_keeps_plain_text_editing(cx: &mut TestAppContext) {
1052        let (cx, view, actions) = harness(cx, items());
1053        set_query(cx, &view, "  PREF session ");
1054        cx.update(|_, cx| {
1055            let state = view.read(cx).command.read(cx);
1056            assert_eq!(state.input().read(cx).value(), "  PREF session ");
1057            assert_eq!(state.visible_indices(), [0]);
1058            assert_eq!(state.highlighted_index(), Some(0));
1059        });
1060        // The filter also follows programmatic input changes, which emit no Change event.
1061        cx.update(|window, cx| {
1062            let input = view.read(cx).command.read(cx).input().clone();
1063            input.update(cx, |input, cx| input.set_value("pOIntER", window, cx));
1064        });
1065        draw(cx);
1066        cx.update(|_, cx| {
1067            assert_eq!(view.read(cx).command.read(cx).visible_indices(), [2]);
1068        });
1069        set_query(cx, &view, "");
1070        cx.simulate_input("Toggle");
1071        cx.simulate_input(" ");
1072        draw(cx);
1073        cx.update(|_, cx| {
1074            let state = view.read(cx).command.read(cx);
1075            assert_eq!(state.input().read(cx).value(), "Toggle ");
1076            assert_eq!(state.visible_indices(), [2, 3]);
1077            assert_eq!(state.highlighted_index(), Some(2));
1078        });
1079        cx.simulate_keystrokes("home");
1080        draw(cx);
1081        cx.update(|_, cx| {
1082            let state = view.read(cx).command.read(cx);
1083            assert_eq!(state.input().read(cx).selected_range(), 0..0);
1084            assert_eq!(state.highlighted_index(), Some(2));
1085        });
1086        cx.simulate_keystrokes("end");
1087        draw(cx);
1088        cx.update(|_, cx| {
1089            assert_eq!(
1090                view.read(cx)
1091                    .command
1092                    .read(cx)
1093                    .input()
1094                    .read(cx)
1095                    .selected_range(),
1096                7..7,
1097            );
1098        });
1099        set_query(cx, &view, "no results");
1100        press(cx, "enter");
1101        cx.update(|_, cx| {
1102            let state = view.read(cx).command.read(cx);
1103            assert!(state.visible_indices().is_empty());
1104            assert_eq!(state.highlighted_index(), None);
1105        });
1106        set_query(cx, &view, "Share");
1107        press(cx, "enter");
1108        let first_option = cx.debug_bounds("option-1").unwrap().center();
1109        cx.simulate_click(first_option, Modifiers::default());
1110        draw(cx);
1111        cx.update(|window, cx| {
1112            let state = view.read(cx).command.read(cx);
1113            assert_eq!(state.visible_indices(), [1]);
1114            assert_eq!(state.highlighted_index(), None);
1115            assert!(state.focus_handle().is_focused(window));
1116            #[cfg(feature = "test-support")]
1117            {
1118                let input = crate::test_support::find(window, &[], &"query".into()).unwrap();
1119                assert_eq!(input.role(), Some(Role::TextInput));
1120                assert_eq!(input.label(), Some("Search commands"));
1121                assert_eq!(input.value(), Some("Share"));
1122                let option = crate::test_support::snapshots(window)
1123                    .into_iter()
1124                    .find(|item| item.role() == Some(Role::ListBoxOption))
1125                    .unwrap();
1126                assert_eq!(option.label(), Some("Share"));
1127                assert_eq!(option.disabled(), Some(true));
1128                assert_eq!(option.selected(), Some(false));
1129            }
1130        });
1131        assert!(actions.borrow().is_empty());
1132    }
1133
1134    #[gpui::test]
1135    fn arrows_and_pointer_share_one_cursor_and_leave_the_input_focused(cx: &mut TestAppContext) {
1136        let (cx, view, actions) = harness(cx, items());
1137        cx.simulate_keystrokes("down");
1138        draw(cx);
1139        cx.update(|window, cx| {
1140            let state = view.read(cx).command.read(cx);
1141            assert_eq!(state.highlighted_index(), Some(2), "skip the disabled row");
1142            assert!(state.focus_handle().is_focused(window));
1143            assert!(
1144                state.scroll.offset().y < px(0.),
1145                "reveal an offscreen result"
1146            );
1147        });
1148        assert!(actions.borrow().is_empty());
1149        cx.simulate_keystrokes("up up");
1150        draw(cx);
1151        cx.update(|_, cx| {
1152            assert_eq!(view.read(cx).command.read(cx).highlighted_index(), Some(4));
1153        });
1154        let last_option = cx.debug_bounds("option-4").unwrap().center();
1155        cx.simulate_click(last_option, Modifiers::default());
1156        draw(cx);
1157        assert_eq!(*actions.borrow(), [SharedString::from("notes")]);
1158        press(cx, "enter");
1159        assert_eq!(
1160            *actions.borrow(),
1161            ["notes", "notes"].map(SharedString::from)
1162        );
1163        set_query(cx, &view, "Toggle");
1164        cx.simulate_keystrokes("down");
1165        draw(cx);
1166        press(cx, "enter");
1167        assert_eq!(
1168            *actions.borrow(),
1169            ["notes", "notes", "toolbar"].map(SharedString::from),
1170        );
1171        cx.update(|window, cx| {
1172            let state = view.read(cx).command.read(cx);
1173            assert!(state.focus_handle().is_focused(window));
1174            assert_eq!(state.input().read(cx).value(), "Toggle");
1175        });
1176        cx.simulate_keystrokes("tab");
1177        draw(cx);
1178        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
1179    }
1180
1181    #[gpui::test]
1182    fn marked_text_never_navigates_or_executes_a_command(cx: &mut TestAppContext) {
1183        let mut items = items();
1184        items.push(SearchItem::new("note-settings", "메모 설정"));
1185        let (cx, view, actions) = harness(cx, items);
1186        cx.update(|window, cx| {
1187            let input = view.read(cx).command.read(cx).input().clone();
1188            input.update(cx, |input, cx| {
1189                input.replace_and_mark_text_in_range(None, "메", Some(1..1), window, cx);
1190            });
1191        });
1192        draw(cx);
1193        cx.simulate_keystrokes("down");
1194        press(cx, "enter");
1195        cx.update(|window, cx| {
1196            let command = view.read(cx).command.clone();
1197            assert_eq!(command.read(cx).visible_indices(), [4, 5]);
1198            assert_eq!(command.read(cx).highlighted_index(), Some(4));
1199            let input = command.read(cx).input().clone();
1200            input.update(cx, |input, cx| {
1201                assert!(input.marked_text_range(window, cx).is_some());
1202                input.replace_text_in_range(None, "메모", window, cx);
1203            });
1204        });
1205        assert!(actions.borrow().is_empty());
1206        draw(cx);
1207        cx.simulate_keystrokes("down");
1208        press(cx, "enter");
1209        assert_eq!(*actions.borrow(), [SharedString::from("note-settings")]);
1210        cx.update(|window, cx| {
1211            let input = view.read(cx).command.read(cx).input().clone();
1212            input.update(cx, |input, cx| {
1213                assert!(input.marked_text_range(window, cx).is_none());
1214                assert_eq!(input.value(), "메모");
1215            });
1216        });
1217    }
1218
1219    #[gpui::test]
1220    fn fuzzy_terms_rank_word_starts_and_keep_groups_contiguous(cx: &mut TestAppContext) {
1221        let (cx, view, actions) = harness(
1222            cx,
1223            vec![
1224                SearchItem::new("export", "Export recording").group("File"),
1225                SearchItem::new("report", "Send report").group("File"),
1226                SearchItem::new("present", "Present slides").group("View"),
1227                SearchItem::new("pointer", "Show pointer").group("View"),
1228            ],
1229        );
1230        let visible = |query: &str, cx: &mut VisualTestContext| {
1231            cx.update(|window, cx| {
1232                let command = view.read(cx).command.clone();
1233                command.update(cx, |state, cx| {
1234                    state.set_query(query.to_owned(), window, cx);
1235                    state.visible_indices().to_vec()
1236                })
1237            })
1238        };
1239        assert_eq!(visible("", cx), [0, 1, 2, 3], "an empty query keeps order");
1240        assert_eq!(
1241            visible("rep", cx),
1242            [1, 0, 2],
1243            "a word start ranks above in-order letters"
1244        );
1245        assert_eq!(
1246            visible("pnt", cx),
1247            [3, 2, 1],
1248            "tighter in-order matches rank first"
1249        );
1250        assert_eq!(
1251            visible("po", cx),
1252            [3, 0, 1],
1253            "the best group leads, kept contiguous"
1254        );
1255        cx.update(|_, cx| {
1256            let groups = view.read(cx).command.read(cx).visible_groups();
1257            assert_eq!(groups, ["View", "File"]);
1258            assert_eq!(view.read(cx).command.read(cx).highlighted_index(), Some(3));
1259        });
1260        draw(cx);
1261        press(cx, "enter");
1262        assert_eq!(*actions.borrow(), ["pointer"].map(SharedString::from));
1263        press(cx, "down");
1264        press(cx, "enter");
1265        let first = cx.debug_bounds("option-3").unwrap().center();
1266        cx.simulate_click(first, Modifiers::default());
1267        draw(cx);
1268        assert_eq!(
1269            *actions.borrow(),
1270            ["pointer", "export", "pointer"].map(SharedString::from)
1271        );
1272        assert_eq!(visible("re sl", cx), [2], "every term must match");
1273        assert!(visible("xyz", cx).is_empty());
1274    }
1275}