Skip to main content

gpui_deck/
combobox.rs

1//! Editable single or multiple selection over Command's search and the existing Popup.
2//! The native input owns the draft query; the combobox retains only the committed
3//! option and popup lifecycle. Applications supply all presentation.
4
5use std::{cell::Cell, rc::Rc};
6
7use gpui::{
8    Anchor, AnyElement, App, AppContext as _, Bounds, Context, ElementId, Entity,
9    EntityInputHandler as _, EventEmitter, FocusHandle, InteractiveElement, Interactivity,
10    IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString,
11    StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Window, div, px,
12};
13
14use crate::command::CommandGroup;
15use crate::{
16    CommandEvent, CommandList, CommandOption, CommandState, Input, InputAccessibility, InputBase,
17    InputState, InputStyles, Popup, SearchItem, TestSupportExt as _,
18    global_state::{DeferredPopover, GlobalState},
19    input::{Enter, Escape, InputEvent, MoveDown, MoveUp},
20};
21
22/// Committed values after a user selection, removal, or clear, in item order.
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub enum ComboboxEvent {
25    Change(Vec<SharedString>),
26}
27
28/// An ordered collection with editable search and committed values.
29///
30/// Opening with the pointer or an arrow clears the draft to show all options.
31/// Typing filters suggestions without changing the committed value. Enter or a
32/// result click commits; Escape, Tab, blur, and outside presses restore the
33/// committed label. Only the native input participates in Tab traversal.
34///
35/// Single selection is the default. Multiple mode toggles results without closing
36/// the popup or clearing the draft; consumers render selected-value chips.
37pub struct ComboboxState {
38    search: Entity<CommandState>,
39    input: Entity<InputState>,
40    focus: FocusHandle,
41    selected: Vec<usize>,
42    multiple: bool,
43    open: bool,
44    disabled: bool,
45    deferred_context: Option<DeferredPopover>,
46    _search_observation: Subscription,
47    _search_actions: Subscription,
48    _input_events: Subscription,
49}
50
51impl ComboboxState {
52    pub fn new(
53        items: impl IntoIterator<Item = SearchItem>,
54        window: &mut Window,
55        cx: &mut Context<Self>,
56    ) -> Self {
57        let search = cx.new(|cx| CommandState::new(items, window, cx));
58        let input = search.read(cx).input().clone();
59        let focus = search.read(cx).focus_handle().clone();
60        let search_observation = cx.observe(&search, |_, _, cx| cx.notify());
61        let search_actions = cx.subscribe_in(&search, window, |state, _, event, window, cx| {
62            let CommandEvent::Action(value) = event;
63            state.commit(value, window, cx);
64        });
65        let input_events = cx.subscribe_in(&input, window, |state, _, event, window, cx| {
66            match event {
67                InputEvent::Change if !state.disabled && state.focus.is_focused(window) => {
68                    state.search.update(cx, |search, cx| search.sync_query(cx));
69                    state.show_results(window, cx);
70                }
71                InputEvent::Blur => {
72                    // A detached input can report blur while its retained handle
73                    // still owns focus. Discard that draft after drawing too.
74                    let detached = state.focus.is_focused(window);
75                    cx.defer_in(window, move |state, window, cx| {
76                        if detached || !window.is_window_active() || !state.focus.is_focused(window)
77                        {
78                            state.close(window, cx);
79                        }
80                    });
81                }
82                _ => {}
83            }
84        });
85        Self {
86            search,
87            input,
88            focus,
89            selected: Vec::new(),
90            multiple: false,
91            open: false,
92            disabled: false,
93            deferred_context: None,
94            _search_observation: search_observation,
95            _search_actions: search_actions,
96            _input_events: input_events,
97        }
98    }
99
100    /// Allows several committed values. Configure before rendering the state.
101    /// Disabling multiple mode with more than one selected value is an error.
102    pub fn multiple(mut self, multiple: bool) -> Self {
103        assert!(
104            multiple || self.selected.len() <= 1,
105            "ComboboxState single mode cannot have multiple selected values"
106        );
107        self.multiple = multiple;
108        self
109    }
110
111    /// The native query state, also available for application text styling.
112    pub fn input(&self) -> &Entity<InputState> {
113        &self.input
114    }
115
116    pub fn focus_handle(&self) -> &FocusHandle {
117        &self.focus
118    }
119
120    pub fn items<'a>(&'a self, cx: &'a App) -> &'a [SearchItem] {
121        self.search.read(cx).items()
122    }
123
124    /// Original item indices in search order, including matching disabled items.
125    pub fn visible_indices<'a>(&'a self, cx: &'a App) -> &'a [usize] {
126        self.search.read(cx).visible_indices()
127    }
128
129    pub fn highlighted_index(&self, cx: &App) -> Option<usize> {
130        self.search.read(cx).highlighted_index()
131    }
132
133    pub fn selected_indices(&self) -> &[usize] {
134        &self.selected
135    }
136
137    pub fn is_selected(&self, index: usize) -> bool {
138        self.selected.binary_search(&index).is_ok()
139    }
140
141    pub fn selected_values(&self, cx: &App) -> Vec<SharedString> {
142        self.selected
143            .iter()
144            .map(|&index| self.items(cx)[index].value().clone())
145            .collect()
146    }
147
148    pub fn selected_items<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a SearchItem> {
149        self.selected
150            .iter()
151            .map(move |&index| &self.items(cx)[index])
152    }
153
154    pub fn visible_groups(&self, cx: &App) -> Vec<SharedString> {
155        self.search.read(cx).visible_groups()
156    }
157
158    pub fn visible_group_indices(&self, group: Option<&str>, cx: &App) -> Vec<usize> {
159        self.search.read(cx).visible_group_indices(group)
160    }
161
162    pub fn is_open(&self) -> bool {
163        self.open
164    }
165
166    pub fn is_disabled(&self) -> bool {
167        self.disabled
168    }
169
170    /// Sets committed values and closes the draft without emitting Change.
171    /// Unknown/disabled values and multiple values in single mode are rejected.
172    pub fn set_selected_values<V: AsRef<str>>(
173        &mut self,
174        values: impl IntoIterator<Item = V>,
175        window: &mut Window,
176        cx: &mut Context<Self>,
177    ) -> bool {
178        let mut selected = Vec::new();
179        for value in values {
180            let Some(index) = self
181                .items(cx)
182                .iter()
183                .position(|item| item.value().as_ref() == value.as_ref() && !item.is_disabled())
184            else {
185                return false;
186            };
187            if !selected.contains(&index) {
188                selected.push(index);
189            }
190        }
191        if !self.multiple && selected.len() > 1 {
192            return false;
193        }
194        selected.sort_unstable();
195        self.selected = selected;
196        self.close(window, cx);
197        cx.notify();
198        true
199    }
200
201    /// Replaces options without emitting Change. Selection follows stable values;
202    /// missing or disabled values are removed. An active native draft and IME
203    /// composition remain untouched. Closed single selection refreshes its label.
204    pub fn set_items(
205        &mut self,
206        items: impl IntoIterator<Item = SearchItem>,
207        window: &mut Window,
208        cx: &mut Context<Self>,
209    ) {
210        let values = self.selected_values(cx);
211        self.search
212            .update(cx, |search, cx| search.set_items(items, window, cx));
213        self.selected = self
214            .items(cx)
215            .iter()
216            .enumerate()
217            .filter(|(_, item)| !item.is_disabled() && values.contains(item.value()))
218            .map(|(index, _)| index)
219            .collect();
220        if !self.open && !self.is_composing(window, cx) {
221            self.close(window, cx);
222        }
223        cx.notify();
224        window.refresh();
225    }
226
227    /// Removes a committed value as a user action, returning focus to the query.
228    /// Disabled controls and active native composition reject the request.
229    pub fn remove_value(
230        &mut self,
231        value: &str,
232        window: &mut Window,
233        cx: &mut Context<Self>,
234    ) -> bool {
235        if self.disabled || self.is_composing(window, cx) {
236            return false;
237        }
238        let Some(position) = self
239            .selected
240            .iter()
241            .position(|&index| self.items(cx)[index].value().as_ref() == value)
242        else {
243            return false;
244        };
245        self.focus.focus(window, cx);
246        self.selected.remove(position);
247        if !self.multiple {
248            self.close(window, cx);
249        }
250        self.emit_change(window, cx);
251        true
252    }
253
254    /// Clears committed values and the query as a user action, preserving whether
255    /// results are open. Application-owned clear buttons call this method.
256    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
257        if self.disabled || self.is_composing(window, cx) {
258            return false;
259        }
260        let changed = !self.selected.is_empty();
261        self.focus.focus(window, cx);
262        self.selected.clear();
263        self.search
264            .update(cx, |search, cx| search.set_query("", window, cx));
265        if changed {
266            self.emit_change(window, cx);
267        }
268        changed
269    }
270
271    /// Starts a focused draft query without changing the committed selection.
272    pub fn set_query(
273        &mut self,
274        query: impl Into<SharedString>,
275        window: &mut Window,
276        cx: &mut Context<Self>,
277    ) {
278        if self.disabled || self.is_composing(window, cx) {
279            return;
280        }
281        let query = query.into();
282        self.search
283            .update(cx, |search, cx| search.set_query(query, window, cx));
284        self.focus.focus(window, cx);
285        self.show_results(window, cx);
286    }
287
288    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
289        if self.disabled == disabled {
290            return;
291        }
292        if disabled {
293            self.close(window, cx);
294        }
295        self.disabled = disabled;
296        self.input
297            .update(cx, |input, cx| input.set_disabled(disabled, cx));
298        cx.notify();
299        window.refresh();
300    }
301
302    /// Opens all options and highlights the committed option or first enabled item.
303    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
304        if self.open || self.disabled || self.is_composing(window, cx) {
305            return;
306        }
307        let highlighted = self
308            .selected
309            .first()
310            .copied()
311            .or_else(|| self.items(cx).iter().position(|item| !item.is_disabled()));
312        self.search.update(cx, |search, cx| {
313            search.set_query("", window, cx);
314            if let Some(index) = highlighted {
315                search.highlight(index, window, cx);
316            }
317        });
318        self.focus.focus(window, cx);
319        self.show_results(window, cx);
320    }
321
322    /// Discards the draft, restores the committed label, and preserves current focus.
323    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
324        let label = if self.multiple {
325            SharedString::default()
326        } else {
327            self.selected
328                .first()
329                .map(|&index| self.items(cx)[index].label().clone())
330                .unwrap_or_default()
331        };
332        let changed = self.input.read(cx).value() != label;
333        let was_open = self.open;
334        self.open = false;
335        self.deferred_context = None;
336        if changed {
337            self.search
338                .update(cx, |search, cx| search.set_query(label, window, cx));
339        }
340        if was_open || changed {
341            cx.notify();
342            window.refresh();
343        }
344    }
345
346    fn show_results(&mut self, window: &mut Window, cx: &mut Context<Self>) {
347        if self.open || self.disabled {
348            return;
349        }
350        self.open = true;
351        self.deferred_context = Some(GlobalState::register_deferred_popover(cx));
352        cx.notify();
353        window.refresh();
354    }
355
356    fn is_composing(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
357        self.search
358            .update(cx, |search, cx| search.is_composing(window, cx))
359    }
360
361    fn move_cursor(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
362        if self.disabled || self.is_composing(window, cx) {
363            return;
364        }
365        if self.open {
366            self.search
367                .update(cx, |search, cx| search.move_cursor(forward, window, cx));
368        } else {
369            self.open(window, cx);
370        }
371    }
372
373    fn commit(&mut self, value: &SharedString, window: &mut Window, cx: &mut Context<Self>) {
374        if !self.open || self.disabled {
375            return;
376        }
377        let Some(index) = self.items(cx).iter().position(|item| item.value() == value) else {
378            return;
379        };
380        if self.items(cx)[index].is_disabled() || self.is_composing(window, cx) {
381            return;
382        }
383        let changed = if self.multiple {
384            match self.selected.binary_search(&index) {
385                Ok(position) => {
386                    self.selected.remove(position);
387                }
388                Err(position) => self.selected.insert(position, index),
389            }
390            true
391        } else {
392            let changed = self.selected != [index];
393            self.selected = vec![index];
394            self.close(window, cx);
395            changed
396        };
397        if changed {
398            self.emit_change(window, cx);
399        }
400    }
401
402    fn emit_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
403        cx.emit(ComboboxEvent::Change(self.selected_values(cx)));
404        cx.notify();
405        window.refresh();
406    }
407}
408
409impl EventEmitter<ComboboxEvent> for ComboboxState {}
410
411/// An editable input and anchored suggestions with application-owned appearance.
412///
413/// Keep this mounted while closed. The input builder styles the existing native
414/// input's frame. Content should contain a ComboboxList and optional static empty
415/// text; result rows do not take keyboard focus.
416#[derive(IntoElement)]
417pub struct Combobox {
418    base: gpui::Stateful<gpui::Div>,
419    state: Entity<ComboboxState>,
420    input: ComboboxInput,
421    content: Option<AnyElement>,
422    anchor: Anchor,
423    offset: Pixels,
424}
425
426impl Combobox {
427    pub fn new(id: impl Into<ElementId>, state: &Entity<ComboboxState>) -> Self {
428        Self {
429            base: div().id(("combobox", state.entity_id())),
430            state: state.clone(),
431            input: ComboboxInput::new(id, state),
432            content: None,
433            anchor: Anchor::TopLeft,
434            offset: px(0.),
435        }
436    }
437
438    pub fn input(mut self, build: impl FnOnce(ComboboxInput) -> ComboboxInput) -> Self {
439        self.input = build(self.input);
440        self
441    }
442
443    pub fn content(mut self, content: impl IntoElement) -> Self {
444        self.content = Some(content.into_any_element());
445        self
446    }
447
448    pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
449        self.anchor = anchor.into();
450        self
451    }
452
453    pub fn offset(mut self, offset: Pixels) -> Self {
454        self.offset = offset;
455        self
456    }
457}
458
459impl Styled for Combobox {
460    fn style(&mut self) -> &mut StyleRefinement {
461        self.base.style()
462    }
463}
464
465impl RenderOnce for Combobox {
466    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
467        let open = self.state.read(cx).open;
468        let trigger_bounds = Rc::new(Cell::new(Bounds::<Pixels>::default()));
469        let measured_bounds = trigger_bounds.clone();
470        let outside = self.state.clone();
471        let mut popup = Popup::new(("combobox-popup", self.state.entity_id()), self.input)
472            .anchor(self.anchor)
473            .offset(self.offset)
474            .on_position(move |_, bounds| measured_bounds.set(bounds));
475        if open {
476            popup = popup.content(
477                div()
478                    .id("combobox-surface")
479                    .on_mouse_down_out(move |event, window, cx| {
480                        if !trigger_bounds.get().contains(&event.position) {
481                            outside.update(cx, |state, cx| state.close(window, cx));
482                        }
483                    })
484                    .children(self.content),
485            );
486        }
487        let up = self.state.clone();
488        let down = self.state.clone();
489        let confirm = self.state.clone();
490        let cancel = self.state.clone();
491        let tab = self.state.clone();
492        let tab_prev = self.state;
493        self.base
494            .on_action(move |_: &MoveUp, window, cx| {
495                up.update(cx, |state, cx| state.move_cursor(false, window, cx));
496            })
497            .on_action(move |_: &MoveDown, window, cx| {
498                down.update(cx, |state, cx| state.move_cursor(true, window, cx));
499            })
500            .capture_action(move |action: &Enter, window, cx| {
501                confirm.update(cx, |state, cx| {
502                    if state.open && !action.secondary && !action.shift {
503                        // The capture path prevents Input's Enter event from
504                        // activating the same result a second time.
505                        cx.stop_propagation();
506                        state
507                            .search
508                            .update(cx, |search, cx| search.activate_highlighted(window, cx));
509                    } else {
510                        cx.propagate();
511                    }
512                });
513            })
514            .capture_action(move |_: &Escape, window, cx| {
515                cancel.update(cx, |state, cx| {
516                    // Cancel the native composition first; this Escape must not
517                    // also discard the draft or close an enclosing dialog.
518                    if state.is_composing(window, cx) {
519                        state
520                            .input
521                            .update(cx, |input, cx| input.unmark_text(window, cx));
522                        cx.stop_propagation();
523                    } else if state.open {
524                        state.close(window, cx);
525                        cx.stop_propagation();
526                    } else {
527                        cx.propagate();
528                    }
529                });
530            })
531            .on_action(move |_: &crate::root::Tab, window, cx| {
532                tab.update(cx, |state, cx| state.close(window, cx));
533                cx.propagate();
534            })
535            .on_action(move |_: &crate::root::TabPrev, window, cx| {
536                tab_prev.update(cx, |state, cx| state.close(window, cx));
537                cx.propagate();
538            })
539            .child(popup)
540    }
541}
542
543/// The combobox's InputBase frame around its existing single-line editor.
544/// Field-provided name, description, error, and required metadata are preserved.
545#[derive(IntoElement)]
546pub struct ComboboxInput {
547    base: InputBase,
548    state: Entity<ComboboxState>,
549    label: Option<SharedString>,
550    placeholder: SharedString,
551}
552
553impl ComboboxInput {
554    pub fn new(id: impl Into<ElementId>, state: &Entity<ComboboxState>) -> Self {
555        Self {
556            base: InputBase::new(id).role(None::<Role>),
557            state: state.clone(),
558            label: None,
559            placeholder: "Choose an option...".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 ComboboxInput {
580    fn style(&mut self) -> &mut StyleRefinement {
581        self.base.style()
582    }
583}
584
585impl InteractiveElement for ComboboxInput {
586    fn interactivity(&mut self) -> &mut Interactivity {
587        self.base.interactivity()
588    }
589}
590
591impl StatefulInteractiveElement for ComboboxInput {}
592
593impl RenderOnce for ComboboxInput {
594    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
595        let state = self.state.read(cx);
596        let open = state.open;
597        let input = state.input.clone();
598        input.update(cx, |input, cx| {
599            if input.presentation().placeholder() != &self.placeholder {
600                input.set_placeholder(self.placeholder.clone(), window, cx);
601            }
602            let accessibility = input
603                .accessibility()
604                .cloned()
605                .unwrap_or_else(|| InputAccessibility::new(Some(Role::ComboBox)));
606            let label = self
607                .label
608                .or_else(|| accessibility.label().cloned())
609                .unwrap_or_else(|| "Choose an option".into());
610            input.set_accessibility(
611                accessibility
612                    .with_role(Some(Role::ComboBox))
613                    .with_label(Some(label))
614                    .with_placeholder(Some(self.placeholder))
615                    .with_expanded(Some(open)),
616            );
617        });
618        let presentation = input.read(cx).presentation();
619        let trigger = self.state;
620        self.base
621            .semantic_owner::<Input>(input.entity_id())
622            .focused(presentation.focus_handle().is_focused(window))
623            .disabled(presentation.is_disabled())
624            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
625                trigger.update(cx, |state, cx| state.open(window, cx));
626            })
627            .child(Input::new(&input))
628    }
629}
630
631/// A named scrolling list. Render ComboboxOption children in result order,
632/// optionally inside ComboboxGroup wrappers. Keep empty text outside the list.
633#[derive(IntoElement)]
634pub struct ComboboxList {
635    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
636    state: Entity<ComboboxState>,
637    label: Option<SharedString>,
638}
639
640impl ComboboxList {
641    pub fn new(id: impl Into<ElementId>, state: &Entity<ComboboxState>) -> Self {
642        Self {
643            base: div().id(id).test_support().flex().flex_col().min_h_0(),
644            state: state.clone(),
645            label: None,
646        }
647    }
648
649    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
650        self.label = Some(label.into());
651        self
652    }
653}
654
655impl Styled for ComboboxList {
656    fn style(&mut self) -> &mut StyleRefinement {
657        self.base.style()
658    }
659}
660
661impl ParentElement for ComboboxList {
662    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
663        self.base.extend(children);
664    }
665}
666
667impl RenderOnce for ComboboxList {
668    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
669        let state = self.state.read(cx);
670        CommandList::from_base(self.base, &state.search, self.label, state.multiple)
671    }
672}
673
674/// A named result group and heading over the existing Command list navigation.
675/// Items with one group label must be contiguous in the collection. Render only
676/// this group's visible indices; empty groups have no layout or native nodes.
677#[derive(IntoElement)]
678pub struct ComboboxGroup {
679    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
680    state: Entity<ComboboxState>,
681    label: SharedString,
682    heading: gpui::Div,
683    children: Vec<AnyElement>,
684}
685
686impl ComboboxGroup {
687    pub fn new(
688        id: impl Into<ElementId>,
689        state: &Entity<ComboboxState>,
690        label: impl Into<SharedString>,
691    ) -> Self {
692        let label = label.into();
693        Self {
694            base: div().id(id).test_support(),
695            state: state.clone(),
696            heading: div().child(label.clone()),
697            label,
698            children: Vec::new(),
699        }
700    }
701
702    pub fn heading(mut self, build: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
703        self.heading = build(self.heading);
704        self
705    }
706}
707
708impl Styled for ComboboxGroup {
709    fn style(&mut self) -> &mut StyleRefinement {
710        self.base.style()
711    }
712}
713
714impl ParentElement for ComboboxGroup {
715    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
716        self.children.extend(children);
717    }
718}
719
720impl RenderOnce for ComboboxGroup {
721    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
722        CommandGroup::from_base(
723            self.base,
724            &self.state.read(cx).search,
725            self.label,
726            self.heading,
727        )
728        .children(self.children)
729    }
730}
731
732/// One searchable option, sharing Command's navigation and pointer activation.
733/// Selected metadata describes the committed value, not the pending highlight.
734///
735/// The pinned GPUI API cannot link a focused input to a sibling list's active
736/// descendant. This component does not claim that unsupported relationship.
737#[derive(IntoElement)]
738pub struct ComboboxOption {
739    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
740    state: Entity<ComboboxState>,
741    index: usize,
742}
743
744impl ComboboxOption {
745    pub fn new(state: &Entity<ComboboxState>, index: usize) -> Self {
746        Self {
747            base: div()
748                .id((
749                    ElementId::from(("combobox-option", state.entity_id())),
750                    index.to_string(),
751                ))
752                .test_support()
753                .flex_shrink_0(),
754            state: state.clone(),
755            index,
756        }
757    }
758}
759
760impl Styled for ComboboxOption {
761    fn style(&mut self) -> &mut StyleRefinement {
762        self.base.style()
763    }
764}
765
766impl ParentElement for ComboboxOption {
767    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
768        self.base.extend(children);
769    }
770}
771
772impl InteractiveElement for ComboboxOption {
773    fn interactivity(&mut self) -> &mut Interactivity {
774        self.base.interactivity()
775    }
776}
777
778impl StatefulInteractiveElement for ComboboxOption {}
779
780impl RenderOnce for ComboboxOption {
781    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
782        let state = self.state.read(cx);
783        CommandOption::from_base(
784            self.base,
785            &state.search,
786            self.index,
787            state.is_selected(self.index),
788        )
789    }
790}
791
792#[cfg(test)]
793mod tests {
794    use std::{cell::RefCell, rc::Rc};
795
796    use gpui::{
797        KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext, VisualTestContext,
798        prelude::FluentBuilder as _,
799    };
800
801    use super::*;
802    use crate::{Button, Root};
803
804    struct Harness {
805        combo: Entity<ComboboxState>,
806        shown: bool,
807        after: FocusHandle,
808        outer_cancels: Rc<Cell<usize>>,
809        _observation: Subscription,
810    }
811
812    impl Render for Harness {
813        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
814            let state = self.combo.read(cx);
815            let cancels = self.outer_cancels.clone();
816            let option = |index| {
817                ComboboxOption::new(&self.combo, index)
818                    .debug_selector(move || format!("choice-{index}").into())
819                    .h(px(32.))
820                    .child(state.items(cx)[index].label().clone())
821            };
822            let groups = state.visible_groups(cx);
823            let mut list = ComboboxList::new("preset-results", &self.combo)
824                .accessibility_label("Presets")
825                .w(px(320.))
826                .max_h(px(if groups.is_empty() { 160. } else { 64. }));
827            if groups.is_empty() {
828                list = list.children(state.visible_indices(cx).iter().copied().map(option));
829            } else {
830                for group in groups {
831                    list = list.child(
832                        ComboboxGroup::new(
833                            (ElementId::from("group"), group.clone()),
834                            &self.combo,
835                            group.clone(),
836                        )
837                        .heading(|heading| heading.h(px(24.)))
838                        .children(
839                            state
840                                .visible_group_indices(Some(&group), cx)
841                                .into_iter()
842                                .map(option),
843                        ),
844                    );
845                }
846            }
847            div()
848                .w(px(320.))
849                .flex()
850                .flex_col()
851                .on_action(move |_: &Escape, _, _| cancels.set(cancels.get() + 1))
852                .when(self.shown, |this| {
853                    this.child(
854                        Combobox::new("preset", &self.combo)
855                            .input(|input| input.accessibility_label("Preset").w_full().h(px(32.)))
856                            .content(list),
857                    )
858                })
859                .child(
860                    Button::new("after")
861                        .track_focus(&self.after)
862                        .debug_selector(|| "after".into())
863                        .mt(px(200.))
864                        .h(px(32.))
865                        .child("After"),
866                )
867        }
868    }
869
870    type Changes = Rc<RefCell<Vec<Vec<SharedString>>>>;
871
872    fn harness(cx: &mut TestAppContext) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
873        harness_with_mode(cx, false)
874    }
875
876    fn harness_with_mode(
877        cx: &mut TestAppContext,
878        multiple: bool,
879    ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
880        cx.update(crate::init);
881        let (root, cx) = cx.add_window_view(move |window, cx| {
882            let view = cx.new(|cx| {
883                let combo = cx.new(|cx| {
884                    ComboboxState::new(
885                        [
886                            SearchItem::new("balanced", "Balanced"),
887                            SearchItem::new("unavailable", "Unavailable").disabled(true),
888                            SearchItem::new("presentation", "Presentation").keywords(["slides"]),
889                            SearchItem::new("quality", "High quality").keywords(["hq"]),
890                        ],
891                        window,
892                        cx,
893                    )
894                    .multiple(multiple)
895                });
896                combo.update(cx, |state, cx| {
897                    assert!(state.set_selected_values(["balanced"], window, cx));
898                });
899                let observation = cx.observe(&combo, |_, _, cx| cx.notify());
900                Harness {
901                    combo,
902                    shown: true,
903                    after: cx.focus_handle(),
904                    outer_cancels: Rc::new(Cell::new(0)),
905                    _observation: observation,
906                }
907            });
908            Root::new(view, window, cx)
909        });
910        let view = root
911            .read_with(cx, |root, _| root.view().clone())
912            .downcast::<Harness>()
913            .unwrap();
914        let changes = Rc::new(RefCell::new(Vec::new()));
915        cx.update(|window, cx| {
916            let combo = view.read(cx).combo.clone();
917            let changes = changes.clone();
918            cx.subscribe(&combo, move |_, event: &ComboboxEvent, _| {
919                let ComboboxEvent::Change(value) = event;
920                changes.borrow_mut().push(value.clone());
921            })
922            .detach();
923            window.activate_window();
924            combo.read(cx).focus_handle().clone().focus(window, cx);
925            window.draw(cx).clear(cx);
926        });
927        cx.run_until_parked();
928        (cx, view, changes)
929    }
930
931    fn draw(cx: &mut VisualTestContext) {
932        cx.update(|window, cx| window.draw(cx).clear(cx));
933        cx.run_until_parked();
934    }
935
936    fn press(cx: &mut VisualTestContext, key: &str) {
937        let keystroke =
938            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
939        cx.simulate_event(KeyDownEvent {
940            keystroke: keystroke.clone(),
941            is_held: false,
942            prefer_character_input: false,
943        });
944        cx.simulate_event(KeyUpEvent { keystroke });
945        draw(cx);
946    }
947
948    fn type_query(cx: &mut VisualTestContext, query: &str) {
949        cx.simulate_keystrokes(if cfg!(target_os = "macos") {
950            "cmd-a"
951        } else {
952            "ctrl-a"
953        });
954        cx.simulate_input(query);
955        draw(cx);
956    }
957
958    #[gpui::test]
959    fn multiple_toggles_preserve_drafts_and_user_removal_clear_respect_editability(
960        cx: &mut TestAppContext,
961    ) {
962        let (cx, view, changes) = harness_with_mode(cx, true);
963        press(cx, "down");
964        press(cx, "down");
965        press(cx, "enter");
966        cx.update(|_, cx| {
967            let state = view.read(cx).combo.read(cx);
968            assert!(state.is_open());
969            assert_eq!(state.selected_indices(), [0, 2]);
970        });
971        press(cx, "enter");
972        type_query(cx, "hq");
973        let option = cx.debug_bounds("choice-3").unwrap().center();
974        cx.simulate_click(option, Modifiers::default());
975        draw(cx);
976        cx.update(|window, cx| {
977            let combo = view.read(cx).combo.clone();
978            combo.update(cx, |state, cx| {
979                assert!(state.is_open());
980                assert_eq!(state.input().read(cx).value(), "hq");
981                assert_eq!(state.selected_indices(), [0, 3]);
982                assert!(state.remove_value("balanced", window, cx));
983                assert!(!state.remove_value("unavailable", window, cx));
984            });
985        });
986        draw(cx);
987        assert_eq!(changes.borrow().len(), 4);
988        cx.update(|window, cx| {
989            let combo = view.read(cx).combo.clone();
990            combo.update(cx, |state, cx| {
991                assert!(state.clear(window, cx));
992                assert!(!state.clear(window, cx));
993                assert!(state.is_open());
994                assert!(state.selected_indices().is_empty());
995                assert_eq!(state.input().read(cx).value(), "");
996                assert!(state.set_selected_values(["balanced", "quality"], window, cx));
997                state.set_query("hq", window, cx);
998                let input = state.input().clone();
999                input.update(cx, |input, cx| {
1000                    input.replace_and_mark_text_in_range(None, "q", Some(1..1), window, cx);
1001                });
1002                assert!(!state.remove_value("balanced", window, cx));
1003                assert!(!state.clear(window, cx));
1004            });
1005        });
1006        draw(cx);
1007        assert_eq!(changes.borrow().len(), 5);
1008        press(cx, "enter");
1009        assert_eq!(changes.borrow().len(), 5);
1010        press(cx, "escape");
1011        press(cx, "escape");
1012        cx.update(|window, cx| {
1013            let combo = view.read(cx).combo.clone();
1014            combo.update(cx, |state, cx| {
1015                assert!(!state.is_open());
1016                assert_eq!(state.input().read(cx).value(), "");
1017                assert_eq!(state.selected_indices(), [0, 3]);
1018                state.set_disabled(true, window, cx);
1019                assert!(!state.clear(window, cx));
1020                assert!(!state.remove_value("balanced", window, cx));
1021            });
1022        });
1023        assert_eq!(changes.borrow().len(), 5);
1024    }
1025
1026    #[gpui::test]
1027    fn grouped_results_scroll_and_replacement_preserves_query_composition_and_values(
1028        cx: &mut TestAppContext,
1029    ) {
1030        let (cx, view, changes) = harness_with_mode(cx, true);
1031        cx.update(|window, cx| {
1032            let combo = view.read(cx).combo.clone();
1033            combo.update(cx, |state, cx| {
1034                state.set_items(
1035                    [
1036                        SearchItem::new("balanced", "Balanced").group("Standard"),
1037                        SearchItem::new("unavailable", "Unavailable")
1038                            .group("Standard")
1039                            .disabled(true),
1040                        SearchItem::new("presentation", "Presentation").group("Special"),
1041                        SearchItem::new("quality", "High quality").group("Special"),
1042                    ],
1043                    window,
1044                    cx,
1045                );
1046                state.open(window, cx);
1047            });
1048        });
1049        draw(cx);
1050        press(cx, "down");
1051        #[cfg(feature = "test-support")]
1052        let highlighted_bounds = cx.debug_bounds("choice-2").unwrap();
1053        cx.update(|window, cx| {
1054            let state = view.read(cx).combo.read(cx);
1055            assert_eq!(state.highlighted_index(cx), Some(2));
1056            assert!(state.focus_handle().is_focused(window));
1057            #[cfg(feature = "test-support")]
1058            {
1059                let list =
1060                    crate::test_support::find(window, &[], &"preset-results".into()).unwrap();
1061                assert!(highlighted_bounds.top() >= list.bounds().top());
1062                assert!(highlighted_bounds.bottom() <= list.bounds().bottom());
1063                let group = crate::test_support::find(
1064                    window,
1065                    &[],
1066                    &(ElementId::from("group"), SharedString::from("Special")).into(),
1067                )
1068                .unwrap();
1069                assert_eq!(group.role(), Some(Role::Group));
1070                assert_eq!(group.label(), Some("Special"));
1071                let nodes = crate::test_support::snapshots(window);
1072                assert!(
1073                    nodes.iter().any(|node| node.role() == Some(Role::Heading)
1074                        && node.label() == Some("Special"))
1075                );
1076            }
1077        });
1078        type_query(cx, "quality");
1079        cx.update(|window, cx| {
1080            let _ = window;
1081            let state = view.read(cx).combo.read(cx);
1082            assert_eq!(state.visible_groups(cx), [SharedString::from("Special")]);
1083            #[cfg(feature = "test-support")]
1084            assert!(
1085                crate::test_support::find(
1086                    window,
1087                    &[],
1088                    &(ElementId::from("group"), SharedString::from("Standard")).into()
1089                )
1090                .is_none()
1091            );
1092        });
1093        press(cx, "enter");
1094        cx.update(|window, cx| {
1095            let combo = view.read(cx).combo.clone();
1096            combo.update(cx, |state, cx| {
1097                assert!(state.set_selected_values(
1098                    ["balanced", "presentation", "quality"],
1099                    window,
1100                    cx
1101                ));
1102                state.set_query("quality", window, cx);
1103                let input = state.input().clone();
1104                input.update(cx, |input, cx| {
1105                    input.replace_and_mark_text_in_range(Some(0..7), "q", Some(1..1), window, cx);
1106                });
1107                let before = input.read(cx).selected_range();
1108                state.set_items(
1109                    [
1110                        SearchItem::new("query-preview", "Query preview").group("Special"),
1111                        SearchItem::new("quality", "Quality renamed").group("Special"),
1112                        SearchItem::new("balanced", "Balanced")
1113                            .group("Special")
1114                            .disabled(true),
1115                    ],
1116                    window,
1117                    cx,
1118                );
1119                assert_eq!(state.selected_indices(), [1]);
1120                assert_eq!(state.visible_indices(cx), [0, 1]);
1121                assert_eq!(
1122                    state.highlighted_index(cx),
1123                    Some(1),
1124                    "keep the highlighted value when a new matching item is inserted before it"
1125                );
1126                assert_eq!(state.selected_values(cx), [SharedString::from("quality")]);
1127                assert_eq!(input.read(cx).value(), "q");
1128                assert_eq!(input.read(cx).selected_range(), before);
1129                input.update(cx, |input, cx| {
1130                    assert!(input.marked_text_range(window, cx).is_some())
1131                });
1132                assert!(state.is_open());
1133                assert!(state.focus_handle().is_focused(window));
1134            });
1135        });
1136        assert_eq!(
1137            changes.borrow().len(),
1138            1,
1139            "item replacement does not emit selection"
1140        );
1141    }
1142
1143    #[gpui::test]
1144    fn draft_search_commits_once_and_cancellation_restores_selection(cx: &mut TestAppContext) {
1145        let (cx, view, changes) = harness(cx);
1146        cx.simulate_keystrokes("down down");
1147        draw(cx);
1148        cx.update(|window, cx| {
1149            let state = view.read(cx).combo.read(cx);
1150            assert!(state.is_open());
1151            assert_eq!(
1152                state.highlighted_index(cx),
1153                Some(2),
1154                "disabled option is skipped"
1155            );
1156            assert_eq!(state.selected_indices(), [0]);
1157            assert!(state.focus_handle().is_focused(window));
1158        });
1159        press(cx, "escape");
1160        cx.update(|_, cx| {
1161            let state = view.read(cx).combo.read(cx);
1162            assert!(!state.is_open());
1163            assert_eq!(state.input().read(cx).value(), "Balanced");
1164            assert_eq!(view.read(cx).outer_cancels.get(), 0);
1165        });
1166        cx.simulate_keystrokes("down down");
1167        press(cx, "enter");
1168        press(cx, "enter");
1169        assert_eq!(
1170            *changes.borrow(),
1171            [vec![SharedString::from("presentation")]]
1172        );
1173        type_query(cx, "no matching preset");
1174        press(cx, "enter");
1175        cx.update(|_, cx| {
1176            let state = view.read(cx).combo.read(cx);
1177            assert!(state.is_open());
1178            assert!(state.visible_indices(cx).is_empty());
1179            assert_eq!(
1180                state
1181                    .selected_items(cx)
1182                    .next()
1183                    .map(|item| item.value().as_ref()),
1184                Some("presentation")
1185            );
1186        });
1187        cx.simulate_keystrokes("tab");
1188        draw(cx);
1189        cx.update(|window, cx| {
1190            let state = view.read(cx).combo.read(cx);
1191            assert!(!state.is_open());
1192            assert_eq!(state.input().read(cx).value(), "Presentation");
1193            assert!(view.read(cx).after.is_focused(window));
1194        });
1195        cx.simulate_keystrokes("shift-tab");
1196        type_query(cx, "hq");
1197        let option = cx.debug_bounds("choice-3").unwrap().center();
1198        cx.simulate_click(option, Modifiers::default());
1199        draw(cx);
1200        assert_eq!(
1201            *changes.borrow(),
1202            ["presentation", "quality"].map(|value| vec![SharedString::from(value)])
1203        );
1204        cx.update(|window, cx| {
1205            let state = view.read(cx).combo.read(cx);
1206            assert_eq!(state.selected_indices(), [3]);
1207            assert_eq!(state.input().read(cx).value(), "High quality");
1208            assert!(state.focus_handle().is_focused(window));
1209            #[cfg(feature = "test-support")]
1210            {
1211                let input = crate::test_support::find(window, &[], &"preset".into()).unwrap();
1212                assert_eq!(input.role(), Some(Role::ComboBox));
1213                assert_eq!(input.label(), Some("Preset"));
1214                assert_eq!(input.expanded(), Some(false));
1215                assert_eq!(input.value(), Some("High quality"));
1216            }
1217        });
1218        cx.update(|window, cx| {
1219            view.read(cx).combo.clone().update(cx, |state, cx| {
1220                state.set_selected_values(std::iter::empty::<&str>(), window, cx);
1221            });
1222        });
1223        press(cx, "down");
1224        press(cx, "down");
1225        press(cx, "escape");
1226        press(cx, "down");
1227        cx.update(|_, cx| {
1228            let state = view.read(cx).combo.read(cx);
1229            assert!(state.selected_indices().is_empty());
1230            assert_eq!(state.highlighted_index(cx), Some(0));
1231        });
1232    }
1233
1234    #[gpui::test]
1235    fn composition_and_disabled_input_do_not_commit_and_outside_focus_is_preserved(
1236        cx: &mut TestAppContext,
1237    ) {
1238        let (cx, view, changes) = harness(cx);
1239        cx.simulate_keystrokes("down");
1240        draw(cx);
1241        cx.update(|window, cx| {
1242            let input = view.read(cx).combo.read(cx).input().clone();
1243            input.update(cx, |input, cx| {
1244                input.replace_and_mark_text_in_range(None, "pre", Some(3..3), window, cx);
1245            });
1246        });
1247        draw(cx);
1248        cx.simulate_keystrokes("down");
1249        press(cx, "enter");
1250        press(cx, "escape");
1251        cx.update(|window, cx| {
1252            let state = view.read(cx).combo.read(cx);
1253            assert!(state.is_open());
1254            assert_eq!(state.selected_indices(), [0]);
1255            assert_eq!(view.read(cx).outer_cancels.get(), 0);
1256            let input = state.input().clone();
1257            input.update(cx, |input, cx| {
1258                assert!(input.marked_text_range(window, cx).is_none());
1259                input.replace_text_in_range(Some(0..3), "presentation", window, cx);
1260            });
1261        });
1262        assert!(changes.borrow().is_empty());
1263        draw(cx);
1264        press(cx, "enter");
1265        assert_eq!(
1266            *changes.borrow(),
1267            [vec![SharedString::from("presentation")]]
1268        );
1269        cx.simulate_keystrokes("down");
1270        draw(cx);
1271        let after = cx.debug_bounds("after").unwrap().center();
1272        cx.simulate_click(after, Modifiers::default());
1273        draw(cx);
1274        cx.update(|window, cx| {
1275            let combo = view.read(cx).combo.clone();
1276            assert!(!combo.read(cx).is_open());
1277            assert_eq!(combo.read(cx).input().read(cx).value(), "Presentation");
1278            assert!(view.read(cx).after.is_focused(window));
1279            combo.update(cx, |state, cx| state.set_disabled(true, window, cx));
1280        });
1281        draw(cx);
1282        cx.simulate_keystrokes("shift-tab");
1283        draw(cx);
1284        cx.update(|window, cx| {
1285            let combo = view.read(cx).combo.clone();
1286            assert!(
1287                view.read(cx).after.is_focused(window),
1288                "disabled field is skipped"
1289            );
1290            combo.update(cx, |state, cx| {
1291                state.open(window, cx);
1292                state.set_query("hq", window, cx);
1293                assert!(!state.is_open());
1294                assert_eq!(state.selected_indices(), [2]);
1295            });
1296        });
1297        assert_eq!(changes.borrow().len(), 1);
1298        cx.update(|window, cx| {
1299            view.read(cx).combo.clone().update(cx, |state, cx| {
1300                state.set_disabled(false, window, cx);
1301                state.set_query("hq", window, cx);
1302            });
1303        });
1304        draw(cx);
1305        view.update(cx, |view, cx| {
1306            view.shown = false;
1307            cx.notify();
1308        });
1309        draw(cx);
1310        cx.update(|_, cx| {
1311            let state = view.read(cx).combo.read(cx);
1312            assert!(!state.is_open());
1313            assert_eq!(state.input().read(cx).value(), "Presentation");
1314            assert!(!GlobalState::is_in_deferred_context(cx));
1315        });
1316    }
1317}