Skip to main content

gpui_material_components/input/exposed_dropdown/
render.rs

1use std::{
2    cell::{Cell, RefCell},
3    rc::Rc,
4};
5
6use gpui::{
7    AccessibleAction, Anchor, AnyElement, App, Bounds, ElementId, EntityInputHandler, FocusHandle,
8    Hsla, InteractiveElement, IntoElement, ParentElement, RenderOnce, Role, SharedString,
9    StatefulInteractiveElement, Styled, Window, canvas, div, prelude::FluentBuilder, px,
10};
11use gpui_base::{Popup, TestSupportExt};
12use gpui_material_foundation::{
13    OverlayMotion, animate, color, current_material_strings, current_material_theme,
14};
15use gpui_material_theme::{ColorRole, MotionKind, MotionSpeed};
16
17use super::{
18    super::{TextField, TextFieldVariant},
19    AnchorContent, DropdownAnchor, DropdownOption, ExposedDropdown, OpenChange,
20    interaction::Interaction,
21    popup::{PopupContentConfig, build_popup_content, resolve_popup_geometry},
22    state::Opening,
23};
24
25#[allow(clippy::too_many_arguments)]
26fn build_secondary_trigger(
27    id: &ElementId,
28    secondary: Option<(SharedString, AnchorContent)>,
29    default_label: SharedString,
30    secondary_enabled: bool,
31    secondary_focus: &FocusHandle,
32    open: bool,
33    editable: bool,
34    primary: Opening,
35    arrow: f32,
36    ink: Hsla,
37    interaction: Interaction,
38) -> AnyElement {
39    let (secondary_label, secondary_content) = secondary.map_or_else(
40        || (default_label, dropdown_arrow(arrow, ink).into_any_element()),
41        |(label, content)| (label, content(open)),
42    );
43    if secondary_enabled {
44        let pointer = interaction.clone();
45        let a11y = interaction.clone();
46        let expansion = interaction;
47        let accessible_opening = if editable {
48            Opening::PopupFromSecondary
49        } else {
50            primary
51        };
52        gpui_base::Button::new((id.clone(), "toggle-options"))
53            .track_focus(secondary_focus)
54            .accessibility_label(secondary_label)
55            .aria_expanded(open)
56            .min_w(px(36.))
57            .min_h(px(36.))
58            .cursor_pointer()
59            .focus_visible(move |style| style.border_1().border_color(ink))
60            .on_click(move |_, window, cx| {
61                cx.stop_propagation();
62                pointer.request(None, primary, window, cx);
63            })
64            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
65                a11y.request(None, accessible_opening, window, cx);
66            })
67            .on_a11y_action(
68                if open {
69                    AccessibleAction::Collapse
70                } else {
71                    AccessibleAction::Expand
72                },
73                move |_, window, cx| {
74                    expansion.request(Some(!open), accessible_opening, window, cx);
75                },
76            )
77            .child(secondary_content)
78            .into_any_element()
79    } else {
80        div()
81            .id((id.clone(), "toggle-options-disabled"))
82            .role(Role::Group)
83            .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
84            .min_w(px(36.))
85            .min_h(px(36.))
86            .flex()
87            .items_center()
88            .justify_center()
89            .opacity(0.38)
90            .child(secondary_content)
91            .into_any_element()
92    }
93}
94
95impl RenderOnce for ExposedDropdown {
96    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
97        let component_disabled = window
98            .use_keyed_state((self.id.clone(), "component-disabled"), cx, |_, _| {
99                Rc::new(Cell::new(false))
100            })
101            .read(cx)
102            .clone();
103        let input_entity = self.state.read(cx).input.clone();
104        let state_disabled = input_entity.read(cx).presentation().is_disabled();
105        if self.disabled {
106            if !state_disabled {
107                component_disabled.set(true);
108                input_entity.update(cx, |input, cx| input.set_disabled(true, cx));
109            }
110        } else if component_disabled.replace(false) {
111            input_entity.update(cx, |input, cx| input.set_disabled(false, cx));
112        }
113        let disabled = self.disabled || input_entity.read(cx).presentation().is_disabled();
114        let primary_enabled = !disabled && self.primary_enabled;
115        let secondary_enabled = !disabled && self.secondary_enabled;
116        let primary = if self.primary == Some(DropdownAnchor::PrimaryNotEditable) {
117            Opening::PopupFromPrimary
118        } else {
119            Opening::Editor
120        };
121        let visibility = Rc::new(self.visibility);
122        let (
123            input,
124            open,
125            editable,
126            popup_focus,
127            transfer_focus,
128            secondary_focus,
129            scroll,
130            options,
131            active,
132            selected_option,
133        ) = self.state.update(cx, |state, cx| {
134            state.present(
135                &visibility,
136                disabled,
137                primary_enabled,
138                secondary_enabled,
139                primary,
140                window,
141                cx,
142            );
143            let input = state.input.clone();
144            let open = state.open;
145            let editable = state.editable;
146            let popup_focus = state.popup_focus.clone();
147            let transfer_focus = state.restore_focus.is_some();
148            let secondary_focus = state.secondary_focus.clone();
149            let scroll = state.scroll.clone();
150            let (query, composing) = input.update(cx, |input, cx| {
151                (
152                    input.value(),
153                    editable && input.marked_text_range(window, cx).is_some(),
154                )
155            });
156            let filter = editable && !composing && query != state.committed;
157            let (options, active, selected_option) =
158                state.reconcile_options(&self.options, filter.then_some(query));
159            (
160                input,
161                open,
162                editable,
163                popup_focus,
164                transfer_focus,
165                secondary_focus,
166                scroll,
167                options,
168                active,
169                selected_option,
170            )
171        });
172        let last_visible_options = window
173            .use_keyed_state((self.id.clone(), "presented-options"), cx, |_, _| {
174                Rc::new(RefCell::new((
175                    Rc::<[DropdownOption]>::default(),
176                    None::<ElementId>,
177                    None::<ElementId>,
178                )))
179            })
180            .read(cx)
181            .clone();
182        if open {
183            let mut visible = last_visible_options.borrow_mut();
184            visible.0 = options.clone();
185            visible.1.clone_from(&active);
186            visible.2.clone_from(&selected_option);
187        }
188        let theme = current_material_theme(window, cx);
189        let ink = color(theme.colors.color(ColorRole::OnSurface));
190        let selected_bg = color(theme.colors.color(ColorRole::SecondaryContainer));
191        let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
192        let arrow = animate(
193            (self.id.clone(), "arrow"),
194            f32::from(open),
195            theme
196                .motion
197                .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
198            window,
199            cx,
200        )
201        .clamp(0., 1.);
202        let parent = window.current_view();
203        let interaction = Interaction {
204            state: self.state.clone(),
205            _visibility: visibility,
206            select: self.on_select.clone(),
207            primary,
208            primary_enabled,
209            editable,
210            disabled,
211            parent,
212        };
213        let popup_keys = interaction.clone();
214        let outside = interaction.clone();
215        let keys = interaction.clone();
216        let primary_click = interaction.clone();
217        let request: Option<OpenChange> = primary_enabled.then(|| {
218            let interaction = interaction.clone();
219            Rc::new(move |open, window: &mut Window, cx: &mut App| {
220                interaction.request(Some(open), primary, window, cx);
221            }) as OpenChange
222        });
223        let default_secondary_label = {
224            let strings = current_material_strings(window, cx);
225            SharedString::from(if open {
226                strings.close_options.clone()
227            } else {
228                strings.open_options.clone()
229            })
230        };
231        let secondary = build_secondary_trigger(
232            &self.id,
233            self.secondary,
234            default_secondary_label,
235            secondary_enabled,
236            &secondary_focus,
237            open,
238            editable,
239            primary,
240            arrow,
241            ink,
242            interaction,
243        );
244        let options_label = format!("{} options", self.label);
245        let field = TextField::new((self.id.clone(), "value"), self.label, &input)
246            .variant(TextFieldVariant::Outlined)
247            .disabled(disabled)
248            .dropdown(open, request)
249            .trailing(secondary);
250        let editor = if let Some(editor) = self.editor {
251            editor(field)
252        } else {
253            field.into_any_element()
254        };
255
256        let bounds = window
257            .use_keyed_state((self.id.clone(), "bounds"), cx, |_, _| {
258                Rc::new(Cell::new(Bounds::default()))
259            })
260            .read(cx)
261            .clone();
262        let measure = bounds.clone();
263        let geometry = resolve_popup_geometry(
264            bounds.get(),
265            window.viewport_size(),
266            theme.layout.direction,
267            self.match_anchor_width,
268            self.popup_width,
269        );
270        let trigger = div()
271            .id((self.id.clone(), "combobox"))
272            .test_support()
273            .when(
274                primary_enabled && (!editable || self.primary.is_some()),
275                |trigger| {
276                    trigger.on_click(move |_, window, cx| {
277                        primary_click.request(None, primary, window, cx);
278                    })
279                },
280            )
281            // TextField owns the single combo box node and delegates IME to its editor.
282            .capture_key_down(move |event, window, cx| keys.keys(event, window, cx))
283            .child(editor)
284            .relative()
285            .child(
286                canvas(
287                    move |bounds, window, _| {
288                        if measure.replace(bounds) != bounds && open {
289                            window.refresh();
290                        }
291                    },
292                    |_, _, _, _| {},
293                )
294                .absolute()
295                .inset_0(),
296            );
297        let motion = OverlayMotion::sample(&self.id, open, window, cx);
298        let placement = window
299            .use_keyed_state((self.id.clone(), "last-popup-bounds"), cx, |_, _| {
300                Rc::new(Cell::new((Bounds::default(), Bounds::default())))
301            })
302            .read(cx)
303            .clone();
304        let (last_bounds, last_trigger) = placement.get();
305        let trigger_bounds = placement.clone();
306        let popup = Popup::new(self.id.clone(), trigger)
307            .anchor(geometry.anchor)
308            .offset(geometry.gap)
309            .on_position(move |resolved, trigger| trigger_bounds.set((resolved.bounds, trigger)));
310        let content = motion.map(|motion| {
311            let (options, active, selected_option) = if open {
312                (options, active, selected_option)
313            } else {
314                last_visible_options.borrow().clone()
315            };
316            let width = if open {
317                geometry.width
318            } else {
319                last_bounds.size.width
320            };
321            build_popup_content(
322                PopupContentConfig {
323                    id: self.id,
324                    state: self.state,
325                    scroll,
326                    open,
327                    options,
328                    active,
329                    selected_option,
330                    options_label,
331                    transfer_focus,
332                    popup_focus,
333                    popup_keys,
334                    outside,
335                    bounds,
336                    placement,
337                    last_trigger,
338                    width,
339                    height: geometry.height,
340                    appearance: self.appearance,
341                    container_color: self.container_color,
342                    on_select: self.on_select,
343                    option_content: self.option_content,
344                    parent,
345                    theme: (*theme).clone(),
346                    ink,
347                    selected_bg,
348                    selected_ink,
349                },
350                motion,
351                window,
352                cx,
353            )
354        });
355        if open {
356            return div().child(popup.content(content.expect("open dropdown")));
357        }
358        let exit = content
359            .filter(|_| last_bounds.size.width > px(0.))
360            .map(|content| {
361                gpui::deferred(
362                    gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
363                        .child(content),
364                )
365                .with_priority(100)
366            });
367        div().child(popup).children(exit)
368    }
369}
370
371// The official dropdown symbol rotates with the existing expansion animation.
372// Keep this decorative element separate from the Base trigger's semantics.
373fn dropdown_arrow(progress: f32, ink: Hsla) -> impl IntoElement {
374    div()
375        .flex()
376        .items_center()
377        .justify_center()
378        .text_color(ink)
379        .child(
380            crate::Icon::new(crate::IconName::ArrowDropDown)
381                .size(px(24.))
382                .rotate(gpui::radians(std::f32::consts::PI * progress)),
383        )
384}
385
386#[cfg(test)]
387mod tests {
388    use super::super::state::{OptionSnapshot, contains_ignore_case};
389    use super::*;
390
391    #[test]
392    fn option_snapshot_reuses_results_and_invalidates_labels_and_query() {
393        let mut snapshot = OptionSnapshot::default();
394        let options = || -> Rc<[DropdownOption]> {
395            vec![
396                DropdownOption::new("a", "Alpha"),
397                DropdownOption::new("b", "Beta"),
398            ]
399            .into()
400        };
401        let shared = options();
402        assert!(snapshot.reconcile(&shared, None));
403        let unfiltered = snapshot.visible.clone();
404        assert!(Rc::ptr_eq(&unfiltered, &snapshot.source));
405        assert!(Rc::ptr_eq(&unfiltered, &shared));
406        assert!(!snapshot.reconcile(&shared, None));
407        assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
408        let cloned_equal = options();
409        assert!(!snapshot.reconcile(&cloned_equal, None));
410        assert!(Rc::ptr_eq(&snapshot.source, &cloned_equal));
411        assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
412        assert!(snapshot.reconcile(&shared, Some("ALP".into())));
413        assert_eq!(snapshot.visible.len(), 1);
414        assert_eq!(snapshot.visible[0].id, ElementId::from("a"));
415        let renamed: Rc<[DropdownOption]> = vec![
416            DropdownOption::new("a", "Renamed"),
417            DropdownOption::new("b", "Beta"),
418        ]
419        .into();
420        assert!(snapshot.reconcile(&renamed, Some("ALP".into())));
421        assert!(snapshot.visible.is_empty());
422    }
423
424    #[test]
425    fn contains_ignore_case_handles_ascii_and_unicode() {
426        assert!(contains_ignore_case("Alpha Beta", "", ""));
427        assert!(contains_ignore_case("Alpha Beta", "ALP", "alp"));
428        assert!(contains_ignore_case("Alpha Beta", "beta", "beta"));
429        assert!(!contains_ignore_case("Alpha", "Alpha Beta", "alpha beta"));
430        assert!(contains_ignore_case("北京市", "北京", "北京"));
431        assert!(contains_ignore_case("Café Crème", "CAFÉ", "café"));
432    }
433}