Skip to main content

gpui_component/
select.rs

1use gpui::{
2    AnyElement, App, ClickEvent, Context, DismissEvent, Edges, ElementId, Entity, EventEmitter,
3    FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, Length, ParentElement, Render,
4    RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window,
5    deferred, div, prelude::FluentBuilder, px, rems,
6};
7use gpui_base::LogicalStyledExt as _;
8use gpui_base::TestSupportExt as _;
9use rust_i18n::t;
10
11use crate::ThemeStyled as _;
12use crate::{
13    ActiveTheme, Disableable, ElementExt as _, Icon, IconName, IndexPath, Sizable, Size,
14    StyleSized, StyledExt,
15    actions::Cancel,
16    h_flex,
17    input::{clear_button, input_style},
18    list::List,
19    searchable_list::{
20        SearchableListChange, SearchableListDelegate, SearchableListItem, SearchableListState,
21        state::menu_popup,
22    },
23    sizing::DROPDOWN_LIST_PADDING,
24    v_flex,
25};
26use gpui_base::{GlobalState, Select as BaseSelect};
27
28// MARK: Public re-exports for back-compat
29
30/// Re-exported for backward compatibility. New code should prefer [`SearchableGroup`].
31pub use crate::searchable_list::SearchableGroup as SelectGroup;
32/// Re-exported for backward compatibility. New code should prefer [`SearchableListDelegate`].
33pub use crate::searchable_list::SearchableListDelegate as SelectDelegate;
34/// Re-exported for backward compatibility. New code should prefer [`SearchableListItem`].
35pub use crate::searchable_list::SearchableListItem as SelectItem;
36/// Re-exported for backward compatibility. New code should prefer [`SearchableListItemElement`].
37pub use crate::searchable_list::SearchableListItemElement as SelectListItem;
38/// Re-exported for backward compatibility.
39pub use crate::searchable_list::SearchableVec;
40
41#[derive(IntoElement)]
42pub struct Caret {
43    size: Size,
44    color: Option<Hsla>,
45}
46
47impl Caret {
48    /// Create a select caret sized for its trigger.
49    pub fn new(size: Size) -> Self {
50        Self { size, color: None }
51    }
52
53    /// Set the caret color.
54    pub fn text_color(mut self, color: Hsla) -> Self {
55        self.color = Some(color);
56        self
57    }
58}
59
60impl RenderOnce for Caret {
61    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
62        Icon::new(IconName::ChevronDown)
63            .with_size(match self.size {
64                Size::XSmall => Size::XSmall,
65                Size::Small => Size::Small,
66                _ => Size::Medium,
67            })
68            .when_some(self.color, |this, color| this.text_color(color))
69    }
70}
71
72/// Events emitted by [`SelectState`].
73pub enum SelectEvent<D: SearchableListDelegate + 'static>
74where
75    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
76{
77    Confirm(Option<<D::Item as SearchableListItem>::Value>),
78}
79
80// MARK: SelectOptions (builder only — applied to SearchableListState during render)
81
82struct SelectOptions {
83    style: StyleRefinement,
84    size: Size,
85    icon: Option<Icon>,
86    cleanable: bool,
87    placeholder: Option<SharedString>,
88    accessibility_label: Option<SharedString>,
89    title_prefix: Option<SharedString>,
90    search_placeholder: Option<SharedString>,
91    highlight_matches: bool,
92    menu_width: Length,
93    menu_max_h: Length,
94    scroll_bounce: Option<bool>,
95    disabled: bool,
96    appearance: bool,
97    focus_ring_enabled: bool,
98}
99
100impl Default for SelectOptions {
101    fn default() -> Self {
102        Self {
103            style: StyleRefinement::default(),
104            size: Size::default(),
105            icon: None,
106            cleanable: false,
107            placeholder: None,
108            accessibility_label: None,
109            title_prefix: None,
110            menu_width: Length::Auto,
111            menu_max_h: rems(20.).into(),
112            scroll_bounce: None,
113            disabled: false,
114            appearance: true,
115            focus_ring_enabled: true,
116            search_placeholder: None,
117            highlight_matches: false,
118        }
119    }
120}
121
122// MARK: SelectState
123
124/// State of the [`Select`] component.
125///
126/// Emits [`DismissEvent`] when an open menu closes, including after a selection is confirmed.
127pub struct SelectState<D: SearchableListDelegate + 'static>
128where
129    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
130{
131    pub(crate) state: SearchableListState<D>,
132
133    // Select-specific fields
134    searchable: bool,
135    icon: Option<Icon>,
136    title_prefix: Option<SharedString>,
137    focus_ring_enabled: bool,
138}
139
140/// A Select element.
141#[derive(IntoElement)]
142pub struct Select<D: SearchableListDelegate + 'static>
143where
144    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
145{
146    id: ElementId,
147    state: Entity<SelectState<D>>,
148    options: SelectOptions,
149    empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>,
150}
151
152impl<D> SelectState<D>
153where
154    D: SearchableListDelegate + 'static,
155    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
156{
157    /// Create a new Select state.
158    pub fn new(
159        delegate: D,
160        selected_index: Option<IndexPath>,
161        window: &mut Window,
162        cx: &mut Context<Self>,
163    ) -> Self {
164        let weak = cx.entity().downgrade();
165        let weak_confirm = weak.clone();
166        let weak_cancel = weak.clone();
167        let weak_empty = weak;
168
169        let selected_indices = selected_index.into_iter().collect::<Vec<_>>();
170
171        let state = SearchableListState::new(
172            delegate,
173            selected_indices,
174            // on_confirm — commit the selection
175            move |selected_index, _secondary, window, cx| {
176                cx.defer_in(window, {
177                    let weak_confirm = weak_confirm.clone();
178                    move |list_state, window, cx| {
179                        let mut selection = weak_confirm
180                            .upgrade()
181                            .map(|e| e.read(cx).state.selection.clone())
182                            .unwrap_or_default();
183
184                        let changes = {
185                            let mut changes: Vec<SearchableListChange> = selection
186                                .iter()
187                                .map(|(ix, _)| SearchableListChange::Deselect { index: *ix })
188                                .collect();
189
190                            if let Some(ix) = selected_index {
191                                changes.push(SearchableListChange::Select { index: ix });
192                            }
193
194                            changes
195                        };
196
197                        // on_will_change is called directly — entity-handle access would
198                        // re-enter the ListState lock that defer_in holds for this callback.
199                        list_state
200                            .delegate_mut()
201                            .delegate
202                            .on_will_change(&mut selection, &changes);
203
204                        let confirmed = weak_confirm.update(cx, |this, cx| {
205                            this.state.selection = selection;
206
207                            let final_value =
208                                this.state.selection.first().map(|(_, i)| i.value().clone());
209
210                            cx.emit(SelectEvent::Confirm(final_value.clone()));
211                            cx.notify();
212                            this.set_open(false, cx);
213                            this.focus(window, cx);
214
215                            (this.state.selection.clone(), final_value)
216                        });
217
218                        // Clear the query through list_state directly — an entity-handle
219                        // update here would re-enter the ListState lock held above.
220                        // The committed index pointed into the filtered view, so resolve
221                        // the confirmed value in the restored full list; otherwise the
222                        // cursor and the mark would disagree on the next open.
223                        if let Ok((mut new_selection, final_value)) = confirmed {
224                            if !list_state.query_input.read(cx).value().is_empty() {
225                                list_state.set_query("", window, cx);
226                            }
227
228                            if let Some(ix) = final_value
229                                .as_ref()
230                                .and_then(|value| list_state.delegate().delegate.position(value))
231                            {
232                                list_state.set_selected_index(Some(ix), window, cx);
233                                if let Some((slot, _)) = new_selection.first_mut() {
234                                    *slot = ix;
235                                }
236                                _ = weak_confirm.update(cx, |this, cx| {
237                                    if let Some((slot, _)) = this.state.selection.first_mut() {
238                                        *slot = ix;
239                                    }
240                                    cx.notify();
241                                });
242                            }
243
244                            list_state
245                                .delegate_mut()
246                                .update_selection_snapshot(new_selection.clone());
247                            list_state
248                                .delegate_mut()
249                                .delegate
250                                .on_confirm(&new_selection);
251                        }
252                    }
253                });
254            },
255            // on_cancel — clear the query, restore cursor to committed index, close
256            move |_final_selected_index, window, cx| {
257                cx.defer_in(window, {
258                    let weak_cancel = weak_cancel.clone();
259                    move |list_state, window, cx| {
260                        let committed_ix = weak_cancel
261                            .upgrade()
262                            .and_then(|e| e.read(cx).state.selection.first().map(|(ix, _)| *ix));
263
264                        if !list_state.query_input.read(cx).value().is_empty() {
265                            list_state.set_query("", window, cx);
266                        }
267                        list_state.set_selected_index(committed_ix, window, cx);
268
269                        _ = weak_cancel.update(cx, |this, cx| {
270                            this.set_open(false, cx);
271                            this.focus(window, cx);
272                        });
273                    }
274                });
275            },
276            // on_render_empty
277            move |window, cx| {
278                if let Some(empty) = weak_empty
279                    .upgrade()
280                    .and_then(|e| e.read(cx).state.empty.as_ref().map(|f| f(window, cx)))
281                {
282                    empty
283                } else {
284                    h_flex()
285                        .flex_row_dir(cx)
286                        .justify_center()
287                        .py_6()
288                        .text_color(cx.theme().muted_foreground.opacity(0.6))
289                        .child(Icon::new(IconName::Inbox).size(px(28.)))
290                        .into_any_element()
291                }
292            },
293            Self::on_blur,
294            window,
295            cx,
296        );
297
298        Self {
299            state,
300            searchable: false,
301            icon: None,
302            title_prefix: None,
303            focus_ring_enabled: true,
304        }
305    }
306
307    /// Sets whether the dropdown menu is searchable, default is `false`.
308    ///
309    /// When `true`, a search input appears at the top of the dropdown menu.
310    pub fn searchable(mut self, searchable: bool) -> Self {
311        self.searchable = searchable;
312        self
313    }
314
315    /// Set the selected index for the select.
316    pub fn set_selected_index(
317        &mut self,
318        selected_index: Option<IndexPath>,
319        window: &mut Window,
320        cx: &mut Context<Self>,
321    ) {
322        self.state.list.update(cx, |list, cx| {
323            list._set_selected_index(selected_index, window, cx);
324        });
325
326        let item = selected_index
327            .and_then(|ix| self.state.list.read(cx).delegate().delegate.item(ix))
328            .map(|i| i.clone());
329
330        self.state.selection = match (selected_index, item) {
331            (Some(ix), Some(item)) => vec![(ix, item)],
332            _ => vec![],
333        };
334        self.state.sync_snapshot(cx);
335    }
336
337    /// Set selected value for the select.
338    ///
339    /// Looks up the position from the delegate and sets the selected index accordingly.
340    /// Passes `None` when the value is not found.
341    ///
342    /// The delegate looks the value up in its matched items, so an active search query is
343    /// cleared first to get an index into the full item list.
344    pub fn set_selected_value(
345        &mut self,
346        selected_value: &<D::Item as SearchableListItem>::Value,
347        window: &mut Window,
348        cx: &mut Context<Self>,
349    ) {
350        self.state.clear_query(window, cx);
351
352        let selected_index = self
353            .state
354            .list
355            .read(cx)
356            .delegate()
357            .delegate
358            .position(selected_value);
359
360        self.set_selected_index(selected_index, window, cx);
361    }
362
363    /// Replace the delegate (item data) for the select state.
364    pub fn set_items(&mut self, items: D, window: &mut Window, cx: &mut Context<Self>)
365    where
366        D: SearchableListDelegate + 'static,
367    {
368        let mut selection = self.state.selection.clone();
369        self.state.list.update(cx, |list, cx| {
370            let cursor = list
371                .selected_index()
372                .and_then(|ix| list.delegate().delegate.item(ix))
373                .and_then(|item| items.position(item.value()));
374            // A value the new items no longer have is dropped, as
375            // `set_selected_value` does, rather than kept at an index that
376            // now points at another item.
377            selection.retain_mut(|(ix, item)| {
378                let Some(position) = items.position(item.value()) else {
379                    return false;
380                };
381                let Some(replacement) = items.item(position) else {
382                    return false;
383                };
384                *ix = position;
385                *item = replacement.clone();
386                true
387            });
388            list.delegate_mut().delegate = items;
389            list.set_selected_index(cursor, window, cx);
390            list.delegate_mut()
391                .update_selection_snapshot(selection.clone());
392            cx.notify();
393        });
394        self.state.selection = selection;
395        cx.notify();
396    }
397
398    /// Get the current selected index.
399    pub fn selected_index(&self, cx: &App) -> Option<IndexPath> {
400        self.state.list.read(cx).selected_index()
401    }
402
403    /// Get the current selected value.
404    pub fn selected_value(&self) -> Option<&<D::Item as SearchableListItem>::Value> {
405        self.state.selection.first().map(|(_, i)| i.value())
406    }
407
408    /// Focus the select trigger input.
409    pub fn focus(&self, window: &mut Window, cx: &mut App) {
410        self.state.focus_handle.focus(window, cx);
411    }
412
413    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
414        if self.state.list.read(cx).is_focused(window, cx)
415            || self.state.focus_handle.is_focused(window)
416        {
417            return;
418        }
419
420        self.clear_query_and_restore_cursor(window, cx);
421        self.set_open(false, cx);
422        cx.notify();
423    }
424
425    fn toggle_menu(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
426        cx.stop_propagation();
427
428        self.set_open(!self.state.open, cx);
429
430        if self.state.open {
431            self.state.list.focus_handle(cx).focus(window, cx);
432        } else {
433            self.clear_query_and_restore_cursor(window, cx);
434        }
435
436        cx.notify();
437    }
438
439    fn escape(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
440        if !self.state.open {
441            cx.propagate();
442            return;
443        }
444
445        cx.stop_propagation();
446        self.clear_query_and_restore_cursor(window, cx);
447        self.set_open(false, cx);
448        self.focus(window, cx);
449        cx.notify();
450    }
451
452    /// Drop the search query and move the cursor back to the committed
453    /// selection, so the next open shows every item. Call on every menu
454    /// close that does not go through the confirm/cancel callbacks.
455    fn clear_query_and_restore_cursor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
456        self.state.clear_query(window, cx);
457
458        let committed_ix = self.state.selection.first().map(|(ix, _)| *ix);
459        self.state.list.update(cx, |list, cx| {
460            if list.selected_index() != committed_ix {
461                list.set_selected_index(committed_ix, window, cx);
462            }
463        });
464    }
465
466    fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
467        let dismissed = self.state.open && !open;
468        if self.state.open && !open {
469            self.state.menu_side.reset();
470            // Deferred: `set_open` may run inside a list update.
471            let list = self.state.list.downgrade();
472            cx.defer(move |cx| {
473                _ = list.update(cx, |list, _| list.reset_held_items_height());
474            });
475        }
476        self.state.open = open;
477        self.state.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
478
479        if dismissed {
480            cx.emit(DismissEvent);
481        }
482        cx.notify();
483    }
484
485    fn clean(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
486        cx.stop_propagation();
487        self.set_selected_index(None, window, cx);
488        cx.emit(SelectEvent::Confirm(None));
489    }
490
491    fn display_title(&mut self, _: &Window, cx: &mut Context<Self>) -> impl IntoElement {
492        let default_title = div().text_color(cx.theme().muted_foreground).child(
493            self.state
494                .placeholder
495                .clone()
496                .unwrap_or_else(|| t!("Select.placeholder").into()),
497        );
498
499        let Some(selected_index) = self.selected_index(cx) else {
500            return default_title;
501        };
502
503        let Some(title) = self
504            .state
505            .list
506            .read(cx)
507            .delegate()
508            .delegate
509            .item(selected_index)
510            .map(|item| {
511                if let Some(el) = item.display_title() {
512                    el
513                } else if let Some(prefix) = self.title_prefix.as_ref() {
514                    format!("{}{}", prefix, item.title()).into_any_element()
515                } else {
516                    item.title().into_any_element()
517                }
518            })
519        else {
520            return default_title;
521        };
522
523        div()
524            .when(self.state.disabled, |this| {
525                this.text_color(cx.theme().muted_foreground)
526            })
527            .child(title)
528    }
529
530    fn accessibility_value(&self) -> SharedString {
531        let Some((_, item)) = self.state.selection.first() else {
532            return self
533                .state
534                .placeholder
535                .clone()
536                .unwrap_or_else(|| t!("Select.placeholder").into());
537        };
538
539        if let Some(prefix) = self.title_prefix.as_ref() {
540            format!("{}{}", prefix, item.title()).into()
541        } else {
542            item.title()
543        }
544    }
545}
546
547impl<D> Render for SelectState<D>
548where
549    D: SearchableListDelegate + 'static,
550    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
551{
552    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
553        let searchable = self.searchable;
554        let is_focused = self.state.focus_handle.is_focused(window);
555        let show_clean = self.state.cleanable && self.selected_index(cx).is_some();
556        let bounds = self.state.bounds;
557        let menu_side = self.state.menu_side.clone();
558        let allow_open = !(self.state.open || self.state.disabled);
559        let outline_visible = self.state.open || (is_focused && !self.state.disabled);
560
561        let (bg, fg) = input_style(self.state.disabled, cx);
562
563        self.state.list.update(cx, |list, cx| {
564            list.set_searchable(searchable, cx);
565            list.delegate_mut().size = self.state.size;
566            list.delegate_mut().highlight_matches = self.state.highlight_matches;
567        });
568
569        div().size_full().relative().child(
570            div()
571                .relative()
572                .on_prepaint({
573                    let state = cx.entity();
574                    move |bounds, _, cx| state.update(cx, |r, _| r.state.bounds = bounds)
575                })
576                .child(
577                    div()
578                        .id("input")
579                        .test_support()
580                        .relative()
581                        .flex()
582                        .items_center()
583                        .justify_between()
584                        .border_1()
585                        .border_color(cx.theme().transparent)
586                        .when(self.state.appearance, |this| {
587                            this.bg(bg)
588                                .text_color(fg)
589                                .when(self.state.disabled, |this| this.opacity(0.5))
590                                .border_color(cx.theme().input)
591                                .rounded(cx.theme().radius)
592                        })
593                        .input_size(self.state.size)
594                        .input_text_size(self.state.size)
595                        .refine_style(&self.state.style)
596                        .when(outline_visible && self.state.appearance, |this| {
597                            this.border_1().border_color(cx.theme().ring)
598                        })
599                        .when(
600                            outline_visible && self.state.appearance && self.focus_ring_enabled,
601                            |this| this.focus_ring_style(window, cx),
602                        )
603                        .when(allow_open, |this| {
604                            this.on_click(cx.listener(Self::toggle_menu))
605                        })
606                        .child(
607                            h_flex()
608                                .flex_row_dir(cx)
609                                .id("inner")
610                                .w_full()
611                                .min_w_0()
612                                .overflow_hidden()
613                                .whitespace_nowrap()
614                                .items_center()
615                                .justify_between()
616                                .gap_1()
617                                .child(
618                                    div()
619                                        .id("title")
620                                        .flex_1()
621                                        .min_w_0()
622                                        .overflow_hidden()
623                                        .whitespace_nowrap()
624                                        .truncate()
625                                        .child(self.display_title(window, cx)),
626                                )
627                                .when(show_clean, |this| {
628                                    this.child(clear_button(cx).map(|this| {
629                                        if self.state.disabled {
630                                            this.disabled(true)
631                                        } else {
632                                            this.on_click(cx.listener(Self::clean))
633                                        }
634                                    }))
635                                })
636                                .when(!show_clean, |this| {
637                                    let icon = match self.icon.clone() {
638                                        Some(icon) => icon
639                                            .xsmall()
640                                            .text_color(cx.theme().muted_foreground)
641                                            .into_any_element(),
642                                        None => Caret::new(self.state.size)
643                                            .text_color(cx.theme().muted_foreground)
644                                            .into_any_element(),
645                                    };
646
647                                    this.child(icon)
648                                }),
649                        ),
650                )
651                .when(self.state.open, |this| {
652                    this.child(
653                        deferred(menu_popup(
654                            &menu_side,
655                            ("select-popup", cx.entity_id()),
656                            bounds,
657                            v_flex()
658                                .occlude()
659                                .map(|this| match self.state.menu_width {
660                                    Length::Auto => this.w(bounds.size.width),
661                                    Length::Definite(w) => this.w(w),
662                                })
663                                .popover_style(cx)
664                                .child(
665                                    List::new(&self.state.list)
666                                        .when_some(
667                                            self.state.search_placeholder.clone(),
668                                            |this, placeholder| {
669                                                this.search_placeholder(placeholder)
670                                            },
671                                        )
672                                        .with_size(self.state.size)
673                                        .max_h(self.state.menu_max_h)
674                                        .hold_items_height(menu_side.is_above())
675                                        .when_some(self.state.scroll_bounce, |list, on| {
676                                            list.scroll_bounce(on)
677                                        })
678                                        .paddings(Edges::all(DROPDOWN_LIST_PADDING)),
679                                )
680                                .on_mouse_down_out(cx.listener(|this, _, window, cx| {
681                                    this.escape(&Cancel, window, cx);
682                                })),
683                            cx,
684                        ))
685                        .with_priority(gpui_base::POPUP_PRIORITY),
686                    )
687                }),
688        )
689    }
690}
691
692impl<D> Select<D>
693where
694    D: SearchableListDelegate + 'static,
695    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
696{
697    pub fn new(state: &Entity<SelectState<D>>) -> Self {
698        Self {
699            id: ("select", state.entity_id()).into(),
700            state: state.clone(),
701            options: SelectOptions::default(),
702            empty: None,
703        }
704    }
705
706    /// Sets an explicit identity for the select root.
707    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
708        self.id = id.into();
709        self
710    }
711
712    /// Set the width of the dropdown menu, default: `Length::Auto`.
713    pub fn menu_width(mut self, width: impl Into<Length>) -> Self {
714        self.options.menu_width = width.into();
715        self
716    }
717
718    /// Set the max height of the dropdown menu, default: 20rem.
719    pub fn menu_max_h(mut self, max_h: impl Into<Length>) -> Self {
720        self.options.menu_max_h = max_h.into();
721        self
722    }
723
724    /// Set the placeholder shown when no value is selected.
725    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
726        self.options.placeholder = Some(placeholder.into());
727        self
728    }
729
730    /// Set the name a screen reader announces for the select.
731    ///
732    /// The placeholder and selected value are not used as the accessible name,
733    /// because they describe the current value rather than the control itself.
734    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
735        self.options.accessibility_label = Some(label.into());
736        self
737    }
738
739    /// Override the trailing icon, replacing the default chevron.
740    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
741        self.options.icon = Some(icon.into());
742        self
743    }
744
745    /// Set a label prefix shown before the selected title in the trigger.
746    ///
747    /// e.g. `title_prefix("Country: ")` → "Country: United States"
748    pub fn title_prefix(mut self, prefix: impl Into<SharedString>) -> Self {
749        self.options.title_prefix = Some(prefix.into());
750        self
751    }
752
753    /// Show a clear button when a value is selected.
754    pub fn cleanable(mut self, cleanable: bool) -> Self {
755        self.options.cleanable = cleanable;
756        self
757    }
758
759    /// Highlight the part of each row that matches the search query, default is `false`.
760    ///
761    /// Rows render with [`SearchableListItem::render_highlighted`]; the default
762    /// highlights the matched text of `title()` in the theme's
763    /// `list_highlight_foreground` color.
764    pub fn highlight_matches(mut self, highlight: bool) -> Self {
765        self.options.highlight_matches = highlight;
766        self
767    }
768
769    /// Set the placeholder text for the search input.
770    pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
771        self.options.search_placeholder = Some(placeholder.into());
772        self
773    }
774
775    /// Bounce the dropdown list at its vertical boundaries. On by default on iOS,
776    /// Android and macOS, off elsewhere; reduced motion disables displacement.
777    pub fn scroll_bounce(mut self, enabled: bool) -> Self {
778        self.options.scroll_bounce = Some(enabled);
779        self
780    }
781
782    /// Set the disabled state.
783    pub fn disabled(mut self, disabled: bool) -> Self {
784        self.options.disabled = disabled;
785        self
786    }
787
788    /// Set a custom closure that renders the empty-state element.
789    pub fn empty<E: IntoElement + 'static>(
790        mut self,
791        builder: impl Fn(&mut Window, &App) -> E + 'static,
792    ) -> Self {
793        self.empty = Some(Box::new(move |window, cx| {
794            builder(window, cx).into_any_element()
795        }));
796        self
797    }
798
799    /// Control whether the trigger shows a border and background (`true` by default).
800    pub fn appearance(mut self, appearance: bool) -> Self {
801        self.options.appearance = appearance;
802        self
803    }
804}
805
806impl<D> Sizable for Select<D>
807where
808    D: SearchableListDelegate + 'static,
809    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
810{
811    fn with_size(mut self, size: impl Into<Size>) -> Self {
812        self.options.size = size.into();
813        self
814    }
815}
816
817impl<D> crate::FocusableExt for Select<D>
818where
819    D: SearchableListDelegate + 'static,
820    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
821{
822    fn focus_ring(mut self, enabled: bool) -> Self {
823        self.options.focus_ring_enabled = enabled;
824        self
825    }
826
827    fn is_focus_ring_enabled(&self) -> bool {
828        self.options.focus_ring_enabled
829    }
830}
831
832impl<D> EventEmitter<SelectEvent<D>> for SelectState<D>
833where
834    D: SearchableListDelegate + 'static,
835    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
836{
837}
838
839impl<D> EventEmitter<DismissEvent> for SelectState<D>
840where
841    D: SearchableListDelegate + 'static,
842    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
843{
844}
845
846impl<D> Focusable for SelectState<D>
847where
848    D: SearchableListDelegate + 'static,
849    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
850{
851    fn focus_handle(&self, cx: &App) -> FocusHandle {
852        if self.state.open {
853            self.state.list.focus_handle(cx)
854        } else {
855            self.state.focus_handle.clone()
856        }
857    }
858}
859
860impl<D> Styled for Select<D>
861where
862    D: SearchableListDelegate + 'static,
863    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
864{
865    fn style(&mut self) -> &mut StyleRefinement {
866        &mut self.options.style
867    }
868}
869
870impl<D> RenderOnce for Select<D>
871where
872    D: SearchableListDelegate + 'static,
873    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
874{
875    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
876        let disabled = self.options.disabled;
877        let accessibility_label = self.options.accessibility_label.clone();
878        let focus_handle = self.state.read(cx).state.focus_handle.clone();
879        let empty = self.empty;
880        let opts = self.options;
881
882        self.state.update(cx, |this, _| {
883            this.state.style = opts.style;
884            this.state.size = opts.size;
885            this.state.cleanable = opts.cleanable;
886            this.state.placeholder = opts.placeholder;
887            this.state.search_placeholder = opts.search_placeholder;
888            this.state.highlight_matches = opts.highlight_matches;
889            this.state.menu_width = opts.menu_width;
890            this.state.menu_max_h = opts.menu_max_h;
891            this.state.scroll_bounce = opts.scroll_bounce;
892            this.state.disabled = opts.disabled;
893            this.state.appearance = opts.appearance;
894            this.focus_ring_enabled = opts.focus_ring_enabled;
895            this.icon = opts.icon;
896            this.title_prefix = opts.title_prefix;
897
898            if let Some(empty) = empty {
899                this.state.empty = Some(empty);
900            }
901        });
902
903        let is_open = self.state.read(cx).state.open;
904        let accessibility_value = self.state.read(cx).accessibility_value();
905        let content_focus_handle = self.state.read(cx).state.list.focus_handle(cx);
906        let open_state = self.state.clone();
907
908        BaseSelect::new(self.id)
909            .open(is_open)
910            .disabled(disabled)
911            .when_some(accessibility_label, |this, label| {
912                this.accessibility_label(label)
913            })
914            .focus_handle(&focus_handle)
915            .content_focus_handle(&content_focus_handle)
916            .accessibility_value(accessibility_value)
917            .on_open_change(move |open, window, cx| {
918                open_state.update(cx, |state, cx| {
919                    if !open {
920                        state.clear_query_and_restore_cursor(window, cx);
921                    }
922                    state.set_open(open, cx);
923                });
924            })
925            .size_full()
926            .child(self.state)
927    }
928}
929
930// MARK: Tests
931
932#[cfg(test)]
933mod tests {
934    use gpui::{AppContext as _, RenderOnce as _, TestAppContext};
935
936    use crate::{
937        IndexPath,
938        searchable_list::{SearchableListDelegate as _, SearchableVec},
939        select::{Select, SelectGroup, SelectState},
940    };
941
942    struct MenuSideProbe {
943        state: gpui::Entity<SelectState<SearchableVec<String>>>,
944        at_bottom: bool,
945    }
946
947    impl gpui::Render for MenuSideProbe {
948        fn render(
949            &mut self,
950            _: &mut gpui::Window,
951            _: &mut gpui::Context<Self>,
952        ) -> impl gpui::IntoElement {
953            use gpui::{ParentElement as _, Styled as _, prelude::FluentBuilder as _};
954
955            gpui::div()
956                .when(self.at_bottom, |this| this.pt(gpui::px(1000.)))
957                .child(Select::new(&self.state).w(gpui::px(200.)))
958        }
959    }
960
961    #[gpui::test]
962    fn the_menu_side_is_recorded_on_open_and_reset_on_close(cx: &mut TestAppContext) {
963        cx.update(crate::init);
964        for at_bottom in [false, true] {
965            let (view, cx) = cx.add_window_view(|window, cx| {
966                let items = (0..30).map(|ix| format!("Item {ix}")).collect::<Vec<_>>();
967                MenuSideProbe {
968                    state: cx.new(|cx| {
969                        SelectState::new(SearchableVec::new(items), None, window, cx)
970                            .searchable(true)
971                    }),
972                    at_bottom,
973                }
974            });
975            let state = view.read_with(cx, |view, _| view.state.clone());
976            cx.update(|window, cx| window.draw(cx).clear(cx));
977
978            state.update(cx, |state, cx| state.set_open(true, cx));
979            cx.update(|window, cx| window.draw(cx).clear(cx));
980            assert_eq!(
981                state.read_with(cx, |state, _| state.state.menu_side.is_above()),
982                at_bottom,
983                "the menu opens above a trigger at the bottom of the window",
984            );
985
986            state.update(cx, |state, cx| state.set_open(false, cx));
987            assert!(
988                !state.read_with(cx, |state, _| state.state.menu_side.is_above()),
989                "closing forgets the side",
990            );
991        }
992    }
993
994    #[gpui::test]
995    fn an_explicit_accessibility_label_does_not_replace_the_placeholder(cx: &mut TestAppContext) {
996        cx.update(crate::init);
997        let cx = cx.add_empty_window();
998        cx.update(|window, cx| {
999            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1000            let state = cx.new(|cx| SelectState::new(items, None, window, cx));
1001
1002            let plain = Select::new(&state).placeholder("Choose a language");
1003            assert_eq!(plain.options.accessibility_label, None);
1004            assert_eq!(
1005                plain.options.placeholder.as_deref(),
1006                Some("Choose a language")
1007            );
1008
1009            let named = Select::new(&state)
1010                .placeholder("Choose a language")
1011                .accessibility_label("Programming language");
1012            assert_eq!(
1013                named.options.accessibility_label.as_deref(),
1014                Some("Programming language")
1015            );
1016            assert_eq!(
1017                named.options.placeholder.as_deref(),
1018                Some("Choose a language"),
1019                "an accessible name must not change what is drawn"
1020            );
1021        });
1022    }
1023
1024    #[gpui::test]
1025    fn test_select_initial_selection_seeds_cursor(cx: &mut TestAppContext) {
1026        cx.update(crate::init);
1027        let cx = cx.add_empty_window();
1028        cx.update(|window, cx| {
1029            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1030            let state = cx.new(|cx| SelectState::new(items, Some(IndexPath::new(1)), window, cx));
1031
1032            assert_eq!(
1033                state.read(cx).selected_index(cx),
1034                Some(IndexPath::new(1)),
1035                "initial cursor should be seeded on ListState so display_title can read it",
1036            );
1037            assert_eq!(state.read(cx).selected_value(), Some(&"Go"));
1038        });
1039    }
1040
1041    #[gpui::test]
1042    fn test_select_initial_grouped_selection_seeds_cursor(cx: &mut TestAppContext) {
1043        cx.update(crate::init);
1044        let cx = cx.add_empty_window();
1045        cx.update(|window, cx| {
1046            let mut groups: SearchableVec<SelectGroup<&'static str>> = SearchableVec::new(vec![]);
1047            groups.push(SelectGroup::new("A").items(["Apple", "Avocado"]));
1048            groups.push(SelectGroup::new("B").items(["Banana", "Blueberry", "Blackberry"]));
1049
1050            let initial = IndexPath::new(1).section(1);
1051            let state = cx.new(|cx| SelectState::new(groups, Some(initial), window, cx));
1052
1053            assert_eq!(state.read(cx).selected_index(cx), Some(initial));
1054            assert_eq!(state.read(cx).selected_value(), Some(&"Blueberry"));
1055        });
1056    }
1057
1058    #[gpui::test]
1059    fn test_select_set_selected_value_clears_search_query(cx: &mut TestAppContext) {
1060        cx.update(crate::init);
1061        let cx = cx.add_empty_window();
1062        cx.update(|window, cx| {
1063            let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1064            let state = cx.new(|cx| SelectState::new(items, None, window, cx).searchable(true));
1065            let list = state.read(cx).state.list.clone();
1066
1067            list.update(cx, |list, cx| list.set_query("Rust", window, cx));
1068            assert_eq!(list.read(cx).delegate().delegate.items_count(0), 1);
1069
1070            state.update(cx, |state, cx| {
1071                state.set_selected_value(&"Go", window, cx);
1072            });
1073
1074            assert_eq!(state.read(cx).selected_value(), Some(&"Go"));
1075            assert_eq!(state.read(cx).selected_index(cx), Some(IndexPath::new(1)));
1076            assert_eq!(list.read(cx).query_input.read(cx).value(), "");
1077        });
1078    }
1079
1080    #[gpui::test]
1081    fn test_select_set_selected_value_clears_grouped_search_query(cx: &mut TestAppContext) {
1082        cx.update(crate::init);
1083        let cx = cx.add_empty_window();
1084        cx.update(|window, cx| {
1085            let mut groups: SearchableVec<SelectGroup<&'static str>> = SearchableVec::new(vec![]);
1086            groups.push(SelectGroup::new("A").items(["Apple", "Avocado"]));
1087            groups.push(SelectGroup::new("B").items(["Banana", "Blueberry"]));
1088
1089            let state = cx.new(|cx| SelectState::new(groups, None, window, cx).searchable(true));
1090            let list = state.read(cx).state.list.clone();
1091
1092            list.update(cx, |list, cx| list.set_query("Blue", window, cx));
1093            state.update(cx, |state, cx| {
1094                state.set_selected_value(&"Banana", window, cx);
1095            });
1096
1097            assert_eq!(state.read(cx).selected_value(), Some(&"Banana"));
1098            assert_eq!(
1099                state.read(cx).selected_index(cx),
1100                Some(IndexPath::new(0).section(1)),
1101            );
1102        });
1103    }
1104
1105    #[gpui::test]
1106    fn test_select_accessibility_value_tracks_placeholder_and_selection(cx: &mut TestAppContext) {
1107        cx.update(crate::init);
1108        let window = cx.add_empty_window();
1109        window.update(|window, cx| {
1110            let items = SearchableVec::new(vec!["Rust", "Go"]);
1111            let state = cx.new(|cx| SelectState::new(items, None, window, cx).searchable(true));
1112
1113            _ = Select::new(&state)
1114                .placeholder("Choose a language")
1115                .accessibility_label("Programming language")
1116                .render(window, cx);
1117            assert_eq!(state.read(cx).accessibility_value(), "Choose a language");
1118
1119            state.update(cx, |state, cx| {
1120                state.set_selected_value(&"Rust", window, cx);
1121            });
1122            assert_eq!(state.read(cx).accessibility_value(), "Rust");
1123
1124            let list = state.read(cx).state.list.clone();
1125            list.update(cx, |list, cx| list.set_query("Go", window, cx));
1126            assert_eq!(list.read(cx).delegate().delegate.items_count(0), 1);
1127            // Filtering changes the available rows, not the committed value.
1128            assert_eq!(state.read(cx).accessibility_value(), "Rust");
1129
1130            _ = Select::new(&state)
1131                .placeholder("Choose a language")
1132                .title_prefix("Language: ")
1133                .render(window, cx);
1134            assert_eq!(state.read(cx).accessibility_value(), "Language: Rust");
1135
1136            state.update(cx, |state, cx| state.set_selected_index(None, window, cx));
1137            assert_eq!(state.read(cx).accessibility_value(), "Choose a language");
1138
1139            _ = Select::new(&state).render(window, cx);
1140            assert_eq!(
1141                state.read(cx).accessibility_value(),
1142                rust_i18n::t!("Select.placeholder").to_string(),
1143            );
1144        });
1145    }
1146
1147    #[gpui::test]
1148    fn replacing_items_reconciles_the_cursor_and_selection(cx: &mut TestAppContext) {
1149        cx.update(crate::init);
1150        let cx = cx.add_empty_window();
1151        cx.update(|window, cx| {
1152            let state = cx.new(|cx| {
1153                SelectState::new(
1154                    vec!["main", "topic", "release"],
1155                    Some(IndexPath::new(0)),
1156                    window,
1157                    cx,
1158                )
1159            });
1160            let list = state.read(cx).state.list.clone();
1161            list.update(cx, |list, cx| {
1162                list.set_selected_index(Some(IndexPath::new(1)), window, cx)
1163            });
1164            state.update(cx, |state, cx| {
1165                state.set_items(vec!["release", "main", "topic"], window, cx)
1166            });
1167            assert_eq!(state.read(cx).selected_index(cx), Some(IndexPath::new(2)));
1168            assert_eq!(state.read(cx).selected_value(), Some(&"main"));
1169            assert_eq!(state.read(cx).state.selection[0].0, IndexPath::new(1));
1170            assert_eq!(
1171                list.read(cx).delegate().selection_snapshot[0].0,
1172                IndexPath::new(1)
1173            );
1174            state.update(cx, |state, cx| {
1175                state.set_items(vec!["main", "replacement"], window, cx)
1176            });
1177            assert_eq!(state.read(cx).selected_index(cx), None);
1178            assert_eq!(state.read(cx).selected_value(), Some(&"main"));
1179
1180            // A selected value the new items no longer have is dropped.
1181            state.update(cx, |state, cx| {
1182                state.set_items(vec!["replacement", "other"], window, cx)
1183            });
1184            assert_eq!(state.read(cx).selected_value(), None);
1185            assert!(state.read(cx).state.selection.is_empty());
1186            assert!(list.read(cx).delegate().selection_snapshot.is_empty());
1187        });
1188    }
1189
1190    #[derive(Clone)]
1191    struct RemoteChoice {
1192        value: &'static str,
1193        title: &'static str,
1194        unavailable: bool,
1195    }
1196
1197    impl super::SelectItem for RemoteChoice {
1198        type Value = &'static str;
1199        fn value(&self) -> &&'static str {
1200            &self.value
1201        }
1202        fn title(&self) -> gpui::SharedString {
1203            self.title.into()
1204        }
1205        fn disabled(&self) -> bool {
1206            self.unavailable
1207        }
1208    }
1209
1210    #[gpui::test]
1211    fn disabled_items_cannot_be_confirmed(cx: &mut TestAppContext) {
1212        use crate::list::ListDelegate as _;
1213        cx.update(crate::init);
1214        let cx = cx.add_empty_window();
1215        for unavailable in [true, false] {
1216            let state = cx.update(|window, cx| {
1217                let state = cx.new(|cx| {
1218                    SelectState::new(
1219                        vec![RemoteChoice {
1220                            value: "main",
1221                            title: "Main",
1222                            unavailable,
1223                        }],
1224                        Some(IndexPath::new(0)),
1225                        window,
1226                        cx,
1227                    )
1228                });
1229                state.update(cx, |state, cx| state.set_open(true, cx));
1230                let list = state.read(cx).state.list.clone();
1231                list.update(cx, |list, cx| {
1232                    list.delegate_mut().confirm(false, window, cx)
1233                });
1234                state
1235            });
1236            cx.run_until_parked();
1237            cx.update(|_, cx| assert_eq!(state.read(cx).state.open, unavailable));
1238        }
1239    }
1240
1241    /// A page holding a select under retained views.
1242    #[cfg(feature = "gpui-fast")]
1243    mod retained {
1244        use std::{cell::Cell, rc::Rc};
1245
1246        use gpui::{
1247            AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
1248            TestAppContext, Window, div, px,
1249        };
1250
1251        use crate::{
1252            searchable_list::SearchableVec,
1253            select::{Select, SelectState},
1254        };
1255
1256        /// A page that shows a select and what it selected, counting its
1257        /// renders.
1258        struct Page {
1259            state: Entity<SelectState<SearchableVec<&'static str>>>,
1260            renders: Rc<Cell<usize>>,
1261        }
1262
1263        impl Render for Page {
1264            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1265                self.renders.set(self.renders.get() + 1);
1266                let selected = self.state.read(cx).selected_index(cx);
1267                div()
1268                    .w(px(240.))
1269                    .child(Select::new(&self.state))
1270                    .child(format!("{selected:?}"))
1271            }
1272        }
1273
1274        /// Drawing a select again changes nothing in it: the page around it,
1275        /// which reads its selection, is not built again for it.
1276        #[gpui::test]
1277        fn drawing_a_select_again_leaves_the_page_around_it_retained(cx: &mut TestAppContext) {
1278            cx.update(crate::init);
1279            let renders = Rc::new(Cell::new(0));
1280            let (_, cx) = cx.add_window_view({
1281                let renders = renders.clone();
1282                move |window, cx| {
1283                    let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1284                    Page {
1285                        state: cx.new(|cx| SelectState::new(items, None, window, cx)),
1286                        renders,
1287                    }
1288                }
1289            });
1290            cx.update(|window, cx| window.draw(cx).clear(cx));
1291            cx.update(|window, cx| window.draw(cx).clear(cx));
1292            let rendered = renders.get();
1293            for _ in 0..3 {
1294                cx.update(|window, cx| window.draw(cx).clear(cx));
1295            }
1296            assert_eq!(renders.get(), rendered, "the page was built again");
1297        }
1298    }
1299}