Skip to main content

gpui_base/
select.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ElementId, FocusHandle, InteractiveElement as _,
5    IntoElement, KeyBinding, ParentElement, RenderOnce, Role, SharedString,
6    StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
7    prelude::FluentBuilder as _,
8};
9
10use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
11use crate::{StyledExt as _, TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
12
13const CONTEXT: &str = "Select";
14
15#[doc(hidden)]
16pub fn init(cx: &mut App) {
17    cx.bind_keys([
18        KeyBinding::new(
19            "space",
20            Confirm { secondary: false },
21            Some("Select && !Input"),
22        ),
23        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
24        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
25        KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
26        KeyBinding::new(
27            if cx.platform_info().is_mac() {
28                "cmd-enter"
29            } else {
30                "ctrl-enter"
31            },
32            Confirm { secondary: true },
33            Some(CONTEXT),
34        ),
35        KeyBinding::new("escape", Cancel, Some(CONTEXT)),
36    ]);
37}
38
39type OpenChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
40type ActionHandler = Rc<dyn Fn(&mut Window, &mut App)>;
41
42/// An unstyled controlled select root.
43///
44/// Applications own the trigger and popup presentation, the option collection,
45/// and the selected value. This root owns combobox accessibility semantics,
46/// keyboard opening and dismissal, and focus transfer between the trigger and
47/// popup content.
48///
49/// GPUI marks the active option on the option element itself rather than on the
50/// container, so the application marks its highlighted option with
51/// `aria_active_descendant()`; this root cannot do it on the caller's behalf.
52#[derive(IntoElement)]
53pub struct Select {
54    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
55    open: bool,
56    disabled: bool,
57    focus_handle: Option<FocusHandle>,
58    content_focus_handle: Option<FocusHandle>,
59    accessibility_label: Option<SharedString>,
60    accessibility_value: Option<SharedString>,
61    style: StyleRefinement,
62    children: Vec<AnyElement>,
63    on_open_change: Option<OpenChangeHandler>,
64    key_context: &'static str,
65    on_dismiss: Option<ActionHandler>,
66    on_confirm: Option<ActionHandler>,
67}
68
69impl Select {
70    pub fn new(id: impl Into<ElementId>) -> Self {
71        Self {
72            base: div().id(id).test_support(),
73            open: false,
74            disabled: false,
75            focus_handle: None,
76            content_focus_handle: None,
77            accessibility_label: None,
78            accessibility_value: None,
79            style: StyleRefinement::default(),
80            children: Vec::new(),
81            on_open_change: None,
82            key_context: CONTEXT,
83            on_dismiss: None,
84            on_confirm: None,
85        }
86    }
87
88    /// Sets the application-controlled open state.
89    pub fn open(mut self, open: bool) -> Self {
90        self.open = open;
91        self
92    }
93
94    /// Prevents keyboard and accessible activation and removes the trigger from tab traversal.
95    pub fn disabled(mut self, disabled: bool) -> Self {
96        self.disabled = disabled;
97        self
98    }
99
100    /// Supplies the focus handle for the select trigger.
101    pub fn focus_handle(mut self, focus_handle: &FocusHandle) -> Self {
102        self.focus_handle = Some(focus_handle.clone());
103        self
104    }
105
106    /// Supplies the focus handle that receives keyboard navigation while open.
107    pub fn content_focus_handle(mut self, focus_handle: &FocusHandle) -> Self {
108        self.content_focus_handle = Some(focus_handle.clone());
109        self
110    }
111
112    /// Sets the accessible name exposed by the controlled root.
113    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
114        self.accessibility_label = Some(label.into());
115        self
116    }
117
118    /// Sets the committed value exposed by the controlled root.
119    ///
120    /// Supply a readable selection title, not the current search query or cursor.
121    pub fn accessibility_value(mut self, value: impl Into<SharedString>) -> Self {
122        self.accessibility_value = Some(value.into());
123        self
124    }
125
126    /// Handles requests to update the controlled open state.
127    pub fn on_open_change(
128        mut self,
129        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
130    ) -> Self {
131        self.on_open_change = Some(Rc::new(handler));
132        self
133    }
134
135    #[doc(hidden)]
136    pub fn key_context(mut self, key_context: &'static str) -> Self {
137        self.key_context = key_context;
138        self
139    }
140
141    /// Handles a dismissal, however it was requested: the Cancel action, or
142    /// the accessible activation that closes an open control.
143    ///
144    /// This runs before the controlled open state is asked to close, so a
145    /// caller that commits its pending value on dismissal can still read that
146    /// value here.
147    pub fn on_dismiss(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
148        self.on_dismiss = Some(Rc::new(handler));
149        self
150    }
151
152    /// Handles the Confirm action while the select is open.
153    ///
154    /// Confirming a closed select opens it instead, so this never runs for
155    /// that case.
156    pub fn on_confirm(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
157        self.on_confirm = Some(Rc::new(handler));
158        self
159    }
160}
161
162impl Styled for Select {
163    fn style(&mut self) -> &mut StyleRefinement {
164        &mut self.style
165    }
166}
167
168impl ParentElement for Select {
169    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
170        self.children.extend(elements);
171    }
172}
173
174impl RenderOnce for Select {
175    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
176        let open = self.open;
177        let disabled = self.disabled;
178        let focus_handle = self.focus_handle;
179        let content_focus_handle = self.content_focus_handle;
180        let on_open_change = self.on_open_change;
181        let on_dismiss = self.on_dismiss;
182        let on_confirm = self.on_confirm;
183
184        // Every way of closing runs the same steps. A caller that tracks
185        // dismissal has to see one however the popup was closed, and the
186        // accessible activation closes exactly what Escape closes.
187        let close: ActionHandler = Rc::new({
188            let on_open_change = on_open_change.clone();
189            let on_dismiss = on_dismiss.clone();
190            let focus_handle = focus_handle.clone();
191            move |window: &mut Window, cx: &mut App| {
192                if let Some(handler) = on_dismiss.as_ref() {
193                    handler(window, cx);
194                }
195                if let Some(handler) = on_open_change.as_ref() {
196                    handler(false, window, cx);
197                }
198                if let Some(handle) = focus_handle.as_ref() {
199                    handle.focus(window, cx);
200                }
201            }
202        });
203
204        #[expect(
205            clippy::redundant_clone,
206            reason = "FocusHandle::clone refreshes tab metadata from the focus map"
207        )]
208        let focus_handle = focus_handle.clone().filter(|_| !disabled);
209
210        self.base
211            .role(Role::ComboBox)
212            .aria_expanded(open)
213            .when_some(self.accessibility_label, |this, label| {
214                this.aria_label(label)
215            })
216            .when_some(self.accessibility_value, |this, value| {
217                this.aria_value(value)
218            })
219            .key_context(self.key_context)
220            .when_some(focus_handle, |this, handle| {
221                this.track_focus(&handle.tab_stop(true))
222            })
223            .when(!disabled, |this| {
224                let on_open_change = on_open_change.clone();
225                let content_focus_handle = content_focus_handle.clone();
226                let close = close.clone();
227
228                // Platform adapters may flatten the trigger child.
229                // Expose activation on the semantic root itself.
230                this.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
231                    if open {
232                        close(window, cx);
233                        return;
234                    }
235
236                    if let Some(handler) = on_open_change.as_ref() {
237                        handler(true, window, cx);
238                    }
239                    if let Some(handle) = content_focus_handle.as_ref() {
240                        handle.focus(window, cx);
241                    }
242                })
243            })
244            .on_action({
245                let on_open_change = on_open_change.clone();
246                let content_focus_handle = content_focus_handle.clone();
247                move |_: &SelectUp, window, cx| {
248                    if disabled {
249                        cx.propagate();
250                        return;
251                    }
252
253                    if !open {
254                        if let Some(handler) = on_open_change.as_ref() {
255                            handler(true, window, cx);
256                        }
257                    }
258
259                    if let Some(handle) = content_focus_handle.as_ref() {
260                        handle.focus(window, cx);
261                    }
262                    cx.propagate();
263                }
264            })
265            .on_action({
266                let on_open_change = on_open_change.clone();
267                let content_focus_handle = content_focus_handle.clone();
268                move |_: &SelectDown, window, cx| {
269                    if disabled {
270                        cx.propagate();
271                        return;
272                    }
273
274                    if !open {
275                        if let Some(handler) = on_open_change.as_ref() {
276                            handler(true, window, cx);
277                        }
278                    }
279
280                    if let Some(handle) = content_focus_handle.as_ref() {
281                        handle.focus(window, cx);
282                    }
283                    cx.propagate();
284                }
285            })
286            .on_action({
287                let on_open_change = on_open_change.clone();
288                move |_: &Confirm, window, cx| {
289                    if disabled {
290                        cx.propagate();
291                        return;
292                    }
293
294                    if open {
295                        if let Some(handler) = on_confirm.as_ref() {
296                            handler(window, cx);
297                        }
298                    } else if let Some(handler) = on_open_change.as_ref() {
299                        handler(true, window, cx);
300                    }
301
302                    if let Some(handle) = content_focus_handle.as_ref() {
303                        handle.focus(window, cx);
304                    }
305                }
306            })
307            .on_action(move |_: &Cancel, window, cx| {
308                if !open {
309                    cx.propagate();
310                    return;
311                }
312
313                cx.stop_propagation();
314                close(window, cx);
315            })
316            .children(self.children)
317            .refine_style(&self.style)
318            .a11y_disabled(disabled)
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use crate::input::InputState;
326    use gpui::{
327        AppContext as _, Context, Element as _, Entity, Focusable, Render, TestAppContext,
328        VisualTestContext, accesskit, px,
329    };
330    use std::sync::{Arc, Mutex};
331
332    struct SelectHarness {
333        open: bool,
334        disabled: bool,
335        focus_handle: FocusHandle,
336        content_focus_handle: FocusHandle,
337        search_input: Option<Entity<InputState>>,
338        changes: Arc<Mutex<Vec<bool>>>,
339        parent_confirms: Arc<Mutex<usize>>,
340        confirmations: Arc<Mutex<usize>>,
341        /// Every step of a close, in the order it ran.
342        closing: Arc<Mutex<Vec<&'static str>>>,
343    }
344
345    impl SelectHarness {
346        fn new(disabled: bool, cx: &mut Context<Self>) -> Self {
347            Self {
348                open: false,
349                disabled,
350                focus_handle: cx.focus_handle(),
351                content_focus_handle: cx.focus_handle(),
352                search_input: None,
353                changes: Arc::new(Mutex::new(Vec::new())),
354                closing: Arc::new(Mutex::new(Vec::new())),
355                parent_confirms: Arc::new(Mutex::new(0)),
356                confirmations: Arc::new(Mutex::new(0)),
357            }
358        }
359    }
360
361    impl Focusable for SelectHarness {
362        fn focus_handle(&self, _: &App) -> FocusHandle {
363            self.focus_handle.clone()
364        }
365    }
366
367    impl Render for SelectHarness {
368        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
369            let state = cx.entity();
370            let changes = self.changes.clone();
371            let opened = self.closing.clone();
372            let dismissed = self.closing.clone();
373            let confirmed = self.closing.clone();
374
375            let parent_confirms = self.parent_confirms.clone();
376            let confirmations = self.confirmations.clone();
377            div()
378                .on_action(move |_: &Confirm, _, _| *parent_confirms.lock().unwrap() += 1)
379                .child(
380                    Select::new("select")
381                        .open(self.open)
382                        .disabled(self.disabled)
383                        .focus_handle(&self.focus_handle)
384                        .content_focus_handle(&self.content_focus_handle)
385                        .on_open_change(move |open, _, cx| {
386                            changes.lock().unwrap().push(open);
387                            opened
388                                .lock()
389                                .unwrap()
390                                .push(if open { "open" } else { "close" });
391                            state.update(cx, |state, cx| {
392                                state.open = open;
393                                cx.notify();
394                            });
395                        })
396                        .on_dismiss(move |_, _| dismissed.lock().unwrap().push("dismiss"))
397                        .on_confirm(move |_, _| {
398                            confirmed.lock().unwrap().push("confirm");
399                            *confirmations.lock().unwrap() += 1;
400                        })
401                        .when_some(self.search_input.clone(), |this, input| {
402                            this.child(crate::Input::new(&input))
403                        })
404                        .when(self.search_input.is_none(), |this| {
405                            this.child(div().track_focus(&self.content_focus_handle).size(px(20.)))
406                        }),
407                )
408        }
409    }
410
411    fn harness(
412        cx: &mut TestAppContext,
413        disabled: bool,
414    ) -> (&mut VisualTestContext, gpui::Entity<SelectHarness>) {
415        cx.update(crate::init);
416        let (state, cx) = cx.add_window_view(move |_, cx| SelectHarness::new(disabled, cx));
417        cx.update(|window, cx| {
418            state.focus_handle(cx).focus(window, cx);
419            window.draw(cx).clear(cx);
420        });
421        (cx, state)
422    }
423
424    #[gpui::test]
425    fn arrows_open_and_transfer_focus_to_content(cx: &mut TestAppContext) {
426        let (cx, state) = harness(cx, false);
427
428        cx.simulate_keystrokes("down");
429        cx.update(|window, cx| {
430            assert!(state.read(cx).open);
431            assert!(state.read(cx).content_focus_handle.is_focused(window));
432        });
433        assert_eq!(
434            &*state
435                .read_with(cx, |state, _| state.changes.clone())
436                .lock()
437                .unwrap(),
438            &[true]
439        );
440    }
441
442    #[gpui::test]
443    fn confirm_opens_a_closed_select(cx: &mut TestAppContext) {
444        let (cx, state) = harness(cx, false);
445
446        cx.simulate_keystrokes("enter");
447        cx.update(|window, cx| {
448            assert!(state.read(cx).open);
449            assert!(state.read(cx).content_focus_handle.is_focused(window));
450        });
451    }
452
453    #[gpui::test]
454    fn space_opens_and_confirms_a_non_searchable_select(cx: &mut TestAppContext) {
455        let (cx, state) = harness(cx, false);
456        cx.simulate_keystrokes("space");
457        cx.update(|window, cx| {
458            assert!(state.read(cx).open);
459            assert!(state.read(cx).content_focus_handle.is_focused(window));
460            window.draw(cx).clear(cx);
461        });
462        cx.simulate_keystrokes("space");
463        assert_eq!(
464            &*state
465                .read_with(cx, |state, _| state.closing.clone())
466                .lock()
467                .unwrap(),
468            &["open", "confirm"]
469        );
470    }
471
472    #[gpui::test]
473    fn space_in_a_select_search_input_remains_text(cx: &mut TestAppContext) {
474        let (cx, state) = harness(cx, false);
475        let input = cx.update(|window, cx| {
476            let input = cx.new(|cx| InputState::new(window, cx));
477            state.update(cx, |state, cx| {
478                state.content_focus_handle = input.focus_handle(cx);
479                state.search_input = Some(input.clone());
480                cx.notify();
481            });
482            window.draw(cx).clear(cx);
483            input
484        });
485        cx.simulate_keystrokes("space");
486        cx.update(|window, cx| {
487            assert!(state.read(cx).open);
488            assert!(input.focus_handle(cx).is_focused(window));
489            window.draw(cx).clear(cx);
490        });
491        cx.simulate_keystrokes("t w o space w o r d s");
492        assert_eq!(input.read_with(cx, |input, _| input.value()), "two words");
493        assert_eq!(
494            &*state
495                .read_with(cx, |state, _| state.closing.clone())
496                .lock()
497                .unwrap(),
498            &["open"]
499        );
500        assert!(state.read_with(cx, |state, _| state.open));
501    }
502
503    #[gpui::test]
504    fn escape_closes_and_restores_trigger_focus(cx: &mut TestAppContext) {
505        let (cx, state) = harness(cx, false);
506
507        cx.simulate_keystrokes("down escape");
508        cx.update(|window, cx| {
509            assert!(!state.read(cx).open);
510            assert!(state.read(cx).focus_handle.is_focused(window));
511        });
512        assert_eq!(
513            &*state
514                .read_with(cx, |state, _| state.changes.clone())
515                .lock()
516                .unwrap(),
517            &[true, false]
518        );
519    }
520
521    /// Closing runs `on_dismiss`, and runs it before the open state is asked
522    /// to close, so a caller that commits a pending value on dismissal can
523    /// still read that value.
524    ///
525    /// Every close shares one path, which is the point: the accessible
526    /// activation used to close by calling `on_open_change` alone, so a
527    /// consumer wiring `on_dismiss` — `crates/shell` forwards it to JS as
528    /// `onDismiss` — saw Escape but not a screen reader pressing the same
529    /// control. GPUI exposes no way to dispatch an accessibility action in a
530    /// test (`Window::handle_a11y_action` is `pub(crate)`), so this covers the
531    /// shared path through the route a test can reach.
532    #[gpui::test]
533    fn every_close_dismisses_before_it_closes(cx: &mut TestAppContext) {
534        let (cx, state) = harness(cx, false);
535
536        cx.simulate_keystrokes("down escape");
537        assert_eq!(
538            &*state
539                .read_with(cx, |state, _| state.closing.clone())
540                .lock()
541                .unwrap(),
542            &["open", "dismiss", "close"]
543        );
544    }
545
546    #[gpui::test]
547    fn disabled_select_is_not_keyboard_interactive(cx: &mut TestAppContext) {
548        let (cx, state) = harness(cx, true);
549
550        cx.simulate_keystrokes("down enter space");
551        assert!(!state.read_with(cx, |state, _| state.open));
552        assert!(
553            state
554                .read_with(cx, |state, _| state.changes.clone())
555                .lock()
556                .unwrap()
557                .is_empty()
558        );
559    }
560
561    #[gpui::test]
562    fn projects_application_owned_accessible_state(cx: &mut TestAppContext) {
563        let window = cx.add_empty_window();
564        window.update(|window, cx| {
565            let mut info = |select: Select| {
566                let mut node = accesskit::Node::new(Role::ComboBox);
567                select
568                    .render(window, cx)
569                    .into_element()
570                    .write_a11y_info(&mut node);
571                node
572            };
573            let enabled = info(
574                Select::new("enabled")
575                    .open(true)
576                    .accessibility_label("Programming language")
577                    .accessibility_value("Rust"),
578            );
579            // Open, so the expanded assertion below says something about
580            // `disabled` rather than about the default open state.
581            let disabled = info(Select::new("disabled").open(true).disabled(true));
582
583            assert_eq!(enabled.label(), Some("Programming language"));
584            assert_eq!(enabled.value(), Some("Rust"));
585            assert_eq!(enabled.is_expanded(), Some(true));
586            assert_eq!(
587                disabled.is_expanded(),
588                Some(true),
589                "a disabled control still reports the state it is in"
590            );
591            assert!(enabled.supports_action(accesskit::Action::Click));
592            assert!(!disabled.supports_action(accesskit::Action::Click));
593        });
594    }
595
596    #[gpui::test]
597    fn confirm_is_consumed_when_opening_and_accepting(cx: &mut TestAppContext) {
598        let (cx, state) = harness(cx, false);
599        cx.simulate_keystrokes("enter");
600        cx.update(|window, cx| window.draw(cx).clear(cx));
601        cx.simulate_keystrokes("enter");
602        state.read_with(cx, |state, _| {
603            assert!(state.open);
604            assert_eq!(*state.confirmations.lock().unwrap(), 1);
605            assert_eq!(*state.parent_confirms.lock().unwrap(), 0);
606        });
607    }
608}