Skip to main content

gpui_deck/
select.rs

1//! Selection behavior and composable, unstyled trigger/listbox parts.
2//! Modified for GPUI Deck: retained option navigation and focus lifecycle.
3
4use std::{collections::HashSet, time::Duration};
5
6use gpui::{
7    AccessibleAction, AnyElement, App, ClickEvent, Context, ElementId, Entity, EventEmitter,
8    FocusHandle, InteractiveElement, Interactivity, IntoElement, KeyBinding, KeyDownEvent,
9    MouseButton, ParentElement, Pixels, RenderOnce, Role, ScrollHandle, SharedString,
10    StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Window, div,
11    prelude::FluentBuilder as _, px,
12};
13use web_time::Instant;
14
15use crate::{
16    ElementExt as _, Popup, StyledExt as _, TestSupportExt as _,
17    a11y_disabled::A11yDisabledExt as _,
18    actions::{Cancel, Confirm, SelectDown, SelectFirst, SelectLast, SelectUp},
19    global_state::{DeferredPopover, GlobalState},
20    scroll_area::RevealViewport,
21};
22
23const CONTEXT: &str = "Select";
24
25pub(crate) fn init(cx: &mut App) {
26    cx.bind_keys([
27        KeyBinding::new("space", Confirm { secondary: false }, Some(CONTEXT)),
28        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
29        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
30        KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
31        KeyBinding::new("end", SelectLast, Some(CONTEXT)),
32        KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
33        KeyBinding::new("escape", Cancel, Some(CONTEXT)),
34    ]);
35}
36
37/// One option in a select. Its unique value identifies it across list updates.
38#[derive(Clone, Debug)]
39pub struct SelectItem {
40    value: SharedString,
41    label: SharedString,
42    disabled: bool,
43}
44
45impl SelectItem {
46    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
47        Self {
48            value: value.into(),
49            label: label.into(),
50            disabled: false,
51        }
52    }
53
54    pub fn disabled(mut self, disabled: bool) -> Self {
55        self.disabled = disabled;
56        self
57    }
58
59    pub fn value(&self) -> &SharedString {
60        &self.value
61    }
62
63    pub fn label(&self) -> &SharedString {
64        &self.label
65    }
66
67    pub fn is_disabled(&self) -> bool {
68        self.disabled
69    }
70}
71
72fn collect_items(items: impl IntoIterator<Item = SelectItem>) -> Vec<SelectItem> {
73    let items: Vec<_> = items.into_iter().collect();
74    let mut values = HashSet::with_capacity(items.len());
75    assert!(
76        items.iter().all(|item| values.insert(&item.value)),
77        "SelectItem values must be unique"
78    );
79    items
80}
81
82fn enabled_index(items: &[SelectItem], value: &str) -> Option<usize> {
83    items
84        .iter()
85        .position(|item| !item.disabled && item.value.as_ref() == value)
86}
87
88/// Emitted once when a user commits a different value.
89#[derive(Clone, Debug, Eq, PartialEq)]
90pub enum SelectEvent {
91    Change(SharedString),
92}
93
94/// Retained selection, keyboard cursor, disabled state and popup focus.
95///
96/// Applications can replace the ordered options with [`Self::set_items`]. Arrow keys wrap and
97/// skip disabled items; opening highlights the committed item or first enabled
98/// item. Enter/Space commits, Escape discards the pending cursor and restores
99/// trigger focus. Home/End highlight an enabled edge while open. Typing searches
100/// labels by a case-insensitive prefix, committing while closed and only moving
101/// the cursor while open. Repeated letters cycle; a one-second pause resets the
102/// prefix. The application owns option presentation, not this behavior.
103pub struct SelectState {
104    items: Vec<SelectItem>,
105    selected: Option<usize>,
106    highlighted: Option<usize>,
107    open: bool,
108    disabled: bool,
109    open_on_pointer_down: bool,
110    focus: FocusHandle,
111    content_focus: FocusHandle,
112    scroll: ScrollHandle,
113    reveal_highlight: bool,
114    deferred_context: Option<DeferredPopover>,
115    dismiss_subscription: Option<Subscription>,
116    search: String,
117    searched_at: Option<Instant>,
118}
119
120impl SelectState {
121    pub fn new(items: impl IntoIterator<Item = SelectItem>, cx: &mut Context<Self>) -> Self {
122        Self {
123            items: collect_items(items),
124            selected: None,
125            highlighted: None,
126            open: false,
127            disabled: false,
128            open_on_pointer_down: false,
129            focus: cx.focus_handle().tab_stop(true),
130            content_focus: cx.focus_handle(),
131            scroll: ScrollHandle::new(),
132            reveal_highlight: false,
133            deferred_context: None,
134            dismiss_subscription: None,
135            search: String::new(),
136            searched_at: None,
137        }
138    }
139
140    pub fn default_value(mut self, value: impl AsRef<str>) -> Self {
141        self.selected = enabled_index(&self.items, value.as_ref());
142        self
143    }
144
145    pub fn items(&self) -> &[SelectItem] {
146        &self.items
147    }
148
149    /// Replaces the options without emitting [`SelectEvent::Change`]. A committed
150    /// value survives while enabled. An open list keeps its highlighted value,
151    /// then prefers the committed value or first enabled option if it disappeared.
152    /// With no enabled options the popup closes using its normal focus policy.
153    pub fn set_items(
154        &mut self,
155        items: impl IntoIterator<Item = SelectItem>,
156        window: &mut Window,
157        cx: &mut Context<Self>,
158    ) {
159        let items = collect_items(items);
160        let remap = |index: usize| enabled_index(&items, &self.items[index].value);
161        self.selected = self.selected.and_then(remap);
162        self.highlighted = self.highlighted.and_then(remap);
163        self.items = items;
164        self.search.clear();
165        self.searched_at = None;
166        if self.open {
167            self.highlighted = self
168                .highlighted
169                .or(self.selected)
170                .or_else(|| self.items.iter().position(|item| !item.disabled));
171            if self.highlighted.is_none() {
172                self.close(window, cx);
173                return;
174            }
175            self.reveal_highlight = true;
176        }
177        cx.notify();
178        window.refresh();
179    }
180
181    pub fn selected_index(&self) -> Option<usize> {
182        self.selected
183    }
184
185    pub fn highlighted_index(&self) -> Option<usize> {
186        self.highlighted
187    }
188
189    pub fn selected_item(&self) -> Option<&SelectItem> {
190        self.selected.map(|ix| &self.items[ix])
191    }
192
193    /// Sets or clears the committed value without emitting Change.
194    ///
195    /// Unknown or disabled options are rejected without changing the value,
196    /// pending cursor, popup or focus. An accepted update closes the popup using
197    /// its normal focus lifecycle and clears the typeahead prefix. Returns
198    /// whether the value was accepted, including an unchanged value. Application
199    /// updates remain available when the control itself is disabled.
200    pub fn set_selected_value(
201        &mut self,
202        value: Option<&str>,
203        window: &mut Window,
204        cx: &mut Context<Self>,
205    ) -> bool {
206        let selected = match value {
207            Some(value) => {
208                let Some(index) = enabled_index(&self.items, value) else {
209                    return false;
210                };
211                Some(index)
212            }
213            None => None,
214        };
215        self.close(window, cx);
216        self.selected = selected;
217        self.search.clear();
218        self.searched_at = None;
219        cx.notify();
220        window.refresh();
221        true
222    }
223
224    pub fn is_open(&self) -> bool {
225        self.open
226    }
227
228    pub fn is_disabled(&self) -> bool {
229        self.disabled
230    }
231
232    pub fn focus_handle(&self) -> &FocusHandle {
233        &self.focus
234    }
235
236    pub fn content_focus_handle(&self) -> &FocusHandle {
237        &self.content_focus
238    }
239
240    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
241        if self.disabled == disabled {
242            return;
243        }
244        if disabled {
245            self.close(window, cx);
246        }
247        self.disabled = disabled;
248        cx.notify();
249        window.refresh();
250    }
251
252    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
253        if self.disabled || self.open {
254            return;
255        }
256        self.highlighted = self
257            .selected
258            .or_else(|| self.items.iter().position(|item| !item.disabled));
259        if self.highlighted.is_none() {
260            return;
261        }
262        self.open = true;
263        self.reveal_highlight = true;
264        self.search.clear();
265        self.searched_at = None;
266        self.deferred_context = Some(GlobalState::register_deferred_popover(cx));
267        self.dismiss_subscription =
268            Some(
269                cx.on_focus_out(&self.content_focus, window, |_, event, window, cx| {
270                    // Focus callbacks run while drawing. Close after that phase so
271                    // notify/refresh can remove the popup. A detached focus handle
272                    // can remain focused; never restore its now-hidden trigger.
273                    cx.defer_in(window, move |state, window, cx| {
274                        let detached = event
275                            .blurred
276                            .upgrade()
277                            .is_some_and(|focus| focus.is_focused(window));
278                        if !window.is_window_active()
279                            || detached
280                            || !state.content_focus.contains_focused(window, cx)
281                        {
282                            state.dismiss(window, cx);
283                        }
284                    });
285                }),
286            );
287        self.content_focus.focus(window, cx);
288        cx.notify();
289        window.refresh();
290    }
291
292    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
293        if !self.open {
294            return;
295        }
296        // A pointer press or an ancestor closing may already have moved focus.
297        // Do not move it back into a control the user has just left.
298        if self.content_focus.is_focused(window) || self.content_focus.contains_focused(window, cx)
299        {
300            self.focus.focus(window, cx);
301        }
302        self.dismiss(window, cx);
303    }
304
305    fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
306        if !self.open {
307            return;
308        }
309        self.open = false;
310        self.highlighted = None;
311        self.reveal_highlight = false;
312        self.deferred_context = None;
313        self.dismiss_subscription = None;
314        self.search.clear();
315        self.searched_at = None;
316        cx.notify();
317        window.refresh();
318    }
319
320    fn move_cursor(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
321        if self.disabled {
322            return;
323        }
324        if !self.open {
325            self.open(window, cx);
326            return;
327        }
328        let Some(current) = self.highlighted else {
329            return;
330        };
331        let len = self.items.len();
332        let next = (1..=len)
333            .map(|step| {
334                if forward {
335                    (current + step) % len
336                } else {
337                    (current + len - step) % len
338                }
339            })
340            .find(|&ix| !self.items[ix].disabled);
341        if let Some(index) = next {
342            self.highlight(index, true, window, cx);
343        }
344    }
345
346    fn highlight(&mut self, ix: usize, reveal: bool, window: &mut Window, cx: &mut Context<Self>) {
347        if !self.open || self.disabled || self.items[ix].disabled {
348            return;
349        }
350        if self.highlighted == Some(ix) && !reveal {
351            return;
352        }
353        self.highlighted = Some(ix);
354        self.reveal_highlight = reveal;
355        cx.notify();
356        window.refresh();
357    }
358
359    fn edge(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
360        if !self.open {
361            cx.propagate();
362            return;
363        }
364        let index = if last {
365            self.items.iter().rposition(|item| !item.disabled)
366        } else {
367            self.items.iter().position(|item| !item.disabled)
368        };
369        if let Some(index) = index {
370            self.highlight(index, true, window, cx);
371        }
372    }
373
374    fn typeahead(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
375        if self.disabled
376            || event.prefer_character_input
377            || (!self.focus.is_focused(window) && !self.content_focus.is_focused(window))
378        {
379            return;
380        }
381        let modifiers = event.keystroke.modifiers;
382        if modifiers.control || modifiers.alt || modifiers.platform || modifiers.function {
383            return;
384        }
385        let text = event
386            .keystroke
387            .key_char
388            .as_deref()
389            .unwrap_or(&event.keystroke.key);
390        let mut characters = text.chars();
391        let Some(character) = characters.next() else {
392            return;
393        };
394        if characters.next().is_some() || character.is_control() || character.is_whitespace() {
395            return;
396        }
397        let now = cx.background_executor().now();
398        if self
399            .searched_at
400            .is_none_or(|at| now.duration_since(at) >= Duration::from_secs(1))
401        {
402            self.search.clear();
403        }
404        self.search.extend(character.to_lowercase());
405        self.searched_at = Some(now);
406        let first = self.search.chars().next().unwrap();
407        let repeated = self.search.chars().all(|character| character == first);
408        let prefix = if repeated {
409            first.to_string()
410        } else {
411            self.search.clone()
412        };
413        let current = if self.open {
414            self.highlighted
415        } else {
416            self.selected
417        };
418        let count = self.items.len();
419        let start = current.unwrap_or(0);
420        let index = (0..count)
421            .map(|distance| (start + distance) % count)
422            .filter(|index| !repeated || current != Some(*index))
423            .find(|&index| {
424                !self.items[index].disabled
425                    && self.items[index].label.to_lowercase().starts_with(&prefix)
426            });
427        if let Some(index) = index {
428            if self.open {
429                self.highlight(index, true, window, cx);
430            } else if self.selected != Some(index) {
431                self.selected = Some(index);
432                cx.emit(SelectEvent::Change(self.items[index].value.clone()));
433                cx.notify();
434                window.refresh();
435            }
436        }
437        cx.stop_propagation();
438    }
439
440    fn commit(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
441        if !self.open || self.disabled || self.items[ix].disabled {
442            return;
443        }
444        let changed = self.selected != Some(ix);
445        self.selected = Some(ix);
446        self.close(window, cx);
447        if changed {
448            cx.emit(SelectEvent::Change(self.items[ix].value.clone()));
449        }
450    }
451
452    fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
453        if self.disabled {
454            return;
455        }
456        if !self.open {
457            self.open(window, cx);
458        } else if let Some(ix) = self.highlighted {
459            self.commit(ix, window, cx);
460        }
461    }
462}
463
464impl EventEmitter<SelectEvent> for SelectState {}
465
466/// A select root with application-owned trigger and option-list presentation.
467///
468/// The root keeps the positioned listbox inside its keyboard/focus ancestry.
469/// Its `trigger` is visual content; the root supplies activation and semantics.
470/// Build `content` from [`SelectOption`] elements for the same retained state.
471#[derive(IntoElement)]
472pub struct Select {
473    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
474    state: Entity<SelectState>,
475    label: Option<SharedString>,
476    field: crate::FieldMetadata,
477    trigger: Option<AnyElement>,
478    content: Option<AnyElement>,
479    list_max_height: Option<Pixels>,
480    style: StyleRefinement,
481}
482
483impl Select {
484    pub fn new(id: impl Into<ElementId>, state: &Entity<SelectState>) -> Self {
485        Self {
486            base: div().id(id).test_support(),
487            state: state.clone(),
488            label: None,
489            field: crate::FieldMetadata::default(),
490            trigger: None,
491            content: None,
492            list_max_height: None,
493            style: StyleRefinement::default(),
494        }
495    }
496
497    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
498        self.label = Some(label.into());
499        self
500    }
501
502    /// Applies a [`crate::ControlField`]'s label, description, required and
503    /// invalid metadata to this control's native node. The field label takes
504    /// precedence over `accessibility_label`.
505    pub fn field(mut self, metadata: crate::FieldMetadata) -> Self {
506        self.field = metadata;
507        self
508    }
509
510    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
511        self.trigger = Some(trigger.into_any_element());
512        self
513    }
514
515    pub fn content(mut self, content: impl IntoElement) -> Self {
516        self.content = Some(content.into_any_element());
517        self
518    }
519
520    /// Limits the height of the scrollable listbox. By default it can grow to
521    /// the usable window height. Short lists keep their natural height.
522    pub fn list_max_height(mut self, height: Pixels) -> Self {
523        self.list_max_height = Some(height.max(px(0.)));
524        self
525    }
526}
527
528impl Styled for Select {
529    fn style(&mut self) -> &mut StyleRefinement {
530        &mut self.style
531    }
532}
533
534impl InteractiveElement for Select {
535    fn interactivity(&mut self) -> &mut Interactivity {
536        self.base.interactivity()
537    }
538}
539
540impl StatefulInteractiveElement for Select {}
541
542impl RenderOnce for Select {
543    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
544        let model = self.state.read(cx);
545        let open = model.open;
546        let disabled = model.disabled;
547        let focus = model.focus.clone();
548        let content_focus = model.content_focus.clone();
549        let scroll = model.scroll.clone();
550        let value = model.selected_item().map(|item| item.label.clone());
551        let trigger_state = self.state.clone();
552        let press_state = self.state.clone();
553        let accessible_state = self.state.clone();
554        let up_state = self.state.clone();
555        let down_state = self.state.clone();
556        let first_state = self.state.clone();
557        let last_state = self.state.clone();
558        let typeahead_state = self.state.clone();
559        let confirm_state = self.state.clone();
560        let cancel_state = self.state.clone();
561        let outside_state = self.state.clone();
562        let tab_state = self.state.clone();
563        let tab_prev_state = self.state.clone();
564        let field = self.field;
565
566        let trigger = div()
567            .id("select-trigger")
568            .when(!disabled, |this| {
569                this.on_mouse_down(MouseButton::Left, move |_, _, cx| {
570                    // Outside-down dismissal may already have changed the state.
571                    press_state.update(cx, |state, _| state.open_on_pointer_down = open);
572                })
573                .on_click(move |event, window, cx| {
574                    trigger_state.update(cx, |state, cx| {
575                        let was_open = if matches!(event, ClickEvent::Mouse(_)) {
576                            state.open_on_pointer_down
577                        } else {
578                            state.open
579                        };
580                        if was_open {
581                            state.close(window, cx);
582                        } else {
583                            state.open(window, cx);
584                        }
585                    });
586                })
587            })
588            .children(self.trigger);
589        let popup =
590            Popup::new(("select-popup", self.state.entity_id()), trigger).when(open, |this| {
591                let available = Popup::available_height(window);
592                let height = self.list_max_height.unwrap_or(available).min(available);
593                this.content(
594                    div()
595                        .id("select-listbox")
596                        .test_support()
597                        .role(Role::ListBox)
598                        .track_focus(&content_focus)
599                        .on_mouse_down_out(move |_, window, cx| {
600                            outside_state.update(cx, |state, cx| state.close(window, cx));
601                        })
602                        .child(RevealViewport::popup(
603                            "select-viewport",
604                            height,
605                            scroll,
606                            self.content,
607                        )),
608                )
609            });
610
611        self.base
612            .role(Role::ComboBox)
613            .aria_expanded(open)
614            .when_some(field.label.or(self.label), |this, label| {
615                this.aria_label(label)
616            })
617            .when_some(field.description, |this, description| {
618                this.aria_description(description)
619            })
620            .when_some(value, |this, value| this.aria_value(value))
621            .key_context(CONTEXT)
622            .when(!disabled || focus.is_focused(window), |this| {
623                this.track_focus(&focus.tab_stop(!disabled))
624            })
625            .when(!disabled, |this| {
626                this.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
627                    accessible_state.update(cx, |state, cx| {
628                        if state.is_open() {
629                            state.close(window, cx);
630                        } else {
631                            state.open(window, cx);
632                        }
633                    });
634                })
635            })
636            .on_action(move |_: &SelectUp, window, cx| {
637                up_state.update(cx, |state, cx| state.move_cursor(false, window, cx));
638            })
639            .on_action(move |_: &SelectDown, window, cx| {
640                down_state.update(cx, |state, cx| state.move_cursor(true, window, cx));
641            })
642            .on_action(move |_: &SelectFirst, window, cx| {
643                first_state.update(cx, |state, cx| state.edge(false, window, cx));
644            })
645            .on_action(move |_: &SelectLast, window, cx| {
646                last_state.update(cx, |state, cx| state.edge(true, window, cx));
647            })
648            .on_key_down(move |event, window, cx| {
649                typeahead_state.update(cx, |state, cx| state.typeahead(event, window, cx));
650            })
651            .on_action(move |_: &Confirm, window, cx| {
652                confirm_state.update(cx, |state, cx| state.confirm(window, cx));
653            })
654            .on_action(move |_: &Cancel, window, cx| {
655                if !cancel_state.read(cx).is_open() {
656                    cx.propagate();
657                    return;
658                }
659                cx.stop_propagation();
660                cancel_state.update(cx, |state, cx| state.close(window, cx));
661            })
662            .on_action(move |_: &crate::root::Tab, window, cx| {
663                tab_state.update(cx, |state, cx| state.close(window, cx));
664                cx.propagate();
665            })
666            .on_action(move |_: &crate::root::TabPrev, window, cx| {
667                tab_prev_state.update(cx, |state, cx| state.close(window, cx));
668                cx.propagate();
669            })
670            .child(popup)
671            .refine_style(&self.style)
672            .a11y_form(disabled, field.required, field.invalid)
673    }
674}
675
676/// One unstyled option. Selection, hover, disabled and activation come from state.
677#[derive(IntoElement)]
678pub struct SelectOption {
679    state: Entity<SelectState>,
680    index: usize,
681    style: StyleRefinement,
682    children: Vec<AnyElement>,
683}
684
685impl SelectOption {
686    /// Use the option's index in the current [`SelectState::items`] at render time.
687    pub fn new(state: &Entity<SelectState>, index: usize) -> Self {
688        Self {
689            state: state.clone(),
690            index,
691            style: StyleRefinement::default(),
692            children: Vec::new(),
693        }
694    }
695}
696
697impl Styled for SelectOption {
698    fn style(&mut self) -> &mut StyleRefinement {
699        &mut self.style
700    }
701}
702
703impl ParentElement for SelectOption {
704    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
705        self.children.extend(elements);
706    }
707}
708
709impl RenderOnce for SelectOption {
710    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
711        let model = self.state.read(cx);
712        let item = model
713            .items
714            .get(self.index)
715            .expect("SelectOption index must identify an item");
716        let disabled = model.disabled || item.disabled;
717        let selected = model.selected == Some(self.index);
718        let highlighted = model.highlighted == Some(self.index);
719        let reveal = highlighted && model.reveal_highlight;
720        let label = item.label.clone();
721        let value = item.value.clone();
722        let hover_value = value.clone();
723        let hover_state = self.state.clone();
724        let reveal_state = self.state.clone();
725        let click_state = self.state;
726
727        div()
728            .id((ElementId::from("select-option"), value.clone()))
729            .test_support()
730            .role(Role::ListBoxOption)
731            .aria_label(label)
732            .aria_selected(selected)
733            .when(highlighted, |this| this.aria_active_descendant())
734            .when(!disabled, |this| {
735                this.on_hover(move |hovered, window, cx| {
736                    if *hovered {
737                        hover_state.update(cx, |state, cx| {
738                            if let Some(index) = enabled_index(&state.items, &hover_value) {
739                                state.highlight(index, false, window, cx);
740                            }
741                        });
742                    }
743                })
744                .on_click(move |_, window, cx| {
745                    click_state.update(cx, |state, cx| {
746                        if let Some(index) = enabled_index(&state.items, &value) {
747                            state.commit(index, window, cx);
748                        }
749                    });
750                })
751            })
752            .children(self.children)
753            .refine_style(&self.style)
754            .when(reveal, |this| {
755                this.on_prepaint(move |bounds, window, cx| {
756                    // Reveal only on open or keyboard navigation. A wheel
757                    // gesture can then scroll away without being pulled back.
758                    reveal_state.update(cx, |state, _| state.reveal_highlight = false);
759                    window.request_autoscroll(bounds);
760                })
761            })
762            .a11y_disabled(disabled)
763    }
764}
765
766#[cfg(test)]
767mod tests {
768    use std::{cell::RefCell, rc::Rc};
769
770    use super::*;
771    use crate::Root;
772    use gpui::{
773        AppContext as _, KeyUpEvent, Keystroke, Modifiers, MouseButton, Render, ScrollDelta,
774        ScrollEvent, TestAppContext, point, size,
775    };
776
777    struct Harness {
778        select: Entity<SelectState>,
779        shown: bool,
780        _observation: Subscription,
781    }
782
783    impl Render for Harness {
784        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
785            div().size_full().when(self.shown, |this| {
786                this.child(
787                    Select::new("select", &self.select)
788                        .trigger(
789                            div()
790                                .debug_selector(|| "trigger".into())
791                                .w(px(180.))
792                                .h(px(32.))
793                                .child("Choose"),
794                        )
795                        .content(
796                            div().w(px(180.)).children(
797                                self.select.read(cx).items().iter().enumerate().map(
798                                    |(index, item)| {
799                                        SelectOption::new(&self.select, index).h(px(32.)).child(
800                                            div()
801                                                .debug_selector(move || format!("option-{index}"))
802                                                .size_full()
803                                                .child(item.label().clone()),
804                                        )
805                                    },
806                                ),
807                            ),
808                        ),
809                )
810            })
811        }
812    }
813
814    #[gpui::test]
815    fn long_list_reveals_pending_keyboard_choices_and_allows_manual_scrolling(
816        cx: &mut TestAppContext,
817    ) {
818        cx.update(crate::init);
819        let (root, cx) = cx.add_window_view(|window, cx| {
820            let view = cx.new(|cx| {
821                let select = cx.new(|cx| {
822                    let items = ('A'..='Z').map(|c| SelectItem::new(c.to_string(), c.to_string()));
823                    SelectState::new(items, cx).default_value("U")
824                });
825                let observation = cx.observe(&select, |_, _, cx| cx.notify());
826                Harness {
827                    select,
828                    shown: true,
829                    _observation: observation,
830                }
831            });
832            Root::new(view, window, cx)
833        });
834        let view = root
835            .read_with(cx, |root, _| root.view().clone())
836            .downcast::<Harness>()
837            .unwrap();
838        let select = view.read_with(cx, |view, _| view.select.clone());
839        cx.simulate_resize(size(px(260.), px(132.)));
840        cx.update(|window, cx| {
841            window.activate_window();
842            select.read(cx).focus_handle().clone().focus(window, cx);
843            window.draw(cx).clear(cx);
844        });
845
846        let scroll = select.read_with(cx, |state, _| state.scroll.clone());
847        for (key, index, selector) in [
848            ("enter", 20, "option-20"),
849            ("end", 25, "option-25"),
850            ("down", 0, "option-0"),
851            ("p", 15, "option-15"),
852            ("home", 0, "option-0"),
853        ] {
854            cx.simulate_keystrokes(key);
855            cx.update(|window, cx| {
856                window.draw(cx).clear(cx);
857                window.simulate_next_frame(cx);
858                window.draw(cx).clear(cx);
859                let state = select.read(cx);
860                assert_eq!(state.highlighted_index(), Some(index));
861                assert_eq!(state.selected_index(), Some(20));
862                assert!(state.content_focus_handle().is_focused(window));
863                assert!(scroll.max_offset().y > px(0.));
864                assert!(scroll.bounds().top() >= px(0.));
865                assert!(scroll.bounds().bottom() <= window.viewport_size().height);
866            });
867            let bounds = cx.debug_bounds(selector).unwrap();
868            assert!(bounds.top() >= scroll.bounds().top(), "{key}: {bounds:?}");
869            assert!(
870                bounds.bottom() <= scroll.bounds().bottom(),
871                "{key}: {bounds:?}"
872            );
873        }
874
875        cx.simulate_event(ScrollEvent {
876            position: scroll.bounds().center(),
877            delta: ScrollDelta::Pixels(point(px(0.), px(-120.))),
878            ..Default::default()
879        });
880        cx.update(|window, cx| {
881            window.draw(cx).clear(cx);
882            window.simulate_next_frame(cx);
883            window.draw(cx).clear(cx);
884        });
885        assert!(cx.debug_bounds("option-0").unwrap().bottom() <= scroll.bounds().top());
886
887        cx.simulate_keystrokes("end");
888        cx.update(|window, cx| {
889            select.update(cx, |state, cx| {
890                let items = state.items().iter().rev().cloned().collect::<Vec<_>>();
891                state.set_items(items, window, cx);
892            });
893            window.draw(cx).clear(cx);
894            window.simulate_next_frame(cx);
895            window.draw(cx).clear(cx);
896        });
897        let moved = cx.debug_bounds("option-0").unwrap();
898        assert!(moved.top() >= scroll.bounds().top() && moved.bottom() <= scroll.bounds().bottom());
899        cx.simulate_keystrokes("enter");
900        cx.update(|window, cx| {
901            assert_eq!(
902                select.read(cx).selected_item().unwrap().value().as_ref(),
903                "Z"
904            );
905            assert!(select.read(cx).focus_handle().is_focused(window));
906        });
907    }
908
909    #[gpui::test]
910    fn edge_keys_and_typeahead_keep_pending_and_committed_selection_distinct(
911        cx: &mut TestAppContext,
912    ) {
913        cx.update(crate::init);
914        let changes = Rc::new(RefCell::new(Vec::new()));
915        let recorded = changes.clone();
916        let (root, cx) = cx.add_window_view(|window, cx| {
917            let view = cx.new(|cx| {
918                let select = cx.new(|cx| {
919                    SelectState::new(
920                        [
921                            SelectItem::new("unavailable-first", "Apricot").disabled(true),
922                            SelectItem::new("apple", "Apple"),
923                            SelectItem::new("avocado", "Avocado"),
924                            SelectItem::new("banana", "Banana"),
925                            SelectItem::new("blueberry", "Blueberry"),
926                            SelectItem::new("unavailable-match", "Blackberry").disabled(true),
927                            SelectItem::new("eclair", "Éclair"),
928                            SelectItem::new("unavailable-last", "Zucchini").disabled(true),
929                        ],
930                        cx,
931                    )
932                    .default_value("banana")
933                });
934                cx.subscribe(&select, move |_, _, event: &SelectEvent, _| {
935                    let SelectEvent::Change(value) = event;
936                    recorded.borrow_mut().push(value.clone());
937                })
938                .detach();
939                let observation = cx.observe(&select, |_, _, cx| cx.notify());
940                Harness {
941                    select,
942                    shown: true,
943                    _observation: observation,
944                }
945            });
946            Root::new(view, window, cx)
947        });
948        let view = root
949            .read_with(cx, |root, _| root.view().clone())
950            .downcast::<Harness>()
951            .unwrap();
952        cx.update(|window, cx| {
953            window.activate_window();
954            view.read(cx)
955                .select
956                .read(cx)
957                .focus_handle()
958                .clone()
959                .focus(window, cx);
960            window.draw(cx).clear(cx);
961        });
962
963        // Closed Home/End do not open or change a select. Typing selects in
964        // place; repeated letters cycle and a longer prefix narrows the match.
965        cx.simulate_keystrokes("home end a a");
966        cx.update(|window, cx| {
967            let state = view.read(cx).select.read(cx);
968            assert!(!state.is_open());
969            assert_eq!(state.selected_index(), Some(2));
970            assert!(state.focus_handle().is_focused(window));
971        });
972        cx.executor().advance_clock(Duration::from_secs(1));
973        cx.simulate_keystrokes("b l");
974        cx.update(|_, cx| {
975            assert_eq!(view.read(cx).select.read(cx).selected_index(), Some(4));
976        });
977        assert_eq!(
978            *changes.borrow(),
979            ["apple", "avocado", "banana", "blueberry"]
980                .map(SharedString::from)
981                .to_vec()
982        );
983
984        cx.simulate_keystrokes("down home");
985        cx.update(|window, cx| {
986            window.draw(cx).clear(cx);
987            let state = view.read(cx).select.read(cx);
988            assert!(state.is_open());
989            assert_eq!(state.highlighted_index(), Some(1));
990            assert_eq!(state.selected_index(), Some(4));
991            assert!(state.content_focus_handle().is_focused(window));
992        });
993        cx.simulate_keystrokes("end");
994        cx.update(|_, cx| {
995            let state = view.read(cx).select.read(cx);
996            assert_eq!(state.highlighted_index(), Some(6));
997            assert_eq!(state.selected_index(), Some(4));
998        });
999        cx.simulate_keystrokes("a a");
1000        cx.update(|_, cx| {
1001            assert_eq!(view.read(cx).select.read(cx).highlighted_index(), Some(2));
1002        });
1003        assert_eq!(changes.borrow().len(), 4);
1004        cx.simulate_keystrokes("escape down b l enter");
1005        cx.update(|window, cx| {
1006            window.draw(cx).clear(cx);
1007            let state = view.read(cx).select.read(cx);
1008            assert!(!state.is_open());
1009            assert_eq!(state.selected_index(), Some(4));
1010            assert!(state.focus_handle().is_focused(window));
1011        });
1012        assert_eq!(changes.borrow().len(), 4, "unchanged commits emit no event");
1013
1014        // Native character preference, shortcuts, disabled controls, and
1015        // events outside the select's own focus scopes never change its value.
1016        cx.simulate_keystrokes("ctrl-a alt-a");
1017        let keystroke = Keystroke {
1018            key: "a".into(),
1019            key_char: Some("a".into()),
1020            modifiers: Modifiers::default(),
1021        };
1022        cx.simulate_event(KeyDownEvent {
1023            keystroke: keystroke.clone(),
1024            is_held: false,
1025            prefer_character_input: true,
1026        });
1027        cx.simulate_event(KeyUpEvent { keystroke });
1028        cx.update(|window, cx| {
1029            let select = view.read(cx).select.clone();
1030            assert_eq!(select.read(cx).selected_index(), Some(4));
1031            select.update(cx, |state, cx| state.set_disabled(true, window, cx));
1032            window.draw(cx).clear(cx);
1033        });
1034        cx.simulate_keystrokes("a home end");
1035        cx.update(|window, cx| {
1036            let select = view.read(cx).select.clone();
1037            assert_eq!(select.read(cx).selected_index(), Some(4));
1038            select.update(cx, |state, cx| state.set_disabled(false, window, cx));
1039            window.blur(cx);
1040            let event = KeyDownEvent {
1041                keystroke: Keystroke {
1042                    key: "a".into(),
1043                    key_char: Some("a".into()),
1044                    modifiers: Modifiers::default(),
1045                },
1046                is_held: false,
1047                prefer_character_input: false,
1048            };
1049            select.update(cx, |state, cx| state.typeahead(&event, window, cx));
1050            assert_eq!(select.read(cx).selected_index(), Some(4));
1051            select.read(cx).focus_handle().clone().focus(window, cx);
1052        });
1053        cx.executor().advance_clock(Duration::from_secs(1));
1054        let keystroke = Keystroke {
1055            key: "É".into(),
1056            key_char: Some("É".into()),
1057            modifiers: Modifiers::default(),
1058        };
1059        cx.simulate_event(KeyDownEvent {
1060            keystroke: keystroke.clone(),
1061            is_held: false,
1062            prefer_character_input: false,
1063        });
1064        cx.simulate_event(KeyUpEvent { keystroke });
1065        cx.update(|_, cx| {
1066            assert_eq!(view.read(cx).select.read(cx).selected_index(), Some(6));
1067        });
1068        assert_eq!(changes.borrow().last().unwrap().as_ref(), "eclair");
1069
1070        // Application resets validate before disturbing a pending cursor, then
1071        // close with the same focus policy and never report a user change.
1072        cx.simulate_keystrokes("down home");
1073        cx.update(|window, cx| {
1074            let select = view.read(cx).select.clone();
1075            select.update(cx, |state, cx| {
1076                for value in ["missing", "unavailable-first"] {
1077                    assert!(!state.set_selected_value(Some(value), window, cx));
1078                    assert_eq!(state.selected_index(), Some(6));
1079                    assert_eq!(state.highlighted_index(), Some(1));
1080                    assert!(state.is_open());
1081                    assert!(state.content_focus_handle().is_focused(window));
1082                }
1083                assert!(state.set_selected_value(Some("banana"), window, cx));
1084                assert_eq!(state.selected_index(), Some(3));
1085                assert!(!state.is_open());
1086                assert!(state.focus_handle().is_focused(window));
1087                state.open(window, cx);
1088                assert!(state.set_selected_value(None, window, cx));
1089                assert_eq!(state.selected_index(), None);
1090                assert!(!state.is_open());
1091                assert!(state.focus_handle().is_focused(window));
1092                state.set_disabled(true, window, cx);
1093                assert!(state.set_selected_value(Some("apple"), window, cx));
1094                assert_eq!(state.selected_index(), Some(1));
1095                window.blur(cx);
1096                assert!(state.set_selected_value(None, window, cx));
1097                assert!(window.focused(cx).is_none());
1098            });
1099        });
1100        assert_eq!(
1101            changes.borrow().len(),
1102            5,
1103            "application updates emit no Change"
1104        );
1105    }
1106
1107    #[gpui::test]
1108    fn refreshing_items_preserves_value_and_pending_focus(cx: &mut TestAppContext) {
1109        cx.update(crate::init);
1110        let changes = Rc::new(RefCell::new(Vec::new()));
1111        let recorded = changes.clone();
1112        let (root, cx) = cx.add_window_view(|window, cx| {
1113            let view = cx.new(|cx| {
1114                let select = cx.new(|cx| {
1115                    SelectState::new(
1116                        [
1117                            SelectItem::new("en", "English"),
1118                            SelectItem::new("ko", "Korean"),
1119                        ],
1120                        cx,
1121                    )
1122                    .default_value("en")
1123                });
1124                cx.subscribe(&select, move |_, _, event: &SelectEvent, _| {
1125                    recorded.borrow_mut().push(event.clone());
1126                })
1127                .detach();
1128                let observation = cx.observe(&select, |_, _, cx| cx.notify());
1129                Harness {
1130                    select,
1131                    shown: true,
1132                    _observation: observation,
1133                }
1134            });
1135            Root::new(view, window, cx)
1136        });
1137        let view = root
1138            .read_with(cx, |root, _| root.view().clone())
1139            .downcast::<Harness>()
1140            .unwrap();
1141        let select = view.read_with(cx, |view, _| view.select.clone());
1142        cx.update(|window, cx| {
1143            window.activate_window();
1144            select.read(cx).focus_handle().clone().focus(window, cx);
1145            window.draw(cx).clear(cx);
1146        });
1147        cx.simulate_keystrokes("enter end");
1148        cx.update(|window, cx| {
1149            select.update(cx, |state, cx| {
1150                state.set_items(
1151                    [
1152                        SelectItem::new("ko", "한국어"),
1153                        SelectItem::new("en", "English"),
1154                        SelectItem::new("ja", "Japanese"),
1155                    ],
1156                    window,
1157                    cx,
1158                );
1159                assert_eq!(state.selected_index(), Some(1));
1160                assert_eq!(state.highlighted_index(), Some(0));
1161                assert!(state.content_focus_handle().is_focused(window));
1162            });
1163            window.draw(cx).clear(cx);
1164        });
1165        cx.simulate_keystrokes("enter");
1166        cx.update(|window, cx| {
1167            select.update(cx, |state, cx| {
1168                assert_eq!(state.selected_item().unwrap().label().as_ref(), "한국어");
1169                state.open(window, cx);
1170            });
1171        });
1172        cx.simulate_keystrokes("end");
1173        cx.update(|window, cx| {
1174            select.update(cx, |state, cx| {
1175                state.set_items(
1176                    [
1177                        SelectItem::new("en", "English"),
1178                        SelectItem::new("ko", "Korean"),
1179                        SelectItem::new("ja", "Japanese").disabled(true),
1180                    ],
1181                    window,
1182                    cx,
1183                );
1184                assert_eq!(state.highlighted_index(), state.selected_index());
1185                assert_eq!(state.highlighted_index(), Some(1));
1186                state.set_items([SelectItem::new("en", "English")], window, cx);
1187                assert!(state.selected_item().is_none());
1188                assert_eq!(state.highlighted_index(), Some(0));
1189                state.set_items(
1190                    [SelectItem::new("en", "English").disabled(true)],
1191                    window,
1192                    cx,
1193                );
1194                assert!(!state.is_open());
1195                assert!(state.focus_handle().is_focused(window));
1196                state.set_items([], window, cx);
1197                state.open(window, cx);
1198                assert!(!state.is_open());
1199                state.set_items(
1200                    [
1201                        SelectItem::new("en", "English"),
1202                        SelectItem::new("ko", "Korean"),
1203                    ],
1204                    window,
1205                    cx,
1206                );
1207                state.open(window, cx);
1208            });
1209            window.draw(cx).clear(cx);
1210        });
1211        // A press that starts on Korean cannot commit a different row that
1212        // replaces it before the pointer is released at the same coordinates.
1213        let option = cx.debug_bounds("option-1").unwrap().center();
1214        cx.simulate_mouse_down(option, MouseButton::Left, Modifiers::default());
1215        cx.update(|window, cx| {
1216            select.update(cx, |state, cx| {
1217                state.set_items(
1218                    [
1219                        SelectItem::new("en", "English"),
1220                        SelectItem::new("ja", "Japanese"),
1221                    ],
1222                    window,
1223                    cx,
1224                );
1225            });
1226            window.draw(cx).clear(cx);
1227        });
1228        cx.simulate_mouse_up(option, MouseButton::Left, Modifiers::default());
1229        cx.update(|_, cx| {
1230            assert!(select.read(cx).selected_item().is_none());
1231            assert!(select.read(cx).is_open());
1232        });
1233        assert_eq!(*changes.borrow(), [SelectEvent::Change("ko".into())]);
1234    }
1235
1236    #[gpui::test]
1237    fn trigger_toggle_and_host_unmount_clear_retained_popup(cx: &mut TestAppContext) {
1238        cx.update(crate::init);
1239        let (root, cx) = cx.add_window_view(|window, cx| {
1240            let view = cx.new(|cx| {
1241                let select = cx.new(|cx| SelectState::new([SelectItem::new("first", "First")], cx));
1242                let observation = cx.observe(&select, |_, _, cx| cx.notify());
1243                Harness {
1244                    select,
1245                    shown: true,
1246                    _observation: observation,
1247                }
1248            });
1249            Root::new(view, window, cx)
1250        });
1251        let view = root
1252            .read_with(cx, |root, _| root.view().clone())
1253            .downcast::<Harness>()
1254            .unwrap();
1255        cx.update(|window, cx| {
1256            window.activate_window();
1257            window.draw(cx).clear(cx);
1258        });
1259        let trigger = cx.debug_bounds("trigger").unwrap().center();
1260        cx.simulate_click(trigger, Modifiers::default());
1261        cx.update(|window, cx| window.draw(cx).clear(cx));
1262        cx.update(|_, cx| assert!(view.read(cx).select.read(cx).is_open()));
1263        cx.simulate_mouse_down(trigger, MouseButton::Left, Modifiers::default());
1264        cx.update(|window, cx| window.draw(cx).clear(cx));
1265        cx.simulate_mouse_up(trigger, MouseButton::Left, Modifiers::default());
1266        cx.update(|window, cx| window.draw(cx).clear(cx));
1267        cx.update(|_, cx| assert!(!view.read(cx).select.read(cx).is_open()));
1268
1269        cx.simulate_click(trigger, Modifiers::default());
1270        cx.update(|window, cx| window.draw(cx).clear(cx));
1271        cx.update(|_, cx| assert!(view.read(cx).select.read(cx).is_open()));
1272        view.update(cx, |view, cx| {
1273            view.shown = false;
1274            cx.notify();
1275        });
1276        cx.update(|window, cx| window.draw(cx).clear(cx));
1277        cx.run_until_parked();
1278        cx.update(|window, cx| window.draw(cx).clear(cx));
1279        cx.update(|window, cx| {
1280            let state = view.read(cx).select.read(cx);
1281            assert!(!state.is_open());
1282            assert!(!state.focus_handle().is_focused(window));
1283            assert!(!GlobalState::is_in_deferred_context(cx));
1284        });
1285    }
1286}