Skip to main content

gpui_component/
select.rs

1use gpui::ColorExt as _;
2use gpui::{
3    AnyElement, App, ClickEvent, Context, DismissEvent, Edges, ElementId, Entity, EventEmitter,
4    FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, Length, ParentElement, Render,
5    RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window,
6    deferred, div, prelude::FluentBuilder, px, rems,
7};
8use rust_i18n::t;
9
10use crate::ThemeStyled as _;
11use crate::{
12    ActiveTheme, Disableable, ElementExt as _, Icon, IconName, IndexPath, Sizable, Size,
13    StyleSized, StyledExt,
14    actions::Cancel,
15    h_flex,
16    input::{clear_button, input_style},
17    list::List,
18    searchable_list::{
19        SearchableListChange, SearchableListDelegate, SearchableListItem, SearchableListState,
20    },
21    v_flex,
22};
23use gpui_base::{GlobalState, Select as BaseSelect};
24
25// MARK: Public re-exports for back-compat
26
27/// Re-exported for backward compatibility. New code should prefer [`SearchableGroup`].
28pub use crate::searchable_list::SearchableGroup as SelectGroup;
29/// Re-exported for backward compatibility. New code should prefer [`SearchableListDelegate`].
30pub use crate::searchable_list::SearchableListDelegate as SelectDelegate;
31/// Re-exported for backward compatibility. New code should prefer [`SearchableListItem`].
32pub use crate::searchable_list::SearchableListItem as SelectItem;
33/// Re-exported for backward compatibility. New code should prefer [`SearchableListItemElement`].
34pub use crate::searchable_list::SearchableListItemElement as SelectListItem;
35/// Re-exported for backward compatibility.
36pub use crate::searchable_list::SearchableVec;
37
38#[derive(IntoElement)]
39pub struct Caret {
40    size: Size,
41    color: Option<Hsla>,
42}
43
44impl Caret {
45    /// Create a select caret sized for its trigger.
46    pub fn new(size: Size) -> Self {
47        Self { size, color: None }
48    }
49
50    /// Set the caret color.
51    pub fn text_color(mut self, color: Hsla) -> Self {
52        self.color = Some(color);
53        self
54    }
55}
56
57impl RenderOnce for Caret {
58    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
59        Icon::new(IconName::ChevronDown)
60            .with_size(match self.size {
61                Size::XSmall => Size::XSmall,
62                Size::Small => Size::Small,
63                _ => Size::Medium,
64            })
65            .when_some(self.color, |this, color| this.text_color(color))
66    }
67}
68
69/// Events emitted by [`SelectState`].
70pub enum SelectEvent<D: SearchableListDelegate + 'static>
71where
72    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
73{
74    Confirm(Option<<D::Item as SearchableListItem>::Value>),
75}
76
77// MARK: SelectOptions (builder only — applied to SearchableListState during render)
78
79struct SelectOptions {
80    style: StyleRefinement,
81    size: Size,
82    icon: Option<Icon>,
83    cleanable: bool,
84    placeholder: Option<SharedString>,
85    accessibility_label: Option<SharedString>,
86    title_prefix: Option<SharedString>,
87    search_placeholder: Option<SharedString>,
88    menu_width: Length,
89    menu_max_h: Length,
90    disabled: bool,
91    appearance: bool,
92    focus_ring_enabled: bool,
93}
94
95impl Default for SelectOptions {
96    fn default() -> Self {
97        Self {
98            style: StyleRefinement::default(),
99            size: Size::default(),
100            icon: None,
101            cleanable: false,
102            placeholder: None,
103            accessibility_label: None,
104            title_prefix: None,
105            menu_width: Length::Auto,
106            menu_max_h: rems(20.).into(),
107            disabled: false,
108            appearance: true,
109            focus_ring_enabled: true,
110            search_placeholder: None,
111        }
112    }
113}
114
115// MARK: SelectState
116
117/// State of the [`Select`] component.
118pub struct SelectState<D: SearchableListDelegate + 'static>
119where
120    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
121{
122    pub(crate) state: SearchableListState<D>,
123
124    // Select-specific fields
125    searchable: bool,
126    icon: Option<Icon>,
127    title_prefix: Option<SharedString>,
128    focus_ring_enabled: bool,
129}
130
131/// A Select element.
132#[derive(IntoElement)]
133pub struct Select<D: SearchableListDelegate + 'static>
134where
135    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
136{
137    id: ElementId,
138    state: Entity<SelectState<D>>,
139    options: SelectOptions,
140    empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>,
141}
142
143impl<D> SelectState<D>
144where
145    D: SearchableListDelegate + 'static,
146    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
147{
148    /// Create a new Select state.
149    pub fn new(
150        delegate: D,
151        selected_index: Option<IndexPath>,
152        window: &mut Window,
153        cx: &mut Context<Self>,
154    ) -> Self {
155        let weak = cx.entity().downgrade();
156        let weak_confirm = weak.clone();
157        let weak_cancel = weak.clone();
158        let weak_empty = weak;
159
160        let selected_indices = selected_index.into_iter().collect::<Vec<_>>();
161
162        let state = SearchableListState::new(
163            delegate,
164            selected_indices,
165            // on_confirm — commit the selection
166            move |selected_index, _secondary, window, cx| {
167                cx.defer_in(window, {
168                    let weak_confirm = weak_confirm.clone();
169                    move |list_state, window, cx| {
170                        let mut selection = weak_confirm
171                            .upgrade()
172                            .map(|e| e.read(cx).state.selection.clone())
173                            .unwrap_or_default();
174
175                        let changes = {
176                            let mut changes: Vec<SearchableListChange> = selection
177                                .iter()
178                                .map(|(ix, _)| SearchableListChange::Deselect { index: *ix })
179                                .collect();
180
181                            if let Some(ix) = selected_index {
182                                changes.push(SearchableListChange::Select { index: ix });
183                            }
184
185                            changes
186                        };
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 new_selection = weak_confirm.update(cx, |this, cx| {
196                            this.state.selection = selection;
197
198                            let final_value =
199                                this.state.selection.first().map(|(_, i)| i.value().clone());
200
201                            cx.emit(SelectEvent::Confirm(final_value));
202                            cx.notify();
203                            this.set_open(false, cx);
204                            this.focus(window, cx);
205
206                            this.state.selection.clone()
207                        });
208
209                        // Sync snapshot and fire on_confirm directly — same re-entrancy guard.
210                        if let Ok(new_selection) = new_selection {
211                            list_state
212                                .delegate_mut()
213                                .update_selection_snapshot(new_selection.clone());
214                            list_state
215                                .delegate_mut()
216                                .delegate
217                                .on_confirm(&new_selection);
218                        }
219                    }
220                });
221            },
222            // on_cancel — restore cursor to committed index, close
223            move |_final_selected_index, window, cx| {
224                cx.defer_in(window, {
225                    let weak_cancel = weak_cancel.clone();
226                    move |list_state, window, cx| {
227                        let committed_ix = weak_cancel
228                            .upgrade()
229                            .and_then(|e| e.read(cx).state.selection.first().map(|(ix, _)| *ix));
230
231                        list_state.set_selected_index(committed_ix, window, cx);
232
233                        _ = weak_cancel.update(cx, |this, cx| {
234                            this.set_open(false, cx);
235                            this.focus(window, cx);
236                        });
237                    }
238                });
239            },
240            // on_render_empty
241            move |window, cx| {
242                if let Some(empty) = weak_empty
243                    .upgrade()
244                    .and_then(|e| e.read(cx).state.empty.as_ref().map(|f| f(window, cx)))
245                {
246                    empty
247                } else {
248                    h_flex()
249                        .justify_center()
250                        .py_6()
251                        .text_color(cx.theme().muted_foreground.opacity(0.6))
252                        .child(Icon::new(IconName::Inbox).size(px(28.)))
253                        .into_any_element()
254                }
255            },
256            Self::on_blur,
257            window,
258            cx,
259        );
260
261        Self {
262            state,
263            searchable: false,
264            icon: None,
265            title_prefix: None,
266            focus_ring_enabled: true,
267        }
268    }
269
270    /// Sets whether the dropdown menu is searchable, default is `false`.
271    ///
272    /// When `true`, a search input appears at the top of the dropdown menu.
273    pub fn searchable(mut self, searchable: bool) -> Self {
274        self.searchable = searchable;
275        self
276    }
277
278    /// Set the selected index for the select.
279    pub fn set_selected_index(
280        &mut self,
281        selected_index: Option<IndexPath>,
282        window: &mut Window,
283        cx: &mut Context<Self>,
284    ) {
285        self.state.list.update(cx, |list, cx| {
286            list._set_selected_index(selected_index, window, cx);
287        });
288
289        let item = selected_index
290            .and_then(|ix| self.state.list.read(cx).delegate().delegate.item(ix))
291            .map(|i| i.clone());
292
293        self.state.selection = match (selected_index, item) {
294            (Some(ix), Some(item)) => vec![(ix, item)],
295            _ => vec![],
296        };
297        self.state.sync_snapshot(cx);
298    }
299
300    /// Set selected value for the select.
301    ///
302    /// Looks up the position from the delegate and sets the selected index accordingly.
303    /// Passes `None` when the value is not found.
304    ///
305    /// The delegate looks the value up in its matched items, so an active search query is
306    /// cleared first to get an index into the full item list.
307    pub fn set_selected_value(
308        &mut self,
309        selected_value: &<D::Item as SearchableListItem>::Value,
310        window: &mut Window,
311        cx: &mut Context<Self>,
312    ) {
313        self.state.clear_query(window, cx);
314
315        let selected_index = self
316            .state
317            .list
318            .read(cx)
319            .delegate()
320            .delegate
321            .position(selected_value);
322
323        self.set_selected_index(selected_index, window, cx);
324    }
325
326    /// Replace the delegate (item data) for the select state.
327    pub fn set_items(&mut self, items: D, _: &mut Window, cx: &mut Context<Self>)
328    where
329        D: SearchableListDelegate + 'static,
330    {
331        self.state.list.update(cx, |list, _| {
332            list.delegate_mut().delegate = items;
333        });
334    }
335
336    /// Get the current selected index.
337    pub fn selected_index(&self, cx: &App) -> Option<IndexPath> {
338        self.state.list.read(cx).selected_index()
339    }
340
341    /// Get the current selected value.
342    pub fn selected_value(&self) -> Option<&<D::Item as SearchableListItem>::Value> {
343        self.state.selection.first().map(|(_, i)| i.value())
344    }
345
346    /// Focus the select trigger input.
347    pub fn focus(&self, window: &mut Window, cx: &mut App) {
348        self.state.focus_handle.focus(window, cx);
349    }
350
351    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
352        if self.state.list.read(cx).is_focused(window, cx)
353            || self.state.focus_handle.is_focused(window)
354        {
355            return;
356        }
357
358        let committed_ix = self.state.selection.first().map(|(ix, _)| *ix);
359        if self.selected_index(cx) != committed_ix {
360            self.state.list.update(cx, |list, cx| {
361                list.set_selected_index(committed_ix, window, cx);
362            });
363        }
364
365        self.set_open(false, cx);
366        cx.notify();
367    }
368
369    fn toggle_menu(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
370        cx.stop_propagation();
371
372        self.set_open(!self.state.open, cx);
373
374        if self.state.open {
375            self.state.list.focus_handle(cx).focus(window, cx);
376        }
377
378        cx.notify();
379    }
380
381    fn escape(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
382        if !self.state.open {
383            cx.propagate();
384            return;
385        }
386
387        cx.stop_propagation();
388        self.set_open(false, cx);
389        self.focus(window, cx);
390        cx.notify();
391    }
392
393    fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
394        self.state.open = open;
395        self.state.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
396
397        cx.notify();
398    }
399
400    fn clean(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
401        cx.stop_propagation();
402        self.set_selected_index(None, window, cx);
403        cx.emit(SelectEvent::Confirm(None));
404    }
405
406    fn display_title(&mut self, _: &Window, cx: &mut Context<Self>) -> impl IntoElement {
407        let default_title = div().text_color(cx.theme().muted_foreground).child(
408            self.state
409                .placeholder
410                .clone()
411                .unwrap_or_else(|| t!("Select.placeholder").into()),
412        );
413
414        let Some(selected_index) = self.selected_index(cx) else {
415            return default_title;
416        };
417
418        let Some(title) = self
419            .state
420            .list
421            .read(cx)
422            .delegate()
423            .delegate
424            .item(selected_index)
425            .map(|item| {
426                if let Some(el) = item.display_title() {
427                    el
428                } else if let Some(prefix) = self.title_prefix.as_ref() {
429                    format!("{}{}", prefix, item.title()).into_any_element()
430                } else {
431                    item.title().into_any_element()
432                }
433            })
434        else {
435            return default_title;
436        };
437
438        div()
439            .when(self.state.disabled, |this| {
440                this.text_color(cx.theme().muted_foreground)
441            })
442            .child(title)
443    }
444}
445
446impl<D> Render for SelectState<D>
447where
448    D: SearchableListDelegate + 'static,
449    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
450{
451    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
452        let searchable = self.searchable;
453        let is_focused = self.state.focus_handle.is_focused(window);
454        let show_clean = self.state.cleanable && self.selected_index(cx).is_some();
455        let bounds = self.state.bounds;
456        let allow_open = !(self.state.open || self.state.disabled);
457        let outline_visible = self.state.open || (is_focused && !self.state.disabled);
458
459        let (bg, fg) = input_style(self.state.disabled, cx);
460
461        self.state.list.update(cx, |list, cx| {
462            list.set_searchable(searchable, cx);
463            list.delegate_mut().size = self.state.size;
464        });
465
466        div().size_full().relative().child(
467            div()
468                .relative()
469                .on_prepaint({
470                    let state = cx.entity();
471                    move |bounds, _, cx| state.update(cx, |r, _| r.state.bounds = bounds)
472                })
473                .child(
474                    div()
475                        .id("input")
476                        .relative()
477                        .flex()
478                        .items_center()
479                        .justify_between()
480                        .border_1()
481                        .border_color(cx.theme().transparent)
482                        .when(self.state.appearance, |this| {
483                            this.bg(bg)
484                                .text_color(fg)
485                                .when(self.state.disabled, |this| this.opacity(0.5))
486                                .border_color(cx.theme().input)
487                                .rounded(cx.theme().radius)
488                        })
489                        .input_size(self.state.size)
490                        .input_text_size(self.state.size)
491                        .refine_style(&self.state.style)
492                        .when(outline_visible && self.state.appearance, |this| {
493                            this.border_1().border_color(cx.theme().ring)
494                        })
495                        .when(
496                            outline_visible && self.state.appearance && self.focus_ring_enabled,
497                            |this| this.focus_ring_style(window, cx),
498                        )
499                        .when(allow_open, |this| {
500                            this.on_click(cx.listener(Self::toggle_menu))
501                        })
502                        .child(
503                            h_flex()
504                                .id("inner")
505                                .w_full()
506                                .min_w_0()
507                                .overflow_hidden()
508                                .whitespace_nowrap()
509                                .items_center()
510                                .justify_between()
511                                .gap_1()
512                                .child(
513                                    div()
514                                        .id("title")
515                                        .flex_1()
516                                        .min_w_0()
517                                        .overflow_hidden()
518                                        .whitespace_nowrap()
519                                        .truncate()
520                                        .child(self.display_title(window, cx)),
521                                )
522                                .when(show_clean, |this| {
523                                    this.child(clear_button(cx).map(|this| {
524                                        if self.state.disabled {
525                                            this.disabled(true)
526                                        } else {
527                                            this.on_click(cx.listener(Self::clean))
528                                        }
529                                    }))
530                                })
531                                .when(!show_clean, |this| {
532                                    let icon = match self.icon.clone() {
533                                        Some(icon) => icon
534                                            .xsmall()
535                                            .text_color(cx.theme().muted_foreground)
536                                            .into_any_element(),
537                                        None => Caret::new(self.state.size)
538                                            .text_color(cx.theme().muted_foreground)
539                                            .into_any_element(),
540                                    };
541
542                                    this.child(icon)
543                                }),
544                        ),
545                )
546                .when(self.state.open, |this| {
547                    this.child(
548                        deferred(crate::popover::dropdown_popup(
549                            ("select-popup", cx.entity_id()),
550                            bounds,
551                            v_flex()
552                                .occlude()
553                                .map(|this| match self.state.menu_width {
554                                    Length::Auto => this.w(bounds.size.width + px(2.)),
555                                    Length::Definite(w) => this.w(w),
556                                })
557                                .popover_style(cx)
558                                .child(
559                                    List::new(&self.state.list)
560                                        .when_some(
561                                            self.state.search_placeholder.clone(),
562                                            |this, placeholder| {
563                                                this.search_placeholder(placeholder)
564                                            },
565                                        )
566                                        .with_size(self.state.size)
567                                        .max_h(self.state.menu_max_h)
568                                        .paddings(Edges::all(px(4.))),
569                                )
570                                .on_mouse_down_out(cx.listener(|this, _, window, cx| {
571                                    this.escape(&Cancel, window, cx);
572                                })),
573                            cx,
574                        ))
575                        .with_priority(gpui_base::POPUP_PRIORITY),
576                    )
577                }),
578        )
579    }
580}
581
582impl<D> Select<D>
583where
584    D: SearchableListDelegate + 'static,
585    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
586{
587    pub fn new(state: &Entity<SelectState<D>>) -> Self {
588        Self {
589            id: ("select", state.entity_id()).into(),
590            state: state.clone(),
591            options: SelectOptions::default(),
592            empty: None,
593        }
594    }
595
596    /// Set the width of the dropdown menu, default: `Length::Auto`.
597    pub fn menu_width(mut self, width: impl Into<Length>) -> Self {
598        self.options.menu_width = width.into();
599        self
600    }
601
602    /// Set the max height of the dropdown menu, default: 20rem.
603    pub fn menu_max_h(mut self, max_h: impl Into<Length>) -> Self {
604        self.options.menu_max_h = max_h.into();
605        self
606    }
607
608    /// Set the placeholder shown when no value is selected.
609    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
610        self.options.placeholder = Some(placeholder.into());
611        self
612    }
613
614    /// Set the name a screen reader announces for the select.
615    ///
616    /// The placeholder and selected value are not used as the accessible name,
617    /// because they describe the current value rather than the control itself.
618    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
619        self.options.accessibility_label = Some(label.into());
620        self
621    }
622
623    /// Override the trailing icon, replacing the default chevron.
624    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
625        self.options.icon = Some(icon.into());
626        self
627    }
628
629    /// Set a label prefix shown before the selected title in the trigger.
630    ///
631    /// e.g. `title_prefix("Country: ")` → "Country: United States"
632    pub fn title_prefix(mut self, prefix: impl Into<SharedString>) -> Self {
633        self.options.title_prefix = Some(prefix.into());
634        self
635    }
636
637    /// Show a clear button when a value is selected.
638    pub fn cleanable(mut self, cleanable: bool) -> Self {
639        self.options.cleanable = cleanable;
640        self
641    }
642
643    /// Set the placeholder text for the search input.
644    pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
645        self.options.search_placeholder = Some(placeholder.into());
646        self
647    }
648
649    /// Set the disabled state.
650    pub fn disabled(mut self, disabled: bool) -> Self {
651        self.options.disabled = disabled;
652        self
653    }
654
655    /// Set a custom closure that renders the empty-state element.
656    pub fn empty<E: IntoElement + 'static>(
657        mut self,
658        builder: impl Fn(&mut Window, &App) -> E + 'static,
659    ) -> Self {
660        self.empty = Some(Box::new(move |window, cx| {
661            builder(window, cx).into_any_element()
662        }));
663        self
664    }
665
666    /// Control whether the trigger shows a border and background (`true` by default).
667    pub fn appearance(mut self, appearance: bool) -> Self {
668        self.options.appearance = appearance;
669        self
670    }
671}
672
673impl<D> Sizable for Select<D>
674where
675    D: SearchableListDelegate + 'static,
676    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
677{
678    fn with_size(mut self, size: impl Into<Size>) -> Self {
679        self.options.size = size.into();
680        self
681    }
682}
683
684impl<D> crate::FocusableExt for Select<D>
685where
686    D: SearchableListDelegate + 'static,
687    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
688{
689    fn focus_ring(mut self, enabled: bool) -> Self {
690        self.options.focus_ring_enabled = enabled;
691        self
692    }
693
694    fn is_focus_ring_enabled(&self) -> bool {
695        self.options.focus_ring_enabled
696    }
697}
698
699impl<D> EventEmitter<SelectEvent<D>> for SelectState<D>
700where
701    D: SearchableListDelegate + 'static,
702    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
703{
704}
705
706impl<D> EventEmitter<DismissEvent> for SelectState<D>
707where
708    D: SearchableListDelegate + 'static,
709    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
710{
711}
712
713impl<D> Focusable for SelectState<D>
714where
715    D: SearchableListDelegate + 'static,
716    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
717{
718    fn focus_handle(&self, cx: &App) -> FocusHandle {
719        if self.state.open {
720            self.state.list.focus_handle(cx)
721        } else {
722            self.state.focus_handle.clone()
723        }
724    }
725}
726
727impl<D> Styled for Select<D>
728where
729    D: SearchableListDelegate + 'static,
730    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
731{
732    fn style(&mut self) -> &mut StyleRefinement {
733        &mut self.options.style
734    }
735}
736
737impl<D> RenderOnce for Select<D>
738where
739    D: SearchableListDelegate + 'static,
740    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
741{
742    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
743        let disabled = self.options.disabled;
744        let accessibility_label = self.options.accessibility_label.clone();
745        let focus_handle = self.state.read(cx).state.focus_handle.clone();
746        let empty = self.empty;
747        let opts = self.options;
748
749        self.state.update(cx, |this, _| {
750            this.state.style = opts.style;
751            this.state.size = opts.size;
752            this.state.cleanable = opts.cleanable;
753            this.state.placeholder = opts.placeholder;
754            this.state.search_placeholder = opts.search_placeholder;
755            this.state.menu_width = opts.menu_width;
756            this.state.menu_max_h = opts.menu_max_h;
757            this.state.disabled = opts.disabled;
758            this.state.appearance = opts.appearance;
759            this.focus_ring_enabled = opts.focus_ring_enabled;
760            this.icon = opts.icon;
761            this.title_prefix = opts.title_prefix;
762
763            if let Some(empty) = empty {
764                this.state.empty = Some(empty);
765            }
766        });
767
768        let is_open = self.state.read(cx).state.open;
769        let content_focus_handle = self.state.read(cx).state.list.focus_handle(cx);
770        let open_state = self.state.clone();
771
772        BaseSelect::new(self.id)
773            .open(is_open)
774            .disabled(disabled)
775            .when_some(accessibility_label, |this, label| {
776                this.accessibility_label(label)
777            })
778            .focus_handle(&focus_handle)
779            .content_focus_handle(&content_focus_handle)
780            .on_open_change(move |open, _, cx| {
781                open_state.update(cx, |state, cx| state.set_open(open, cx));
782            })
783            .size_full()
784            .child(self.state)
785    }
786}
787
788// MARK: Tests
789
790#[cfg(test)]
791mod tests {
792    use gpui::{AppContext as _, TestAppContext};
793
794    use crate::{
795        IndexPath,
796        searchable_list::{SearchableListDelegate as _, SearchableVec},
797        select::{Select, SelectGroup, SelectState},
798    };
799
800    #[gpui::test]
801    fn an_explicit_accessibility_label_does_not_replace_the_placeholder(cx: &mut TestAppContext) {
802        cx.update(crate::init);
803        let cx = cx.add_empty_window();
804        cx.update(|window, cx| {
805            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
806            let state = cx.new(|cx| SelectState::new(items, None, window, cx));
807
808            let plain = Select::new(&state).placeholder("Choose a language");
809            assert_eq!(plain.options.accessibility_label, None);
810            assert_eq!(
811                plain.options.placeholder.as_deref(),
812                Some("Choose a language")
813            );
814
815            let named = Select::new(&state)
816                .placeholder("Choose a language")
817                .accessibility_label("Programming language");
818            assert_eq!(
819                named.options.accessibility_label.as_deref(),
820                Some("Programming language")
821            );
822            assert_eq!(
823                named.options.placeholder.as_deref(),
824                Some("Choose a language"),
825                "an accessible name must not change what is drawn"
826            );
827        });
828    }
829
830    #[gpui::test]
831    fn test_select_initial_selection_seeds_cursor(cx: &mut TestAppContext) {
832        cx.update(crate::init);
833        let cx = cx.add_empty_window();
834        cx.update(|window, cx| {
835            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
836            let state = cx.new(|cx| SelectState::new(items, Some(IndexPath::new(1)), window, cx));
837
838            assert_eq!(
839                state.read(cx).selected_index(cx),
840                Some(IndexPath::new(1)),
841                "initial cursor should be seeded on ListState so display_title can read it",
842            );
843            assert_eq!(state.read(cx).selected_value(), Some(&"Go"));
844        });
845    }
846
847    #[gpui::test]
848    fn test_select_initial_grouped_selection_seeds_cursor(cx: &mut TestAppContext) {
849        cx.update(crate::init);
850        let cx = cx.add_empty_window();
851        cx.update(|window, cx| {
852            let mut groups: SearchableVec<SelectGroup<&'static str>> = SearchableVec::new(vec![]);
853            groups.push(SelectGroup::new("A").items(["Apple", "Avocado"]));
854            groups.push(SelectGroup::new("B").items(["Banana", "Blueberry", "Blackberry"]));
855
856            let initial = IndexPath::new(1).section(1);
857            let state = cx.new(|cx| SelectState::new(groups, Some(initial), window, cx));
858
859            assert_eq!(state.read(cx).selected_index(cx), Some(initial));
860            assert_eq!(state.read(cx).selected_value(), Some(&"Blueberry"));
861        });
862    }
863
864    #[gpui::test]
865    fn test_select_set_selected_value_clears_search_query(cx: &mut TestAppContext) {
866        cx.update(crate::init);
867        let cx = cx.add_empty_window();
868        cx.update(|window, cx| {
869            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
870            let state = cx.new(|cx| SelectState::new(items, None, window, cx).searchable(true));
871            let list = state.read(cx).state.list.clone();
872
873            list.update(cx, |list, cx| list.set_query("Rust", window, cx));
874            assert_eq!(list.read(cx).delegate().delegate.items_count(0), 1);
875
876            state.update(cx, |state, cx| {
877                state.set_selected_value(&"Go", window, cx);
878            });
879
880            assert_eq!(state.read(cx).selected_value(), Some(&"Go"));
881            assert_eq!(state.read(cx).selected_index(cx), Some(IndexPath::new(1)));
882            assert_eq!(list.read(cx).query_input.read(cx).value(), "");
883        });
884    }
885
886    #[gpui::test]
887    fn test_select_set_selected_value_clears_grouped_search_query(cx: &mut TestAppContext) {
888        cx.update(crate::init);
889        let cx = cx.add_empty_window();
890        cx.update(|window, cx| {
891            let mut groups: SearchableVec<SelectGroup<&'static str>> = SearchableVec::new(vec![]);
892            groups.push(SelectGroup::new("A").items(["Apple", "Avocado"]));
893            groups.push(SelectGroup::new("B").items(["Banana", "Blueberry"]));
894
895            let state = cx.new(|cx| SelectState::new(groups, None, window, cx).searchable(true));
896            let list = state.read(cx).state.list.clone();
897
898            list.update(cx, |list, cx| list.set_query("Blue", window, cx));
899            state.update(cx, |state, cx| {
900                state.set_selected_value(&"Banana", window, cx);
901            });
902
903            assert_eq!(state.read(cx).selected_value(), Some(&"Banana"));
904            assert_eq!(
905                state.read(cx).selected_index(cx),
906                Some(IndexPath::new(0).section(1)),
907            );
908        });
909    }
910}