1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use crate::motion::{OverlayMotion, ScaledOverlay, menu_pivot};
7use gpui::{
8 Anchor, App, AppContext, Bounds, Context, ElementId, Entity, EntityInputHandler, Focusable,
9 InteractiveElement, IntoElement, ListAlignment, ListOffset, ListSizingBehavior, ListState,
10 ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
11 Subscription, Window, canvas, div, list, prelude::FluentBuilder, px,
12};
13use gpui_base::{Popup, TestSupportExt};
14use gpui_material_foundation::{Surface, animate, color, logical_anchor, window_material_theme};
15use gpui_material_theme::{
16 ColorRole, Elevation, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
17};
18
19use super::{TextField, TextFieldEvent, TextFieldState, TextFieldVariant};
20
21#[derive(Clone, PartialEq, Eq)]
23pub struct DropdownOption {
24 pub id: ElementId,
25 pub label: SharedString,
26}
27
28impl DropdownOption {
29 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
30 Self {
31 id: id.into(),
32 label: label.into(),
33 }
34 }
35}
36
37#[derive(Default)]
40struct OptionSnapshot {
41 source: Rc<[DropdownOption]>,
42 query: Option<SharedString>,
43 visible: Rc<[DropdownOption]>,
44}
45
46impl OptionSnapshot {
47 fn reconcile(&mut self, source: Vec<DropdownOption>, query: Option<SharedString>) -> bool {
48 if self.source.as_ref() == source.as_slice() && self.query == query {
49 return false;
50 }
51 self.source = source.into();
52 self.visible = if let Some(query) = &query {
53 let query = query.to_lowercase();
54 self.source
55 .iter()
56 .filter(|option| option.label.to_lowercase().contains(&query))
57 .cloned()
58 .collect()
59 } else {
60 self.source.clone()
61 };
62 self.query = query;
63 true
64 }
65}
66
67pub struct ExposedDropdownState {
69 input: Entity<TextFieldState>,
70 committed: SharedString,
71 editable: bool,
72 open: bool,
73 active: Option<ElementId>,
74 scroll: ListState,
75 presented: Rc<[DropdownOption]>,
76 metrics: Option<(
77 gpui::Pixels,
78 f32,
79 gpui::Pixels,
80 gpui_material_theme::Typography,
81 u64,
82 )>,
83 options: OptionSnapshot,
84 _input: Subscription,
85}
86
87impl ExposedDropdownState {
88 pub fn new(
89 value: impl Into<SharedString>,
90 editable: bool,
91 window: &mut Window,
92 cx: &mut Context<Self>,
93 ) -> Self {
94 let committed = value.into();
95 let input = cx.new(|cx| {
96 let mut state = TextFieldState::new(window, cx).default_value(committed.clone());
97 state.set_readonly(!editable, cx);
98 state
99 });
100 let subscription = cx.subscribe_in(&input, window, |state, input, event, window, cx| {
101 if !state.editable || !matches!(event, TextFieldEvent::Change) {
102 return;
103 }
104 if input.update(cx, |input, cx| {
105 input.marked_text_range(window, cx).is_some()
106 }) {
107 return;
108 }
109 if input.read(cx).value() != state.committed {
110 state.open = true;
111 state.active = None;
112 }
113 cx.notify();
114 });
115 Self {
116 input,
117 committed,
118 editable,
119 open: false,
120 active: None,
121 scroll: ListState::new(0, ListAlignment::Top, px(280.)),
122 presented: Rc::default(),
123 metrics: None,
124 options: OptionSnapshot::default(),
125 _input: subscription,
126 }
127 }
128
129 pub fn set_value(
131 &mut self,
132 value: impl Into<SharedString>,
133 window: &mut Window,
134 cx: &mut Context<Self>,
135 ) {
136 self.committed = value.into();
137 self.open = false;
138 self.active = None;
139 self.input.update(cx, |input, cx| {
140 if input.value() != self.committed {
141 input.set_value(self.committed.clone(), window, cx);
142 }
143 });
144 cx.notify();
145 }
146
147 fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
148 self.input.read(cx).focus_handle(cx).focus(window, cx);
149 if self.open {
150 self.cancel(window, cx);
151 } else {
152 self.open = true;
153 cx.notify();
154 }
155 }
156
157 fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
158 let choices = &self.options.visible;
159 let index = self
160 .active
161 .as_ref()
162 .and_then(|id| choices.iter().position(|choice| &choice.id == id));
163 let next = index.map_or_else(
164 || {
165 if backwards {
166 choices.len().saturating_sub(1)
167 } else {
168 0
169 }
170 },
171 |index| {
172 if backwards {
173 index
174 .checked_sub(1)
175 .unwrap_or(choices.len().saturating_sub(1))
176 } else {
177 (index + 1) % choices.len()
178 }
179 },
180 );
181 self.active = choices.get(next).map(|choice| choice.id.clone());
182 self.open = true;
183 if self.scroll.bounds_for_item(next).is_some() {
184 self.scroll.scroll_to_reveal_item(next);
185 } else {
186 self.scroll.scroll_to(ListOffset {
187 item_ix: next,
188 offset_in_item: px(0.),
189 });
190 }
191 cx.notify();
192 }
193
194 fn pending(&self) -> Option<DropdownOption> {
195 let choices = &self.options.visible;
196 let index = self
197 .active
198 .as_ref()
199 .and_then(|id| choices.iter().position(|choice| &choice.id == id))
200 .unwrap_or(0);
201 choices.get(index).cloned()
202 }
203
204 fn cancel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
205 self.set_value(self.committed.clone(), window, cx);
206 }
207}
208
209type Select = Rc<dyn Fn(&DropdownOption, &mut Window, &mut App)>;
210
211#[derive(IntoElement)]
214pub struct ExposedDropdown {
215 id: ElementId,
216 label: SharedString,
217 state: Entity<ExposedDropdownState>,
218 options: Vec<DropdownOption>,
219 on_select: Option<Select>,
220}
221
222impl ExposedDropdown {
223 pub fn new(
224 id: impl Into<ElementId>,
225 label: impl Into<SharedString>,
226 state: &Entity<ExposedDropdownState>,
227 options: impl IntoIterator<Item = DropdownOption>,
228 ) -> Self {
229 Self {
230 id: id.into(),
231 label: label.into(),
232 state: state.clone(),
233 options: options.into_iter().collect(),
234 on_select: None,
235 }
236 }
237
238 pub fn on_select(
239 mut self,
240 on_select: impl Fn(&DropdownOption, &mut Window, &mut App) + 'static,
241 ) -> Self {
242 self.on_select = Some(Rc::new(on_select));
243 self
244 }
245}
246
247fn choose(
248 state: &Entity<ExposedDropdownState>,
249 choice: &DropdownOption,
250 callback: &Option<Select>,
251 window: &mut Window,
252 cx: &mut App,
253) {
254 state.update(cx, |state, cx| {
255 state.set_value(choice.label.clone(), window, cx)
256 });
257 if let Some(callback) = callback {
258 callback(choice, window, cx);
259 }
260}
261
262impl RenderOnce for ExposedDropdown {
263 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
264 let model = self.state.read(cx);
265 let input = model.input.clone();
266 let open = model.open;
267 let editable = model.editable;
268 let scroll = model.scroll.clone();
269 let query = input.read(cx).value();
270 let committed = model.committed.clone();
271 let composing = input.update(cx, |input, cx| {
272 input.marked_text_range(window, cx).is_some()
273 });
274 let filter = editable && !composing && query != committed;
275 let (options, active) = self.state.update(cx, |state, _| {
276 if state
277 .options
278 .reconcile(self.options, filter.then_some(query))
279 {
280 let index = state.active.as_ref().and_then(|id| {
281 state
282 .options
283 .visible
284 .iter()
285 .position(|option| &option.id == id)
286 });
287 if index.is_none() {
288 state.active = None;
289 }
290 }
291 (state.options.visible.clone(), state.active.clone())
292 });
293 let last_visible_options = window
294 .use_keyed_state((self.id.clone(), "presented-options"), cx, |_, _| {
295 Rc::new(RefCell::new((
296 Rc::<[DropdownOption]>::default(),
297 None::<ElementId>,
298 )))
299 })
300 .read(cx)
301 .clone();
302 if open {
303 let mut visible = last_visible_options.borrow_mut();
304 visible.0 = options.clone();
305 visible.1.clone_from(&active);
306 }
307 let theme = window_material_theme(window, cx);
308 let anchor = logical_anchor(Anchor::TopLeft, theme.layout.direction);
309 let ink = color(theme.colors.color(ColorRole::OnSurface));
310 let selected = color(theme.colors.color(ColorRole::SecondaryContainer));
311 let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
312 let typography = theme.typography.clone();
313 let text_style = TypeRole::LabelLarge.style(TypographyEmphasis::Baseline);
314 let arrow = animate(
315 (self.id.clone(), "arrow"),
316 f32::from(open),
317 theme
318 .motion
319 .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
320 window,
321 cx,
322 )
323 .clamp(0., 1.);
324 let parent = window.current_view();
325 let close = self.state.clone();
326 let keys = close.clone();
327 let toggle = close.clone();
328 let callback = self.on_select.clone();
329 let key_input = input.clone();
330 let primary_toggle = self.state.clone();
331 let bounds = window
332 .use_keyed_state((self.id.clone(), "bounds"), cx, |_, _| {
333 Rc::new(Cell::new(Bounds::default()))
334 })
335 .read(cx)
336 .clone();
337 let measure = bounds.clone();
338 let popup_width = bounds.get().size.width;
339 let trigger = div()
340 .id((self.id.clone(), "combobox"))
341 .test_support()
342 .when(!editable, |trigger| {
343 trigger.on_click(move |_, window, cx| {
344 primary_toggle.update(cx, |state, cx| state.toggle(window, cx));
345 cx.notify(parent);
346 })
347 })
348 .capture_key_down(move |event, window, cx| {
353 let key = event.keystroke.key.as_str();
354 if !matches!(key, "up" | "down" | "enter" | "escape")
355 && !(key == "space" && !editable)
356 {
357 return;
358 }
359 if key_input.update(cx, |input, cx| {
360 input.marked_text_range(window, cx).is_some()
361 }) {
362 return;
363 }
364 let open = keys.read(cx).open;
365 match key {
366 "up" | "down" => keys.update(cx, |state, cx| state.navigate(key == "up", cx)),
367 "escape" if open => keys.update(cx, |state, cx| state.cancel(window, cx)),
368 "enter" if open => {
369 if let Some(choice) = keys.read(cx).pending() {
370 choose(&keys, &choice, &callback, window, cx);
371 }
372 }
373 "enter" | "space" if !editable => {
374 keys.update(cx, |state, cx| state.toggle(window, cx));
375 }
376 _ => return,
377 }
378 cx.notify(parent);
379 cx.stop_propagation();
380 })
381 .child(
382 TextField::new("value", self.label, &input)
383 .variant(TextFieldVariant::Outlined)
384 .expanded(open)
385 .trailing(
386 gpui_base::Button::new("toggle-options")
387 .accessibility_label(if open {
388 "Close options"
389 } else {
390 "Open options"
391 })
392 .aria_expanded(open)
393 .min_w(px(36.))
394 .min_h(px(36.))
395 .focus_visible(move |style| style.border_1().border_color(ink))
396 .on_click(move |_, window, cx| {
397 cx.stop_propagation();
398 toggle.update(cx, |state, cx| state.toggle(window, cx));
399 cx.notify(parent);
400 })
401 .child(dropdown_arrow(arrow, ink)),
402 ),
403 );
404 let height = (window.viewport_size().height * 0.55).min(px(280.));
405 let trigger = trigger
406 .relative()
407 .child(
408 canvas(
409 move |bounds, window, _| {
410 if measure.replace(bounds).size != bounds.size && open {
411 window.refresh();
412 }
413 },
414 |_, _, _, _| {},
415 )
416 .absolute()
417 .inset_0(),
418 )
419 .when(!editable, |trigger| {
421 trigger.child(div().absolute().inset_0().cursor_default())
422 });
423 let motion = OverlayMotion::sample(&self.id, open, window, cx);
424
425 let placement = window
426 .use_keyed_state((self.id.clone(), "last-popup-bounds"), cx, |_, _| {
427 Rc::new(Cell::new((Bounds::default(), Bounds::default())))
428 })
429 .read(cx)
430 .clone();
431 let (last_bounds, last_trigger) = placement.get();
432 let trigger_bounds = placement.clone();
433 let popup = Popup::new(self.id.clone(), trigger)
434 .anchor(anchor)
435 .offset(px(4.))
436 .on_position(move |resolved, trigger| trigger_bounds.set((resolved.bounds, trigger)));
437 let content = motion.map(|motion| {
438 let dp = move |value| motion.px(value);
439 let spacing = dp(16.);
440 let (options, active) = if open {
441 (options, active)
442 } else {
443 last_visible_options.borrow().clone()
444 };
445 let width = if open {
446 popup_width.max(px(120.)).min(window.viewport_size().width)
447 } else {
448 last_bounds.size.width
449 };
450 let font_revision = gpui_material_foundation::font_cache_revision(cx);
451 self.state.update(cx, |state, _| {
452 let metrics = (
453 width,
454 motion.scale,
455 window.rem_size(),
456 typography,
457 font_revision,
458 );
459 if !Rc::ptr_eq(&state.presented, &options) {
460 state.scroll.reset(options.len());
461 if let Some(index) = active
462 .as_ref()
463 .and_then(|id| options.iter().position(|option| &option.id == id))
464 {
465 state.scroll.scroll_to(ListOffset {
466 item_ix: index,
467 offset_in_item: px(0.),
468 });
469 }
470 state.presented = options.clone();
471 } else if state.metrics.as_ref() != Some(&metrics) {
472 let anchor = state.scroll.logical_scroll_top();
473 state.scroll.remeasure();
474 state.scroll.scroll_to(anchor);
475 }
476 state.metrics = Some(metrics);
477 });
478 let content = div()
479 .id(if open { "options" } else { "options-exit" })
480 .test_support()
481 .opacity(motion.alpha)
482 .w(width * motion.scale)
483 .text_color(ink)
484 .max_h(height * motion.scale)
485 .when(open, |list| {
486 list.role(Role::ListBox)
487 .on_mouse_down_out(move |event, window, cx| {
488 if !bounds.get().contains(&event.position) {
489 close.update(cx, |state, cx| state.cancel(window, cx));
490 cx.notify(parent);
491 }
492 })
493 })
494 .child(
495 Surface::new(ColorRole::SurfaceContainer)
496 .shadow_elevation(Elevation::Level2)
497 .shadow_scale(motion.scale)
498 .rounded(spacing * 0.25)
499 .w_full()
500 .py(spacing * 0.5)
501 .child(if options.is_empty() {
502 div()
503 .id("options-scroll-region")
504 .test_support()
505 .max_h((height - px(16.)).max(px(0.)) * motion.scale)
506 .overflow_hidden()
507 .child(
508 div()
509 .px(spacing * 0.75)
510 .py(spacing * 0.5)
511 .child("No matching options"),
512 )
513 .into_any_element()
514 } else {
515 let row_state = self.state.clone();
516 let row_callback = self.on_select.clone();
517 div()
518 .id("options-scroll-region")
519 .test_support()
520 .max_h((height - px(16.)).max(px(0.)) * motion.scale)
521 .overflow_hidden()
522 .child(
523 list(scroll.clone(), move |index, _, _| {
524 let choice = options[index].clone();
525 let current = active.as_ref() == Some(&choice.id);
526 let state = row_state.clone();
527 let callback = row_callback.clone();
528 let accessible = choice.clone();
529 let accessible_state = state.clone();
530 let accessible_callback = callback.clone();
531 div()
532 .id(choice.id.clone())
533 .test_support()
534 .when(open, |row| {
535 row.role(Role::ListBoxOption)
536 .aria_label(choice.label.clone())
537 .aria_selected(current)
538 .aria_position_in_set(index + 1)
539 .aria_size_of_set(options.len())
540 })
541 .when(current, |row| {
542 row.bg(selected).text_color(selected_ink)
543 })
544 .when(open && current, |row| {
545 row.aria_active_descendant()
546 })
547 .when(open, |row| {
548 row.hover(move |style| {
549 style.bg(if current {
550 selected.blend(selected_ink.opacity(0.08))
551 } else {
552 ink.opacity(0.08)
553 })
554 })
555 })
556 .min_h(dp(48.))
557 .w_full()
558 .px(spacing * 0.75)
559 .flex()
560 .items_center()
561 .child(choice.label.clone())
562 .when(open, |row| {
563 row.on_a11y_action(
564 gpui::AccessibleAction::Click,
565 move |_, window, cx| {
566 choose(
567 &accessible_state,
568 &accessible,
569 &accessible_callback,
570 window,
571 cx,
572 );
573 cx.notify(parent);
574 },
575 )
576 .on_click(move |_, window, cx| {
577 choose(&state, &choice, &callback, window, cx);
578 cx.notify(parent);
579 })
580 })
581 .into_any_element()
582 })
583 .with_sizing_behavior(ListSizingBehavior::Infer)
584 .w_full()
585 .max_h((height - px(16.)).max(px(0.)) * motion.scale),
586 )
587 .into_any_element()
588 }),
589 )
590 .when(!open, |list| {
591 list.child(div().absolute().inset_0().occlude())
592 });
593 let content =
594 gpui_material_foundation::text_style(content, text_style, motion.scale, window, cx);
595 ScaledOverlay::new(content, motion, move |menu| {
596 menu_pivot(
597 menu,
598 if open {
599 placement.get().1
600 } else {
601 last_trigger
602 },
603 )
604 })
605 .width(width)
606 });
607 if open {
608 return div().child(popup.content(content.expect("open dropdown")));
609 }
610 let exit = content
611 .filter(|_| last_bounds.size.width > px(0.))
612 .map(|content| {
613 gpui::deferred(
614 gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
615 .child(content),
616 )
617 .with_priority(100)
618 });
619 div().child(popup).children(exit)
620 }
621}
622
623fn dropdown_arrow(progress: f32, ink: gpui::Hsla) -> impl IntoElement {
626 div()
627 .flex()
628 .items_center()
629 .justify_center()
630 .text_color(ink)
631 .child(
632 crate::Icon::new(crate::IconName::ArrowDropDown)
633 .size(px(24.))
634 .rotate(gpui::radians(std::f32::consts::PI * progress)),
635 )
636}
637
638#[cfg(test)]
639mod tests {
640 use super::*;
641
642 #[test]
643 fn option_snapshot_reuses_results_and_invalidates_labels_and_query() {
644 let mut snapshot = OptionSnapshot::default();
645 let options = || {
646 vec![
647 DropdownOption::new("a", "Alpha"),
648 DropdownOption::new("b", "Beta"),
649 ]
650 };
651 assert!(snapshot.reconcile(options(), None));
652 let unfiltered = snapshot.visible.clone();
653 assert!(Rc::ptr_eq(&unfiltered, &snapshot.source));
654 assert!(!snapshot.reconcile(options(), None));
655 assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
656 assert!(snapshot.reconcile(options(), Some("ALP".into())));
657 assert_eq!(snapshot.visible.len(), 1);
658 assert_eq!(snapshot.visible[0].id, ElementId::from("a"));
659 assert!(snapshot.reconcile(
660 vec![
661 DropdownOption::new("a", "Renamed"),
662 DropdownOption::new("b", "Beta")
663 ],
664 Some("ALP".into())
665 ));
666 assert!(snapshot.visible.is_empty());
667 }
668}