Skip to main content

arc_ui/actions/
split_button.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/split-button/split-button.tsx` & `.module.css`
3//!
4//! P2 Component #4: `split-button`
5//!
6//! - One joined control with two halves: primary action button + trailing chevron menu trigger.
7//! - Primary press scales the whole pill (`0.97`, backdrop canvas); menu trigger press answers in
8//!   color only so the anchored menu always measures a still trigger rect.
9//! - Variants: `Primary` (`ControlHeights::MD`, `Radii::CONTROL`, `foreground` surface) and
10//!   `Secondary` (`ControlHeights::SM`, `Radii::PILL`, `surface` fill with `border`).
11//! - Floating menu: `ArcPresence` (`y: -5px -> 0`, `130ms` exit), staggered items (`35ms` capped
12//!   at 4), rotating `0° -> 180°` chevron (`PathBuilder` + `motion.spring.snappy`), keyboard
13//!   navigation (`ArrowDown`/`ArrowUp`/`Enter`/`Escape`), destructive styling, and outside dismiss.
14
15use std::{cell::RefCell, rc::Rc, time::Duration};
16
17use arc_motion::{
18    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, TransformOrigin, arc_spring,
19    arc_spring_with_options, is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
20};
21use arc_tokens::{
22    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
23};
24use gpui_kit::{
25    App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
26    MouseButton, MouseDownEvent, ParentElement, PathBuilder, RenderOnce, Role, SharedString,
27    Styled, TestSupportExt as _, Window, assets::IconName, base::Button as BaseButton, canvas,
28    deferred, div, point, prelude::*, px, quad,
29};
30
31type ActionCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
32
33/// Visual style for [`SplitButton`].
34#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
35pub enum SplitButtonVariant {
36    #[default]
37    Primary,
38    Secondary,
39}
40
41/// One menu item inside a [`SplitButton`] dropdown.
42#[derive(Clone)]
43pub struct SplitButtonAction {
44    pub label: SharedString,
45    pub icon: Option<IconName>,
46    pub disabled: bool,
47    pub destructive: bool,
48    pub on_select: Option<ActionCallback>,
49}
50
51impl SplitButtonAction {
52    pub fn new(label: impl Into<SharedString>) -> Self {
53        Self {
54            label: label.into(),
55            icon: None,
56            disabled: false,
57            destructive: false,
58            on_select: None,
59        }
60    }
61
62    pub fn icon(mut self, icon: IconName) -> Self {
63        self.icon = Some(icon);
64        self
65    }
66
67    pub fn disabled(mut self, disabled: bool) -> Self {
68        self.disabled = disabled;
69        self
70    }
71
72    pub fn destructive(mut self, destructive: bool) -> Self {
73        self.destructive = destructive;
74        self
75    }
76
77    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
78        self.on_select = Some(Rc::new(handler));
79        self
80    }
81}
82
83#[derive(Clone)]
84struct SplitButtonInternal {
85    open: bool,
86    opened_at_secs: f64,
87    highlighted: Option<usize>,
88    primary_hovered: bool,
89    primary_pressed: bool,
90    trigger_hovered: bool,
91    trigger_pressed: bool,
92    last_key: SharedString,
93    morph_armed_until_secs: f64,
94    label_changed_at_secs: f64,
95    measured_slot_width: Rc<RefCell<f32>>,
96    has_measured: Rc<RefCell<bool>>,
97    group_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
98    menu_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
99    focus_handle: FocusHandle,
100}
101
102impl SplitButtonInternal {
103    fn new(initial_key: SharedString, now: f64, focus_handle: FocusHandle) -> Self {
104        Self {
105            open: false,
106            opened_at_secs: now - 10.0,
107            highlighted: None,
108            primary_hovered: false,
109            primary_pressed: false,
110            trigger_hovered: false,
111            trigger_pressed: false,
112            last_key: initial_key,
113            morph_armed_until_secs: f64::NEG_INFINITY,
114            label_changed_at_secs: now - 10.0,
115            measured_slot_width: Rc::new(RefCell::new(0.0)),
116            has_measured: Rc::new(RefCell::new(false)),
117            group_bounds: Rc::new(RefCell::new(None)),
118            menu_bounds: Rc::new(RefCell::new(None)),
119            focus_handle,
120        }
121    }
122}
123
124/// Arc `SplitButton` joining one primary action with a dropdown menu of sibling actions.
125#[derive(IntoElement)]
126pub struct SplitButton {
127    id: ElementId,
128    label: SharedString,
129    icon: Option<IconName>,
130    actions: Vec<SplitButtonAction>,
131    variant: SplitButtonVariant,
132    disabled: bool,
133    on_click: Option<ActionCallback>,
134}
135
136impl SplitButton {
137    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
138        Self {
139            id: id.into(),
140            label: label.into(),
141            icon: None,
142            actions: Vec::new(),
143            variant: SplitButtonVariant::Primary,
144            disabled: false,
145            on_click: None,
146        }
147    }
148
149    pub fn icon(mut self, icon: IconName) -> Self {
150        self.icon = Some(icon);
151        self
152    }
153
154    pub fn variant(mut self, variant: SplitButtonVariant) -> Self {
155        self.variant = variant;
156        self
157    }
158
159    pub fn disabled(mut self, disabled: bool) -> Self {
160        self.disabled = disabled;
161        self
162    }
163
164    pub fn action(mut self, action: SplitButtonAction) -> Self {
165        self.actions.push(action);
166        self
167    }
168
169    pub fn actions(mut self, actions: impl IntoIterator<Item = SplitButtonAction>) -> Self {
170        self.actions.extend(actions);
171        self
172    }
173
174    pub fn on_click(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
175        self.on_click = Some(Rc::new(handler));
176        self
177    }
178}
179
180fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
181    let rad = angle_deg.to_radians();
182    let cos_a = rad.cos();
183    let sin_a = rad.sin();
184    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
185    let mut builder = PathBuilder::stroke(px(1.75));
186    for (i, (lx, ly)) in pts.iter().enumerate() {
187        let rx = cx + lx * cos_a - ly * sin_a;
188        let ry = cy + lx * sin_a + ly * cos_a;
189        let p = point(px(rx), px(ry));
190        if i == 0 {
191            builder.move_to(p);
192        } else {
193            builder.line_to(p);
194        }
195    }
196    if let Ok(path) = builder.build() {
197        window.paint_path(path, color);
198    }
199}
200
201fn next_enabled_index(
202    actions: &[SplitButtonAction],
203    current: Option<usize>,
204    step: isize,
205) -> Option<usize> {
206    if actions.is_empty() {
207        return None;
208    }
209    let len = actions.len() as isize;
210    let start = match current {
211        Some(idx) => idx as isize,
212        None => {
213            if step > 0 {
214                -1
215            } else {
216                len
217            }
218        }
219    };
220    for offset in 1..=len {
221        let idx = (start + step * offset).rem_euclid(len) as usize;
222        if !actions[idx].disabled {
223            return Some(idx);
224        }
225    }
226    None
227}
228
229impl RenderOnce for SplitButton {
230    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
231        let theme = cx.arc_theme().clone();
232        let colors = theme.colors;
233        let motion = theme.motion;
234        let reduced = is_reduced_motion(cx);
235        let now = motion_now(cx);
236
237        let content_key: SharedString = match self.icon {
238            Some(icon) => format!("{icon:?}|{}", self.label).into(),
239            None => self.label.clone(),
240        };
241
242        let state_id =
243            ElementId::NamedChild(self.id.clone().into(), "__arc-split-button-state".into());
244        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
245            SplitButtonInternal::new(content_key.clone(), now, cx.focus_handle())
246        });
247
248        {
249            let prev = internal.read(cx).last_key.clone();
250            if prev != content_key {
251                internal.update(cx, |s, _| {
252                    s.last_key = content_key.clone();
253                    s.morph_armed_until_secs = now + 0.7;
254                    s.label_changed_at_secs = now;
255                });
256            }
257        }
258
259        let snap = internal.read(cx).clone();
260        let is_open = snap.open && !self.disabled;
261
262        // Primary half scales the whole pill to 0.97; trigger half never scales.
263        let target_scale = if !self.disabled && !reduced && snap.primary_pressed {
264            0.97
265        } else {
266            1.0
267        };
268        let animated_scale = if reduced {
269            1.0
270        } else {
271            arc_spring(
272                (self.id.clone(), "press-scale"),
273                target_scale,
274                motion.spring.snappy,
275                window,
276                cx,
277            )
278        };
279
280        let chevron_deg = if reduced {
281            if is_open { 180.0 } else { 0.0 }
282        } else {
283            arc_spring(
284                (self.id.clone(), "chevron-deg"),
285                if is_open { 180.0 } else { 0.0 },
286                motion.spring.snappy,
287                window,
288                cx,
289            )
290        };
291
292        // Label width morph (`motion.spring.morph`).
293        let measured_w = *snap.measured_slot_width.borrow();
294        let morph_active = !reduced
295            && *snap.has_measured.borrow()
296            && measured_w > 0.0
297            && now <= snap.morph_armed_until_secs;
298        let morphed_w = if measured_w > 0.0 {
299            let sample = arc_spring_with_options(
300                (self.id.clone(), "slot-width"),
301                measured_w,
302                SpringOptions::new(motion.spring.morph),
303                window,
304                cx,
305            );
306            if morph_active {
307                Some(sample.value)
308            } else {
309                None
310            }
311        } else {
312            None
313        };
314
315        // Label crossfade with subtle blur fallback.
316        let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
317        let label_dur = if reduced {
318            motion.duration.instant.as_secs_f64()
319        } else {
320            motion.duration.standard.as_secs_f64()
321        };
322        let (label_op, label_y) = if label_elapsed < label_dur {
323            window.request_animation_frame();
324            let t = (label_elapsed / label_dur).clamp(0.0, 1.0) as f32;
325            let e = if reduced {
326                t
327            } else {
328                CubicBezier::from_spec(motion.ease.enter).sample(t)
329            };
330            let blur = BlurFallback::evaluate(px((1.0 - e) * f32::from(motion.blur.soft)), reduced);
331            (
332                (e * blur.opacity_multiplier).clamp(0.0, 1.0),
333                if reduced { 0.0 } else { 5.0 * (1.0 - e) },
334            )
335        } else {
336            (1.0, 0.0)
337        };
338
339        // Menu presence (`130ms` exit matches split-button.module.css line 41).
340        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
341            .animate_initial(false)
342            .config(ArcPresenceConfig {
343                enter_duration: motion.duration.fast,
344                exit_duration: Duration::from_millis(130),
345                enter_ease: motion.ease.enter,
346                exit_ease: motion.ease.standard,
347                fade_on_reduced_motion: true,
348            })
349            .sample(window, cx);
350
351        let is_secondary = self.variant == SplitButtonVariant::Secondary;
352        let radius = if is_secondary {
353            Radii::PILL
354        } else {
355            Radii::CONTROL
356        };
357        let min_h = if is_secondary {
358            ControlHeights::SM
359        } else {
360            ControlHeights::MD
361        };
362        let trigger_w = if is_secondary { px(28.0) } else { px(32.0) };
363
364        let (base_bg, border_color, fg, divider_color, primary_bg, trigger_bg) = if is_secondary {
365            let hover_bg = colors.surface_muted;
366            let active_bg = oklab_mix(colors.surface_muted, colors.border, 0.45);
367            let p_bg = if self.disabled {
368                colors.surface
369            } else if snap.primary_pressed {
370                active_bg
371            } else if snap.primary_hovered {
372                hover_bg
373            } else {
374                colors.surface
375            };
376            let t_bg = if self.disabled {
377                colors.surface
378            } else if snap.trigger_pressed || is_open {
379                active_bg
380            } else if snap.trigger_hovered {
381                hover_bg
382            } else {
383                colors.surface
384            };
385            (
386                colors.surface,
387                colors.border,
388                colors.foreground,
389                colors.border_subtle,
390                p_bg,
391                t_bg,
392            )
393        } else {
394            let hover_bg = oklab_mix(colors.foreground, colors.background, 0.88);
395            let active_bg = oklab_mix(colors.foreground, colors.background, 0.80);
396            let p_bg = if self.disabled {
397                colors.foreground
398            } else if snap.primary_pressed {
399                active_bg
400            } else if snap.primary_hovered {
401                hover_bg
402            } else {
403                colors.foreground
404            };
405            let t_bg = if self.disabled {
406                colors.foreground
407            } else if snap.trigger_pressed || is_open {
408                active_bg
409            } else if snap.trigger_hovered {
410                hover_bg
411            } else {
412                colors.foreground
413            };
414            (
415                colors.foreground,
416                colors.foreground,
417                colors.background,
418                oklab_mix(colors.background, colors.foreground, 0.18),
419                p_bg,
420                t_bg,
421            )
422        };
423
424        let group_bounds_ref = snap.group_bounds.clone();
425        let menu_bounds_for_outside = snap.menu_bounds.clone();
426        let group_bounds_for_outside = snap.group_bounds.clone();
427        let internal_outside = internal.clone();
428        let backdrop = canvas(
429            move |rect, _, _| {
430                *group_bounds_ref.borrow_mut() = Some(rect);
431            },
432            move |rect, _, window, _| {
433                let paint_rect = scaled_bounds(
434                    rect,
435                    animated_scale,
436                    animated_scale,
437                    TransformOrigin::CENTER,
438                );
439                window.paint_quad(quad(
440                    paint_rect,
441                    Corners::all(radius),
442                    base_bg,
443                    Edges::all(px(1.0)),
444                    border_color,
445                    BorderStyle::Solid,
446                ));
447
448                // Close menu when user clicks outside both the split button and its menu.
449                if is_open {
450                    let g_ref = group_bounds_for_outside.clone();
451                    let m_ref = menu_bounds_for_outside.clone();
452                    let st = internal_outside.clone();
453                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
454                        if !phase.bubble() {
455                            return;
456                        }
457                        let in_group = g_ref.borrow().is_some_and(|b| b.contains(&event.position));
458                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
459                        if !in_group && !in_menu {
460                            st.update(cx, |s, _| {
461                                s.open = false;
462                                s.highlighted = None;
463                            });
464                            window.refresh();
465                        }
466                    });
467                }
468            },
469        )
470        .absolute()
471        .inset_0();
472
473        let slot_w_ref = snap.measured_slot_width.clone();
474        let has_m_ref = snap.has_measured.clone();
475        let slot_probe = canvas(
476            move |rect, window, _| {
477                let w = f32::from(rect.size.width);
478                let prev = *slot_w_ref.borrow();
479                *slot_w_ref.borrow_mut() = w;
480                if w > 0.0 {
481                    *has_m_ref.borrow_mut() = true;
482                }
483                if (w - prev).abs() > 0.5 && prev > 0.0 {
484                    window.request_animation_frame();
485                }
486            },
487            |_, _, _, _| {},
488        )
489        .absolute()
490        .inset_0();
491
492        let primary_id = ElementId::NamedChild(self.id.clone().into(), "primary".into());
493        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
494
495        let int_p_hover = internal.clone();
496        let int_p_down = internal.clone();
497        let int_p_up = internal.clone();
498        let int_p_out = internal.clone();
499        let int_t_hover = internal.clone();
500        let int_t_down = internal.clone();
501        let int_t_up = internal.clone();
502        let int_t_out = internal.clone();
503        let int_t_click = internal.clone();
504        let on_click = self.on_click;
505        let is_disabled = self.disabled;
506        let focus_for_open = snap.focus_handle.clone();
507        let actions_for_trigger = self.actions.clone();
508
509        let primary_btn = BaseButton::new(primary_id)
510            .disabled(self.disabled)
511            .accessibility_label(self.label.clone())
512            .on_click(move |_, window, cx| {
513                if is_disabled {
514                    return;
515                }
516                if let Some(handler) = &on_click {
517                    handler(&(), window, cx);
518                }
519                window.refresh();
520            })
521            .relative()
522            .flex()
523            .items_center()
524            .justify_center()
525            .min_h(min_h)
526            .when(is_secondary, |this| {
527                this.min_w(px(142.0))
528                    .px(Spacing::S3)
529                    .text_size(Typography::TEXT_XS)
530            })
531            .when(!is_secondary, |this| {
532                this.px(Spacing::S4).text_size(Typography::TEXT_SM)
533            })
534            .rounded_tl(radius)
535            .rounded_bl(radius)
536            .bg(primary_bg)
537            .text_color(fg)
538            .when(self.disabled, |this| this.opacity(0.52))
539            .when(!self.disabled, |this| this.cursor_pointer())
540            .on_hover(move |hovered, window, cx| {
541                int_p_hover.update(cx, |s, _| {
542                    s.primary_hovered = *hovered;
543                    if !*hovered {
544                        s.primary_pressed = false;
545                    }
546                });
547                window.refresh();
548            })
549            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
550                if is_disabled {
551                    return;
552                }
553                int_p_down.update(cx, |s, _| s.primary_pressed = true);
554                window.refresh();
555            })
556            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
557                int_p_up.update(cx, |s, _| s.primary_pressed = false);
558                window.refresh();
559            })
560            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
561                int_p_out.update(cx, |s, _| s.primary_pressed = false);
562                window.refresh();
563            })
564            .child(
565                div()
566                    .relative()
567                    .flex()
568                    .items_center()
569                    .when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
570                    .child(
571                        div()
572                            .relative()
573                            .flex_none()
574                            .flex()
575                            .flex_row()
576                            .items_center()
577                            .gap(Spacing::S2)
578                            .mt(px(label_y))
579                            .opacity(label_op)
580                            .child(slot_probe)
581                            .when_some(self.icon, |this, icon| this.child(icon))
582                            .child(self.label.clone()),
583                    ),
584            );
585
586        let trigger_label = SharedString::from(format!("{} more actions", self.label));
587        let trigger_btn = BaseButton::new(trigger_id)
588            .disabled(self.disabled)
589            .accessibility_label(trigger_label)
590            .on_click(move |_, window, cx| {
591                if is_disabled {
592                    return;
593                }
594                let t_now = motion_now(cx);
595                let mut became_open = false;
596                int_t_click.update(cx, |s, _| {
597                    s.open = !s.open;
598                    became_open = s.open;
599                    if s.open {
600                        s.opened_at_secs = t_now;
601                        s.highlighted = next_enabled_index(&actions_for_trigger, None, 1);
602                    } else {
603                        s.highlighted = None;
604                    }
605                });
606                if became_open {
607                    window.focus(&focus_for_open, cx);
608                }
609                window.refresh();
610            })
611            .relative()
612            .flex()
613            .items_center()
614            .justify_center()
615            .w(trigger_w)
616            .min_h(min_h)
617            .border_l_1()
618            .border_color(divider_color)
619            .rounded_tr(radius)
620            .rounded_br(radius)
621            .bg(trigger_bg)
622            .text_color(fg)
623            .when(self.disabled, |this| this.opacity(0.52))
624            .when(!self.disabled, |this| this.cursor_pointer())
625            .on_hover(move |hovered, window, cx| {
626                int_t_hover.update(cx, |s, _| {
627                    s.trigger_hovered = *hovered;
628                    if !*hovered {
629                        s.trigger_pressed = false;
630                    }
631                });
632                window.refresh();
633            })
634            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
635                if is_disabled {
636                    return;
637                }
638                int_t_down.update(cx, |s, _| s.trigger_pressed = true);
639                window.refresh();
640            })
641            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
642                int_t_up.update(cx, |s, _| s.trigger_pressed = false);
643                window.refresh();
644            })
645            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
646                int_t_out.update(cx, |s, _| s.trigger_pressed = false);
647                window.refresh();
648            })
649            .child(
650                canvas(
651                    |_, _, _| {},
652                    move |rect, _, window, _| {
653                        let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
654                        let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
655                        paint_rotated_chevron(cx, cy, chevron_deg, fg, window);
656                    },
657                )
658                .size(px(16.0)),
659            );
660
661        // Floating menu rendered via `deferred` overlay with staggered item entrance.
662        let menu_el = if menu_presence.should_render() && !self.actions.is_empty() {
663            let p = menu_presence.progress.clamp(0.0, 1.0);
664            let menu_y = if reduced { 0.0 } else { -5.0 * (1.0 - p) };
665            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
666            let menu_bounds_ref = snap.menu_bounds.clone();
667            let menu_probe = canvas(
668                move |rect, _, _| {
669                    *menu_bounds_ref.borrow_mut() = Some(rect);
670                },
671                |_, _, _, _| {},
672            )
673            .absolute()
674            .inset_0();
675
676            let int_key = internal.clone();
677            let actions_key = self.actions.clone();
678            let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
679            let focus_handle = snap.focus_handle.clone();
680            let highlighted = snap.highlighted;
681
682            let item_rows = self.actions.into_iter().enumerate().map(|(idx, action)| {
683                let is_hi = highlighted == Some(idx);
684                let item_id = ElementId::NamedChild(
685                    self.id.clone().into(),
686                    SharedString::from(format!("menu-item-{idx}")),
687                );
688                let stagger_delay = if reduced {
689                    0.0
690                } else {
691                    (idx.min(4) as f64) * 0.035
692                };
693                let item_op = if reduced || !is_open {
694                    1.0
695                } else {
696                    let t = ((menu_elapsed - stagger_delay)
697                        / motion.duration.standard.as_secs_f64())
698                    .clamp(0.0, 1.0) as f32;
699                    if t < 1.0 {
700                        window.request_animation_frame();
701                    }
702                    CubicBezier::from_spec(motion.ease.enter).sample(t)
703                };
704
705                let int_hi = internal.clone();
706                let int_sel = internal.clone();
707                let on_select = action.on_select.clone();
708                let item_disabled = action.disabled;
709                let item_fg = if action.destructive {
710                    colors.danger
711                } else {
712                    colors.foreground
713                };
714                let hi_bg = if action.destructive {
715                    oklab_mix(colors.danger, colors.surface, 0.08)
716                } else {
717                    colors.surface_muted
718                };
719
720                div()
721                    .id(item_id)
722                    .test_support()
723                    .role(Role::MenuItem)
724                    .aria_label(action.label.clone())
725                    .flex()
726                    .flex_row()
727                    .items_center()
728                    .gap(px(10.0))
729                    .min_h(ControlHeights::SM)
730                    .px(px(10.0))
731                    .rounded(px(6.0))
732                    .text_size(Typography::TEXT_SM)
733                    .text_color(item_fg)
734                    .bg(if is_hi && !item_disabled {
735                        hi_bg
736                    } else {
737                        Hsla::transparent_black()
738                    })
739                    .opacity(if item_disabled { 0.45 } else { item_op })
740                    .when(!item_disabled, |this| this.cursor_pointer())
741                    .on_hover(move |hovered, window, cx| {
742                        if item_disabled {
743                            return;
744                        }
745                        int_hi.update(cx, |s, _| {
746                            if *hovered {
747                                s.highlighted = Some(idx);
748                            } else if s.highlighted == Some(idx) {
749                                s.highlighted = None;
750                            }
751                        });
752                        window.refresh();
753                    })
754                    .on_click(move |_, window, cx| {
755                        if item_disabled {
756                            return;
757                        }
758                        int_sel.update(cx, |s, _| {
759                            s.open = false;
760                            s.highlighted = None;
761                        });
762                        if let Some(cb) = &on_select {
763                            cb(&(), window, cx);
764                        }
765                        window.refresh();
766                    })
767                    .when_some(action.icon, |this, icon| this.child(icon))
768                    .child(action.label)
769            });
770
771            Some(
772                deferred(
773                    div()
774                        .id(menu_id)
775                        .test_support()
776                        .track_focus(&focus_handle)
777                        .role(Role::Menu)
778                        .absolute()
779                        .top(min_h + px(4.0 + menu_y))
780                        .right_0()
781                        .min_w(px(192.0))
782                        .p(px(5.0))
783                        .rounded(Radii::PANEL)
784                        .border_1()
785                        .border_color(colors.border)
786                        .bg(colors.surface_raised)
787                        .shadow(Shadows::floating(theme.mode))
788                        .opacity(p)
789                        .flex()
790                        .flex_col()
791                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
792                            match event.keystroke.key.as_str() {
793                                "escape" => {
794                                    int_key.update(cx, |s, _| {
795                                        s.open = false;
796                                        s.highlighted = None;
797                                    });
798                                    window.refresh();
799                                }
800                                "down" => {
801                                    int_key.update(cx, |s, _| {
802                                        s.highlighted =
803                                            next_enabled_index(&actions_key, s.highlighted, 1);
804                                    });
805                                    window.refresh();
806                                }
807                                "up" => {
808                                    int_key.update(cx, |s, _| {
809                                        s.highlighted =
810                                            next_enabled_index(&actions_key, s.highlighted, -1);
811                                    });
812                                    window.refresh();
813                                }
814                                "enter" | "space" => {
815                                    let sel = int_key.read(cx).highlighted;
816                                    if let Some(idx) = sel
817                                        && let Some(act) = actions_key.get(idx)
818                                        && !act.disabled
819                                    {
820                                        int_key.update(cx, |s, _| {
821                                            s.open = false;
822                                            s.highlighted = None;
823                                        });
824                                        if let Some(cb) = &act.on_select {
825                                            cb(&(), window, cx);
826                                        }
827                                        window.refresh();
828                                    }
829                                }
830                                _ => {}
831                            }
832                        })
833                        .child(menu_probe)
834                        .children(item_rows),
835                )
836                .with_priority(1),
837            )
838        } else {
839            None
840        };
841
842        div()
843            .id(self.id)
844            .relative()
845            .self_start()
846            .flex()
847            .flex_row()
848            .items_stretch()
849            .p(px(1.0))
850            .rounded(radius)
851            .child(backdrop)
852            .child(primary_btn)
853            .child(trigger_btn)
854            .when_some(menu_el, |this, menu| this.child(menu))
855    }
856}
857
858#[cfg(test)]
859mod tests {
860    use std::{cell::Cell, rc::Rc};
861
862    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
863    use gpui_kit::{
864        Context, MouseButton, Render, Role, TestAppContext, div,
865        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
866    };
867
868    use super::*;
869
870    struct SplitHost {
871        primary_clicks: Rc<Cell<usize>>,
872        menu_clicks: Rc<Cell<usize>>,
873    }
874
875    impl Render for SplitHost {
876        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
877            let p_clicks = self.primary_clicks.clone();
878            let m_clicks = self.menu_clicks.clone();
879            div().p(Spacing::S6).child(
880                SplitButton::new("merge-split", "Merge pull request")
881                    .on_click(cx.listener(move |_, _, _, _| {
882                        p_clicks.set(p_clicks.get() + 1);
883                    }))
884                    .actions([
885                        SplitButtonAction::new("Squash and merge").on_select(cx.listener(
886                            move |_, _, _, _| {
887                                m_clicks.set(m_clicks.get() + 1);
888                            },
889                        )),
890                        SplitButtonAction::new("Rebase and merge").disabled(true),
891                    ]),
892            )
893        }
894    }
895
896    #[gpui_kit::test]
897    fn split_button_primary_and_menu_selection_work(cx: &mut TestAppContext) {
898        cx.update(|cx| {
899            gpui_kit::init(cx);
900            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
901        });
902        let primary_clicks = Rc::new(Cell::new(0usize));
903        let menu_clicks = Rc::new(Cell::new(0usize));
904        let (_view, cx) = cx.add_window_view(|_, _| SplitHost {
905            primary_clicks: primary_clicks.clone(),
906            menu_clicks: menu_clicks.clone(),
907        });
908
909        cx.update(|window, cx| {
910            window.render_frame(cx);
911            let primary = window.find_by_label("Merge pull request");
912            assert_eq!(primary.role(), Some(Role::Button));
913            let pos = primary.bounds().center();
914            window.pointer_down(pos, MouseButton::Left, cx);
915            window.pointer_up(pos, MouseButton::Left, cx);
916            assert_eq!(primary_clicks.get(), 1);
917
918            // Open menu via chevron trigger
919            let trigger = window.find_by_label("Merge pull request more actions");
920            let t_pos = trigger.bounds().center();
921            window.pointer_down(t_pos, MouseButton::Left, cx);
922            window.pointer_up(t_pos, MouseButton::Left, cx);
923            window.render_frame(cx);
924
925            let item = window.find_by_label("Squash and merge");
926            assert_eq!(item.role(), Some(Role::MenuItem));
927            let i_pos = item.bounds().center();
928            window.pointer_down(i_pos, MouseButton::Left, cx);
929            window.pointer_up(i_pos, MouseButton::Left, cx);
930            assert_eq!(menu_clicks.get(), 1);
931        });
932    }
933}