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