1use std::{
2 cell::{Cell, RefCell},
3 rc::{Rc, Weak},
4};
5
6use crate::{
7 MenuSurfaceStyle,
8 motion::{OverlayMotion, ScaledOverlay, menu_pivot},
9};
10use gpui::{
11 AccessibleAction, Anchor, AnyElement, App, AppContext, Bounds, Context, ElementId, Entity,
12 EntityInputHandler, FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement,
13 KeyDownEvent, ListAlignment, ListOffset, ListSizingBehavior, ListState, ParentElement, Pixels,
14 RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Subscription, Window,
15 canvas, div, list, prelude::FluentBuilder, px,
16};
17use gpui_base::{Popup, TestSupportExt};
18use gpui_material_foundation::{animate, color, logical_anchor, window_material_theme};
19use gpui_material_theme::{ColorRole, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis};
20
21use super::{TextField, TextFieldEvent, TextFieldState, TextFieldVariant};
22
23#[derive(Clone, PartialEq, Eq)]
25pub struct DropdownOption {
26 pub id: ElementId,
27 pub label: SharedString,
28}
29
30impl DropdownOption {
31 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
32 Self {
33 id: id.into(),
34 label: label.into(),
35 }
36 }
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum DropdownAnchor {
42 PrimaryEditable,
44 PrimaryNotEditable,
46}
47
48type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
49type Dismiss = Rc<dyn Fn(&mut Window, &mut App)>;
50type Select = Rc<dyn Fn(&DropdownOption, &mut Window, &mut App)>;
51type Editor = Box<dyn FnOnce(TextField) -> AnyElement>;
52type AnchorContent = Box<dyn FnOnce(bool) -> AnyElement>;
53type OptionContent = Rc<dyn Fn(&DropdownOption, bool, &mut Window, &mut App) -> AnyElement>;
54
55#[derive(Default)]
56struct Visibility {
57 controlled: Option<bool>,
58 change: Option<OpenChange>,
59 dismiss: Option<Dismiss>,
60}
61
62#[derive(Clone, Copy)]
63enum Opening {
64 Editor,
65 PopupFromPrimary,
66 PopupFromSecondary,
67}
68
69#[derive(Default)]
72struct OptionSnapshot {
73 source: Rc<[DropdownOption]>,
74 query: Option<SharedString>,
75 visible: Rc<[DropdownOption]>,
76}
77
78impl OptionSnapshot {
79 fn reconcile(&mut self, source: Vec<DropdownOption>, query: Option<SharedString>) -> bool {
80 if self.source.as_ref() == source.as_slice() && self.query == query {
81 return false;
82 }
83 self.source = source.into();
84 self.visible = if let Some(query) = &query {
85 let query = query.to_lowercase();
86 self.source
87 .iter()
88 .filter(|option| option.label.to_lowercase().contains(&query))
89 .cloned()
90 .collect()
91 } else {
92 self.source.clone()
93 };
94 self.query = query;
95 true
96 }
97}
98
99pub struct ExposedDropdownState {
101 input: Entity<TextFieldState>,
102 committed: SharedString,
103 editable: bool,
104 open: bool,
105 presented_open: bool,
106 visibility: Weak<Visibility>,
107 primary_enabled: bool,
108 opening: Option<Opening>,
109 popup_focus: FocusHandle,
110 secondary_focus: FocusHandle,
111 restore_focus: Option<FocusHandle>,
112 focus_epoch: u64,
113 active: Option<ElementId>,
114 selected: Option<ElementId>,
115 scroll: ListState,
116 presented: Rc<[DropdownOption]>,
117 metrics: Option<(
118 gpui::Pixels,
119 f32,
120 gpui::Pixels,
121 gpui_material_theme::Typography,
122 u64,
123 )>,
124 options: OptionSnapshot,
125 _input: Subscription,
126}
127
128impl ExposedDropdownState {
129 pub fn new(
130 value: impl Into<SharedString>,
131 editable: bool,
132 window: &mut Window,
133 cx: &mut Context<Self>,
134 ) -> Self {
135 let value = value.into();
136 let input = cx.new(|cx| TextFieldState::new(window, cx).default_value(value));
137 Self::with_editor(&input, editable, window, cx)
138 }
139
140 pub fn with_editor(
142 input: &Entity<TextFieldState>,
143 editable: bool,
144 window: &mut Window,
145 cx: &mut Context<Self>,
146 ) -> Self {
147 let committed = input.read(cx).value();
148 input.update(cx, |input, cx| input.set_readonly(!editable, cx));
149 let subscription = cx.subscribe_in(input, window, |state, input, event, window, cx| {
150 if !state.editable || !matches!(event, TextFieldEvent::Change) {
151 return;
152 }
153 if input.update(cx, |input, cx| {
154 input.marked_text_range(window, cx).is_some()
155 }) {
156 return;
157 }
158 if input.read(cx).value() != state.committed {
159 state.active = None;
160 if state.primary_enabled {
161 state.request_open(true, Some(Opening::Editor), window, cx);
162 }
163 }
164 cx.notify();
165 });
166 Self {
167 input: input.clone(),
168 committed,
169 editable,
170 open: false,
171 presented_open: false,
172 visibility: Weak::new(),
173 primary_enabled: true,
174 opening: None,
175 popup_focus: cx.focus_handle(),
176 secondary_focus: cx.focus_handle(),
177 restore_focus: None,
178 focus_epoch: 0,
179 active: None,
180 selected: None,
181 scroll: ListState::new(0, ListAlignment::Top, px(280.)),
182 presented: Rc::default(),
183 metrics: None,
184 options: OptionSnapshot::default(),
185 _input: subscription,
186 }
187 }
188
189 pub fn set_value(
191 &mut self,
192 value: impl Into<SharedString>,
193 window: &mut Window,
194 cx: &mut Context<Self>,
195 ) {
196 let value = value.into();
197 if self.committed != value {
198 self.selected = None;
199 }
200 self.committed = value;
201 if self
202 .visibility
203 .upgrade()
204 .is_none_or(|policy| policy.controlled.is_none())
205 {
206 self.open = false;
207 }
208 self.reset_draft(window, cx);
209 }
210
211 pub fn is_open(&self) -> bool {
212 self.open
213 }
214
215 pub fn selected_option_id(&self) -> Option<&ElementId> {
216 self.selected.as_ref()
217 }
218
219 pub fn scroll_state(&self) -> &ListState {
221 &self.scroll
222 }
223
224 pub fn set_scroll_state(&mut self, scroll: &ListState, cx: &mut Context<Self>) {
226 let anchor = scroll.logical_scroll_top();
227 scroll.reset(self.presented.len());
228 scroll.scroll_to(anchor);
229 self.scroll = scroll.clone();
230 self.metrics = None;
231 cx.notify();
232 }
233
234 fn reset_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
235 self.active = None;
236 self.input.update(cx, |input, cx| {
237 if input.value() != self.committed {
238 input.set_value(self.committed.clone(), window, cx);
239 }
240 });
241 cx.notify();
242 }
243
244 fn request_open(
245 &mut self,
246 open: bool,
247 opening: Option<Opening>,
248 window: &mut Window,
249 cx: &mut Context<Self>,
250 ) {
251 if self.open == open {
252 return;
253 }
254 self.opening = opening;
255 let visibility = self.visibility.upgrade();
256 if visibility
257 .as_ref()
258 .is_none_or(|policy| policy.controlled.is_none())
259 {
260 self.open = open;
261 if !open {
262 self.reset_draft(window, cx);
263 }
264 }
265 if let Some(visibility) = visibility
266 && (visibility.change.is_some() || !open && visibility.dismiss.is_some())
267 {
268 window.defer(cx, move |window, cx| {
269 if let Some(change) = &visibility.change {
270 change(open, window, cx);
271 }
272 if !open && let Some(dismiss) = &visibility.dismiss {
273 dismiss(window, cx);
274 }
275 });
276 }
277 cx.notify();
278 }
279
280 fn present(
281 &mut self,
282 visibility: &Rc<Visibility>,
283 primary_enabled: bool,
284 secondary_enabled: bool,
285 primary: Opening,
286 window: &mut Window,
287 cx: &mut Context<Self>,
288 ) {
289 self.primary_enabled = primary_enabled;
290 self.open = visibility.controlled.unwrap_or(self.open);
291 self.visibility = Rc::downgrade(visibility);
292 let opening = self.opening.take();
293 if self.presented_open == self.open {
294 if !self.open {
295 self.active = None;
296 }
297 return;
298 }
299 self.presented_open = self.open;
300 self.focus_epoch = self.focus_epoch.wrapping_add(1);
301 let epoch = self.focus_epoch;
302 if self.open {
303 let editor = self.input.read(cx).focus_handle(cx);
304 let (focus, restore) = match opening.unwrap_or(primary) {
305 Opening::Editor => (editor.clone(), None),
306 Opening::PopupFromPrimary => (self.popup_focus.clone(), Some(editor)),
307 Opening::PopupFromSecondary => {
308 (self.popup_focus.clone(), Some(self.secondary_focus.clone()))
309 }
310 };
311 self.restore_focus = restore;
312 if !focus.is_focused(window) {
313 let state = cx.weak_entity();
314 window.on_next_frame(move |window, cx| {
315 if state
316 .upgrade()
317 .is_some_and(|state| state.read(cx).focus_epoch == epoch)
318 {
319 focus.focus(window, cx);
320 }
321 });
322 }
323 } else {
324 self.reset_draft(window, cx);
325 if let Some(mut restore) = self.restore_focus.take()
326 && self.popup_focus.contains_focused(window, cx)
327 {
328 if !secondary_enabled && restore == self.secondary_focus {
329 restore = self.input.read(cx).focus_handle(cx);
330 }
331 let popup = self.popup_focus.clone();
332 let state = cx.weak_entity();
333 window.defer(cx, move |window, cx| {
334 if state
335 .upgrade()
336 .is_some_and(|state| state.read(cx).focus_epoch == epoch)
337 && popup.contains_focused(window, cx)
338 {
339 restore.focus(window, cx);
340 }
341 });
342 }
343 }
344 }
345
346 fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
347 let choices = &self.options.visible;
348 let index = self
349 .active
350 .as_ref()
351 .and_then(|id| choices.iter().position(|choice| &choice.id == id));
352 let next = index.map_or_else(
353 || {
354 if backwards {
355 choices.len().saturating_sub(1)
356 } else {
357 0
358 }
359 },
360 |index| {
361 if backwards {
362 index
363 .checked_sub(1)
364 .unwrap_or(choices.len().saturating_sub(1))
365 } else {
366 (index + 1) % choices.len()
367 }
368 },
369 );
370 self.active = choices.get(next).map(|choice| choice.id.clone());
371 if self.scroll.bounds_for_item(next).is_some() {
372 self.scroll.scroll_to_reveal_item(next);
373 } else {
374 self.scroll.scroll_to(ListOffset {
375 item_ix: next,
376 offset_in_item: px(0.),
377 });
378 }
379 cx.notify();
380 }
381
382 fn pending(&self) -> Option<DropdownOption> {
383 let choices = &self.options.visible;
384 let index = self
385 .active
386 .as_ref()
387 .and_then(|id| choices.iter().position(|choice| &choice.id == id))
388 .unwrap_or(0);
389 choices.get(index).cloned()
390 }
391}
392
393#[derive(IntoElement)]
396pub struct ExposedDropdown {
397 id: ElementId,
398 label: SharedString,
399 state: Entity<ExposedDropdownState>,
400 options: Vec<DropdownOption>,
401 primary: Option<DropdownAnchor>,
402 primary_enabled: bool,
403 secondary_enabled: bool,
404 secondary: Option<(SharedString, AnchorContent)>,
405 editor: Option<Editor>,
406 option_content: Option<OptionContent>,
407 visibility: Visibility,
408 match_anchor_width: bool,
409 popup_width: Pixels,
410 appearance: MenuSurfaceStyle,
411 container_color: Option<Hsla>,
412 on_select: Option<Select>,
413}
414
415impl ExposedDropdown {
416 pub fn new(
417 id: impl Into<ElementId>,
418 label: impl Into<SharedString>,
419 state: &Entity<ExposedDropdownState>,
420 options: impl IntoIterator<Item = DropdownOption>,
421 ) -> Self {
422 Self {
423 id: id.into(),
424 label: label.into(),
425 state: state.clone(),
426 options: options.into_iter().collect(),
427 primary: None,
428 primary_enabled: true,
429 secondary_enabled: true,
430 secondary: None,
431 editor: None,
432 option_content: None,
433 visibility: Visibility::default(),
434 match_anchor_width: true,
435 popup_width: px(240.),
436 appearance: MenuSurfaceStyle::default(),
437 container_color: None,
438 on_select: None,
439 }
440 }
441
442 pub fn primary_anchor(mut self, anchor: DropdownAnchor) -> Self {
444 self.primary = Some(anchor);
445 self
446 }
447
448 pub fn primary_anchor_enabled(mut self, enabled: bool) -> Self {
449 self.primary_enabled = enabled;
450 self
451 }
452
453 pub fn secondary_anchor<E: IntoElement>(
455 mut self,
456 label: impl Into<SharedString>,
457 content: impl FnOnce(bool) -> E + 'static,
458 ) -> Self {
459 self.secondary = Some((
460 label.into(),
461 Box::new(move |open| content(open).into_any_element()),
462 ));
463 self
464 }
465
466 pub fn secondary_anchor_enabled(mut self, enabled: bool) -> Self {
467 self.secondary_enabled = enabled;
468 self
469 }
470
471 pub fn editor<E: IntoElement>(mut self, render: impl FnOnce(TextField) -> E + 'static) -> Self {
473 self.editor = Some(Box::new(move |field| render(field).into_any_element()));
474 self
475 }
476
477 pub fn option_content<E: IntoElement>(
479 mut self,
480 render: impl Fn(&DropdownOption, bool, &mut Window, &mut App) -> E + 'static,
481 ) -> Self {
482 self.option_content = Some(Rc::new(move |option, highlighted, window, cx| {
483 render(option, highlighted, window, cx).into_any_element()
484 }));
485 self
486 }
487
488 pub fn open(mut self, open: bool) -> Self {
489 self.visibility.controlled = Some(open);
490 self
491 }
492
493 pub fn on_open_change(
494 mut self,
495 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
496 ) -> Self {
497 self.visibility.change = Some(Rc::new(callback));
498 self
499 }
500
501 pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
502 self.visibility.dismiss = Some(Rc::new(callback));
503 self
504 }
505
506 pub fn match_anchor_width(mut self, matches: bool) -> Self {
507 self.match_anchor_width = matches;
508 self
509 }
510
511 pub fn popup_width(mut self, width: Pixels) -> Self {
513 if f32::from(width).is_finite() && width > px(0.) {
514 self.popup_width = width;
515 }
516 self
517 }
518
519 pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
520 self.appearance = appearance;
521 self
522 }
523
524 pub fn container_color(mut self, color: Hsla) -> Self {
525 self.container_color = Some(color);
526 self
527 }
528
529 pub fn on_select(
530 mut self,
531 on_select: impl Fn(&DropdownOption, &mut Window, &mut App) + 'static,
532 ) -> Self {
533 self.on_select = Some(Rc::new(on_select));
534 self
535 }
536}
537
538fn choose(
539 state: &Entity<ExposedDropdownState>,
540 choice: &DropdownOption,
541 callback: &Option<Select>,
542 window: &mut Window,
543 cx: &mut App,
544) {
545 state.update(cx, |state, cx| {
546 state.committed = choice.label.clone();
547 state.selected = Some(choice.id.clone());
548 state.reset_draft(window, cx);
549 state.request_open(false, None, window, cx);
550 });
551 if let Some(callback) = callback {
552 callback(choice, window, cx);
553 }
554}
555
556#[derive(Clone)]
557struct Interaction {
558 state: Entity<ExposedDropdownState>,
559 _visibility: Rc<Visibility>,
561 select: Option<Select>,
562 primary: Opening,
563 primary_enabled: bool,
564 editable: bool,
565 parent: gpui::EntityId,
566}
567
568impl Interaction {
569 fn request(&self, open: Option<bool>, opening: Opening, window: &mut Window, cx: &mut App) {
570 self.state.update(cx, |state, cx| {
571 let open = open.unwrap_or(!state.open);
572 if open && matches!(opening, Opening::Editor) {
573 state.input.read(cx).focus_handle(cx).focus(window, cx);
574 }
575 state.request_open(open, open.then_some(opening), window, cx);
576 });
577 cx.notify(self.parent);
578 }
579
580 fn dismiss(&self, window: &mut Window, cx: &mut App) {
581 self.request(Some(false), self.primary, window, cx);
582 }
583
584 fn keys(&self, event: &KeyDownEvent, window: &mut Window, cx: &mut App) {
585 let key = event.keystroke.key.as_str();
586 if event.keystroke.modifiers.modified()
587 || !(matches!(key, "up" | "down" | "enter" | "escape")
588 || key == "space" && !self.editable)
589 {
590 return;
591 }
592 let model = self.state.read(cx);
593 let open = model.open;
594 let input = model.input.clone();
595 if !open && !self.primary_enabled
596 || input.update(cx, |input, cx| {
597 input.marked_text_range(window, cx).is_some()
598 })
599 {
600 return;
601 }
602 match key {
603 "up" | "down" => self.state.update(cx, |state, cx| {
604 state.navigate(key == "up", cx);
605 if state.open {
606 return;
607 }
608 state.request_open(true, Some(self.primary), window, cx);
609 }),
610 "escape" if open => self.dismiss(window, cx),
611 "enter" if open => {
612 if let Some(choice) = self.state.read(cx).pending() {
613 choose(&self.state, &choice, &self.select, window, cx);
614 }
615 }
616 "enter" | "space" if !self.editable => self.request(None, self.primary, window, cx),
617 _ => return,
618 }
619 cx.notify(self.parent);
620 cx.stop_propagation();
621 }
622}
623
624impl RenderOnce for ExposedDropdown {
625 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
626 let primary = if self.primary == Some(DropdownAnchor::PrimaryNotEditable) {
627 Opening::PopupFromPrimary
628 } else {
629 Opening::Editor
630 };
631 let visibility = Rc::new(self.visibility);
632 self.state.update(cx, |state, cx| {
633 state.present(
634 &visibility,
635 self.primary_enabled,
636 self.secondary_enabled,
637 primary,
638 window,
639 cx,
640 );
641 });
642 let model = self.state.read(cx);
643 let input = model.input.clone();
644 let open = model.open;
645 let editable = model.editable;
646 let popup_focus = model.popup_focus.clone();
647 let transfer_focus = model.restore_focus.is_some();
648 let secondary_focus = model.secondary_focus.clone();
649 let scroll = model.scroll.clone();
650 let query = input.read(cx).value();
651 let committed = model.committed.clone();
652 let composing = input.update(cx, |input, cx| {
653 input.marked_text_range(window, cx).is_some()
654 });
655 let filter = editable && !composing && query != committed;
656 let (options, active, selected_option) = self.state.update(cx, |state, _| {
657 if state
658 .options
659 .reconcile(self.options, filter.then_some(query))
660 {
661 let index = state.active.as_ref().and_then(|id| {
662 state
663 .options
664 .visible
665 .iter()
666 .position(|option| &option.id == id)
667 });
668 if index.is_none() {
669 state.active = None;
670 }
671 }
672 (
673 state.options.visible.clone(),
674 state.active.clone(),
675 state.selected.clone(),
676 )
677 });
678 let last_visible_options = window
679 .use_keyed_state((self.id.clone(), "presented-options"), cx, |_, _| {
680 Rc::new(RefCell::new((
681 Rc::<[DropdownOption]>::default(),
682 None::<ElementId>,
683 None::<ElementId>,
684 )))
685 })
686 .read(cx)
687 .clone();
688 if open {
689 let mut visible = last_visible_options.borrow_mut();
690 visible.0 = options.clone();
691 visible.1.clone_from(&active);
692 visible.2.clone_from(&selected_option);
693 }
694 let theme = window_material_theme(window, cx).clone();
695 let ink = color(theme.colors.color(ColorRole::OnSurface));
696 let selected = color(theme.colors.color(ColorRole::SecondaryContainer));
697 let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
698 let typography = theme.typography.clone();
699 let text_style = TypeRole::LabelLarge.style(TypographyEmphasis::Baseline);
700 let arrow = animate(
701 (self.id.clone(), "arrow"),
702 f32::from(open),
703 theme
704 .motion
705 .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
706 window,
707 cx,
708 )
709 .clamp(0., 1.);
710 let parent = window.current_view();
711 let interaction = Interaction {
712 state: self.state.clone(),
713 _visibility: visibility,
714 select: self.on_select.clone(),
715 primary,
716 primary_enabled: self.primary_enabled,
717 editable,
718 parent,
719 };
720 let popup_keys = interaction.clone();
721 let outside = interaction.clone();
722 let keys = interaction.clone();
723 let primary_click = interaction.clone();
724 let request: Option<OpenChange> = self.primary_enabled.then(|| {
725 let interaction = interaction.clone();
726 Rc::new(move |open, window: &mut Window, cx: &mut App| {
727 interaction.request(Some(open), primary, window, cx);
728 }) as OpenChange
729 });
730 let (secondary_label, secondary_content) = self.secondary.map_or_else(
731 || {
732 let label = if open {
733 "Close options"
734 } else {
735 "Open options"
736 };
737 (
738 SharedString::from(label),
739 dropdown_arrow(arrow, ink).into_any_element(),
740 )
741 },
742 |(label, content)| (label, content(open)),
743 );
744 let secondary = if self.secondary_enabled {
745 let pointer = interaction.clone();
746 let a11y = interaction.clone();
747 let expansion = interaction;
748 let accessible_opening = if editable {
749 Opening::PopupFromSecondary
750 } else {
751 primary
752 };
753 gpui_base::Button::new("toggle-options")
754 .track_focus(&secondary_focus)
755 .accessibility_label(secondary_label)
756 .aria_expanded(open)
757 .min_w(px(36.))
758 .min_h(px(36.))
759 .focus_visible(move |style| style.border_1().border_color(ink))
760 .on_click(move |_, window, cx| {
761 cx.stop_propagation();
762 pointer.request(None, primary, window, cx);
763 })
764 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
765 a11y.request(None, accessible_opening, window, cx);
766 })
767 .on_a11y_action(
768 if open {
769 AccessibleAction::Collapse
770 } else {
771 AccessibleAction::Expand
772 },
773 move |_, window, cx| {
774 expansion.request(Some(!open), accessible_opening, window, cx);
775 },
776 )
777 .child(secondary_content)
778 .into_any_element()
779 } else {
780 div()
781 .id("toggle-options-disabled")
782 .role(Role::Group)
783 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
784 .min_w(px(36.))
785 .min_h(px(36.))
786 .flex()
787 .items_center()
788 .justify_center()
789 .opacity(0.38)
790 .child(secondary_content)
791 .into_any_element()
792 };
793 let options_label = format!("{} options", self.label);
794 let field = TextField::new("value", self.label, &input)
795 .variant(TextFieldVariant::Outlined)
796 .dropdown(open, request)
797 .trailing(secondary);
798 let editor = if let Some(editor) = self.editor {
799 editor(field)
800 } else {
801 field.into_any_element()
802 };
803
804 let bounds = window
805 .use_keyed_state((self.id.clone(), "bounds"), cx, |_, _| {
806 Rc::new(Cell::new(Bounds::default()))
807 })
808 .read(cx)
809 .clone();
810 let measure = bounds.clone();
811 let measured = bounds.get();
812 let viewport = window.viewport_size();
813 let default_height = (viewport.height * 0.55).min(px(280.));
814 let gap = px(4.);
815 let margin = px(8.);
816 let (anchor, height) = if measured.size.height > px(0.) {
817 let below = (viewport.height - measured.bottom() - gap - margin).max(px(0.));
818 let above = (measured.top() - gap - margin).max(px(0.));
819 if below < default_height && above > below {
820 (Anchor::BottomLeft, default_height.min(above))
821 } else {
822 (Anchor::TopLeft, default_height.min(below))
823 }
824 } else {
825 (Anchor::TopLeft, default_height)
826 };
827 let anchor = logical_anchor(anchor, theme.layout.direction);
828 let width = if self.match_anchor_width {
829 if measured.size.width > px(0.) {
830 measured.size.width
831 } else {
832 px(120.)
833 }
834 } else {
835 self.popup_width
836 };
837 let width = width.min((viewport.width - margin * 2.).max(px(0.)));
838 let trigger = div()
839 .id((self.id.clone(), "combobox"))
840 .test_support()
841 .when(
842 self.primary_enabled && (!editable || self.primary.is_some()),
843 |trigger| {
844 trigger.on_click(move |_, window, cx| {
845 primary_click.request(None, primary, window, cx);
846 })
847 },
848 )
849 .capture_key_down(move |event, window, cx| keys.keys(event, window, cx))
851 .child(editor)
852 .relative()
853 .child(
854 canvas(
855 move |bounds, window, _| {
856 if measure.replace(bounds) != bounds && open {
857 window.refresh();
858 }
859 },
860 |_, _, _, _| {},
861 )
862 .absolute()
863 .inset_0(),
864 )
865 .when(!editable, |trigger| {
867 trigger.child(div().absolute().inset_0().cursor_default())
868 });
869 let motion = OverlayMotion::sample(&self.id, open, window, cx);
870
871 let placement = window
872 .use_keyed_state((self.id.clone(), "last-popup-bounds"), cx, |_, _| {
873 Rc::new(Cell::new((Bounds::default(), Bounds::default())))
874 })
875 .read(cx)
876 .clone();
877 let (last_bounds, last_trigger) = placement.get();
878 let trigger_bounds = placement.clone();
879 let popup = Popup::new(self.id.clone(), trigger)
880 .anchor(anchor)
881 .offset(gap)
882 .on_position(move |resolved, trigger| trigger_bounds.set((resolved.bounds, trigger)));
883 let content = motion.map(|motion| {
884 let dp = move |value| motion.px(value);
885 let spacing = dp(16.);
886 let (options, active, selected_option) = if open {
887 (options, active, selected_option)
888 } else {
889 last_visible_options.borrow().clone()
890 };
891 let width = if open { width } else { last_bounds.size.width };
892 let scroll_height =
893 (height - self.appearance.popup_vertical_insets()).max(px(0.)) * motion.scale;
894 let font_revision = gpui_material_foundation::font_cache_revision(cx);
895 self.state.update(cx, |state, _| {
896 let metrics = (
897 width,
898 motion.scale,
899 window.rem_size(),
900 typography,
901 font_revision,
902 );
903 if !Rc::ptr_eq(&state.presented, &options) {
904 let old_top = state.scroll.logical_scroll_top();
905 let old_id = state
906 .presented
907 .get(old_top.item_ix)
908 .map(|option| &option.id);
909 let anchor = active
910 .as_ref()
911 .or(old_id)
912 .and_then(|id| options.iter().position(|option| &option.id == id));
913 state.scroll.reset(options.len());
914 if let Some(index) = anchor {
915 state.scroll.scroll_to(ListOffset {
916 item_ix: index,
917 offset_in_item: if active.is_some() {
918 px(0.)
919 } else {
920 old_top.offset_in_item
921 },
922 });
923 }
924 state.presented = options.clone();
925 } else if state.metrics.as_ref() != Some(&metrics) {
926 let anchor = state.scroll.logical_scroll_top();
927 state.scroll.remeasure();
928 state.scroll.scroll_to(anchor);
929 }
930 state.metrics = Some(metrics);
931 });
932 let content = div()
933 .id(if open { "options" } else { "options-exit" })
934 .test_support()
935 .opacity(motion.alpha)
936 .w(width * motion.scale)
937 .text_color(ink)
938 .max_h(height * motion.scale)
939 .when(open, |list| {
940 list.role(Role::ListBox)
941 .aria_label(options_label)
942 .when(transfer_focus, |list| {
943 list.track_focus(&popup_focus).tab_stop(false)
944 })
945 .capture_key_down(move |event, window, cx| {
946 popup_keys.keys(event, window, cx)
947 })
948 .on_mouse_down_out(move |event, window, cx| {
949 if !bounds.get().contains(&event.position) {
950 outside.dismiss(window, cx);
951 }
952 })
953 })
954 .child(
955 self.appearance
956 .dropdown_surface(&theme, motion)
957 .when_some(self.container_color, |surface, color| surface.bg(color))
958 .w_full()
959 .child(if options.is_empty() {
960 div()
961 .id("options-scroll-region")
962 .test_support()
963 .max_h(scroll_height)
964 .overflow_hidden()
965 .child(
966 div()
967 .px(spacing * 0.75)
968 .py(spacing * 0.5)
969 .child("No matching options"),
970 )
971 .into_any_element()
972 } else {
973 let row_state = self.state.clone();
974 let row_callback = self.on_select.clone();
975 let option_content = self.option_content.clone();
976 div()
977 .id("options-scroll-region")
978 .test_support()
979 .max_h(scroll_height)
980 .overflow_hidden()
981 .child(
982 list(scroll.clone(), move |index, window, cx| {
983 let choice = options[index].clone();
984 let current = active.as_ref().or(selected_option.as_ref())
985 == Some(&choice.id);
986 let content = option_content.as_ref().map_or_else(
987 || choice.label.clone().into_any_element(),
988 |content| content(&choice, current, window, cx),
989 );
990 let state = row_state.clone();
991 let callback = row_callback.clone();
992 let accessible = choice.clone();
993 let accessible_state = state.clone();
994 let accessible_callback = callback.clone();
995 div()
996 .id(choice.id.clone())
997 .test_support()
998 .when(open, |row| {
999 row.role(Role::ListBoxOption)
1000 .aria_label(choice.label.clone())
1001 .aria_selected(current)
1002 .aria_position_in_set(index + 1)
1003 .aria_size_of_set(options.len())
1004 })
1005 .when(current, |row| {
1006 row.bg(selected).text_color(selected_ink)
1007 })
1008 .when(open && current, |row| {
1009 row.aria_active_descendant()
1010 })
1011 .when(open, |row| {
1012 row.hover(move |style| {
1013 style.bg(if current {
1014 selected.blend(selected_ink.opacity(0.08))
1015 } else {
1016 ink.opacity(0.08)
1017 })
1018 })
1019 })
1020 .min_h(dp(48.))
1021 .w_full()
1022 .px(spacing * 0.75)
1023 .flex()
1024 .items_center()
1025 .child(content)
1026 .when(open, |row| {
1027 row.on_a11y_action(
1028 gpui::AccessibleAction::Click,
1029 move |_, window, cx| {
1030 choose(
1031 &accessible_state,
1032 &accessible,
1033 &accessible_callback,
1034 window,
1035 cx,
1036 );
1037 cx.notify(parent);
1038 },
1039 )
1040 .on_click(move |_, window, cx| {
1041 choose(&state, &choice, &callback, window, cx);
1042 cx.notify(parent);
1043 })
1044 })
1045 .into_any_element()
1046 })
1047 .with_sizing_behavior(ListSizingBehavior::Infer)
1048 .w_full()
1049 .max_h(scroll_height),
1050 )
1051 .into_any_element()
1052 }),
1053 )
1054 .when(!open, |list| {
1055 list.child(div().absolute().inset_0().occlude())
1056 });
1057 let content =
1058 gpui_material_foundation::text_style(content, text_style, motion.scale, window, cx);
1059 ScaledOverlay::new(content, motion, move |menu| {
1060 menu_pivot(
1061 menu,
1062 if open {
1063 placement.get().1
1064 } else {
1065 last_trigger
1066 },
1067 )
1068 })
1069 .width(width)
1070 });
1071 if open {
1072 return div().child(popup.content(content.expect("open dropdown")));
1073 }
1074 let exit = content
1075 .filter(|_| last_bounds.size.width > px(0.))
1076 .map(|content| {
1077 gpui::deferred(
1078 gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
1079 .child(content),
1080 )
1081 .with_priority(100)
1082 });
1083 div().child(popup).children(exit)
1084 }
1085}
1086
1087fn dropdown_arrow(progress: f32, ink: gpui::Hsla) -> impl IntoElement {
1090 div()
1091 .flex()
1092 .items_center()
1093 .justify_center()
1094 .text_color(ink)
1095 .child(
1096 crate::Icon::new(crate::IconName::ArrowDropDown)
1097 .size(px(24.))
1098 .rotate(gpui::radians(std::f32::consts::PI * progress)),
1099 )
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104 use super::*;
1105
1106 #[test]
1107 fn option_snapshot_reuses_results_and_invalidates_labels_and_query() {
1108 let mut snapshot = OptionSnapshot::default();
1109 let options = || {
1110 vec![
1111 DropdownOption::new("a", "Alpha"),
1112 DropdownOption::new("b", "Beta"),
1113 ]
1114 };
1115 assert!(snapshot.reconcile(options(), None));
1116 let unfiltered = snapshot.visible.clone();
1117 assert!(Rc::ptr_eq(&unfiltered, &snapshot.source));
1118 assert!(!snapshot.reconcile(options(), None));
1119 assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
1120 assert!(snapshot.reconcile(options(), Some("ALP".into())));
1121 assert_eq!(snapshot.visible.len(), 1);
1122 assert_eq!(snapshot.visible[0].id, ElementId::from("a"));
1123 assert!(snapshot.reconcile(
1124 vec![
1125 DropdownOption::new("a", "Renamed"),
1126 DropdownOption::new("b", "Beta")
1127 ],
1128 Some("ALP".into())
1129 ));
1130 assert!(snapshot.visible.is_empty());
1131 }
1132}