1use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
19
20use arc_motion::{
21 ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
22 arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
23};
24use arc_tokens::{
25 ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
26};
27use gpui_kit::{
28 App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
29 MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
30 TestSupportExt as _, Window,
31 assets::IconName,
32 base::{Button as BaseButton, StyledExt as _},
33 canvas, deferred, div, point,
34 prelude::*,
35 px,
36};
37
38type SelectCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
39
40pub const HIGHLIGHT_GRACE_SECS: f64 = 0.07;
42pub const ITEM_STAGGER_SECS: f64 = 0.035;
44pub const ITEM_STAGGER_CAP: usize = 4;
45
46#[derive(Clone)]
48pub struct DropdownItem {
49 pub label: SharedString,
50 pub icon: Option<IconName>,
51 pub disabled: bool,
52 pub destructive: bool,
53 pub separator_before: bool,
54 pub on_select: Option<SelectCallback>,
55}
56
57impl DropdownItem {
58 pub fn new(label: impl Into<SharedString>) -> Self {
59 Self {
60 label: label.into(),
61 icon: None,
62 disabled: false,
63 destructive: false,
64 separator_before: false,
65 on_select: None,
66 }
67 }
68
69 pub fn icon(mut self, icon: IconName) -> Self {
70 self.icon = Some(icon);
71 self
72 }
73
74 pub fn disabled(mut self, disabled: bool) -> Self {
75 self.disabled = disabled;
76 self
77 }
78
79 pub fn destructive(mut self, destructive: bool) -> Self {
80 self.destructive = destructive;
81 self
82 }
83
84 pub fn separator_before(mut self, separator: bool) -> Self {
85 self.separator_before = separator;
86 self
87 }
88
89 pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
90 self.on_select = Some(Rc::new(handler));
91 self
92 }
93}
94
95#[derive(Clone)]
96struct DropdownMenuInternal {
97 open: bool,
98 opened_at_secs: f64,
99 highlighted: Option<usize>,
100 pointer_mode: bool,
101 grace_until_secs: Option<f64>,
102 last_highlight_rect: Option<(f32, f32, bool)>,
103 trigger_hovered: bool,
104 trigger_pressed: bool,
105 last_label: SharedString,
106 morph_armed_until_secs: f64,
107 label_changed_at_secs: f64,
108 measured_label_width: Rc<RefCell<f32>>,
109 has_measured_label: Rc<RefCell<bool>>,
110 trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
111 menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
112 item_offsets: Rc<RefCell<HashMap<usize, (f32, f32)>>>,
113 focus_handle: FocusHandle,
114}
115
116impl DropdownMenuInternal {
117 fn new(initial_label: SharedString, now: f64, focus_handle: FocusHandle) -> Self {
118 Self {
119 open: false,
120 opened_at_secs: now - 10.0,
121 highlighted: None,
122 pointer_mode: false,
123 grace_until_secs: None,
124 last_highlight_rect: None,
125 trigger_hovered: false,
126 trigger_pressed: false,
127 last_label: initial_label,
128 morph_armed_until_secs: f64::NEG_INFINITY,
129 label_changed_at_secs: now - 10.0,
130 measured_label_width: Rc::new(RefCell::new(0.0)),
131 has_measured_label: Rc::new(RefCell::new(false)),
132 trigger_bounds: Rc::new(RefCell::new(None)),
133 menu_bounds: Rc::new(RefCell::new(None)),
134 item_offsets: Rc::new(RefCell::new(HashMap::new())),
135 focus_handle,
136 }
137 }
138}
139
140fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
141 let rad = angle_deg.to_radians();
142 let cos_a = rad.cos();
143 let sin_a = rad.sin();
144 let pts = [(-3.75_f32, -1.85_f32), (0.0, 1.85), (3.75, -1.85)];
145 let mut builder = PathBuilder::stroke(px(1.8));
146 for (i, (lx, ly)) in pts.iter().enumerate() {
147 let rx = cx + lx * cos_a - ly * sin_a;
148 let ry = cy + lx * sin_a + ly * cos_a;
149 let p = point(px(rx), px(ry));
150 if i == 0 {
151 builder.move_to(p);
152 } else {
153 builder.line_to(p);
154 }
155 }
156 if let Ok(path) = builder.build() {
157 window.paint_path(path, color);
158 }
159}
160
161pub fn next_enabled_item(
163 items: &[DropdownItem],
164 current: Option<usize>,
165 step: isize,
166) -> Option<usize> {
167 if items.is_empty() {
168 return None;
169 }
170 let len = items.len() as isize;
171 let start = match current {
172 Some(idx) => idx as isize,
173 None => {
174 if step > 0 {
175 -1
176 } else {
177 len
178 }
179 }
180 };
181 for offset in 1..=len {
182 let idx = (start + step * offset).rem_euclid(len) as usize;
183 if !items[idx].disabled {
184 return Some(idx);
185 }
186 }
187 None
188}
189
190pub fn item_enter_progress(elapsed: f64, index: usize, reduced: bool) -> f32 {
192 if reduced {
193 return 1.0;
194 }
195 let delay = (index.min(ITEM_STAGGER_CAP) as f64) * ITEM_STAGGER_SECS;
196 let t = ((elapsed - delay) / 0.24).clamp(0.0, 1.0) as f32;
197 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
198}
199
200#[derive(IntoElement)]
203pub struct DropdownMenu {
204 id: ElementId,
205 label: SharedString,
206 icon: Option<IconName>,
207 items: Vec<DropdownItem>,
208}
209
210impl DropdownMenu {
211 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
212 Self {
213 id: id.into(),
214 label: label.into(),
215 icon: None,
216 items: Vec::new(),
217 }
218 }
219
220 pub fn icon(mut self, icon: IconName) -> Self {
221 self.icon = Some(icon);
222 self
223 }
224
225 pub fn item(mut self, item: DropdownItem) -> Self {
226 self.items.push(item);
227 self
228 }
229
230 pub fn items(mut self, items: impl IntoIterator<Item = DropdownItem>) -> Self {
231 self.items.extend(items);
232 self
233 }
234}
235
236impl RenderOnce for DropdownMenu {
237 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
238 let theme = cx.arc_theme().clone();
239 let colors = theme.colors;
240 let motion = theme.motion;
241 let reduced = is_reduced_motion(cx);
242 let now = motion_now(cx);
243
244 let state_id =
245 ElementId::NamedChild(self.id.clone().into(), "__arc-dropdown-menu-state".into());
246 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
247 DropdownMenuInternal::new(self.label.clone(), now, cx.focus_handle())
248 });
249
250 {
251 let prev = internal.read(cx).last_label.clone();
252 if prev != self.label {
253 internal.update(cx, |s, _| {
254 s.last_label = self.label.clone();
255 s.morph_armed_until_secs = now + 0.7;
256 s.label_changed_at_secs = now;
257 });
258 }
259 }
260
261 {
263 let grace = internal.read(cx).grace_until_secs;
264 if let Some(until) = grace {
265 if now >= until {
266 internal.update(cx, |s, _| {
267 if s.highlighted.is_none() {
268 s.last_highlight_rect = None;
269 }
270 s.grace_until_secs = None;
271 });
272 } else {
273 window.request_animation_frame();
274 }
275 }
276 }
277
278 let snap = internal.read(cx).clone();
279 let is_open = snap.open;
280
281 let chevron_deg = if reduced {
283 if is_open { 180.0 } else { 0.0 }
284 } else {
285 arc_spring(
286 (self.id.clone(), "chevron-deg"),
287 if is_open { 180.0 } else { 0.0 },
288 motion.spring.snappy,
289 window,
290 cx,
291 )
292 };
293
294 let measured_w = *snap.measured_label_width.borrow();
296 let morph_active = !reduced
297 && *snap.has_measured_label.borrow()
298 && measured_w > 0.0
299 && now <= snap.morph_armed_until_secs;
300 let morphed_w = if measured_w > 0.0 {
301 let sample = arc_spring_with_options(
302 (self.id.clone(), "label-width"),
303 measured_w,
304 SpringOptions::new(motion.spring.morph),
305 window,
306 cx,
307 );
308 if morph_active {
309 Some(sample.value)
310 } else {
311 None
312 }
313 } else {
314 None
315 };
316
317 let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
319 let label_dur = if reduced {
320 motion.duration.instant.as_secs_f64()
321 } else {
322 motion.duration.standard.as_secs_f64()
323 };
324 let (label_op, label_y) = if label_elapsed < label_dur {
325 window.request_animation_frame();
326 let t = (label_elapsed / label_dur).clamp(0.0, 1.0) as f32;
327 let e = if reduced {
328 t
329 } else {
330 CubicBezier::from_spec(motion.ease.enter).sample(t)
331 };
332 let blur = BlurFallback::evaluate(px((1.0 - e) * f32::from(motion.blur.soft)), reduced);
333 (
334 (e * blur.opacity_multiplier).clamp(0.0, 1.0),
335 if reduced { 0.0 } else { 4.0 * (1.0 - e) },
336 )
337 } else {
338 (1.0, 0.0)
339 };
340
341 let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
343 .animate_initial(false)
344 .config(ArcPresenceConfig {
345 enter_duration: motion.duration.fast,
346 exit_duration: Duration::from_millis(130),
347 enter_ease: motion.ease.enter,
348 exit_ease: motion.ease.standard,
349 fade_on_reduced_motion: true,
350 })
351 .sample(window, cx);
352
353 let trigger_bg = if snap.trigger_pressed {
354 oklab_mix(colors.surface_muted, colors.border, 0.55)
355 } else if is_open || snap.trigger_hovered {
356 colors.surface_muted
357 } else {
358 colors.surface
359 };
360 let trigger_border = if snap.trigger_pressed || is_open || snap.trigger_hovered {
361 colors.border_strong
362 } else {
363 colors.border
364 };
365
366 let label_w_ref = snap.measured_label_width.clone();
367 let has_m_ref = snap.has_measured_label.clone();
368 let label_probe = canvas(
369 move |rect, window, _| {
370 let w = f32::from(rect.size.width);
371 let prev = *label_w_ref.borrow();
372 *label_w_ref.borrow_mut() = w;
373 if w > 0.0 {
374 *has_m_ref.borrow_mut() = true;
375 }
376 if (w - prev).abs() > 0.5 && prev > 0.0 {
377 window.request_animation_frame();
378 }
379 },
380 |_, _, _, _| {},
381 )
382 .absolute()
383 .inset_0();
384
385 let trigger_bounds_ref = snap.trigger_bounds.clone();
386 let trigger_bounds_outside = snap.trigger_bounds.clone();
387 let menu_bounds_outside = snap.menu_bounds.clone();
388 let internal_outside = internal.clone();
389 let trigger_probe = canvas(
390 move |rect, _, _| {
391 *trigger_bounds_ref.borrow_mut() = Some(rect);
392 },
393 move |_, _, window, _| {
394 if is_open {
395 let t_ref = trigger_bounds_outside.clone();
396 let m_ref = menu_bounds_outside.clone();
397 let st = internal_outside.clone();
398 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
399 if !phase.bubble() {
400 return;
401 }
402 let in_trigger =
403 t_ref.borrow().is_some_and(|b| b.contains(&event.position));
404 let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
405 if !in_trigger && !in_menu {
406 st.update(cx, |s, _| {
407 s.open = false;
408 s.highlighted = None;
409 s.last_highlight_rect = None;
410 });
411 window.refresh();
412 }
413 });
414 }
415 },
416 )
417 .absolute()
418 .inset_0();
419
420 let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
421 let int_hover = internal.clone();
422 let int_down = internal.clone();
423 let int_up = internal.clone();
424 let int_out = internal.clone();
425 let int_click = internal.clone();
426 let focus_for_open = snap.focus_handle.clone();
427 let chevron_color = colors.text_muted;
428
429 let trigger_btn = BaseButton::new(trigger_id)
430 .accessibility_label(self.label.clone())
431 .on_click(move |_, window, cx| {
432 let t_now = motion_now(cx);
433 let mut became_open = false;
434 int_click.update(cx, |s, _| {
435 s.open = !s.open;
436 became_open = s.open;
437 if s.open {
438 s.opened_at_secs = t_now;
439 s.highlighted = None;
440 s.last_highlight_rect = None;
441 s.grace_until_secs = None;
442 }
443 });
444 if became_open {
445 window.focus(&focus_for_open, cx);
446 }
447 window.refresh();
448 })
449 .relative()
450 .flex()
451 .flex_row()
452 .items_center()
453 .gap(Spacing::S2)
454 .min_h(ControlHeights::SM)
455 .px(Spacing::S3)
456 .rounded(Radii::CONTROL)
457 .border_1()
458 .border_color(trigger_border)
459 .bg(trigger_bg)
460 .text_color(colors.foreground)
461 .text_size(Typography::TEXT_SM)
462 .font_medium()
463 .when(
464 snap.trigger_hovered && !is_open && !snap.trigger_pressed,
465 |this| this.shadow(Shadows::resting(theme.mode)),
466 )
467 .cursor_pointer()
468 .on_hover(move |hovered, window, cx| {
469 int_hover.update(cx, |s, _| {
470 s.trigger_hovered = *hovered;
471 if !*hovered {
472 s.trigger_pressed = false;
473 }
474 });
475 window.refresh();
476 })
477 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
478 int_down.update(cx, |s, _| s.trigger_pressed = true);
479 window.refresh();
480 })
481 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
482 int_up.update(cx, |s, _| s.trigger_pressed = false);
483 window.refresh();
484 })
485 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
486 int_out.update(cx, |s, _| s.trigger_pressed = false);
487 window.refresh();
488 })
489 .child(trigger_probe)
490 .when_some(self.icon, |this, icon| {
491 this.child(div().text_color(colors.text_secondary).child(icon))
492 })
493 .child(
494 div()
495 .relative()
496 .flex()
497 .items_center()
498 .when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
499 .child(
500 div()
501 .relative()
502 .flex_none()
503 .mt(px(label_y))
504 .opacity(label_op)
505 .child(label_probe)
506 .child(self.label.clone()),
507 ),
508 )
509 .child(
510 canvas(
511 |_, _, _| {},
512 move |rect, _, window, _| {
513 let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
514 let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
515 paint_rotated_chevron(cx, cy, chevron_deg, chevron_color, window);
516 },
517 )
518 .size(px(15.0)),
519 );
520
521 let menu_el = if menu_presence.should_render() && !self.items.is_empty() {
523 let p = menu_presence.progress.clamp(0.0, 1.0);
524 let menu_y = if reduced { 0.0 } else { -5.0 * (1.0 - p) };
525 let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
526
527 let active_geom = snap
529 .highlighted
530 .and_then(|idx| {
531 let (top, h) = snap.item_offsets.borrow().get(&idx).copied()?;
532 let danger = self.items.get(idx).is_some_and(|it| it.destructive);
533 Some((top, h, danger))
534 })
535 .or(snap.last_highlight_rect);
536
537 let has_hi = snap.highlighted.is_some()
538 || snap.grace_until_secs.is_some_and(|until| now < until);
539 let hi_op = arc_transition(
540 (self.id.clone(), "hi-op"),
541 if has_hi && active_geom.is_some() {
542 1.0
543 } else {
544 0.0
545 },
546 if reduced {
547 Duration::ZERO
548 } else {
549 Duration::from_millis(80)
550 },
551 motion.ease.standard,
552 window,
553 cx,
554 );
555
556 let (target_top, target_h, is_danger) = active_geom.unwrap_or((5.0, 36.0, false));
557 let (pill_top, pill_h) = if reduced || !snap.pointer_mode {
558 let _ = arc_spring_with_options(
561 (self.id.clone(), "hi-top"),
562 target_top,
563 SpringOptions::new(motion.spring.snappy),
564 window,
565 cx,
566 );
567 let _ = arc_spring_with_options(
568 (self.id.clone(), "hi-h"),
569 target_h,
570 SpringOptions::new(motion.spring.snappy),
571 window,
572 cx,
573 );
574 (target_top, target_h)
575 } else {
576 (
577 arc_spring(
578 (self.id.clone(), "hi-top"),
579 target_top,
580 motion.spring.snappy,
581 window,
582 cx,
583 ),
584 arc_spring(
585 (self.id.clone(), "hi-h"),
586 target_h,
587 motion.spring.snappy,
588 window,
589 cx,
590 ),
591 )
592 };
593
594 let pill_bg = if is_danger {
595 oklab_mix(colors.danger, colors.surface, 0.08)
596 } else {
597 colors.surface_muted
598 };
599
600 let menu_bounds_ref = snap.menu_bounds.clone();
601 let menu_probe = canvas(
602 move |rect, _, _| {
603 *menu_bounds_ref.borrow_mut() = Some(rect);
604 },
605 |_, _, _, _| {},
606 )
607 .absolute()
608 .inset_0();
609
610 let int_key = internal.clone();
611 let items_for_key = self.items.clone();
612 let offsets_for_key = snap.item_offsets.clone();
613 let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
614 let focus_handle = snap.focus_handle.clone();
615
616 let mut children_els = Vec::with_capacity(self.items.len() * 2);
617 for (idx, item) in self.items.into_iter().enumerate() {
618 if item.separator_before {
619 children_els.push(
620 div()
621 .h(px(1.0))
622 .my(Spacing::S1)
623 .mx(px(-5.0))
624 .bg(colors.border_subtle)
625 .into_any_element(),
626 );
627 }
628
629 let item_id = ElementId::NamedChild(
630 self.id.clone().into(),
631 SharedString::from(format!("item-{idx}")),
632 );
633 let item_p = if is_open {
634 let ip = item_enter_progress(menu_elapsed, idx, reduced);
635 if ip < 0.999 {
636 window.request_animation_frame();
637 }
638 ip
639 } else {
640 1.0
641 };
642 let item_dy = if reduced || !is_open {
643 0.0
644 } else {
645 -2.0 * (1.0 - item_p)
646 };
647
648 let offsets_ref = snap.item_offsets.clone();
649 let menu_b_ref = snap.menu_bounds.clone();
650 let int_rect = internal.clone();
651 let is_curr_hi = snap.highlighted == Some(idx);
652 let is_item_danger = item.destructive;
653 let item_probe = canvas(
654 move |rect, _, cx| {
655 if let Some(mb) = *menu_b_ref.borrow() {
656 let rel_top = f32::from(rect.origin.y - mb.origin.y);
657 let h = f32::from(rect.size.height);
658 offsets_ref.borrow_mut().insert(idx, (rel_top, h));
659 if is_curr_hi {
660 int_rect.update(cx, |s, _| {
661 s.last_highlight_rect = Some((rel_top, h, is_item_danger));
662 });
663 }
664 }
665 },
666 |_, _, _, _| {},
667 )
668 .absolute()
669 .inset_0();
670
671 let int_hi = internal.clone();
672 let int_sel = internal.clone();
673 let offsets_for_hover = snap.item_offsets.clone();
674 let on_select = item.on_select.clone();
675 let item_disabled = item.disabled;
676 let item_fg = if item.destructive {
677 colors.danger
678 } else {
679 colors.foreground
680 };
681 let icon_fg = if item.destructive {
682 colors.danger
683 } else {
684 colors.text_secondary
685 };
686
687 children_els.push(
688 div()
689 .id(item_id)
690 .test_support()
691 .role(Role::MenuItem)
692 .aria_label(item.label.clone())
693 .relative()
694 .flex()
695 .flex_row()
696 .items_center()
697 .gap(px(10.0))
698 .min_h(ControlHeights::SM)
699 .px(px(11.0))
700 .rounded(px(6.0))
701 .text_size(Typography::TEXT_SM)
702 .text_color(item_fg)
703 .mt(px(item_dy))
704 .opacity(if item_disabled { 0.45 } else { item_p })
705 .when(!item_disabled, |this| this.cursor_pointer())
706 .on_hover(move |hovered, window, cx| {
707 if item_disabled {
708 return;
709 }
710 let t_now = motion_now(cx);
711 let geom = offsets_for_hover.borrow().get(&idx).copied();
712 int_hi.update(cx, |s, _| {
713 s.pointer_mode = true;
714 if *hovered {
715 s.highlighted = Some(idx);
716 s.grace_until_secs = None;
717 if let Some((top, h)) = geom {
718 s.last_highlight_rect = Some((top, h, is_item_danger));
719 }
720 } else if s.highlighted == Some(idx) {
721 s.highlighted = None;
722 s.grace_until_secs = Some(t_now + HIGHLIGHT_GRACE_SECS);
723 }
724 });
725 window.refresh();
726 })
727 .on_click(move |_, window, cx| {
728 if item_disabled {
729 return;
730 }
731 int_sel.update(cx, |s, _| {
732 s.open = false;
733 s.highlighted = None;
734 });
735 if let Some(cb) = &on_select {
736 cb(&(), window, cx);
737 }
738 window.refresh();
739 })
740 .child(item_probe)
741 .when_some(item.icon, |this, icon| {
742 this.child(div().w(px(17.0)).text_color(icon_fg).child(icon))
743 })
744 .child(item.label)
745 .into_any_element(),
746 );
747 }
748
749 let highlight_pill = div()
750 .absolute()
751 .left(px(5.0))
752 .right(px(5.0))
753 .top(px(pill_top))
754 .h(px(pill_h))
755 .rounded(px(6.0))
756 .bg(pill_bg)
757 .opacity(hi_op.clamp(0.0, 1.0));
758
759 Some(
760 deferred(
761 div()
762 .id(menu_id)
763 .test_support()
764 .track_focus(&focus_handle)
765 .role(Role::Menu)
766 .absolute()
767 .top(ControlHeights::SM + px(6.0 + menu_y))
768 .right_0()
769 .min_w(px(192.0))
770 .p(px(5.0))
771 .rounded(Radii::PANEL)
772 .border_1()
773 .border_color(colors.border)
774 .bg(colors.surface_raised)
775 .shadow(Shadows::floating(theme.mode))
776 .opacity(p)
777 .flex()
778 .flex_col()
779 .on_key_down(move |event: &KeyDownEvent, window, cx| {
780 match event.keystroke.key.as_str() {
781 "escape" => {
782 int_key.update(cx, |s, _| {
783 s.open = false;
784 s.highlighted = None;
785 });
786 window.refresh();
787 }
788 "down" => {
789 int_key.update(cx, |s, _| {
790 s.pointer_mode = false;
791 s.grace_until_secs = None;
792 let next =
793 next_enabled_item(&items_for_key, s.highlighted, 1);
794 s.highlighted = next;
795 if let Some(idx) = next
796 && let Some(&(top, h)) =
797 offsets_for_key.borrow().get(&idx)
798 {
799 let danger = items_for_key
800 .get(idx)
801 .is_some_and(|it| it.destructive);
802 s.last_highlight_rect = Some((top, h, danger));
803 }
804 });
805 window.refresh();
806 }
807 "up" => {
808 int_key.update(cx, |s, _| {
809 s.pointer_mode = false;
810 s.grace_until_secs = None;
811 let next =
812 next_enabled_item(&items_for_key, s.highlighted, -1);
813 s.highlighted = next;
814 if let Some(idx) = next
815 && let Some(&(top, h)) =
816 offsets_for_key.borrow().get(&idx)
817 {
818 let danger = items_for_key
819 .get(idx)
820 .is_some_and(|it| it.destructive);
821 s.last_highlight_rect = Some((top, h, danger));
822 }
823 });
824 window.refresh();
825 }
826 "enter" | "space" => {
827 let sel = int_key.read(cx).highlighted;
828 if let Some(idx) = sel
829 && let Some(act) = items_for_key.get(idx)
830 && !act.disabled
831 {
832 int_key.update(cx, |s, _| {
833 s.open = false;
834 s.highlighted = None;
835 });
836 if let Some(cb) = &act.on_select {
837 cb(&(), window, cx);
838 }
839 window.refresh();
840 }
841 }
842 _ => {}
843 }
844 })
845 .child(menu_probe)
846 .child(highlight_pill)
847 .children(children_els),
848 )
849 .with_priority(1),
850 )
851 } else {
852 None
853 };
854
855 div()
856 .id(self.id)
857 .relative()
858 .self_start()
859 .child(trigger_btn)
860 .when_some(menu_el, |this, menu| this.child(menu))
861 }
862}
863
864#[cfg(test)]
865mod tests {
866 use std::{cell::Cell, rc::Rc};
867
868 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
869 use gpui_kit::{
870 Context, MouseButton, Render, Role, TestAppContext, div,
871 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
872 };
873
874 use super::*;
875
876 #[test]
877 fn loop_navigation_skips_disabled_and_stagger_caps_at_four() {
878 let items = vec![
879 DropdownItem::new("Rename"),
880 DropdownItem::new("Duplicate").disabled(true),
881 DropdownItem::new("Delete").destructive(true),
882 ];
883 assert_eq!(next_enabled_item(&items, None, 1), Some(0));
884 assert_eq!(next_enabled_item(&items, Some(0), 1), Some(2));
885 assert_eq!(next_enabled_item(&items, Some(2), 1), Some(0));
886 assert_eq!(next_enabled_item(&items, Some(0), -1), Some(2));
887
888 let p0 = item_enter_progress(0.05, 0, false);
889 let p4 = item_enter_progress(0.05, 4, false);
890 let p9 = item_enter_progress(0.05, 9, false);
891 assert!(p0 > p4);
892 assert_eq!(p4, p9, "indices >= 4 share the capped 140ms delay");
893 assert_eq!(item_enter_progress(0.0, 3, true), 1.0);
894 }
895
896 struct Host {
897 selected: Rc<Cell<usize>>,
898 }
899
900 impl Render for Host {
901 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
902 let sel = self.selected.clone();
903 div().p(Spacing::S6).child(
904 DropdownMenu::new("actions-menu", "选项").items([
905 DropdownItem::new("重命名").on_select(cx.listener(move |_, _, _, _| {
906 sel.set(1);
907 })),
908 DropdownItem::new("归档").disabled(true),
909 DropdownItem::new("删除")
910 .separator_before(true)
911 .destructive(true),
912 ]),
913 )
914 }
915 }
916
917 #[gpui_kit::test]
918 fn dropdown_menu_opens_and_invokes_item_callback(cx: &mut TestAppContext) {
919 cx.update(|cx| {
920 gpui_kit::init(cx);
921 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
922 });
923 let selected = Rc::new(Cell::new(0));
924 let (_view, cx) = cx.add_window_view(|_, _| Host {
925 selected: selected.clone(),
926 });
927
928 cx.update(|window, cx| {
929 window.render_frame(cx);
930 let trigger = window.find_by_label("选项");
931 assert_eq!(trigger.role(), Some(Role::Button));
932 let pos = trigger.bounds().center();
933 window.pointer_down(pos, MouseButton::Left, cx);
934 window.pointer_up(pos, MouseButton::Left, cx);
935 window.render_frame(cx);
936
937 let item = window.find_by_label("重命名");
938 assert_eq!(item.role(), Some(Role::MenuItem));
939 let ipos = item.bounds().center();
940 window.pointer_down(ipos, MouseButton::Left, cx);
941 window.pointer_up(ipos, MouseButton::Left, cx);
942 assert_eq!(selected.get(), 1);
943 });
944 }
945}