Skip to main content

gpui_material_components/input/exposed_dropdown/
render.rs

1use std::{
2    cell::{Cell, RefCell},
3    rc::Rc,
4};
5
6use crate::{
7    MenuSurfaceStyle,
8    motion::{OverlayMotion, ScaledOverlay, menu_pivot},
9};
10use gpui::{
11    AccessibleAction, Anchor, AnyElement, App, Bounds, ElementId, Entity, EntityInputHandler,
12    FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, KeyDownEvent,
13    ListSizingBehavior, ListState, ParentElement, Pixels, RenderOnce, Role, SharedString,
14    StatefulInteractiveElement, Styled, Window, canvas, div, list, prelude::FluentBuilder, px,
15};
16use gpui_base::{Popup, TestSupportExt};
17use gpui_material_foundation::{
18    ThemeScope, animate, color, current_material_theme, logical_anchor,
19};
20use gpui_material_theme::{
21    ColorRole, Direction, MaterialTheme, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
22};
23
24use super::{
25    super::{TextField, TextFieldVariant},
26    AnchorContent, DropdownAnchor, DropdownOption, ExposedDropdown, OpenChange, OptionContent,
27    Select,
28    state::{ExposedDropdownState, Opening, Visibility},
29};
30
31fn choose(
32    state: &Entity<ExposedDropdownState>,
33    choice: &DropdownOption,
34    callback: &Option<Select>,
35    window: &mut Window,
36    cx: &mut App,
37) {
38    state.update(cx, |state, cx| {
39        state.committed = choice.label.clone();
40        state.selected = Some(choice.id.clone());
41        state.reset_draft(window, cx);
42        state.request_open(false, None, window, cx);
43    });
44    if let Some(callback) = callback {
45        callback(choice, window, cx);
46    }
47}
48
49#[derive(Clone)]
50struct Interaction {
51    state: Entity<ExposedDropdownState>,
52    // The mounted handlers own the policy. The editor subscription observes it weakly.
53    _visibility: Rc<Visibility>,
54    select: Option<Select>,
55    primary: Opening,
56    primary_enabled: bool,
57    editable: bool,
58    parent: gpui::EntityId,
59}
60
61impl Interaction {
62    fn request(&self, open: Option<bool>, opening: Opening, window: &mut Window, cx: &mut App) {
63        self.state.update(cx, |state, cx| {
64            let open = open.unwrap_or(!state.open);
65            if open && matches!(opening, Opening::Editor) {
66                state.input.read(cx).focus_handle(cx).focus(window, cx);
67            }
68            state.request_open(open, open.then_some(opening), window, cx);
69        });
70        cx.notify(self.parent);
71    }
72
73    fn dismiss(&self, window: &mut Window, cx: &mut App) {
74        self.request(Some(false), self.primary, window, cx);
75    }
76
77    fn keys(&self, event: &KeyDownEvent, window: &mut Window, cx: &mut App) {
78        let key = event.keystroke.key.as_str();
79        if event.keystroke.modifiers.modified()
80            || !(matches!(key, "up" | "down" | "enter" | "escape")
81                || key == "space" && !self.editable)
82        {
83            return;
84        }
85        let model = self.state.read(cx);
86        let open = model.open;
87        let input = model.input.clone();
88        if !open && !self.primary_enabled
89            || input.update(cx, |input, cx| {
90                input.marked_text_range(window, cx).is_some()
91            })
92        {
93            return;
94        }
95        match key {
96            "up" | "down" => self.state.update(cx, |state, cx| {
97                state.navigate(key == "up", cx);
98                if state.open {
99                    return;
100                }
101                state.request_open(true, Some(self.primary), window, cx);
102            }),
103            "escape" if open => self.dismiss(window, cx),
104            "enter" if open => {
105                if let Some(choice) = self.state.read(cx).pending() {
106                    choose(&self.state, &choice, &self.select, window, cx);
107                }
108            }
109            "enter" | "space" if !self.editable => self.request(None, self.primary, window, cx),
110            _ => return,
111        }
112        cx.notify(self.parent);
113        cx.stop_propagation();
114    }
115}
116
117#[allow(clippy::too_many_arguments)]
118fn build_secondary_trigger(
119    secondary: Option<(SharedString, AnchorContent)>,
120    secondary_enabled: bool,
121    secondary_focus: &FocusHandle,
122    open: bool,
123    editable: bool,
124    primary: Opening,
125    arrow: f32,
126    ink: Hsla,
127    interaction: Interaction,
128) -> AnyElement {
129    let (secondary_label, secondary_content) = secondary.map_or_else(
130        || {
131            let label = if open {
132                "Close options"
133            } else {
134                "Open options"
135            };
136            (
137                SharedString::from(label),
138                dropdown_arrow(arrow, ink).into_any_element(),
139            )
140        },
141        |(label, content)| (label, content(open)),
142    );
143    if secondary_enabled {
144        let pointer = interaction.clone();
145        let a11y = interaction.clone();
146        let expansion = interaction;
147        let accessible_opening = if editable {
148            Opening::PopupFromSecondary
149        } else {
150            primary
151        };
152        gpui_base::Button::new("toggle-options")
153            .track_focus(secondary_focus)
154            .accessibility_label(secondary_label)
155            .aria_expanded(open)
156            .min_w(px(36.))
157            .min_h(px(36.))
158            .focus_visible(move |style| style.border_1().border_color(ink))
159            .on_click(move |_, window, cx| {
160                cx.stop_propagation();
161                pointer.request(None, primary, window, cx);
162            })
163            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
164                a11y.request(None, accessible_opening, window, cx);
165            })
166            .on_a11y_action(
167                if open {
168                    AccessibleAction::Collapse
169                } else {
170                    AccessibleAction::Expand
171                },
172                move |_, window, cx| {
173                    expansion.request(Some(!open), accessible_opening, window, cx);
174                },
175            )
176            .child(secondary_content)
177            .into_any_element()
178    } else {
179        div()
180            .id("toggle-options-disabled")
181            .role(Role::Group)
182            .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
183            .min_w(px(36.))
184            .min_h(px(36.))
185            .flex()
186            .items_center()
187            .justify_center()
188            .opacity(0.38)
189            .child(secondary_content)
190            .into_any_element()
191    }
192}
193
194struct PopupGeometry {
195    anchor: Anchor,
196    height: Pixels,
197    width: Pixels,
198    gap: Pixels,
199}
200
201fn resolve_popup_geometry(
202    measured: Bounds<Pixels>,
203    viewport: gpui::Size<Pixels>,
204    direction: Direction,
205    match_anchor_width: bool,
206    popup_width: Pixels,
207) -> PopupGeometry {
208    let default_height = (viewport.height * 0.55).min(px(280.));
209    let gap = px(4.);
210    let margin = px(8.);
211    let (anchor, height) = if measured.size.height > px(0.) {
212        let below = (viewport.height - measured.bottom() - gap - margin).max(px(0.));
213        let above = (measured.top() - gap - margin).max(px(0.));
214        if below < default_height && above > below {
215            (Anchor::BottomLeft, default_height.min(above))
216        } else {
217            (Anchor::TopLeft, default_height.min(below))
218        }
219    } else {
220        (Anchor::TopLeft, default_height)
221    };
222    let anchor = logical_anchor(anchor, direction);
223    let width = if match_anchor_width {
224        if measured.size.width > px(0.) {
225            measured.size.width
226        } else {
227            px(120.)
228        }
229    } else {
230        popup_width
231    };
232    let width = width.min((viewport.width - margin * 2.).max(px(0.)));
233    PopupGeometry {
234        anchor,
235        height,
236        width,
237        gap,
238    }
239}
240
241struct OptionRowContext {
242    state: Entity<ExposedDropdownState>,
243    on_select: Option<Select>,
244    option_content: Option<OptionContent>,
245    open: bool,
246    parent: gpui::EntityId,
247    ink: Hsla,
248    selected_bg: Hsla,
249    selected_ink: Hsla,
250    min_height: Pixels,
251    horizontal_padding: Pixels,
252}
253
254fn render_option_row(
255    choice: DropdownOption,
256    index: usize,
257    total: usize,
258    current: bool,
259    ctx: &OptionRowContext,
260    window: &mut Window,
261    cx: &mut App,
262) -> AnyElement {
263    let content = ctx.option_content.as_ref().map_or_else(
264        || choice.label.clone().into_any_element(),
265        |content| content(&choice, current, window, cx),
266    );
267    let state = ctx.state.clone();
268    let callback = ctx.on_select.clone();
269    let accessible = choice.clone();
270    let accessible_state = state.clone();
271    let accessible_callback = callback.clone();
272    let parent = ctx.parent;
273    let ink = ctx.ink;
274    let selected = ctx.selected_bg;
275    let selected_ink = ctx.selected_ink;
276    div()
277        .id(choice.id.clone())
278        .test_support()
279        .when(ctx.open, |row| {
280            row.role(Role::ListBoxOption)
281                .aria_label(choice.label.clone())
282                .aria_selected(current)
283                .aria_position_in_set(index + 1)
284                .aria_size_of_set(total)
285        })
286        .when(current, |row| row.bg(selected).text_color(selected_ink))
287        .when(ctx.open && current, |row| row.aria_active_descendant())
288        .when(ctx.open, |row| {
289            row.hover(move |style| {
290                style.bg(if current {
291                    selected.blend(selected_ink.opacity(0.08))
292                } else {
293                    ink.opacity(0.08)
294                })
295            })
296        })
297        .min_h(ctx.min_height)
298        .w_full()
299        .px(ctx.horizontal_padding)
300        .flex()
301        .items_center()
302        .child(content)
303        .when(ctx.open, |row| {
304            row.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
305                choose(
306                    &accessible_state,
307                    &accessible,
308                    &accessible_callback,
309                    window,
310                    cx,
311                );
312                cx.notify(parent);
313            })
314            .on_click(move |_, window, cx| {
315                choose(&state, &choice, &callback, window, cx);
316                cx.notify(parent);
317            })
318        })
319        .into_any_element()
320}
321
322struct PopupContentConfig {
323    state: Entity<ExposedDropdownState>,
324    scroll: ListState,
325    open: bool,
326    options: Rc<[DropdownOption]>,
327    active: Option<ElementId>,
328    selected_option: Option<ElementId>,
329    options_label: String,
330    transfer_focus: bool,
331    popup_focus: FocusHandle,
332    popup_keys: Interaction,
333    outside: Interaction,
334    bounds: Rc<Cell<Bounds<Pixels>>>,
335    placement: Rc<Cell<(Bounds<Pixels>, Bounds<Pixels>)>>,
336    last_trigger: Bounds<Pixels>,
337    width: Pixels,
338    height: Pixels,
339    appearance: MenuSurfaceStyle,
340    container_color: Option<Hsla>,
341    on_select: Option<Select>,
342    option_content: Option<OptionContent>,
343    parent: gpui::EntityId,
344    theme: MaterialTheme,
345    ink: Hsla,
346    selected_bg: Hsla,
347    selected_ink: Hsla,
348}
349
350fn build_popup_content(
351    config: PopupContentConfig,
352    motion: OverlayMotion,
353    window: &mut Window,
354    cx: &mut App,
355) -> AnyElement {
356    let dp = move |value| motion.px(value);
357    let spacing = dp(16.);
358    let scroll_height =
359        (config.height - config.appearance.popup_vertical_insets()).max(px(0.)) * motion.scale;
360    let font_revision = gpui_material_foundation::font_cache_revision(cx);
361    config.state.update(cx, |state, _| {
362        state.sync_presented_list(
363            &config.options,
364            config.active.as_ref(),
365            (
366                config.width,
367                motion.scale,
368                window.rem_size(),
369                config.theme.typography.clone(),
370                font_revision,
371            ),
372        );
373    });
374    let options = config.options;
375    let active = config.active;
376    let selected_option = config.selected_option;
377    let open = config.open;
378    let list_body = if options.is_empty() {
379        div()
380            .id("options-scroll-region")
381            .test_support()
382            .max_h(scroll_height)
383            .overflow_hidden()
384            .child(
385                div()
386                    .px(spacing * 0.75)
387                    .py(spacing * 0.5)
388                    .child("No matching options"),
389            )
390            .into_any_element()
391    } else {
392        let row_ctx = Rc::new(OptionRowContext {
393            state: config.state,
394            on_select: config.on_select,
395            option_content: config.option_content,
396            open,
397            parent: config.parent,
398            ink: config.ink,
399            selected_bg: config.selected_bg,
400            selected_ink: config.selected_ink,
401            min_height: dp(48.),
402            horizontal_padding: spacing * 0.75,
403        });
404        div()
405            .id("options-scroll-region")
406            .test_support()
407            .max_h(scroll_height)
408            .overflow_hidden()
409            .child(
410                list(config.scroll, move |index, window, cx| {
411                    let choice = options[index].clone();
412                    let current = active.as_ref().or(selected_option.as_ref()) == Some(&choice.id);
413                    render_option_row(choice, index, options.len(), current, &row_ctx, window, cx)
414                })
415                .with_sizing_behavior(ListSizingBehavior::Infer)
416                .w_full()
417                .max_h(scroll_height),
418            )
419            .into_any_element()
420    };
421    let bounds = config.bounds;
422    let popup_focus = config.popup_focus;
423    let popup_keys = config.popup_keys;
424    let outside = config.outside;
425    let content = div()
426        .id(if open { "options" } else { "options-exit" })
427        .test_support()
428        .opacity(motion.alpha)
429        .w(config.width * motion.scale)
430        .text_color(config.ink)
431        .max_h(config.height * motion.scale)
432        .when(open, |list| {
433            list.role(Role::ListBox)
434                .aria_label(config.options_label)
435                .when(config.transfer_focus, |list| {
436                    list.track_focus(&popup_focus).tab_stop(false)
437                })
438                .capture_key_down(move |event, window, cx| popup_keys.keys(event, window, cx))
439                .on_mouse_down_out(move |event, window, cx| {
440                    if !bounds.get().contains(&event.position) {
441                        outside.dismiss(window, cx);
442                    }
443                })
444        })
445        .child(
446            config
447                .appearance
448                .dropdown_surface(&config.theme, motion)
449                .when_some(config.container_color, |surface, color| surface.bg(color))
450                .w_full()
451                .child(list_body),
452        )
453        .when(!open, |list| {
454            list.child(div().absolute().inset_0().occlude())
455        });
456    let text_style = TypeRole::LabelLarge.style(TypographyEmphasis::Baseline);
457    let content =
458        gpui_material_foundation::text_style(content, text_style, motion.scale, window, cx);
459    let placement = config.placement;
460    let last_trigger = config.last_trigger;
461    let scaled = ScaledOverlay::new(content, motion, move |menu| {
462        menu_pivot(
463            menu,
464            if open {
465                placement.get().1
466            } else {
467                last_trigger
468            },
469        )
470    })
471    .width(config.width);
472    ThemeScope::inherit(scaled, window, cx)
473}
474
475impl RenderOnce for ExposedDropdown {
476    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
477        let primary = if self.primary == Some(DropdownAnchor::PrimaryNotEditable) {
478            Opening::PopupFromPrimary
479        } else {
480            Opening::Editor
481        };
482        let visibility = Rc::new(self.visibility);
483        self.state.update(cx, |state, cx| {
484            state.present(
485                &visibility,
486                self.primary_enabled,
487                self.secondary_enabled,
488                primary,
489                window,
490                cx,
491            );
492        });
493        let model = self.state.read(cx);
494        let input = model.input.clone();
495        let open = model.open;
496        let editable = model.editable;
497        let popup_focus = model.popup_focus.clone();
498        let transfer_focus = model.restore_focus.is_some();
499        let secondary_focus = model.secondary_focus.clone();
500        let scroll = model.scroll.clone();
501        let query = input.read(cx).value();
502        let committed = model.committed.clone();
503        let composing = input.update(cx, |input, cx| {
504            input.marked_text_range(window, cx).is_some()
505        });
506        let filter = editable && !composing && query != committed;
507        let (options, active, selected_option) = self.state.update(cx, |state, _| {
508            state.reconcile_options(self.options, filter.then_some(query))
509        });
510        let last_visible_options = window
511            .use_keyed_state((self.id.clone(), "presented-options"), cx, |_, _| {
512                Rc::new(RefCell::new((
513                    Rc::<[DropdownOption]>::default(),
514                    None::<ElementId>,
515                    None::<ElementId>,
516                )))
517            })
518            .read(cx)
519            .clone();
520        if open {
521            let mut visible = last_visible_options.borrow_mut();
522            visible.0 = options.clone();
523            visible.1.clone_from(&active);
524            visible.2.clone_from(&selected_option);
525        }
526        let theme = current_material_theme(window, cx).clone();
527        let ink = color(theme.colors.color(ColorRole::OnSurface));
528        let selected_bg = color(theme.colors.color(ColorRole::SecondaryContainer));
529        let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
530        let arrow = animate(
531            (self.id.clone(), "arrow"),
532            f32::from(open),
533            theme
534                .motion
535                .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
536            window,
537            cx,
538        )
539        .clamp(0., 1.);
540        let parent = window.current_view();
541        let interaction = Interaction {
542            state: self.state.clone(),
543            _visibility: visibility,
544            select: self.on_select.clone(),
545            primary,
546            primary_enabled: self.primary_enabled,
547            editable,
548            parent,
549        };
550        let popup_keys = interaction.clone();
551        let outside = interaction.clone();
552        let keys = interaction.clone();
553        let primary_click = interaction.clone();
554        let request: Option<OpenChange> = self.primary_enabled.then(|| {
555            let interaction = interaction.clone();
556            Rc::new(move |open, window: &mut Window, cx: &mut App| {
557                interaction.request(Some(open), primary, window, cx);
558            }) as OpenChange
559        });
560        let secondary = build_secondary_trigger(
561            self.secondary,
562            self.secondary_enabled,
563            &secondary_focus,
564            open,
565            editable,
566            primary,
567            arrow,
568            ink,
569            interaction,
570        );
571        let options_label = format!("{} options", self.label);
572        let field = TextField::new("value", self.label, &input)
573            .variant(TextFieldVariant::Outlined)
574            .dropdown(open, request)
575            .trailing(secondary);
576        let editor = if let Some(editor) = self.editor {
577            editor(field)
578        } else {
579            field.into_any_element()
580        };
581
582        let bounds = window
583            .use_keyed_state((self.id.clone(), "bounds"), cx, |_, _| {
584                Rc::new(Cell::new(Bounds::default()))
585            })
586            .read(cx)
587            .clone();
588        let measure = bounds.clone();
589        let geometry = resolve_popup_geometry(
590            bounds.get(),
591            window.viewport_size(),
592            theme.layout.direction,
593            self.match_anchor_width,
594            self.popup_width,
595        );
596        let trigger = div()
597            .id((self.id.clone(), "combobox"))
598            .test_support()
599            .when(
600                self.primary_enabled && (!editable || self.primary.is_some()),
601                |trigger| {
602                    trigger.on_click(move |_, window, cx| {
603                        primary_click.request(None, primary, window, cx);
604                    })
605                },
606            )
607            // TextField owns the single combo box node and delegates IME to its editor.
608            .capture_key_down(move |event, window, cx| keys.keys(event, window, cx))
609            .child(editor)
610            .relative()
611            .child(
612                canvas(
613                    move |bounds, window, _| {
614                        if measure.replace(bounds) != bounds && open {
615                            window.refresh();
616                        }
617                    },
618                    |_, _, _, _| {},
619                )
620                .absolute()
621                .inset_0(),
622            )
623            // Keep the default cursor over the read-only editor's I-beam.
624            .when(!editable, |trigger| {
625                trigger.child(div().absolute().inset_0().cursor_default())
626            });
627        let motion = OverlayMotion::sample(&self.id, open, window, cx);
628        let placement = window
629            .use_keyed_state((self.id.clone(), "last-popup-bounds"), cx, |_, _| {
630                Rc::new(Cell::new((Bounds::default(), Bounds::default())))
631            })
632            .read(cx)
633            .clone();
634        let (last_bounds, last_trigger) = placement.get();
635        let trigger_bounds = placement.clone();
636        let popup = Popup::new(self.id.clone(), trigger)
637            .anchor(geometry.anchor)
638            .offset(geometry.gap)
639            .on_position(move |resolved, trigger| trigger_bounds.set((resolved.bounds, trigger)));
640        let content = motion.map(|motion| {
641            let (options, active, selected_option) = if open {
642                (options, active, selected_option)
643            } else {
644                last_visible_options.borrow().clone()
645            };
646            let width = if open {
647                geometry.width
648            } else {
649                last_bounds.size.width
650            };
651            build_popup_content(
652                PopupContentConfig {
653                    state: self.state,
654                    scroll,
655                    open,
656                    options,
657                    active,
658                    selected_option,
659                    options_label,
660                    transfer_focus,
661                    popup_focus,
662                    popup_keys,
663                    outside,
664                    bounds,
665                    placement,
666                    last_trigger,
667                    width,
668                    height: geometry.height,
669                    appearance: self.appearance,
670                    container_color: self.container_color,
671                    on_select: self.on_select,
672                    option_content: self.option_content,
673                    parent,
674                    theme,
675                    ink,
676                    selected_bg,
677                    selected_ink,
678                },
679                motion,
680                window,
681                cx,
682            )
683        });
684        if open {
685            return div().child(popup.content(content.expect("open dropdown")));
686        }
687        let exit = content
688            .filter(|_| last_bounds.size.width > px(0.))
689            .map(|content| {
690                gpui::deferred(
691                    gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
692                        .child(content),
693                )
694                .with_priority(100)
695            });
696        div().child(popup).children(exit)
697    }
698}
699
700// The official dropdown symbol rotates with the existing expansion animation.
701// Keep this decorative element separate from the Base trigger's semantics.
702fn dropdown_arrow(progress: f32, ink: Hsla) -> impl IntoElement {
703    div()
704        .flex()
705        .items_center()
706        .justify_center()
707        .text_color(ink)
708        .child(
709            crate::Icon::new(crate::IconName::ArrowDropDown)
710                .size(px(24.))
711                .rotate(gpui::radians(std::f32::consts::PI * progress)),
712        )
713}
714
715#[cfg(test)]
716mod tests {
717    use super::super::state::OptionSnapshot;
718    use super::*;
719
720    #[test]
721    fn option_snapshot_reuses_results_and_invalidates_labels_and_query() {
722        let mut snapshot = OptionSnapshot::default();
723        let options = || {
724            vec![
725                DropdownOption::new("a", "Alpha"),
726                DropdownOption::new("b", "Beta"),
727            ]
728        };
729        assert!(snapshot.reconcile(options(), None));
730        let unfiltered = snapshot.visible.clone();
731        assert!(Rc::ptr_eq(&unfiltered, &snapshot.source));
732        assert!(!snapshot.reconcile(options(), None));
733        assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
734        assert!(snapshot.reconcile(options(), Some("ALP".into())));
735        assert_eq!(snapshot.visible.len(), 1);
736        assert_eq!(snapshot.visible[0].id, ElementId::from("a"));
737        assert!(snapshot.reconcile(
738            vec![
739                DropdownOption::new("a", "Renamed"),
740                DropdownOption::new("b", "Beta")
741            ],
742            Some("ALP".into())
743        ));
744        assert!(snapshot.visible.is_empty());
745    }
746}