Skip to main content

gpui_component/
combobox.rs

1use gpui::ColorExt as _;
2use gpui::{
3    AnyElement, App, Bounds, ClickEvent, Context, DismissEvent, Edges, ElementId, Entity,
4    EventEmitter, FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, Length,
5    MouseDownEvent, ParentElement, Pixels, Render, RenderOnce, SharedString,
6    StatefulInteractiveElement, StyleRefinement, Styled, Window, deferred, div,
7    prelude::FluentBuilder, px, rems,
8};
9
10use rust_i18n::t;
11
12pub use crate::select::Caret;
13
14use crate::ThemeStyled as _;
15use crate::{
16    ActiveTheme, Disableable, ElementExt as _, Icon, IconName, IndexPath, Sizable, Size,
17    StyleSized, StyledExt, h_flex,
18    input::{clear_button, input_style},
19    list::{List, ListState},
20    searchable_list::{
21        SearchableListAdapter, SearchableListChange, SearchableListDelegate, SearchableListItem,
22        SearchableListState,
23    },
24    sizing::DROPDOWN_LIST_PADDING,
25    v_flex,
26};
27use gpui_base::{Combobox as BaseCombobox, GlobalState};
28
29// MARK: ComboboxTriggerContext
30
31/// Context passed to the `render_trigger` closure on [`Combobox`].
32///
33/// The fields are private and reached through the methods below, so that a new
34/// one can be added without breaking the trigger renderers.
35pub struct ComboboxTriggerContext<'a, D: SearchableListDelegate + 'static> {
36    selection: &'a [(IndexPath, D::Item)],
37    placeholder: Option<&'a SharedString>,
38    open: bool,
39    disabled: bool,
40    size: Size,
41}
42
43impl<'a, D: SearchableListDelegate + 'static> ComboboxTriggerContext<'a, D> {
44    /// The items currently selected, empty when the combobox has no value.
45    pub fn selection(&self) -> &'a [(IndexPath, D::Item)] {
46        self.selection
47    }
48
49    pub fn placeholder(&self) -> Option<&'a SharedString> {
50        self.placeholder
51    }
52
53    /// Whether the dropdown list is showing.
54    pub fn is_open(&self) -> bool {
55        self.open
56    }
57
58    pub fn is_disabled(&self) -> bool {
59        self.disabled
60    }
61
62    pub fn size(&self) -> Size {
63        self.size
64    }
65}
66
67// MARK: ComboboxChange
68
69/// Back-compat alias — new code should use [`SearchableListChange`] directly.
70pub type ComboboxChange = SearchableListChange;
71
72// MARK: ComboboxOptions
73
74struct ComboboxOptions {
75    style: StyleRefinement,
76    size: Size,
77    cleanable: bool,
78    placeholder: Option<SharedString>,
79    search_placeholder: Option<SharedString>,
80    menu_width: Length,
81    menu_max_h: Length,
82    disabled: bool,
83    appearance: bool,
84    focus_ring_enabled: bool,
85    trigger_icon: Option<Icon>,
86    check_icon: Option<Icon>,
87}
88
89impl Default for ComboboxOptions {
90    fn default() -> Self {
91        Self {
92            style: StyleRefinement::default(),
93            size: Size::default(),
94            cleanable: false,
95            placeholder: None,
96            search_placeholder: None,
97            menu_width: Length::Auto,
98            menu_max_h: rems(20.).into(),
99            disabled: false,
100            appearance: true,
101            focus_ring_enabled: true,
102            trigger_icon: None,
103            check_icon: None,
104        }
105    }
106}
107
108// MARK: ComboboxState
109
110/// State of the [`Combobox`] component.
111pub struct ComboboxState<D: SearchableListDelegate + 'static>
112where
113    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
114{
115    pub(crate) state: SearchableListState<D>,
116
117    // Combobox-specific fields
118    multiple: bool,
119    searchable: bool,
120    trigger_icon: Option<Icon>,
121    check_icon: Option<Icon>,
122    render_trigger: Option<
123        Box<dyn Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> AnyElement + 'static>,
124    >,
125    footer: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>,
126    focus_ring_enabled: bool,
127}
128
129/// Events emitted by [`ComboboxState`].
130pub enum ComboboxEvent<D: SearchableListDelegate + 'static>
131where
132    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
133{
134    /// Emitted on every toggle (item added or removed).
135    Change(Vec<<D::Item as SearchableListItem>::Value>),
136    /// Emitted when the popover closes.
137    Confirm(Vec<<D::Item as SearchableListItem>::Value>),
138}
139
140impl<D> ComboboxState<D>
141where
142    D: SearchableListDelegate + 'static,
143    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
144{
145    /// Create a new `Combobox` state.
146    pub fn new(
147        delegate: D,
148        selected_indices: Vec<IndexPath>,
149        window: &mut Window,
150        cx: &mut Context<Self>,
151    ) -> Self {
152        let weak = cx.entity().downgrade();
153        let weak_confirm = weak.clone();
154        let weak_cancel = weak.clone();
155        let weak_empty = weak;
156
157        let state = SearchableListState::new(
158            delegate,
159            selected_indices,
160            move |selected_index, _secondary, window, cx| {
161                cx.defer_in(window, {
162                    let weak_confirm = weak_confirm.clone();
163                    move |list_state, window, cx| {
164                        let Some(index) = selected_index else {
165                            return;
166                        };
167
168                        let Some(item) = list_state.delegate().delegate.item(index).cloned() else {
169                            return;
170                        };
171
172                        let ix = index;
173
174                        let Some(weak) = weak_confirm.upgrade() else {
175                            return;
176                        };
177
178                        let (multiple, mut selection) = {
179                            let s = weak.read(cx);
180                            (s.multiple, s.state.selection.clone())
181                        };
182
183                        let changes = Self::selection_changes(multiple, &selection, ix, &item);
184
185                        let before_indices: Vec<IndexPath> =
186                            selection.iter().map(|(ix, _)| *ix).collect();
187
188                        // on_will_change is called directly — entity-handle access would
189                        // re-enter the ListState lock that defer_in holds for this callback.
190                        list_state
191                            .delegate_mut()
192                            .delegate
193                            .on_will_change(&mut selection, &changes);
194
195                        let after_indices: Vec<IndexPath> =
196                            selection.iter().map(|(ix, _)| *ix).collect();
197                        let changed = before_indices != after_indices;
198                        let should_close = changed && !multiple;
199
200                        let new_selection = weak_confirm.update(cx, |this, cx| {
201                            this.state.selection = selection;
202
203                            if changed {
204                                cx.emit(ComboboxEvent::Change(this.selected_values()));
205                                cx.notify();
206                            }
207
208                            if should_close {
209                                cx.emit(ComboboxEvent::Confirm(this.selected_values()));
210                                this.set_open(false, cx);
211                                this.focus(window, cx);
212                            }
213
214                            this.state.selection.clone()
215                        });
216
217                        // Sync snapshot and fire on_confirm directly — same re-entrancy guard.
218                        if let Ok(new_selection) = new_selection {
219                            list_state
220                                .delegate_mut()
221                                .update_selection_snapshot(new_selection.clone());
222
223                            if should_close {
224                                list_state
225                                    .delegate_mut()
226                                    .delegate
227                                    .on_confirm(&new_selection);
228                            }
229                        }
230                    }
231                });
232            },
233            // on_cancel — close and emit Confirm with current values
234            move |_final_selected_index, window, cx| {
235                cx.defer_in(window, {
236                    let weak_cancel = weak_cancel.clone();
237                    move |_list_state, window, cx| {
238                        _ = weak_cancel.update(cx, |this, cx| {
239                            // Cancel propagates to the BaseCombobox, which may already
240                            // have confirmed and closed before this deferred callback.
241                            if !this.state.open {
242                                return;
243                            }
244                            cx.emit(ComboboxEvent::Confirm(this.selected_values()));
245                            this.set_open(false, cx);
246                            this.focus(window, cx);
247                        });
248                    }
249                });
250            },
251            // on_render_empty
252            move |window, cx| {
253                if let Some(empty) = weak_empty
254                    .upgrade()
255                    .and_then(|e| e.read(cx).state.empty.as_ref().map(|f| f(window, cx)))
256                {
257                    empty
258                } else {
259                    h_flex()
260                        .justify_center()
261                        .py_6()
262                        .text_color(cx.theme().muted_foreground.opacity(0.6))
263                        .child(Icon::new(IconName::Inbox).size(px(28.)))
264                        .into_any_element()
265                }
266            },
267            Self::on_blur,
268            window,
269            cx,
270        );
271
272        Self {
273            state,
274            multiple: false,
275            searchable: false,
276            trigger_icon: None,
277            check_icon: None,
278            render_trigger: None,
279            footer: None,
280            focus_ring_enabled: true,
281        }
282    }
283
284    /// Enable multi-select mode.
285    ///
286    /// When `true`, clicking an item toggles it in the selection and the popover stays open.
287    /// When `false` (default), clicking an item replaces the selection and closes the popover.
288    pub fn multiple(mut self, multiple: bool) -> Self {
289        self.multiple = multiple;
290        self
291    }
292
293    /// Enable or disable the search input at the top of the dropdown.
294    pub fn searchable(mut self, searchable: bool) -> Self {
295        self.searchable = searchable;
296        self
297    }
298
299    /// Return the currently selected values.
300    pub fn selected_values(&self) -> Vec<<D::Item as SearchableListItem>::Value> {
301        self.state.selected_values()
302    }
303
304    /// Return the first selected value, or `None` when nothing is selected.
305    ///
306    /// Convenience for single-select mode (`.multiple(false)`).
307    pub fn selected_value(&self) -> Option<<D::Item as SearchableListItem>::Value> {
308        self.state.selected_values().into_iter().next()
309    }
310
311    /// Return the currently selected `(IndexPath, Item)` pairs.
312    pub fn selection(&self) -> &[(IndexPath, D::Item)] {
313        self.state.selection()
314    }
315
316    /// Replace the entire selection set by item values.
317    ///
318    /// Values are resolved through the current delegate. Values that cannot be resolved are
319    /// ignored. This updates the committed selection and snapshot without emitting a
320    /// [`ComboboxEvent`].
321    pub fn set_selected_values(
322        &mut self,
323        values: &[<D::Item as SearchableListItem>::Value],
324        window: &mut Window,
325        cx: &mut Context<Self>,
326    ) {
327        self.state.clear_query(window, cx);
328
329        let selected_indices = {
330            let list = self.state.list.read(cx);
331            let delegate = &list.delegate().delegate;
332
333            values
334                .iter()
335                .filter_map(|value| delegate.position(value))
336                .collect::<Vec<_>>()
337        };
338
339        self.set_selected_indices(selected_indices, window, cx);
340    }
341
342    /// Replace the entire selection set.
343    pub fn set_selected_indices(
344        &mut self,
345        indices: impl IntoIterator<Item = IndexPath>,
346        _window: &mut Window,
347        cx: &mut Context<Self>,
348    ) {
349        self.state.set_selected_indices(indices, cx);
350        self.state.sync_snapshot(cx);
351        cx.notify();
352    }
353
354    /// Add a single index to the selection, if not already present, returning whether it was added.
355    pub fn add_selected_index(&mut self, index: IndexPath, cx: &mut Context<Self>) -> bool {
356        let added = self.state.add_selected_index(index, cx);
357
358        if added {
359            self.state.sync_snapshot(cx);
360            cx.notify();
361        }
362
363        added
364    }
365
366    /// Remove a single index from the selection, returning whether it was removed.
367    pub fn remove_selected_index(&mut self, index: IndexPath, cx: &mut Context<Self>) -> bool {
368        let removed = self.state.remove_selected_index(index);
369
370        if removed {
371            self.state.sync_snapshot(cx);
372        }
373
374        removed
375    }
376
377    /// Clear all selected values.
378    pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
379        self.state.selection.clear();
380        self.state.sync_snapshot(cx);
381        cx.emit(ComboboxEvent::Change(self.selected_values()));
382        cx.notify();
383    }
384
385    /// Replace the underlying delegate (item data source).
386    pub fn set_items(&mut self, items: D, _: &mut Window, cx: &mut Context<Self>) {
387        self.state.list.update(cx, |list, _| {
388            list.delegate_mut().delegate = items;
389        });
390    }
391
392    /// Focus the trigger.
393    pub fn focus(&self, window: &mut Window, cx: &mut App) {
394        self.state.focus_handle.focus(window, cx);
395    }
396
397    /// Returns the search query.
398    pub fn query(&self, cx: &App) -> SharedString {
399        self.state.list.read(cx).query_input.read(cx).value()
400    }
401
402    /// Sets the search query and updates the filtered items.
403    pub fn set_query(&self, query: impl Into<SharedString>, window: &mut Window, cx: &mut App) {
404        let query = query.into();
405        self.state.list.update(cx, |list, cx| {
406            list.set_query(query.as_ref(), window, cx);
407        });
408    }
409
410    fn selection_changes(
411        multiple: bool,
412        selection: &[(IndexPath, D::Item)],
413        ix: IndexPath,
414        item: &D::Item,
415    ) -> Vec<SearchableListChange> {
416        let is_selected = selection
417            .iter()
418            .any(|(_, selected_item)| selected_item.value() == item.value());
419
420        if multiple {
421            if is_selected {
422                vec![SearchableListChange::Deselect { index: ix }]
423            } else {
424                vec![SearchableListChange::Select { index: ix }]
425            }
426        } else {
427            let mut changes: Vec<SearchableListChange> = selection
428                .iter()
429                .map(|(cur_ix, _)| SearchableListChange::Deselect { index: *cur_ix })
430                .collect();
431            changes.push(SearchableListChange::Select { index: ix });
432            changes
433        }
434    }
435
436    /// Process an item click: single-select replaces the selection and closes; multi-select toggles.
437    ///
438    /// Calls `delegate.on_will_change` before committing and `delegate.on_confirm` when closing.
439    #[allow(dead_code)]
440    pub(crate) fn handle_item_select(
441        &mut self,
442        ix: IndexPath,
443        window: &mut Window,
444        cx: &mut Context<Self>,
445    ) {
446        let Some(item) = self
447            .state
448            .list
449            .read(cx)
450            .delegate()
451            .delegate
452            .item(ix)
453            .cloned()
454        else {
455            return;
456        };
457
458        let changes = Self::selection_changes(self.multiple, &self.state.selection, ix, &item);
459
460        let mut selection = self.state.selection.clone();
461        let before_indices: Vec<IndexPath> = selection.iter().map(|(ix, _)| *ix).collect();
462
463        self.state.list.update(cx, |list, _cx| {
464            list.delegate_mut()
465                .delegate
466                .on_will_change(&mut selection, &changes);
467        });
468
469        let after_indices: Vec<IndexPath> = selection.iter().map(|(ix, _)| *ix).collect();
470        let changed = before_indices != after_indices;
471        let should_close = changed && !self.multiple;
472
473        self.state.selection = selection;
474        self.state.sync_snapshot(cx);
475
476        if changed {
477            cx.emit(ComboboxEvent::Change(self.selected_values()));
478            cx.notify();
479        }
480
481        if should_close {
482            let final_selection = self.state.selection.clone();
483            self.state.list.update(cx, |list, _cx| {
484                list.delegate_mut().delegate.on_confirm(&final_selection);
485            });
486
487            cx.emit(ComboboxEvent::Confirm(self.selected_values()));
488            self.set_open(false, cx);
489            self.focus(window, cx);
490        }
491    }
492
493    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
494        if self.state.list.read(cx).is_focused(window, cx)
495            || self.state.focus_handle.is_focused(window)
496        {
497            return;
498        }
499
500        self.set_open(false, cx);
501        cx.notify();
502    }
503
504    fn toggle_menu(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
505        cx.stop_propagation();
506
507        self.set_open(!self.state.open, cx);
508
509        if self.state.open {
510            self.state.list.focus_handle(cx).focus(window, cx);
511        } else {
512            cx.emit(ComboboxEvent::Confirm(self.selected_values()));
513            self.focus(window, cx);
514        }
515
516        cx.notify();
517    }
518
519    /// Close the menu when a press lands outside the popup.
520    ///
521    /// A press on the trigger is left to propagate: swallowing it here would keep nested
522    /// controls (a tag remove button, the clear button) from ever seeing the press, and
523    /// `toggle_menu` closes the menu on release anyway.
524    fn dismiss(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
525        if !self.state.open || self.state.bounds.contains(&event.position) {
526            return;
527        }
528
529        cx.stop_propagation();
530        cx.emit(ComboboxEvent::Confirm(self.selected_values()));
531
532        self.set_open(false, cx);
533        self.focus(window, cx);
534        cx.notify();
535    }
536
537    fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
538        self.state.open = open;
539        self.state.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
540
541        cx.notify();
542    }
543
544    fn clean(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
545        cx.stop_propagation();
546        self.clear_selection(cx);
547    }
548
549    fn default_trigger_body(&self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
550        let placeholder_text = self
551            .state
552            .placeholder
553            .clone()
554            .unwrap_or_else(|| t!("Combobox.placeholder").into());
555
556        if self.state.selection.is_empty() {
557            return div()
558                .text_color(cx.theme().muted_foreground)
559                .child(placeholder_text)
560                .into_any_element();
561        }
562
563        if self.multiple {
564            let items: Vec<SharedString> = self
565                .state
566                .selection
567                .iter()
568                .map(|(_, i)| i.title())
569                .collect();
570
571            div()
572                .w_full()
573                .overflow_hidden()
574                .whitespace_nowrap()
575                .truncate()
576                .child(items.join(", "))
577                .into_any_element()
578        } else {
579            let title = self
580                .state
581                .selection
582                .first()
583                .map(|(_, i)| i.title())
584                .unwrap_or_default();
585
586            div()
587                .w_full()
588                .overflow_hidden()
589                .whitespace_nowrap()
590                .truncate()
591                .child(title)
592                .into_any_element()
593        }
594    }
595}
596
597impl<D> Render for ComboboxState<D>
598where
599    D: SearchableListDelegate + 'static,
600    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
601{
602    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
603        let searchable = self.searchable;
604        let is_focused = self.state.focus_handle.is_focused(window);
605        let show_clean = self.state.cleanable && !self.state.selection.is_empty();
606        let bounds = self.state.bounds;
607        let allow_open = !self.state.disabled;
608        let outline_visible = self.state.open || (is_focused && !self.state.disabled);
609        let disabled = self.state.disabled;
610
611        let (bg, fg) = input_style(disabled, cx);
612
613        self.state.list.update(cx, |list, cx| {
614            list.set_searchable(searchable, cx);
615            list.delegate_mut().size = self.state.size;
616            list.delegate_mut().check_icon = self.check_icon.clone();
617        });
618
619        let selection = &self.state.selection;
620        let placeholder = self.state.placeholder.as_ref();
621        let open = self.state.open;
622        let size = self.state.size;
623        let has_custom_trigger = self.render_trigger.is_some();
624
625        let trigger_body = if let Some(render_trigger) = &self.render_trigger {
626            let trigger = ComboboxTriggerContext {
627                selection,
628                placeholder,
629                open,
630                disabled,
631                size,
632            };
633
634            render_trigger(&trigger, window, cx)
635        } else {
636            self.default_trigger_body(window, cx)
637        };
638
639        let trailing: AnyElement = if has_custom_trigger {
640            div().into_any_element()
641        } else if show_clean {
642            clear_button(cx)
643                .map(|this| {
644                    if disabled {
645                        this.disabled(true)
646                    } else {
647                        this.on_click(cx.listener(Self::clean))
648                    }
649                })
650                .into_any_element()
651        } else if let Some(icon) = self.trigger_icon.clone() {
652            icon.xsmall()
653                .text_color(cx.theme().muted_foreground)
654                .into_any_element()
655        } else {
656            Caret::new(size)
657                .text_color(cx.theme().muted_foreground)
658                .into_any_element()
659        };
660
661        let toggle_handler: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>> =
662            if allow_open {
663                Some(Box::new(cx.listener(Self::toggle_menu)))
664            } else {
665                None
666            };
667
668        let footer_el = self.footer.as_ref().map(|f| f(window, cx));
669
670        let dismiss_handler: Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static> =
671            Box::new(cx.listener(Self::dismiss));
672
673        div().size_full().relative().child(
674            div()
675                .relative()
676                .on_prepaint({
677                    let state = cx.entity();
678                    move |bounds, _, cx| state.update(cx, |r, _| r.state.bounds = bounds)
679                })
680                .child(render_trigger_container(
681                    disabled,
682                    self.state.appearance,
683                    self.focus_ring_enabled,
684                    self.state.size,
685                    &self.state.style,
686                    bg,
687                    fg,
688                    outline_visible,
689                    allow_open,
690                    trigger_body,
691                    trailing,
692                    toggle_handler,
693                    window,
694                    cx,
695                ))
696                .when(self.state.open, |this| {
697                    this.child(
698                        deferred(render_popup_shell(
699                            ("combobox-popup", cx.entity_id()),
700                            &self.state.list,
701                            self.state.menu_width,
702                            self.state.search_placeholder.clone(),
703                            self.state.size,
704                            self.state.menu_max_h,
705                            bounds,
706                            footer_el,
707                            dismiss_handler,
708                            cx,
709                        ))
710                        .priority(gpui_base::POPUP_PRIORITY),
711                    )
712                }),
713        )
714    }
715}
716
717impl<D> EventEmitter<ComboboxEvent<D>> for ComboboxState<D>
718where
719    D: SearchableListDelegate + 'static,
720    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
721{
722}
723impl<D> EventEmitter<DismissEvent> for ComboboxState<D>
724where
725    D: SearchableListDelegate + 'static,
726    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
727{
728}
729
730impl<D> Focusable for ComboboxState<D>
731where
732    D: SearchableListDelegate + 'static,
733    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
734{
735    fn focus_handle(&self, cx: &App) -> FocusHandle {
736        if self.state.open {
737            self.state.list.focus_handle(cx)
738        } else {
739            self.state.focus_handle.clone()
740        }
741    }
742}
743
744// MARK: Combobox element
745
746/// A combo box with support for single and multi-select.
747///
748/// Clicking an item toggles it in the selection; the dropdown stays open until the user
749/// presses Escape or clicks outside.
750#[derive(IntoElement)]
751pub struct Combobox<D: SearchableListDelegate + 'static>
752where
753    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
754{
755    id: ElementId,
756    state: Entity<ComboboxState<D>>,
757    options: ComboboxOptions,
758    render_trigger: Option<
759        Box<dyn Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> AnyElement + 'static>,
760    >,
761    footer: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>,
762    empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>,
763}
764
765impl<D> Combobox<D>
766where
767    D: SearchableListDelegate + 'static,
768    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
769{
770    pub fn new(state: &Entity<ComboboxState<D>>) -> Self {
771        Self {
772            id: ("multi-combo-box", state.entity_id()).into(),
773            state: state.clone(),
774            options: ComboboxOptions::default(),
775            render_trigger: None,
776            footer: None,
777            empty: None,
778        }
779    }
780
781    /// Set the width of the dropdown menu.
782    pub fn menu_width(mut self, width: impl Into<Length>) -> Self {
783        self.options.menu_width = width.into();
784        self
785    }
786
787    /// Set the maximum height of the dropdown menu.
788    pub fn menu_max_h(mut self, max_h: impl Into<Length>) -> Self {
789        self.options.menu_max_h = max_h.into();
790        self
791    }
792
793    /// Set the placeholder text shown when no items are selected.
794    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
795        self.options.placeholder = Some(placeholder.into());
796        self
797    }
798
799    /// Override the trigger chevron icon.
800    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
801        self.options.trigger_icon = Some(icon.into());
802        self
803    }
804
805    /// Override the trailing check icon shown next to selected items.
806    pub fn check_icon(mut self, icon: impl Into<Icon>) -> Self {
807        self.options.check_icon = Some(icon.into());
808        self
809    }
810
811    /// Set the placeholder text for the search input.
812    pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
813        self.options.search_placeholder = Some(placeholder.into());
814        self
815    }
816
817    /// Show a clear button when at least one item is selected.
818    pub fn cleanable(mut self, cleanable: bool) -> Self {
819        self.options.cleanable = cleanable;
820        self
821    }
822
823    /// Set the disabled state.
824    pub fn disabled(mut self, disabled: bool) -> Self {
825        self.options.disabled = disabled;
826        self
827    }
828
829    /// Set a custom closure that renders the empty-state element.
830    pub fn empty<E: IntoElement + 'static>(
831        mut self,
832        builder: impl Fn(&mut Window, &App) -> E + 'static,
833    ) -> Self {
834        self.empty = Some(Box::new(move |window, cx| {
835            builder(window, cx).into_any_element()
836        }));
837        self
838    }
839
840    /// Control whether the trigger shows a border and background.
841    pub fn appearance(mut self, appearance: bool) -> Self {
842        self.options.appearance = appearance;
843        self
844    }
845
846    /// Override the entire trigger element.
847    pub fn render_trigger<E: IntoElement + 'static>(
848        mut self,
849        f: impl Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> E + 'static,
850    ) -> Self {
851        self.render_trigger = Some(Box::new(move |trigger, window, cx| {
852            f(trigger, window, cx).into_any_element()
853        }));
854        self
855    }
856
857    /// Render an element below a separator at the bottom of the dropdown.
858    pub fn footer<E: IntoElement + 'static>(
859        mut self,
860        f: impl Fn(&mut Window, &mut App) -> E + 'static,
861    ) -> Self {
862        self.footer = Some(Box::new(move |window, cx| f(window, cx).into_any_element()));
863        self
864    }
865}
866
867impl<D> Sizable for Combobox<D>
868where
869    D: SearchableListDelegate + 'static,
870    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
871{
872    fn with_size(mut self, size: impl Into<Size>) -> Self {
873        self.options.size = size.into();
874        self
875    }
876}
877
878impl<D> crate::FocusableExt for Combobox<D>
879where
880    D: SearchableListDelegate + 'static,
881    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
882{
883    fn focus_ring(mut self, enabled: bool) -> Self {
884        self.options.focus_ring_enabled = enabled;
885        self
886    }
887
888    fn is_focus_ring_enabled(&self) -> bool {
889        self.options.focus_ring_enabled
890    }
891}
892
893impl<D> Styled for Combobox<D>
894where
895    D: SearchableListDelegate + 'static,
896    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
897{
898    fn style(&mut self) -> &mut StyleRefinement {
899        &mut self.options.style
900    }
901}
902
903impl<D> RenderOnce for Combobox<D>
904where
905    D: SearchableListDelegate + 'static,
906    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
907{
908    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
909        let disabled = self.options.disabled;
910        let focus_handle = self.state.read(cx).state.focus_handle.clone();
911        let render_trigger = self.render_trigger;
912        let footer = self.footer;
913        let empty = self.empty;
914        let opts = self.options;
915
916        self.state.update(cx, |this, _| {
917            this.state.style = opts.style;
918            this.state.size = opts.size;
919            this.state.cleanable = opts.cleanable;
920            this.state.placeholder = opts.placeholder;
921            this.state.search_placeholder = opts.search_placeholder;
922            this.state.menu_width = opts.menu_width;
923            this.state.menu_max_h = opts.menu_max_h;
924            this.state.disabled = opts.disabled;
925            this.state.appearance = opts.appearance;
926            this.focus_ring_enabled = opts.focus_ring_enabled;
927            this.trigger_icon = opts.trigger_icon;
928            this.check_icon = opts.check_icon;
929            this.render_trigger = render_trigger;
930            this.footer = footer;
931
932            if let Some(empty) = empty {
933                this.state.empty = Some(empty);
934            }
935        });
936
937        let is_open = self.state.read(cx).state.open;
938        let content_focus_handle = self.state.read(cx).state.list.focus_handle(cx);
939        let open_state = self.state.clone();
940        let confirm_state = self.state.clone();
941
942        BaseCombobox::new(self.id)
943            .open(is_open)
944            .disabled(disabled)
945            .focus_handle(&focus_handle)
946            .content_focus_handle(&content_focus_handle)
947            .on_open_change(move |open, _, cx| {
948                open_state.update(cx, |state, cx| state.set_open(open, cx));
949            })
950            // This combobox commits its pending selection when the popup
951            // closes, so it listens for dismissal rather than Confirm.
952            .on_dismiss(move |_, cx| {
953                confirm_state.update(cx, |state, cx| {
954                    cx.emit(ComboboxEvent::Confirm(state.selected_values()));
955                });
956            })
957            .size_full()
958            .child(self.state)
959    }
960}
961
962// MARK: Rendering helpers
963
964/// Renders the styled trigger container.
965#[allow(clippy::too_many_arguments)]
966fn render_trigger_container(
967    disabled: bool,
968    appearance: bool,
969    focus_ring_enabled: bool,
970    size: Size,
971    style: &StyleRefinement,
972    bg: Hsla,
973    fg: Hsla,
974    outline_visible: bool,
975    allow_open: bool,
976    trigger_body: AnyElement,
977    trailing: AnyElement,
978    toggle_handler: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
979    window: &Window,
980    cx: &mut App,
981) -> impl IntoElement {
982    div()
983        .id("input")
984        .relative()
985        .flex()
986        .items_center()
987        .justify_between()
988        .border_1()
989        .border_color(cx.theme().transparent)
990        .when(appearance, |this| {
991            this.bg(bg)
992                .text_color(fg)
993                .when(disabled, |this| this.opacity(0.5))
994                .border_color(cx.theme().input)
995                .rounded(cx.theme().radius)
996        })
997        .input_size(size)
998        .input_text_size(size)
999        .refine_style(style)
1000        .when(outline_visible && appearance, |this| {
1001            this.border_1().border_color(cx.theme().ring)
1002        })
1003        .when(
1004            outline_visible && appearance && focus_ring_enabled,
1005            |this| this.focus_ring_style(window, cx),
1006        )
1007        .when(allow_open, |this| {
1008            this.when_some(toggle_handler, |this, handler| this.on_click(handler))
1009        })
1010        .child(
1011            h_flex()
1012                .id("inner")
1013                .w_full()
1014                .min_w_0()
1015                .overflow_hidden()
1016                .whitespace_nowrap()
1017                .items_center()
1018                .justify_between()
1019                .gap_1()
1020                .child(
1021                    div()
1022                        .flex_1()
1023                        .min_w_0()
1024                        .overflow_hidden()
1025                        .whitespace_nowrap()
1026                        .child(trigger_body),
1027                )
1028                .child(trailing),
1029        )
1030}
1031
1032/// Renders the deferred anchored popup shell containing the searchable list and optional footer.
1033#[allow(clippy::too_many_arguments)]
1034fn render_popup_shell<D: SearchableListDelegate + 'static>(
1035    id: impl Into<ElementId>,
1036    list: &Entity<ListState<SearchableListAdapter<D>>>,
1037    menu_width: Length,
1038    search_placeholder: Option<SharedString>,
1039    size: Size,
1040    menu_max_h: Length,
1041    bounds: Bounds<Pixels>,
1042    footer_el: Option<AnyElement>,
1043    dismiss_handler: Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static>,
1044    cx: &mut App,
1045) -> AnyElement {
1046    let has_footer = footer_el.is_some();
1047
1048    crate::popover::dropdown_popup(
1049        id,
1050        bounds,
1051        v_flex()
1052            .occlude()
1053            .map(|this| match menu_width {
1054                Length::Auto => this.w(bounds.size.width),
1055                Length::Definite(w) => this.w(w),
1056            })
1057            .popover_style(cx)
1058            .child(
1059                List::new(list)
1060                    .when_some(search_placeholder, |this, placeholder| {
1061                        this.search_placeholder(placeholder)
1062                    })
1063                    .with_size(size)
1064                    .max_h(menu_max_h)
1065                    .paddings(Edges::all(DROPDOWN_LIST_PADDING)),
1066            )
1067            .when(has_footer, |this| {
1068                this.child(
1069                    div()
1070                        .border_t_1()
1071                        .border_color(cx.theme().border)
1072                        .p_1()
1073                        .when_some(footer_el, |this, el| this.child(el)),
1074                )
1075            })
1076            .on_mouse_down_out(dismiss_handler),
1077        cx,
1078    )
1079    .into_any_element()
1080}
1081
1082// MARK: Tests
1083
1084#[cfg(test)]
1085mod tests {
1086    use std::{cell::Cell, rc::Rc};
1087
1088    use gpui::{
1089        AppContext as _, Bounds, Context, Entity, Modifiers, MouseButton, MouseDownEvent, Pixels,
1090        Point, Subscription, TestAppContext, point, px, size,
1091    };
1092
1093    use crate::{
1094        IndexPath,
1095        combobox::{Combobox, ComboboxEvent, ComboboxState},
1096        searchable_list::{
1097            SearchableListChange, SearchableListDelegate, SearchableListItem, SearchableListState,
1098            SearchableVec,
1099        },
1100    };
1101
1102    struct TestComboboxEventCollector {
1103        event_count: Rc<Cell<usize>>,
1104        _subscription: Subscription,
1105    }
1106
1107    impl TestComboboxEventCollector {
1108        fn new(
1109            state: &Entity<ComboboxState<SearchableVec<&'static str>>>,
1110            cx: &mut Context<Self>,
1111        ) -> Self {
1112            let event_count = Rc::new(Cell::new(0));
1113            let event_count_for_subscription = event_count.clone();
1114            let _subscription = cx.subscribe(
1115                state,
1116                move |_, _, _: &ComboboxEvent<SearchableVec<&'static str>>, _| {
1117                    event_count_for_subscription.set(event_count_for_subscription.get() + 1);
1118                },
1119            );
1120
1121            Self {
1122                event_count,
1123                _subscription,
1124            }
1125        }
1126    }
1127
1128    #[gpui::test]
1129    fn test_combo_box_builder(cx: &mut TestAppContext) {
1130        cx.update(crate::init);
1131        let cx = cx.add_empty_window();
1132        cx.update(|window, cx| {
1133            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1134            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true));
1135
1136            let _cb = Combobox::new(&state)
1137                .placeholder("Select language")
1138                .search_placeholder("Search...")
1139                .menu_width(gpui::px(300.))
1140                .menu_max_h(gpui::rems(15.))
1141                .cleanable(true)
1142                .disabled(false)
1143                .appearance(true);
1144        });
1145    }
1146
1147    #[gpui::test]
1148    fn test_combo_box_search_filters_items(cx: &mut TestAppContext) {
1149        cx.update(crate::init);
1150        let cx = cx.add_empty_window();
1151        cx.update(|window, cx| {
1152            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1153            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true));
1154
1155            let count_before = state
1156                .read(cx)
1157                .state
1158                .list
1159                .read(cx)
1160                .delegate()
1161                .delegate
1162                .items_count(0);
1163            assert_eq!(count_before, 3);
1164
1165            state.update(cx, |s, cx| {
1166                s.state.list.update(cx, |list, cx| {
1167                    let _ = list
1168                        .delegate_mut()
1169                        .delegate
1170                        .perform_search("Rust", window, cx);
1171                });
1172            });
1173
1174            let count_after = state
1175                .read(cx)
1176                .state
1177                .list
1178                .read(cx)
1179                .delegate()
1180                .delegate
1181                .items_count(0);
1182            assert_eq!(count_after, 1);
1183        });
1184    }
1185
1186    #[gpui::test]
1187    fn test_combo_box_set_query_updates_text_and_filters_items(cx: &mut TestAppContext) {
1188        cx.update(crate::init);
1189        let cx = cx.add_empty_window();
1190        cx.update(|window, cx| {
1191            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1192            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true));
1193
1194            state.update(cx, |state, cx| state.set_query(" Rust ", window, cx));
1195
1196            assert_eq!(state.read(cx).query(cx).as_ref(), " Rust ");
1197            assert_eq!(
1198                state
1199                    .read(cx)
1200                    .state
1201                    .list
1202                    .read(cx)
1203                    .delegate()
1204                    .delegate
1205                    .items_count(0),
1206                1,
1207            );
1208        });
1209    }
1210
1211    #[gpui::test]
1212    fn test_multi_combo_box_builder(cx: &mut TestAppContext) {
1213        cx.update(crate::init);
1214        let cx = cx.add_empty_window();
1215        cx.update(|window, cx| {
1216            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1217            let state = cx.new(|cx| {
1218                ComboboxState::new(items, vec![IndexPath::new(0)], window, cx)
1219                    .multiple(true)
1220                    .searchable(true)
1221            });
1222
1223            let _cb = Combobox::new(&state)
1224                .placeholder("Select frameworks")
1225                .search_placeholder("Search...")
1226                .menu_width(gpui::px(300.))
1227                .cleanable(true)
1228                .disabled(false);
1229
1230            assert_eq!(state.read(cx).selected_values(), vec!["React"]);
1231        });
1232    }
1233
1234    #[gpui::test]
1235    fn test_combo_box_set_selected_values_uses_current_delegate(cx: &mut TestAppContext) {
1236        cx.update(crate::init);
1237        let cx = cx.add_empty_window();
1238        cx.update(|window, cx| {
1239            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1240            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1241
1242            state.update(cx, |state, cx| {
1243                state.set_selected_values(&["Vue", "Missing"], window, cx);
1244
1245                assert_eq!(state.selected_values(), vec!["Vue"]);
1246                assert_eq!(
1247                    state
1248                        .selection()
1249                        .iter()
1250                        .map(|(index, _)| *index)
1251                        .collect::<Vec<_>>(),
1252                    vec![IndexPath::new(1)],
1253                );
1254                assert_eq!(
1255                    state
1256                        .state
1257                        .list
1258                        .read(cx)
1259                        .delegate()
1260                        .selection_snapshot
1261                        .as_slice(),
1262                    state.selection(),
1263                );
1264
1265                state.set_items(SearchableVec::new(vec!["Vue", "Rust", "Go"]), window, cx);
1266                state.set_selected_values(&["Go", "Vue"], window, cx);
1267
1268                assert_eq!(state.selected_values(), vec!["Go", "Vue"]);
1269                assert_eq!(
1270                    state
1271                        .selection()
1272                        .iter()
1273                        .map(|(index, _)| *index)
1274                        .collect::<Vec<_>>(),
1275                    vec![IndexPath::new(2), IndexPath::new(0)],
1276                );
1277                assert_eq!(
1278                    state
1279                        .state
1280                        .list
1281                        .read(cx)
1282                        .delegate()
1283                        .selection_snapshot
1284                        .as_slice(),
1285                    state.selection(),
1286                );
1287
1288                state.set_selected_values(&[], window, cx);
1289
1290                assert!(state.selection().is_empty());
1291                assert!(
1292                    state
1293                        .state
1294                        .list
1295                        .read(cx)
1296                        .delegate()
1297                        .selection_snapshot
1298                        .is_empty()
1299                );
1300            });
1301        });
1302    }
1303
1304    /// A value projected in from outside is not a position in the filtered view,
1305    /// so an active search must not decide which values can be selected.
1306    #[gpui::test]
1307    fn test_combo_box_set_selected_values_keeps_values_hidden_by_the_search(
1308        cx: &mut TestAppContext,
1309    ) {
1310        cx.update(crate::init);
1311        let cx = cx.add_empty_window();
1312        cx.update(|window, cx| {
1313            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1314            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1315
1316            state.update(cx, |state, cx| {
1317                state.set_selected_values(&["React", "Vue"], window, cx);
1318                state.state.list.update(cx, |list, cx| {
1319                    list.set_query("Angular", window, cx);
1320                });
1321
1322                state.set_selected_values(&["React", "Vue", "Angular"], window, cx);
1323
1324                assert_eq!(
1325                    state.selected_values(),
1326                    vec!["React", "Vue", "Angular"],
1327                    "a value the search had hidden must survive being reapplied"
1328                );
1329                assert_eq!(
1330                    state
1331                        .selection()
1332                        .iter()
1333                        .map(|(index, _)| *index)
1334                        .collect::<Vec<_>>(),
1335                    vec![IndexPath::new(0), IndexPath::new(1), IndexPath::new(2)],
1336                    "clearing the query puts every selected item back in view"
1337                );
1338            });
1339        });
1340    }
1341
1342    #[gpui::test]
1343    fn test_combo_box_set_selected_values_does_not_emit_events(cx: &mut TestAppContext) {
1344        cx.update(crate::init);
1345        let cx = cx.add_empty_window();
1346        let state = cx.update(|window, cx| {
1347            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1348            cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true))
1349        });
1350        let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx)));
1351
1352        cx.update(|window, cx| {
1353            state.update(cx, |state, cx| {
1354                state.set_selected_values(&["React", "Vue"], window, cx);
1355            });
1356        });
1357
1358        cx.update(|_, cx| {
1359            assert_eq!(collector.read(cx).event_count.get(), 0);
1360        });
1361    }
1362
1363    #[gpui::test]
1364    fn test_combo_box_initial_selection_seeds_cursor(cx: &mut TestAppContext) {
1365        cx.update(crate::init);
1366        let cx = cx.add_empty_window();
1367        cx.update(|window, cx| {
1368            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1369            let state = cx.new(|cx| {
1370                ComboboxState::new(items, vec![IndexPath::new(1)], window, cx).multiple(true)
1371            });
1372
1373            let state_ref = state.read(cx);
1374            assert_eq!(
1375                state_ref.state.list.read(cx).selected_index(),
1376                Some(IndexPath::new(1)),
1377                "initial selected_indices should seed ListState.selected_index, not just the snapshot",
1378            );
1379            assert_eq!(state_ref.selected_values(), vec!["Vue"]);
1380        });
1381    }
1382
1383    #[gpui::test]
1384    fn test_multi_combo_box_toggle(cx: &mut TestAppContext) {
1385        cx.update(crate::init);
1386        let cx = cx.add_empty_window();
1387        cx.update(|window, cx| {
1388            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1389            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1390
1391            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1392            assert_eq!(state.read(cx).selected_values(), &["React"]);
1393
1394            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(1), cx));
1395            assert_eq!(state.read(cx).selected_values(), &["React", "Vue"]);
1396
1397            state.update(cx, |s, cx| s.remove_selected_index(IndexPath::new(0), cx));
1398            assert_eq!(state.read(cx).selected_values(), &["Vue"]);
1399        });
1400    }
1401
1402    #[gpui::test]
1403    fn test_multi_combo_box_search_selection_uses_value_identity(cx: &mut TestAppContext) {
1404        cx.update(crate::init);
1405        let cx = cx.add_empty_window();
1406        cx.update(|window, cx| {
1407            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1408            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1409
1410            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1411            assert_eq!(state.read(cx).selected_values(), &["React"]);
1412
1413            state.update(cx, |s, cx| {
1414                s.state.list.update(cx, |list, cx| {
1415                    let _ = list
1416                        .delegate_mut()
1417                        .delegate
1418                        .perform_search("Vue", window, cx);
1419                });
1420            });
1421
1422            state.read_with(cx, |s, cx| {
1423                let selection = s.state.selection.clone();
1424                let list = s.state.list.read(cx);
1425                let delegate = &list.delegate().delegate;
1426                let ix = IndexPath::new(0);
1427                let item = delegate.item(ix).expect("filtered item exists");
1428
1429                assert_eq!(item.value(), &"Vue");
1430                assert!(
1431                    !delegate.is_item_checked(ix, item, &selection, cx),
1432                    "filtered row 0 should not inherit React's checked state",
1433                );
1434            });
1435
1436            state.update(cx, |s, cx| {
1437                s.handle_item_select(IndexPath::new(0), window, cx);
1438            });
1439            assert_eq!(state.read(cx).selected_values(), &["React", "Vue"]);
1440        });
1441    }
1442
1443    #[gpui::test]
1444    fn test_multi_combo_box_search_deselects_by_value(cx: &mut TestAppContext) {
1445        cx.update(crate::init);
1446        let cx = cx.add_empty_window();
1447        cx.update(|window, cx| {
1448            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1449            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1450
1451            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1452
1453            state.update(cx, |s, cx| {
1454                s.state.list.update(cx, |list, cx| {
1455                    let _ = list
1456                        .delegate_mut()
1457                        .delegate
1458                        .perform_search("React", window, cx);
1459                });
1460            });
1461
1462            state.update(cx, |s, cx| {
1463                s.handle_item_select(IndexPath::new(0), window, cx);
1464            });
1465            assert!(state.read(cx).selected_values().is_empty());
1466        });
1467    }
1468
1469    #[gpui::test]
1470    fn test_searchable_list_default_change_uses_value_identity(cx: &mut TestAppContext) {
1471        cx.update(crate::init);
1472        let cx = cx.add_empty_window();
1473        cx.update(|window, cx| {
1474            let mut delegate = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1475            let mut selection = vec![(IndexPath::new(1), "Vue")];
1476
1477            let _ = delegate.perform_search("Vue", window, cx);
1478            delegate.on_will_change(
1479                &mut selection,
1480                &[SearchableListChange::Deselect {
1481                    index: IndexPath::new(0),
1482                }],
1483            );
1484            assert!(selection.is_empty());
1485
1486            delegate.on_will_change(
1487                &mut selection,
1488                &[SearchableListChange::Select {
1489                    index: IndexPath::new(0),
1490                }],
1491            );
1492            assert_eq!(selection, vec![(IndexPath::new(0), "Vue")]);
1493        });
1494    }
1495
1496    #[gpui::test]
1497    fn test_multi_combo_box_clear(cx: &mut TestAppContext) {
1498        cx.update(crate::init);
1499        let cx = cx.add_empty_window();
1500        cx.update(|window, cx| {
1501            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1502            let state = cx.new(|cx| {
1503                ComboboxState::new(
1504                    items,
1505                    vec![IndexPath::new(0), IndexPath::new(1)],
1506                    window,
1507                    cx,
1508                )
1509                .multiple(true)
1510            });
1511
1512            assert_eq!(state.read(cx).selected_values().len(), 2);
1513            state.update(cx, |s, cx| s.clear_selection(cx));
1514            assert!(state.read(cx).selected_values().is_empty());
1515        });
1516    }
1517
1518    #[gpui::test]
1519    fn test_single_combo_box_mode(cx: &mut TestAppContext) {
1520        cx.update(crate::init);
1521        let cx = cx.add_empty_window();
1522        cx.update(|window, cx| {
1523            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1524            let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx));
1525
1526            // Default mode is Single.
1527            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1528            assert_eq!(state.read(cx).selected_values(), &["Rust"]);
1529
1530            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(1), cx));
1531            assert_eq!(state.read(cx).selected_values(), &["Rust", "Go"]);
1532        });
1533    }
1534
1535    // Delegate that vetoes all selections via on_will_change by ignoring the changes.
1536    struct VetoDelegate(SearchableVec<&'static str>);
1537
1538    impl SearchableListDelegate for VetoDelegate {
1539        type Item = &'static str;
1540
1541        fn items_count(&self, section: usize) -> usize {
1542            self.0.items_count(section)
1543        }
1544
1545        fn item(&self, ix: IndexPath) -> Option<&&'static str> {
1546            self.0.item(ix)
1547        }
1548
1549        fn position<V>(&self, value: &V) -> Option<IndexPath>
1550        where
1551            &'static str: SearchableListItem<Value = V>,
1552            V: PartialEq,
1553        {
1554            self.0.position(value)
1555        }
1556
1557        fn on_will_change(
1558            &mut self,
1559            _selection: &mut Vec<(IndexPath, &'static str)>,
1560            _changes: &[SearchableListChange],
1561        ) {
1562            // Leave selection unchanged — acts as a veto.
1563        }
1564    }
1565
1566    #[gpui::test]
1567    fn test_on_will_change_veto(cx: &mut TestAppContext) {
1568        cx.update(crate::init);
1569        let cx = cx.add_empty_window();
1570        cx.update(|window, cx| {
1571            let delegate = VetoDelegate(SearchableVec::new(vec!["Rust", "Go", "C++"]));
1572            let state = cx.new(|cx| ComboboxState::new(delegate, vec![], window, cx));
1573
1574            // Pre-select an item directly so we can verify veto prevents changes.
1575            state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1576            assert_eq!(state.read(cx).selected_values(), &["Rust"]);
1577
1578            // Simulate a click on index 1 via handle_item_select; on_will_change vetoes it.
1579            state.update(cx, |s, cx| {
1580                s.handle_item_select(IndexPath::new(1), window, cx);
1581            });
1582
1583            // Selection must remain unchanged because on_will_change left it unmodified.
1584            assert_eq!(state.read(cx).selected_values(), &["Rust"]);
1585        });
1586    }
1587
1588    fn left_press(position: Point<Pixels>) -> MouseDownEvent {
1589        MouseDownEvent {
1590            button: MouseButton::Left,
1591            position,
1592            modifiers: Modifiers::default(),
1593            click_count: 1,
1594            first_mouse: false,
1595        }
1596    }
1597
1598    #[gpui::test]
1599    fn test_combo_box_dismiss_ignores_press_on_trigger(cx: &mut TestAppContext) {
1600        cx.update(crate::init);
1601        let cx = cx.add_empty_window();
1602        let state = cx.update(|window, cx| {
1603            let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1604            cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true))
1605        });
1606        let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx)));
1607
1608        cx.update(|window, cx| {
1609            state.update(cx, |state, cx| {
1610                state.state.bounds = Bounds {
1611                    origin: point(px(10.), px(10.)),
1612                    size: size(px(200.), px(32.)),
1613                };
1614                state.set_open(true, cx);
1615                state.dismiss(&left_press(point(px(20.), px(20.))), window, cx);
1616            });
1617        });
1618
1619        cx.update(|_, cx| {
1620            assert!(
1621                state.read(cx).state.open,
1622                "a press on the trigger must reach nested controls, so the menu stays open \
1623                 and `toggle_menu` closes it on release instead",
1624            );
1625            assert_eq!(collector.read(cx).event_count.get(), 0);
1626        });
1627
1628        cx.update(|window, cx| {
1629            state.update(cx, |state, cx| {
1630                state.dismiss(&left_press(point(px(20.), px(200.))), window, cx);
1631            });
1632        });
1633
1634        cx.update(|_, cx| {
1635            assert!(!state.read(cx).state.open);
1636            assert_eq!(
1637                collector.read(cx).event_count.get(),
1638                1,
1639                "dismissing from outside the trigger emits Confirm",
1640            );
1641        });
1642    }
1643
1644    // Suppress unused import warning for SearchableListState in test module.
1645    #[allow(unused)]
1646    fn _uses_state<D: SearchableListDelegate + 'static>(_: &SearchableListState<D>)
1647    where
1648        <D::Item as SearchableListItem>::Value: PartialEq + Clone,
1649    {
1650    }
1651}