Skip to main content

fc_ui/capabilities/controls/
select.rs

1//! Select component - Dropdown select with keyboard navigation.
2
3use crate::capabilities::foundation::theme::use_theme;
4use crate::capabilities::primitives::icon::Icon;
5use crate::capabilities::primitives::icon_source::IconSource;
6use crate::capabilities::scroll::scrollable::scrollable_vertical;
7use gpui::{prelude::*, *};
8
9actions!(select, [SelectUp, SelectDown, SelectConfirm, SelectCancel]);
10
11#[cfg(test)]
12fn with_test_selector<E: InteractiveElement>(element: E, selector: &'static str) -> E {
13    element.debug_selector(move || selector.into())
14}
15
16#[cfg(not(test))]
17fn with_test_selector<E>(element: E, _selector: &'static str) -> E {
18    element
19}
20
21#[derive(Clone, Debug)]
22pub enum SelectEvent {
23    Change,
24}
25
26#[derive(Clone)]
27pub struct SelectOption<T: Clone> {
28    pub value: T,
29    pub label: SharedString,
30    pub group: Option<SharedString>,
31    pub icon: Option<IconSource>,
32}
33
34impl<T: Clone> SelectOption<T> {
35    pub fn new(value: T, label: impl Into<SharedString>) -> Self {
36        Self {
37            value,
38            label: label.into(),
39            group: None,
40            icon: None,
41        }
42    }
43
44    pub fn with_group(mut self, group: impl Into<SharedString>) -> Self {
45        self.group = Some(group.into());
46        self
47    }
48
49    pub fn with_icon(mut self, icon: impl Into<IconSource>) -> Self {
50        self.icon = Some(icon.into());
51        self
52    }
53}
54
55pub struct Select<T: Clone + 'static> {
56    focus_handle: FocusHandle,
57    options: Vec<SelectOption<T>>,
58    selected_index: Option<usize>,
59    highlighted_index: Option<usize>,
60    placeholder: Option<SharedString>,
61    open: bool,
62    disabled: bool,
63    searchable: bool,
64    clearable: bool,
65    loading: bool,
66    search_query: String,
67    on_change: Option<Box<dyn Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>>,
68    on_clear: Option<Box<dyn Fn(&mut Window, &mut App) + Send + Sync + 'static>>,
69    bounds: Bounds<Pixels>,
70    leading_icon: Option<IconSource>,
71    aria_label: Option<SharedString>,
72    style: StyleRefinement,
73}
74
75impl<T: Clone + 'static> Select<T> {
76    /// Dropdown overlay for the open state: the shared anchored shell
77    /// wrapping the searchable option listbox.
78    fn render_dropdown(
79        &self,
80        cx: &mut Context<Self>,
81        theme: &crate::capabilities::foundation::theme::Theme,
82        bounds: Bounds<Pixels>,
83    ) -> impl IntoElement {
84        let highlighted_idx = self.highlighted_index;
85        let search_query: SharedString = self.search_query.clone().into();
86        let searchable = self.searchable;
87
88        crate::capabilities::controls::anchored_dropdown(
89            bounds.size.width,
90            theme,
91            with_test_selector(
92                div().id("select-listbox").role(Role::ListBox),
93                "select-dropdown",
94            )
95            .flex()
96            .flex_col()
97            .when(searchable, |this| {
98                this.child(
99                    div()
100                        .px(px(12.0))
101                        .pt(px(8.0))
102                        .pb(px(4.0))
103                        .border_b_1()
104                        .border_color(theme.tokens.border)
105                        .child(
106                            div()
107                                .w_full()
108                                .h(px(32.0))
109                                .px(px(8.0))
110                                .flex()
111                                .items_center()
112                                .bg(theme.tokens.background)
113                                .border_1()
114                                .border_color(theme.tokens.input)
115                                .rounded(theme.tokens.radius_sm)
116                                .text_size(px(13.0))
117                                .font_family(theme.tokens.font_family.clone())
118                                .text_color(if search_query.is_empty() {
119                                    theme.tokens.muted_foreground
120                                } else {
121                                    theme.tokens.foreground
122                                })
123                                .child(if search_query.is_empty() {
124                                    SharedString::from("Type to search...")
125                                } else {
126                                    search_query.clone()
127                                }),
128                        ),
129                )
130            })
131            .child(div().max_h(px(300.0)).child(scrollable_vertical({
132                let filtered = self.filtered_options();
133                let loading = self.loading;
134
135                div()
136                    .py(px(4.0))
137                    .when(loading, |this| {
138                        this.child(
139                            div()
140                                .px(px(12.0))
141                                .py(px(16.0))
142                                .flex()
143                                .items_center()
144                                .justify_center()
145                                .gap(px(8.0))
146                                .text_size(px(13.0))
147                                .font_family(theme.tokens.font_family.clone())
148                                .text_color(theme.tokens.muted_foreground)
149                                .child(
150                                    div()
151                                        .text_size(px(18.0))
152                                        .text_color(theme.tokens.primary)
153                                        .child("⟳"),
154                                )
155                                .child("Loading options..."),
156                        )
157                    })
158                    .when(!loading && filtered.is_empty(), |this| {
159                        this.child(
160                            div()
161                                .px(px(12.0))
162                                .py(px(16.0))
163                                .flex()
164                                .items_center()
165                                .justify_center()
166                                .text_size(px(13.0))
167                                .font_family(theme.tokens.font_family.clone())
168                                .text_color(theme.tokens.muted_foreground)
169                                .child("No results found"),
170                        )
171                    })
172                    .when(!loading && !filtered.is_empty(), |this| {
173                        let mut current_group: Option<SharedString> = None;
174                        this.children(filtered.iter().flat_map(|(index, option)| {
175                            let mut elements = Vec::new();
176
177                            if option.group != current_group {
178                                current_group = option.group.clone();
179                                if let Some(group_name) = &option.group {
180                                    elements.push(
181                                        div()
182                                            .px(px(12.0))
183                                            .pt(px(12.0))
184                                            .pb(px(4.0))
185                                            .text_size(px(11.0))
186                                            .font_family(theme.tokens.font_family.clone())
187                                            .font_weight(FontWeight::SEMIBOLD)
188                                            .text_color(theme.tokens.muted_foreground)
189                                            .child(group_name.clone())
190                                            .into_any_element(),
191                                    );
192                                }
193                            }
194
195                            let is_selected = self.selected_index == Some(*index);
196                            let is_highlighted = highlighted_idx == Some(*index);
197                            let index = *index;
198                            let option_for_a11y = cx.entity().clone();
199
200                            elements.push(
201                                div()
202                                    .id(("select-option", index))
203                                    .role(Role::ListBoxOption)
204                                    .aria_label(option.label.clone())
205                                    .aria_selected(is_selected)
206                                    .px(px(12.0))
207                                    .py(px(8.0))
208                                    .text_color(if is_selected {
209                                        theme.tokens.primary
210                                    } else {
211                                        theme.tokens.popover_foreground
212                                    })
213                                    .bg(if is_highlighted {
214                                        theme.tokens.accent
215                                    } else {
216                                        gpui::transparent_black()
217                                    })
218                                    .hover(|mut style| {
219                                        style.background = Some(theme.tokens.accent.into());
220                                        style
221                                    })
222                                    .cursor(CursorStyle::PointingHand)
223                                    .text_size(px(14.0))
224                                    .font_family(theme.tokens.font_family.clone())
225                                    .on_mouse_down(
226                                        MouseButton::Left,
227                                        cx.listener(move |this, _, window, cx| {
228                                            this.select_option(index, window, cx);
229                                        }),
230                                    )
231                                    .on_a11y_action(
232                                        AccessibleAction::Click,
233                                        move |_, window, cx| {
234                                            option_for_a11y.update(cx, |select, cx| {
235                                                select.select_option(index, window, cx);
236                                            });
237                                        },
238                                    )
239                                    .child(
240                                        div()
241                                            .flex()
242                                            .items_center()
243                                            .gap(px(8.0))
244                                            .when_some(option.icon.as_ref(), |div, src| {
245                                                div.child(
246                                                    Icon::new(src.clone())
247                                                        .size(px(14.0))
248                                                        .color(theme.tokens.muted_foreground),
249                                                )
250                                            })
251                                            .child(option.label.clone()),
252                                    )
253                                    .into_any_element(),
254                            );
255
256                            elements
257                        }))
258                    })
259            }))),
260        )
261    }
262
263    pub fn new(cx: &mut Context<Self>) -> Self {
264        Self {
265            focus_handle: cx.focus_handle(),
266            options: Vec::new(),
267            selected_index: None,
268            highlighted_index: None,
269            placeholder: None,
270            open: false,
271            disabled: false,
272            searchable: false,
273            clearable: false,
274            loading: false,
275            search_query: String::new(),
276            on_change: None,
277            on_clear: None,
278            bounds: Bounds::default(),
279            leading_icon: None,
280            aria_label: None,
281            style: StyleRefinement::default(),
282        }
283    }
284
285    pub fn options(mut self, options: Vec<SelectOption<T>>) -> Self {
286        self.options = options;
287        self
288    }
289
290    pub fn selected_index(mut self, index: Option<usize>) -> Self {
291        self.selected_index = index;
292        self.highlighted_index = index;
293        self
294    }
295
296    pub fn placeholder<S: Into<SharedString>>(mut self, placeholder: S) -> Self {
297        self.placeholder = Some(placeholder.into());
298        self
299    }
300
301    pub fn disabled(mut self, disabled: bool) -> Self {
302        self.disabled = disabled;
303        self
304    }
305
306    pub fn searchable(mut self, searchable: bool) -> Self {
307        self.searchable = searchable;
308        self
309    }
310
311    pub fn clearable(mut self, clearable: bool) -> Self {
312        self.clearable = clearable;
313        self
314    }
315
316    pub fn loading(mut self, loading: bool) -> Self {
317        self.loading = loading;
318        self
319    }
320
321    pub fn on_change<F: Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>(
322        mut self,
323        f: F,
324    ) -> Self {
325        self.on_change = Some(Box::new(f));
326        self
327    }
328
329    /// Set a callback invoked when the current selection is cleared.
330    pub fn on_clear<F: Fn(&mut Window, &mut App) + Send + Sync + 'static>(mut self, f: F) -> Self {
331        self.on_clear = Some(Box::new(f));
332        self
333    }
334
335    pub fn leading_icon(mut self, icon: impl Into<IconSource>) -> Self {
336        self.leading_icon = Some(icon.into());
337        self
338    }
339
340    /// Set the field name announced by assistive technology.
341    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
342        self.aria_label = Some(label.into());
343        self
344    }
345
346    pub fn selected_value(&self) -> Option<&T> {
347        self.selected_index
348            .and_then(|i| self.options.get(i))
349            .map(|opt| &opt.value)
350    }
351
352    pub fn selected_label(&self) -> Option<&SharedString> {
353        self.selected_index
354            .and_then(|i| self.options.get(i))
355            .map(|opt| &opt.label)
356    }
357
358    fn filtered_options(&self) -> Vec<(usize, &SelectOption<T>)> {
359        if self.search_query.is_empty() {
360            self.options.iter().enumerate().collect()
361        } else {
362            let query_lower = self.search_query.to_lowercase();
363            self.options
364                .iter()
365                .enumerate()
366                .filter(|(_, opt)| opt.label.to_lowercase().contains(&query_lower))
367                .collect()
368        }
369    }
370
371    fn toggle_dropdown(&mut self, window: &mut Window, cx: &mut Context<Self>) {
372        if !self.disabled {
373            self.open = !self.open;
374            if self.open {
375                window.focus(&self.focus_handle);
376                self.highlighted_index = self.selected_index.or(Some(0));
377            }
378            cx.notify();
379        }
380    }
381
382    fn close_dropdown(&mut self, cx: &mut Context<Self>) {
383        self.open = false;
384        self.highlighted_index = self.selected_index;
385        self.search_query.clear();
386        cx.notify();
387    }
388
389    fn clear_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
390        self.selected_index = None;
391        self.highlighted_index = None;
392
393        cx.emit(SelectEvent::Change);
394        cx.notify();
395
396        if let Some(ref cb) = self.on_clear {
397            (cb)(window, cx);
398        }
399    }
400
401    fn select_option(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
402        if index < self.options.len() {
403            self.selected_index = Some(index);
404            self.highlighted_index = Some(index);
405            self.open = false;
406
407            cx.emit(SelectEvent::Change);
408            cx.notify();
409
410            if let Some(ref cb) = self.on_change {
411                if let Some(option) = self.options.get(index) {
412                    (cb)(&option.value, window, cx);
413                }
414            }
415        }
416    }
417
418    fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
419        if !self.open {
420            return;
421        }
422
423        let filtered = self.filtered_options();
424        if filtered.is_empty() {
425            return;
426        }
427
428        let current_pos = self
429            .highlighted_index
430            .and_then(|idx| filtered.iter().position(|(orig_idx, _)| *orig_idx == idx));
431
432        let new_pos = match current_pos {
433            Some(0) => filtered.len() - 1,
434            Some(pos) => pos - 1,
435            None => filtered.len() - 1,
436        };
437
438        self.highlighted_index = Some(filtered[new_pos].0);
439        cx.notify();
440    }
441
442    fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
443        if !self.open {
444            return;
445        }
446
447        let filtered = self.filtered_options();
448        if filtered.is_empty() {
449            return;
450        }
451
452        let current_pos = self
453            .highlighted_index
454            .and_then(|idx| filtered.iter().position(|(orig_idx, _)| *orig_idx == idx));
455
456        let new_pos = match current_pos {
457            Some(pos) if pos < filtered.len() - 1 => pos + 1,
458            Some(_) => 0,
459            None => 0,
460        };
461
462        self.highlighted_index = Some(filtered[new_pos].0);
463        cx.notify();
464    }
465
466    fn select_confirm(&mut self, _: &SelectConfirm, window: &mut Window, cx: &mut Context<Self>) {
467        if self.open {
468            if let Some(idx) = self.highlighted_index {
469                self.select_option(idx, window, cx);
470            }
471        } else {
472            self.toggle_dropdown(window, cx);
473        }
474    }
475
476    fn select_cancel(&mut self, _: &SelectCancel, _: &mut Window, cx: &mut Context<Self>) {
477        if self.open {
478            self.close_dropdown(cx);
479        }
480    }
481}
482
483impl<T: Clone + 'static> Styled for Select<T> {
484    fn style(&mut self) -> &mut StyleRefinement {
485        &mut self.style
486    }
487}
488
489impl<T: Clone + 'static> Render for Select<T> {
490    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
491        let theme = use_theme(cx);
492        let user_style = self.style.clone();
493
494        let selected_label = self.selected_label().cloned();
495        let placeholder = self
496            .placeholder
497            .clone()
498            .unwrap_or_else(|| "Select...".into());
499        let display_text = selected_label
500            .clone()
501            .unwrap_or_else(|| placeholder.clone());
502
503        let open = self.open;
504        let bounds = self.bounds;
505        let aria_label = self.aria_label.clone();
506        let focus_handle = self.focus_handle.clone().tab_index(0).tab_stop(true);
507
508        let maybe_selected_icon: Option<IconSource> = self
509            .selected_index
510            .and_then(|i| self.options.get(i))
511            .and_then(|opt| opt.icon.clone());
512        let leading_icon = self.leading_icon.clone().or(maybe_selected_icon);
513        let entity_for_a11y_expand = cx.entity().clone();
514        let entity_for_a11y_collapse = cx.entity().clone();
515
516        let trigger = div()
517            .id("select-trigger")
518            .role(Role::ComboBox)
519            .when_some(aria_label, |this, label| this.aria_label(label))
520            .when_some(selected_label, |this, value| this.aria_value(value))
521            .aria_placeholder(placeholder)
522            .aria_expanded(open)
523            .aria_disabled(self.disabled)
524            .when(!self.disabled, |this| this.track_focus(&focus_handle))
525            .relative()
526            .flex()
527            .items_center()
528            .justify_between()
529            .h(px(40.0))
530            .px(px(12.0))
531            .bg(theme.tokens.background)
532            .border_1()
533            .border_color(if open {
534                theme.tokens.ring
535            } else {
536                theme.tokens.input
537            })
538            .rounded(theme.tokens.radius_md)
539            .text_color(if self.selected_index.is_some() {
540                theme.tokens.foreground
541            } else {
542                theme.tokens.muted_foreground
543            })
544            .text_size(px(14.0))
545            .font_family(theme.tokens.font_family.clone())
546            .cursor(if self.disabled {
547                CursorStyle::Arrow
548            } else {
549                CursorStyle::PointingHand
550            })
551            .when(!self.disabled, |div: Stateful<Div>| {
552                div.hover(|mut style| {
553                    style.border_color = Some(theme.tokens.ring);
554                    style
555                })
556            })
557            .on_mouse_down(
558                MouseButton::Left,
559                cx.listener(|this, _, window, cx| {
560                    this.toggle_dropdown(window, cx);
561                }),
562            )
563            .on_a11y_action(AccessibleAction::Expand, move |_, window, cx| {
564                entity_for_a11y_expand.update(cx, |select, cx| {
565                    if !select.open {
566                        select.toggle_dropdown(window, cx);
567                    }
568                });
569            })
570            .on_a11y_action(AccessibleAction::Collapse, move |_, _, cx| {
571                entity_for_a11y_collapse.update(cx, |select, cx| {
572                    if select.open {
573                        select.close_dropdown(cx);
574                    }
575                });
576            })
577            .child(
578                div()
579                    .flex()
580                    .items_center()
581                    .gap(px(8.0))
582                    .when_some(leading_icon.as_ref(), |div, src| {
583                        div.child(
584                            Icon::new(src.clone())
585                                .size(px(14.0))
586                                .color(theme.tokens.muted_foreground),
587                        )
588                    })
589                    .child(display_text),
590            )
591            .child(
592                div()
593                    .ml(px(8.0))
594                    .flex()
595                    .items_center()
596                    .justify_center()
597                    .child(
598                        if self.clearable && self.selected_index.is_some() && !self.disabled {
599                            div()
600                                .w(px(20.0))
601                                .h(px(20.0))
602                                .flex()
603                                .items_center()
604                                .justify_center()
605                                .rounded(px(10.0))
606                                .cursor(CursorStyle::PointingHand)
607                                .hover(|mut style| {
608                                    style.background = Some(theme.tokens.muted.into());
609                                    style
610                                })
611                                .on_mouse_down(
612                                    MouseButton::Left,
613                                    cx.listener(|this, _event: &MouseDownEvent, window, cx| {
614                                        cx.stop_propagation();
615                                        this.clear_selection(window, cx);
616                                    }),
617                                )
618                                .child(
619                                    Icon::new("x")
620                                        .size(px(14.0))
621                                        .color(theme.tokens.muted_foreground),
622                                )
623                                .into_any_element()
624                        } else {
625                            div()
626                                .flex()
627                                .items_center()
628                                .justify_center()
629                                .child(
630                                    Icon::new(if open { "arrow-up" } else { "arrow-down" })
631                                        .size(px(14.0))
632                                        .color(theme.tokens.muted_foreground),
633                                )
634                                .into_any_element()
635                        },
636                    ),
637            )
638            .child({
639                let entity = cx.entity().clone();
640                canvas(
641                    move |bounds, _, cx| {
642                        entity.update(cx, |this, _| {
643                            this.bounds = bounds;
644                        })
645                    },
646                    |_, _, _, _| {},
647                )
648                .absolute()
649                .size_full()
650            });
651        let trigger = with_test_selector(trigger, "select-trigger");
652
653        let searchable = self.searchable;
654
655        div()
656            .relative()
657            .w_full()
658            .key_context("Select")
659            .when(open && !self.disabled, |this: Div| {
660                this.on_action(cx.listener(Select::select_up))
661                    .on_action(cx.listener(Select::select_down))
662                    .on_action(cx.listener(Select::select_confirm))
663                    .on_action(cx.listener(Select::select_cancel))
664            })
665            .when(open && searchable, |this: Div| {
666                this.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
667                    if event.keystroke.key == "backspace" {
668                        this.search_query.pop();
669                        cx.notify();
670                    } else if let Some(text) = &event.keystroke.key_char {
671                        this.search_query.push_str(text);
672                        let filtered = this.filtered_options();
673                        if !filtered.is_empty() {
674                            this.highlighted_index = Some(filtered[0].0);
675                        }
676                        cx.notify();
677                    }
678                }))
679            })
680            .on_mouse_down_out(cx.listener(|this, _, _, cx| {
681                if this.open {
682                    this.close_dropdown(cx);
683                }
684            }))
685            .child(trigger)
686            .when(open, |this| {
687                this.child(self.render_dropdown(cx, &theme, bounds))
688            })
689            .map(|this| {
690                let mut div = this;
691                div.style().refine(&user_style);
692                div
693            })
694    }
695}
696
697/// Initialize select key bindings
698pub fn init_select(cx: &mut App) {
699    if !crate::capabilities::foundation::initialization::begin(cx, "select") {
700        return;
701    }
702    cx.bind_keys([
703        KeyBinding::new("up", SelectUp, Some("Select")),
704        KeyBinding::new("down", SelectDown, Some("Select")),
705        KeyBinding::new("enter", SelectConfirm, Some("Select")),
706        KeyBinding::new("space", SelectConfirm, Some("Select")),
707        KeyBinding::new("escape", SelectCancel, Some("Select")),
708    ]);
709}
710
711impl<T: Clone + 'static> Focusable for Select<T> {
712    fn focus_handle(&self, _: &App) -> FocusHandle {
713        self.focus_handle.clone()
714    }
715}
716
717impl<T: Clone + 'static> EventEmitter<SelectEvent> for Select<T> {}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    fn sample_options() -> Vec<SelectOption<&'static str>> {
724        vec![
725            SelectOption::new("apple", "Apple"),
726            SelectOption::new("banana", "Banana"),
727            SelectOption::new("cherry", "Cherry"),
728        ]
729    }
730
731    #[gpui::test]
732    fn filters_options_case_insensitively_by_label() {
733        let mut app = TestApp::new();
734        let select = app.update(|cx| cx.new(|cx| Select::new(cx).options(sample_options())));
735
736        app.update(|cx| {
737            select.update(cx, |s, _| {
738                assert_eq!(s.filtered_options().len(), 3);
739                s.search_query = "BAN".to_string();
740                let filtered = s.filtered_options();
741                assert_eq!(filtered.len(), 1);
742                assert_eq!(filtered[0].1.label, "Banana");
743                assert_eq!(filtered[0].0, 1);
744                s.search_query.clear();
745                assert_eq!(s.filtered_options().len(), 3);
746            })
747        });
748    }
749
750    #[gpui::test]
751    fn selected_accessors_read_the_selected_option() {
752        let mut app = TestApp::new();
753        let select = app.update(|cx| {
754            cx.new(|cx| {
755                Select::new(cx)
756                    .options(sample_options())
757                    .selected_index(Some(1))
758            })
759        });
760
761        app.update(|cx| {
762            let s = select.read(cx);
763            assert_eq!(s.selected_value(), Some(&"banana"));
764            assert_eq!(s.selected_label().map(|l| l.as_ref()), Some("Banana"));
765        });
766    }
767}