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 _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 ink = ctx.ink;
268 let selected = ctx.selected_bg;
269 let selected_ink = ctx.selected_ink;
270 div()
271 .id(choice.id.clone())
272 .test_support()
273 .when(ctx.open, |row| {
274 row.role(Role::ListBoxOption)
275 .aria_label(choice.label.clone())
276 .aria_selected(current)
277 .aria_position_in_set(index + 1)
278 .aria_size_of_set(total)
279 })
280 .when(current, |row| row.bg(selected).text_color(selected_ink))
281 .when(ctx.open && current, |row| row.aria_active_descendant())
282 .when(ctx.open, |row| {
283 row.hover(move |style| {
284 style.bg(if current {
285 selected.blend(selected_ink.opacity(0.08))
286 } else {
287 ink.opacity(0.08)
288 })
289 })
290 })
291 .min_h(ctx.min_height)
292 .w_full()
293 .px(ctx.horizontal_padding)
294 .flex()
295 .items_center()
296 .child(content)
297 .when(ctx.open, |row| {
298 let state = ctx.state.clone();
299 let callback = ctx.on_select.clone();
300 let parent = ctx.parent;
301 let select_row = Rc::new(move |window: &mut Window, cx: &mut App| {
302 choose(&state, &choice, &callback, window, cx);
303 cx.notify(parent);
304 });
305 let accessible_select = select_row.clone();
306 row.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
307 accessible_select(window, cx);
308 })
309 .on_click(move |_, window, cx| {
310 select_row(window, cx);
311 })
312 })
313 .into_any_element()
314}
315
316struct PopupContentConfig {
317 state: Entity<ExposedDropdownState>,
318 scroll: ListState,
319 open: bool,
320 options: Rc<[DropdownOption]>,
321 active: Option<ElementId>,
322 selected_option: Option<ElementId>,
323 options_label: String,
324 transfer_focus: bool,
325 popup_focus: FocusHandle,
326 popup_keys: Interaction,
327 outside: Interaction,
328 bounds: Rc<Cell<Bounds<Pixels>>>,
329 placement: Rc<Cell<(Bounds<Pixels>, Bounds<Pixels>)>>,
330 last_trigger: Bounds<Pixels>,
331 width: Pixels,
332 height: Pixels,
333 appearance: MenuSurfaceStyle,
334 container_color: Option<Hsla>,
335 on_select: Option<Select>,
336 option_content: Option<OptionContent>,
337 parent: gpui::EntityId,
338 theme: MaterialTheme,
339 ink: Hsla,
340 selected_bg: Hsla,
341 selected_ink: Hsla,
342}
343
344fn build_popup_content(
345 config: PopupContentConfig,
346 motion: OverlayMotion,
347 window: &mut Window,
348 cx: &mut App,
349) -> AnyElement {
350 let dp = move |value| motion.px(value);
351 let spacing = dp(16.);
352 let scroll_height =
353 (config.height - config.appearance.popup_vertical_insets()).max(px(0.)) * motion.scale;
354 let font_revision = gpui_material_foundation::font_cache_revision(cx);
355 config.state.update(cx, |state, _| {
356 state.sync_presented_list(
357 &config.options,
358 config.active.as_ref(),
359 (
360 config.width,
361 motion.scale,
362 window.rem_size(),
363 config.theme.typography.clone(),
364 font_revision,
365 ),
366 );
367 });
368 let options = config.options;
369 let active = config.active;
370 let selected_option = config.selected_option;
371 let open = config.open;
372 let list_body = if options.is_empty() {
373 div()
374 .id("options-scroll-region")
375 .test_support()
376 .max_h(scroll_height)
377 .overflow_hidden()
378 .child(
379 div()
380 .px(spacing * 0.75)
381 .py(spacing * 0.5)
382 .child("No matching options"),
383 )
384 .into_any_element()
385 } else {
386 let row_ctx = Rc::new(OptionRowContext {
387 state: config.state,
388 on_select: config.on_select,
389 option_content: config.option_content,
390 open,
391 parent: config.parent,
392 ink: config.ink,
393 selected_bg: config.selected_bg,
394 selected_ink: config.selected_ink,
395 min_height: dp(48.),
396 horizontal_padding: spacing * 0.75,
397 });
398 div()
399 .id("options-scroll-region")
400 .test_support()
401 .max_h(scroll_height)
402 .overflow_hidden()
403 .child(
404 list(config.scroll, move |index, window, cx| {
405 let choice = options[index].clone();
406 let current = active.as_ref().or(selected_option.as_ref()) == Some(&choice.id);
407 render_option_row(choice, index, options.len(), current, &row_ctx, window, cx)
408 })
409 .with_sizing_behavior(ListSizingBehavior::Infer)
410 .w_full()
411 .max_h(scroll_height),
412 )
413 .into_any_element()
414 };
415 let bounds = config.bounds;
416 let popup_focus = config.popup_focus;
417 let popup_keys = config.popup_keys;
418 let outside = config.outside;
419 let content = div()
420 .id(if open { "options" } else { "options-exit" })
421 .test_support()
422 .opacity(motion.alpha)
423 .w(config.width * motion.scale)
424 .text_color(config.ink)
425 .max_h(config.height * motion.scale)
426 .when(open, |list| {
427 list.role(Role::ListBox)
428 .aria_label(config.options_label)
429 .when(config.transfer_focus, |list| {
430 list.track_focus(&popup_focus).tab_stop(false)
431 })
432 .capture_key_down(move |event, window, cx| popup_keys.keys(event, window, cx))
433 .on_mouse_down_out(move |event, window, cx| {
434 if !bounds.get().contains(&event.position) {
435 outside.dismiss(window, cx);
436 }
437 })
438 })
439 .child(
440 config
441 .appearance
442 .dropdown_surface(&config.theme, motion)
443 .when_some(config.container_color, |surface, color| surface.bg(color))
444 .w_full()
445 .child(list_body),
446 )
447 .when(!open, |list| {
448 list.child(div().absolute().inset_0().occlude())
449 });
450 let text_style = TypeRole::LabelLarge.style(TypographyEmphasis::Baseline);
451 let content =
452 gpui_material_foundation::text_style(content, text_style, motion.scale, window, cx);
453 let placement = config.placement;
454 let last_trigger = config.last_trigger;
455 let scaled = ScaledOverlay::new(content, motion, move |menu| {
456 menu_pivot(
457 menu,
458 if open {
459 placement.get().1
460 } else {
461 last_trigger
462 },
463 )
464 })
465 .width(config.width);
466 ThemeScope::inherit(scaled, window, cx)
467}
468
469impl RenderOnce for ExposedDropdown {
470 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
471 let primary = if self.primary == Some(DropdownAnchor::PrimaryNotEditable) {
472 Opening::PopupFromPrimary
473 } else {
474 Opening::Editor
475 };
476 let visibility = Rc::new(self.visibility);
477 let (
478 input,
479 open,
480 editable,
481 popup_focus,
482 transfer_focus,
483 secondary_focus,
484 scroll,
485 options,
486 active,
487 selected_option,
488 ) = self.state.update(cx, |state, cx| {
489 state.present(
490 &visibility,
491 self.primary_enabled,
492 self.secondary_enabled,
493 primary,
494 window,
495 cx,
496 );
497 let input = state.input.clone();
498 let open = state.open;
499 let editable = state.editable;
500 let popup_focus = state.popup_focus.clone();
501 let transfer_focus = state.restore_focus.is_some();
502 let secondary_focus = state.secondary_focus.clone();
503 let scroll = state.scroll.clone();
504 let (query, composing) = input.update(cx, |input, cx| {
505 (
506 input.value(),
507 editable && input.marked_text_range(window, cx).is_some(),
508 )
509 });
510 let filter = editable && !composing && query != state.committed;
511 let (options, active, selected_option) =
512 state.reconcile_options(&self.options, filter.then_some(query));
513 (
514 input,
515 open,
516 editable,
517 popup_focus,
518 transfer_focus,
519 secondary_focus,
520 scroll,
521 options,
522 active,
523 selected_option,
524 )
525 });
526 let last_visible_options = window
527 .use_keyed_state((self.id.clone(), "presented-options"), cx, |_, _| {
528 Rc::new(RefCell::new((
529 Rc::<[DropdownOption]>::default(),
530 None::<ElementId>,
531 None::<ElementId>,
532 )))
533 })
534 .read(cx)
535 .clone();
536 if open {
537 let mut visible = last_visible_options.borrow_mut();
538 visible.0 = options.clone();
539 visible.1.clone_from(&active);
540 visible.2.clone_from(&selected_option);
541 }
542 let theme = current_material_theme(window, cx);
543 let ink = color(theme.colors.color(ColorRole::OnSurface));
544 let selected_bg = color(theme.colors.color(ColorRole::SecondaryContainer));
545 let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
546 let arrow = animate(
547 (self.id.clone(), "arrow"),
548 f32::from(open),
549 theme
550 .motion
551 .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
552 window,
553 cx,
554 )
555 .clamp(0., 1.);
556 let parent = window.current_view();
557 let interaction = Interaction {
558 state: self.state.clone(),
559 _visibility: visibility,
560 select: self.on_select.clone(),
561 primary,
562 primary_enabled: self.primary_enabled,
563 editable,
564 parent,
565 };
566 let popup_keys = interaction.clone();
567 let outside = interaction.clone();
568 let keys = interaction.clone();
569 let primary_click = interaction.clone();
570 let request: Option<OpenChange> = self.primary_enabled.then(|| {
571 let interaction = interaction.clone();
572 Rc::new(move |open, window: &mut Window, cx: &mut App| {
573 interaction.request(Some(open), primary, window, cx);
574 }) as OpenChange
575 });
576 let secondary = build_secondary_trigger(
577 self.secondary,
578 self.secondary_enabled,
579 &secondary_focus,
580 open,
581 editable,
582 primary,
583 arrow,
584 ink,
585 interaction,
586 );
587 let options_label = format!("{} options", self.label);
588 let field = TextField::new("value", self.label, &input)
589 .variant(TextFieldVariant::Outlined)
590 .dropdown(open, request)
591 .trailing(secondary);
592 let editor = if let Some(editor) = self.editor {
593 editor(field)
594 } else {
595 field.into_any_element()
596 };
597
598 let bounds = window
599 .use_keyed_state((self.id.clone(), "bounds"), cx, |_, _| {
600 Rc::new(Cell::new(Bounds::default()))
601 })
602 .read(cx)
603 .clone();
604 let measure = bounds.clone();
605 let geometry = resolve_popup_geometry(
606 bounds.get(),
607 window.viewport_size(),
608 theme.layout.direction,
609 self.match_anchor_width,
610 self.popup_width,
611 );
612 let trigger = div()
613 .id((self.id.clone(), "combobox"))
614 .test_support()
615 .when(
616 self.primary_enabled && (!editable || self.primary.is_some()),
617 |trigger| {
618 trigger.on_click(move |_, window, cx| {
619 primary_click.request(None, primary, window, cx);
620 })
621 },
622 )
623 .capture_key_down(move |event, window, cx| keys.keys(event, window, cx))
625 .child(editor)
626 .relative()
627 .child(
628 canvas(
629 move |bounds, window, _| {
630 if measure.replace(bounds) != bounds && open {
631 window.refresh();
632 }
633 },
634 |_, _, _, _| {},
635 )
636 .absolute()
637 .inset_0(),
638 )
639 .when(!editable, |trigger| {
641 trigger.child(div().absolute().inset_0().cursor_default())
642 });
643 let motion = OverlayMotion::sample(&self.id, open, window, cx);
644 let placement = window
645 .use_keyed_state((self.id.clone(), "last-popup-bounds"), cx, |_, _| {
646 Rc::new(Cell::new((Bounds::default(), Bounds::default())))
647 })
648 .read(cx)
649 .clone();
650 let (last_bounds, last_trigger) = placement.get();
651 let trigger_bounds = placement.clone();
652 let popup = Popup::new(self.id.clone(), trigger)
653 .anchor(geometry.anchor)
654 .offset(geometry.gap)
655 .on_position(move |resolved, trigger| trigger_bounds.set((resolved.bounds, trigger)));
656 let content = motion.map(|motion| {
657 let (options, active, selected_option) = if open {
658 (options, active, selected_option)
659 } else {
660 last_visible_options.borrow().clone()
661 };
662 let width = if open {
663 geometry.width
664 } else {
665 last_bounds.size.width
666 };
667 build_popup_content(
668 PopupContentConfig {
669 state: self.state,
670 scroll,
671 open,
672 options,
673 active,
674 selected_option,
675 options_label,
676 transfer_focus,
677 popup_focus,
678 popup_keys,
679 outside,
680 bounds,
681 placement,
682 last_trigger,
683 width,
684 height: geometry.height,
685 appearance: self.appearance,
686 container_color: self.container_color,
687 on_select: self.on_select,
688 option_content: self.option_content,
689 parent,
690 theme: (*theme).clone(),
691 ink,
692 selected_bg,
693 selected_ink,
694 },
695 motion,
696 window,
697 cx,
698 )
699 });
700 if open {
701 return div().child(popup.content(content.expect("open dropdown")));
702 }
703 let exit = content
704 .filter(|_| last_bounds.size.width > px(0.))
705 .map(|content| {
706 gpui::deferred(
707 gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
708 .child(content),
709 )
710 .with_priority(100)
711 });
712 div().child(popup).children(exit)
713 }
714}
715
716fn dropdown_arrow(progress: f32, ink: Hsla) -> impl IntoElement {
719 div()
720 .flex()
721 .items_center()
722 .justify_center()
723 .text_color(ink)
724 .child(
725 crate::Icon::new(crate::IconName::ArrowDropDown)
726 .size(px(24.))
727 .rotate(gpui::radians(std::f32::consts::PI * progress)),
728 )
729}
730
731#[cfg(test)]
732mod tests {
733 use super::super::state::{OptionSnapshot, contains_ignore_case};
734 use super::*;
735
736 #[test]
737 fn option_snapshot_reuses_results_and_invalidates_labels_and_query() {
738 let mut snapshot = OptionSnapshot::default();
739 let options = || -> Rc<[DropdownOption]> {
740 vec![
741 DropdownOption::new("a", "Alpha"),
742 DropdownOption::new("b", "Beta"),
743 ]
744 .into()
745 };
746 let shared = options();
747 assert!(snapshot.reconcile(&shared, None));
748 let unfiltered = snapshot.visible.clone();
749 assert!(Rc::ptr_eq(&unfiltered, &snapshot.source));
750 assert!(Rc::ptr_eq(&unfiltered, &shared));
751 assert!(!snapshot.reconcile(&shared, None));
752 assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
753 let cloned_equal = options();
754 assert!(!snapshot.reconcile(&cloned_equal, None));
755 assert!(Rc::ptr_eq(&snapshot.source, &cloned_equal));
756 assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
757 assert!(snapshot.reconcile(&shared, Some("ALP".into())));
758 assert_eq!(snapshot.visible.len(), 1);
759 assert_eq!(snapshot.visible[0].id, ElementId::from("a"));
760 let renamed: Rc<[DropdownOption]> = vec![
761 DropdownOption::new("a", "Renamed"),
762 DropdownOption::new("b", "Beta"),
763 ]
764 .into();
765 assert!(snapshot.reconcile(&renamed, Some("ALP".into())));
766 assert!(snapshot.visible.is_empty());
767 }
768
769 #[test]
770 fn contains_ignore_case_handles_ascii_and_unicode() {
771 assert!(contains_ignore_case("Alpha Beta", "", ""));
772 assert!(contains_ignore_case("Alpha Beta", "ALP", "alp"));
773 assert!(contains_ignore_case("Alpha Beta", "beta", "beta"));
774 assert!(!contains_ignore_case("Alpha", "Alpha Beta", "alpha beta"));
775 assert!(contains_ignore_case("北京市", "北京", "北京"));
776 assert!(contains_ignore_case("Café Crème", "CAFÉ", "café"));
777 }
778}