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};
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, SplitButtonTokens as T,
23    Typography, oklab_mix,
24};
25use gpui_kit::{
26    Anchor, App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
27    KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, PathBuilder, RenderOnce, Role,
28    SharedString, Styled, TestSupportExt as _, Window, anchored, assets::IconName,
29    base::Button as BaseButton, canvas, deferred, div, point, prelude::*, px, quad, svg,
30};
31
32type ActionCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
33
34/// Visual style for [`SplitButton`].
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
36pub enum SplitButtonVariant {
37    #[default]
38    Primary,
39    Secondary,
40}
41
42/// One menu item inside a [`SplitButton`] dropdown.
43#[derive(Clone)]
44pub struct SplitButtonAction {
45    pub label: SharedString,
46    pub icon: Option<IconName>,
47    pub disabled: bool,
48    pub destructive: bool,
49    pub on_select: Option<ActionCallback>,
50}
51
52impl SplitButtonAction {
53    pub fn new(label: impl Into<SharedString>) -> Self {
54        Self {
55            label: label.into(),
56            icon: None,
57            disabled: false,
58            destructive: false,
59            on_select: None,
60        }
61    }
62
63    pub fn icon(mut self, icon: IconName) -> Self {
64        self.icon = Some(icon);
65        self
66    }
67
68    pub fn disabled(mut self, disabled: bool) -> Self {
69        self.disabled = disabled;
70        self
71    }
72
73    pub fn destructive(mut self, destructive: bool) -> Self {
74        self.destructive = destructive;
75        self
76    }
77
78    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
79        self.on_select = Some(Rc::new(handler));
80        self
81    }
82}
83
84#[derive(Clone)]
85struct SplitButtonInternal {
86    open: bool,
87    opened_at_secs: f64,
88    highlighted: Option<usize>,
89    primary_hovered: bool,
90    primary_pressed: bool,
91    trigger_hovered: bool,
92    trigger_pressed: bool,
93    last_key: SharedString,
94    morph_armed_until_secs: f64,
95    label_changed_at_secs: f64,
96    measured_slot_width: Rc<RefCell<f32>>,
97    has_measured: Rc<RefCell<bool>>,
98    group_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
99    menu_bounds: Rc<RefCell<Option<gpui_kit::Bounds<gpui_kit::Pixels>>>>,
100    focus_handle: FocusHandle,
101    trigger_focus: FocusHandle,
102    label: SharedString,
103    previous_label: SharedString,
104    icon: Option<IconName>,
105    previous_icon: Option<IconName>,
106    icon_changed_at_secs: f64,
107}
108
109impl SplitButtonInternal {
110    fn new(
111        initial_key: SharedString,
112        label: SharedString,
113        icon: Option<IconName>,
114        now: f64,
115        focus_handle: FocusHandle,
116        trigger_focus: FocusHandle,
117    ) -> Self {
118        Self {
119            open: false,
120            opened_at_secs: now - 10.0,
121            highlighted: None,
122            primary_hovered: false,
123            primary_pressed: false,
124            trigger_hovered: false,
125            trigger_pressed: false,
126            last_key: initial_key,
127            morph_armed_until_secs: f64::NEG_INFINITY,
128            label_changed_at_secs: now - 10.0,
129            measured_slot_width: Rc::new(RefCell::new(0.0)),
130            has_measured: Rc::new(RefCell::new(false)),
131            group_bounds: Rc::new(RefCell::new(None)),
132            menu_bounds: Rc::new(RefCell::new(None)),
133            focus_handle,
134            trigger_focus,
135            label,
136            previous_label: "".into(),
137            icon,
138            previous_icon: None,
139            icon_changed_at_secs: now - 10.0,
140        }
141    }
142}
143
144/// Arc `SplitButton` joining one primary action with a dropdown menu of sibling actions.
145#[derive(IntoElement)]
146pub struct SplitButton {
147    id: ElementId,
148    label: SharedString,
149    icon: Option<IconName>,
150    actions: Vec<SplitButtonAction>,
151    variant: SplitButtonVariant,
152    disabled: bool,
153    on_click: Option<ActionCallback>,
154}
155
156impl SplitButton {
157    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
158        Self {
159            id: id.into(),
160            label: label.into(),
161            icon: None,
162            actions: Vec::new(),
163            variant: SplitButtonVariant::Primary,
164            disabled: false,
165            on_click: None,
166        }
167    }
168
169    pub fn icon(mut self, icon: IconName) -> Self {
170        self.icon = Some(icon);
171        self
172    }
173
174    pub fn variant(mut self, variant: SplitButtonVariant) -> Self {
175        self.variant = variant;
176        self
177    }
178
179    pub fn disabled(mut self, disabled: bool) -> Self {
180        self.disabled = disabled;
181        self
182    }
183
184    pub fn action(mut self, action: SplitButtonAction) -> Self {
185        self.actions.push(action);
186        self
187    }
188
189    pub fn actions(mut self, actions: impl IntoIterator<Item = SplitButtonAction>) -> Self {
190        self.actions.extend(actions);
191        self
192    }
193
194    pub fn on_click(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
195        self.on_click = Some(Rc::new(handler));
196        self
197    }
198}
199
200fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
201    let rad = angle_deg.to_radians();
202    let cos_a = rad.cos();
203    let sin_a = rad.sin();
204    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
205    let mut builder = PathBuilder::stroke(px(1.75));
206    for (i, (lx, ly)) in pts.iter().enumerate() {
207        let rx = cx + lx * cos_a - ly * sin_a;
208        let ry = cy + lx * sin_a + ly * cos_a;
209        let p = point(px(rx), px(ry));
210        if i == 0 {
211            builder.move_to(p);
212        } else {
213            builder.line_to(p);
214        }
215    }
216    if let Ok(path) = builder.build() {
217        window.paint_path(path, color);
218    }
219}
220
221/// 与上游一致,仅保留至少两个字符的共同前后缀身份。
222fn shared_edges(previous: &str, next: &str) -> (usize, usize) {
223    let previous: Vec<_> = previous.chars().collect();
224    let next: Vec<_> = next.chars().collect();
225    let mut start = previous
226        .iter()
227        .zip(&next)
228        .take_while(|(a, b)| a == b)
229        .count();
230    let mut end = previous[start..]
231        .iter()
232        .rev()
233        .zip(next[start..].iter().rev())
234        .take_while(|(a, b)| a == b)
235        .count();
236    if start < 2 {
237        start = 0;
238    }
239    if end < 2 {
240        end = 0;
241    }
242    (start, end)
243}
244
245fn next_enabled_index(
246    actions: &[SplitButtonAction],
247    current: Option<usize>,
248    step: isize,
249) -> Option<usize> {
250    if actions.is_empty() {
251        return None;
252    }
253    let len = actions.len() as isize;
254    let start = match current {
255        Some(idx) => idx as isize,
256        None => {
257            if step > 0 {
258                -1
259            } else {
260                len
261            }
262        }
263    };
264    for offset in 1..=len {
265        let idx = (start + step * offset).rem_euclid(len) as usize;
266        if !actions[idx].disabled {
267            return Some(idx);
268        }
269    }
270    None
271}
272
273impl RenderOnce for SplitButton {
274    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
275        let theme = cx.arc_theme().clone();
276        let colors = theme.colors;
277        let motion = theme.motion;
278        let reduced = is_reduced_motion(cx);
279        let now = motion_now(cx);
280
281        let content_key: SharedString = match self.icon {
282            Some(icon) => format!("{icon:?}|{}", self.label).into(),
283            None => self.label.clone(),
284        };
285
286        let state_id =
287            ElementId::NamedChild(self.id.clone().into(), "__arc-split-button-state".into());
288        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
289            SplitButtonInternal::new(
290                content_key.clone(),
291                self.label.clone(),
292                self.icon,
293                now,
294                cx.focus_handle(),
295                cx.focus_handle(),
296            )
297        });
298
299        {
300            let prev = internal.read(cx).last_key.clone();
301            if prev != content_key {
302                internal.update(cx, |s, _| {
303                    s.last_key = content_key.clone();
304                    s.morph_armed_until_secs = now + T::MORPH_WINDOW;
305                    if s.label != self.label {
306                        s.previous_label = s.label.clone();
307                        s.label = self.label.clone();
308                        s.label_changed_at_secs = now;
309                    }
310                    if s.icon != self.icon {
311                        s.previous_icon = s.icon;
312                        s.icon = self.icon;
313                        s.icon_changed_at_secs = now;
314                    }
315                });
316            }
317        }
318
319        if self.disabled {
320            internal.update(cx, |s, _| {
321                s.open = false;
322                s.highlighted = None;
323                s.primary_pressed = false;
324                s.trigger_pressed = false;
325            });
326        }
327        let snap = internal.read(cx).clone();
328        let is_open = snap.open && !self.disabled;
329
330        // Primary half scales the whole pill to 0.97; trigger half never scales.
331        let target_scale = if !self.disabled && !reduced && snap.primary_pressed {
332            T::PRESS_SCALE
333        } else {
334            1.0
335        };
336        let animated_scale = if reduced {
337            1.0
338        } else {
339            arc_spring(
340                (self.id.clone(), "press-scale"),
341                target_scale,
342                motion.spring.snappy,
343                window,
344                cx,
345            )
346        };
347
348        let chevron_deg = if reduced {
349            if is_open { 180.0 } else { 0.0 }
350        } else {
351            arc_spring(
352                (self.id.clone(), "chevron-deg"),
353                if is_open { 180.0 } else { 0.0 },
354                motion.spring.snappy,
355                window,
356                cx,
357            )
358        };
359
360        // Label width morph (`motion.spring.morph`).
361        let measured_w = *snap.measured_slot_width.borrow();
362        let morph_active = !reduced
363            && *snap.has_measured.borrow()
364            && measured_w > 0.0
365            && now <= snap.morph_armed_until_secs;
366        let morphed_w = if measured_w > 0.0 && !reduced {
367            let sample = arc_spring_with_options(
368                (self.id.clone(), "slot-width"),
369                measured_w,
370                SpringOptions::new(motion.spring.morph),
371                window,
372                cx,
373            );
374            if morph_active {
375                Some(sample.value)
376            } else {
377                None
378            }
379        } else {
380            None
381        };
382
383        // 字符自然排版负责精确测宽;仅变化的中间段退场/入场,共同前后缀保持可见。
384        let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
385        let label_dur = if reduced {
386            motion.duration.instant
387        } else {
388            motion.duration.standard
389        }
390        .as_secs_f64();
391        let (shared_start, shared_end) = shared_edges(&snap.previous_label, &self.label);
392        let count = self.label.chars().count();
393        let glyphs = self.label.chars().enumerate().map(|(index, ch)| {
394            let kept = index < shared_start || index >= count.saturating_sub(shared_end);
395            let delay = if reduced || kept {
396                0.0
397            } else {
398                (index as f64 * motion.stagger.char.as_secs_f64()).min(T::GLYPH_DELAY_CAP)
399            };
400            let t = if kept {
401                1.0
402            } else {
403                ((label_elapsed - delay) / label_dur).clamp(0.0, 1.0) as f32
404            };
405            if t < 1.0 {
406                window.request_animation_frame();
407            }
408            let e = if reduced {
409                t
410            } else {
411                CubicBezier::from_spec(motion.ease.enter).sample(t)
412            };
413            let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - e), reduced);
414            div()
415                .relative()
416                .flex_none()
417                .top(if reduced {
418                    px(0.0)
419                } else {
420                    T::ENTER_Y * (1.0 - e)
421                })
422                .opacity(e * blur.opacity_multiplier)
423                .child(SharedString::from(if ch == ' ' {
424                    "\u{00a0}".to_owned()
425                } else {
426                    ch.to_string()
427                }))
428        });
429        let previous = snap.previous_label.clone();
430        let old_count = previous.chars().count();
431        let exit_progress = (label_elapsed
432            / if reduced {
433                motion.duration.instant
434            } else {
435                motion.duration.fast
436            }
437            .as_secs_f64())
438        .clamp(0.0, 1.0) as f32;
439        let old_glyphs = previous.chars().enumerate().map(|(index, ch)| {
440            let kept = index < shared_start || index >= old_count.saturating_sub(shared_end);
441            div()
442                .flex_none()
443                .opacity(if kept { 0.0 } else { 1.0 - exit_progress })
444                .child(SharedString::from(if ch == ' ' {
445                    "\u{00a0}".to_owned()
446                } else {
447                    ch.to_string()
448                }))
449        });
450        let label_el = div()
451            .relative()
452            .flex_none()
453            .whitespace_nowrap()
454            .child(div().flex().children(glyphs))
455            .when(!previous.is_empty() && exit_progress < 1.0, |this| {
456                window.request_animation_frame();
457                this.child(
458                    div()
459                        .absolute()
460                        .left_0()
461                        .top(if reduced {
462                            px(0.0)
463                        } else {
464                            T::EXIT_Y * exit_progress
465                        })
466                        .flex()
467                        .children(old_glyphs),
468                )
469            });
470        let icon_progress = ((now - snap.icon_changed_at_secs).max(0.0)
471            / motion.duration.fast.as_secs_f64())
472        .clamp(0.0, 1.0) as f32;
473        if icon_progress < 1.0 {
474            window.request_animation_frame();
475        }
476
477        // Menu presence (`130ms` exit matches split-button.module.css line 41).
478        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
479            .animate_initial(false)
480            .config(ArcPresenceConfig {
481                enter_duration: if reduced {
482                    motion.duration.instant
483                } else {
484                    motion.duration.fast
485                },
486                exit_duration: if reduced {
487                    motion.duration.instant
488                } else {
489                    T::MENU_EXIT
490                },
491                enter_ease: motion.ease.enter,
492                exit_ease: motion.ease.standard,
493                fade_on_reduced_motion: true,
494            })
495            .sample(window, cx);
496
497        let is_secondary = self.variant == SplitButtonVariant::Secondary;
498        let radius = if is_secondary {
499            Radii::PILL
500        } else {
501            Radii::CONTROL
502        };
503        let min_h = if is_secondary {
504            ControlHeights::SM
505        } else {
506            ControlHeights::MD
507        };
508        // 与上游一致:主按钮箭头半 38px,次按钮 32px。
509        let trigger_w = if is_secondary {
510            T::SECONDARY_TRIGGER_WIDTH
511        } else {
512            T::TRIGGER_WIDTH
513        };
514
515        let (base_bg, border_color, fg, divider_color, primary_bg, trigger_bg) = if is_secondary {
516            let hover_bg = colors.surface_muted;
517            let active_bg = oklab_mix(colors.surface_muted, colors.border, 0.45);
518            let p_bg = if self.disabled {
519                colors.surface
520            } else if snap.primary_pressed {
521                active_bg
522            } else if snap.primary_hovered {
523                hover_bg
524            } else {
525                colors.surface
526            };
527            let t_bg = if self.disabled {
528                colors.surface
529            } else if snap.trigger_pressed || is_open {
530                active_bg
531            } else if snap.trigger_hovered {
532                hover_bg
533            } else {
534                colors.surface
535            };
536            (
537                colors.surface,
538                colors.border,
539                colors.foreground,
540                colors.border_subtle,
541                p_bg,
542                t_bg,
543            )
544        } else {
545            let hover_bg = oklab_mix(colors.foreground, colors.background, 0.88);
546            let active_bg = oklab_mix(colors.foreground, colors.background, 0.80);
547            let p_bg = if self.disabled {
548                colors.foreground
549            } else if snap.primary_pressed {
550                active_bg
551            } else if snap.primary_hovered {
552                hover_bg
553            } else {
554                colors.foreground
555            };
556            let t_bg = if self.disabled {
557                colors.foreground
558            } else if snap.trigger_pressed || is_open {
559                active_bg
560            } else if snap.trigger_hovered {
561                hover_bg
562            } else {
563                colors.foreground
564            };
565            (
566                colors.foreground,
567                colors.foreground,
568                colors.background,
569                oklab_mix(colors.background, colors.foreground, 0.18),
570                p_bg,
571                t_bg,
572            )
573        };
574
575        let icon_el = div()
576            .relative()
577            .flex_none()
578            .size(Spacing::S4)
579            .when_some(self.icon, |this, icon| {
580                this.child(
581                    svg()
582                        .path(icon.path())
583                        .size_full()
584                        .text_color(fg)
585                        .opacity(icon_progress),
586                )
587            })
588            .when_some(
589                snap.previous_icon.filter(|_| icon_progress < 1.0),
590                |this, icon| {
591                    this.child(
592                        svg()
593                            .absolute()
594                            .inset_0()
595                            .path(icon.path())
596                            .size_full()
597                            .text_color(fg)
598                            .opacity(1.0 - icon_progress),
599                    )
600                },
601            );
602
603        let group_bounds_ref = snap.group_bounds.clone();
604        let menu_bounds_for_outside = snap.menu_bounds.clone();
605        let group_bounds_for_outside = snap.group_bounds.clone();
606        let internal_outside = internal.clone();
607        let backdrop = canvas(
608            move |rect, _, _| {
609                *group_bounds_ref.borrow_mut() = Some(rect);
610            },
611            move |rect, _, window, _| {
612                let paint_rect = scaled_bounds(
613                    rect,
614                    animated_scale,
615                    animated_scale,
616                    TransformOrigin::CENTER,
617                );
618                window.paint_quad(quad(
619                    paint_rect,
620                    Corners::all(radius.min(paint_rect.size.height * 0.5)),
621                    base_bg,
622                    // 描边交给外层容器:画布铺在两半下面,边框画在这里会被
623                    // 不透明的按钮底色整片盖住,次按钮就只剩一片白。
624                    Edges::all(px(0.0)),
625                    border_color,
626                    BorderStyle::Solid,
627                ));
628
629                // Close menu when user clicks outside both the split button and its menu.
630                if is_open {
631                    let g_ref = group_bounds_for_outside.clone();
632                    let m_ref = menu_bounds_for_outside.clone();
633                    let st = internal_outside.clone();
634                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
635                        if !phase.bubble() {
636                            return;
637                        }
638                        let in_group = g_ref.borrow().is_some_and(|b| b.contains(&event.position));
639                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
640                        if !in_group && !in_menu {
641                            st.update(cx, |s, _| {
642                                s.open = false;
643                                s.highlighted = None;
644                            });
645                            window.refresh();
646                        }
647                    });
648                }
649            },
650        )
651        .absolute()
652        .inset_0();
653
654        let slot_w_ref = snap.measured_slot_width.clone();
655        let has_m_ref = snap.has_measured.clone();
656        let slot_probe = canvas(
657            move |rect, window, _| {
658                let w = f32::from(rect.size.width);
659                let prev = *slot_w_ref.borrow();
660                *slot_w_ref.borrow_mut() = w;
661                if w > 0.0 {
662                    *has_m_ref.borrow_mut() = true;
663                }
664                if (w - prev).abs() > 0.5 && prev > 0.0 {
665                    window.request_animation_frame();
666                }
667            },
668            |_, _, _, _| {},
669        )
670        .absolute()
671        .inset_0();
672
673        let primary_id = ElementId::NamedChild(self.id.clone().into(), "primary".into());
674        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
675
676        let int_p_hover = internal.clone();
677        let int_p_down = internal.clone();
678        let int_p_up = internal.clone();
679        let int_p_out = internal.clone();
680        let int_t_hover = internal.clone();
681        let int_t_down = internal.clone();
682        let int_t_up = internal.clone();
683        let int_t_out = internal.clone();
684        let int_t_click = internal.clone();
685        let on_click = self.on_click;
686        let is_disabled = self.disabled;
687        let focus_for_open = snap.focus_handle.clone();
688        let actions_for_trigger = self.actions.clone();
689        let int_t_key = internal.clone();
690        let actions_for_key = self.actions.clone();
691        let menu_key_focus = snap.focus_handle.clone();
692
693        let primary_btn = BaseButton::new(primary_id)
694            .disabled(self.disabled)
695            .accessibility_label(self.label.clone())
696            .on_click(move |_, window, cx| {
697                if is_disabled {
698                    return;
699                }
700                if let Some(handler) = &on_click {
701                    handler(&(), window, cx);
702                }
703                window.refresh();
704            })
705            .relative()
706            .flex()
707            .items_center()
708            .justify_center()
709            .min_h(min_h)
710            .when(is_secondary, |this| {
711                this.min_w(T::SECONDARY_MIN_WIDTH)
712                    .px(Spacing::S3)
713                    .text_size(Typography::TEXT_XS)
714            })
715            .when(!is_secondary, |this| {
716                this.px(Spacing::S4).text_size(Typography::TEXT_SM)
717            })
718            .flex_none()
719            .whitespace_nowrap()
720            .rounded_tl((radius - px(1.0)).max(px(0.0)))
721            .rounded_bl((radius - px(1.0)).max(px(0.0)))
722            .bg(primary_bg)
723            .text_color(fg)
724            .when(!self.disabled, |this| this.cursor_pointer())
725            .on_hover(move |hovered, window, cx| {
726                int_p_hover.update(cx, |s, _| {
727                    s.primary_hovered = *hovered;
728                    if !*hovered {
729                        s.primary_pressed = false;
730                    }
731                });
732                window.refresh();
733            })
734            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
735                if is_disabled {
736                    return;
737                }
738                int_p_down.update(cx, |s, _| s.primary_pressed = true);
739                window.refresh();
740            })
741            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
742                int_p_up.update(cx, |s, _| s.primary_pressed = false);
743                window.refresh();
744            })
745            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
746                int_p_out.update(cx, |s, _| s.primary_pressed = false);
747                window.refresh();
748            })
749            .child(
750                div()
751                    .relative()
752                    .flex()
753                    .items_center()
754                    .when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
755                    .child(
756                        div()
757                            .relative()
758                            .flex_none()
759                            .flex()
760                            .flex_row()
761                            .items_center()
762                            .gap(Spacing::S2)
763                            .child(slot_probe)
764                            .when(
765                                self.icon.is_some()
766                                    || (snap.previous_icon.is_some() && icon_progress < 1.0),
767                                |this| this.child(icon_el),
768                            )
769                            .child(label_el),
770                    ),
771            );
772
773        let trigger_label = SharedString::from(format!("{} more actions", self.label));
774        let trigger_btn = BaseButton::new(trigger_id)
775            .track_focus(&snap.trigger_focus)
776            .disabled(self.disabled)
777            .aria_expanded(is_open)
778            .on_key_down(move |event: &KeyDownEvent, window, cx| {
779                let key = event.keystroke.key.as_str();
780                if !is_disabled && matches!(key, "down" | "up") && !actions_for_key.is_empty() {
781                    let now = motion_now(cx);
782                    int_t_key.update(cx, |s, _| {
783                        s.open = true;
784                        s.opened_at_secs = now;
785                        s.highlighted = next_enabled_index(
786                            &actions_for_key,
787                            None,
788                            if key == "up" { -1 } else { 1 },
789                        );
790                    });
791                    window.focus(&menu_key_focus, cx);
792                    window.refresh();
793                    cx.stop_propagation();
794                }
795            })
796            .accessibility_label(trigger_label)
797            .on_click(move |_, window, cx| {
798                if is_disabled {
799                    return;
800                }
801                let t_now = motion_now(cx);
802                let mut became_open = false;
803                int_t_click.update(cx, |s, _| {
804                    s.open = !s.open;
805                    became_open = s.open;
806                    if s.open {
807                        s.opened_at_secs = t_now;
808                        s.highlighted = next_enabled_index(&actions_for_trigger, None, 1);
809                    } else {
810                        s.highlighted = None;
811                    }
812                });
813                if became_open {
814                    window.focus(&focus_for_open, cx);
815                }
816                window.refresh();
817            })
818            .relative()
819            .flex()
820            .items_center()
821            .justify_center()
822            .w(trigger_w)
823            .flex_none()
824            .min_h(min_h)
825            .border_l_1()
826            .border_color(divider_color)
827            .rounded_tr((radius - px(1.0)).max(px(0.0)))
828            .rounded_br((radius - px(1.0)).max(px(0.0)))
829            .bg(trigger_bg)
830            .text_color(fg)
831            .when(!self.disabled, |this| this.cursor_pointer())
832            .on_hover(move |hovered, window, cx| {
833                int_t_hover.update(cx, |s, _| {
834                    s.trigger_hovered = *hovered;
835                    if !*hovered {
836                        s.trigger_pressed = false;
837                    }
838                });
839                window.refresh();
840            })
841            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
842                if is_disabled {
843                    return;
844                }
845                int_t_down.update(cx, |s, _| s.trigger_pressed = true);
846                window.refresh();
847            })
848            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
849                int_t_up.update(cx, |s, _| s.trigger_pressed = false);
850                window.refresh();
851            })
852            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
853                int_t_out.update(cx, |s, _| s.trigger_pressed = false);
854                window.refresh();
855            })
856            .child(
857                canvas(
858                    |_, _, _| {},
859                    move |rect, _, window, _| {
860                        let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
861                        let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
862                        paint_rotated_chevron(cx, cy, chevron_deg, fg, window);
863                    },
864                )
865                .size(px(16.0)),
866            );
867
868        // Floating menu rendered via `deferred` overlay with staggered item entrance.
869        let menu_el = if menu_presence.should_render() && !self.actions.is_empty() {
870            let p = menu_presence.progress.clamp(0.0, 1.0);
871            let menu_y = if reduced {
872                0.0
873            } else {
874                -f32::from(T::ENTER_Y) * (1.0 - p)
875            };
876            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
877            let menu_bounds_ref = snap.menu_bounds.clone();
878            let menu_probe = canvas(
879                move |rect, _, _| {
880                    *menu_bounds_ref.borrow_mut() = Some(rect);
881                },
882                |_, _, _, _| {},
883            )
884            .absolute()
885            .inset_0();
886
887            let int_key = internal.clone();
888            let actions_key = self.actions.clone();
889            let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
890            let focus_handle = snap.focus_handle.clone();
891            let highlighted = snap.highlighted;
892            let return_focus = snap.trigger_focus.clone();
893            let has_icons = self.actions.iter().any(|a| a.icon.is_some());
894            let viewport = window.viewport_size();
895            let menu_width =
896                T::MENU_MIN_WIDTH.min((viewport.width - Spacing::S3 * 2.0).max(px(0.0)));
897            let menu_height =
898                ControlHeights::SM * self.actions.len() as f32 + T::MENU_PADDING * 2.0 + px(2.0);
899            let target = snap.group_bounds.borrow().unwrap_or_default();
900            let above = target.bottom() + Spacing::S1 + menu_height > viewport.height - Spacing::S3
901                && target.top() > viewport.height - target.bottom();
902            let layer = anchored()
903                .anchor(if above {
904                    Anchor::BottomRight
905                } else {
906                    Anchor::TopRight
907                })
908                .position(point(
909                    target
910                        .right()
911                        .clamp(Spacing::S3 + menu_width, viewport.width - Spacing::S3),
912                    if above {
913                        target.top() - Spacing::S1 - px(menu_y)
914                    } else {
915                        target.bottom() + Spacing::S1 + px(menu_y)
916                    },
917                ))
918                .snap_to_window_with_margin(Spacing::S3);
919
920            let item_rows = self.actions.into_iter().enumerate().map(|(idx, action)| {
921                let is_hi = highlighted == Some(idx);
922                let item_id = ElementId::NamedChild(
923                    self.id.clone().into(),
924                    SharedString::from(format!("menu-item-{idx}")),
925                );
926                let stagger_delay = if reduced {
927                    0.0
928                } else {
929                    (idx.min(4) as f64) * motion.stagger.item.as_secs_f64()
930                };
931                let item_op = if reduced || !is_open {
932                    1.0
933                } else {
934                    let t = ((menu_elapsed - stagger_delay)
935                        / motion.duration.standard.as_secs_f64())
936                    .clamp(0.0, 1.0) as f32;
937                    if t < 1.0 {
938                        window.request_animation_frame();
939                    }
940                    CubicBezier::from_spec(motion.ease.enter).sample(t)
941                };
942
943                let int_hi = internal.clone();
944                let int_sel = internal.clone();
945                let on_select = action.on_select.clone();
946                let item_disabled = action.disabled;
947                let item_inert = item_disabled || !is_open;
948                let item_return_focus = snap.trigger_focus.clone();
949                let item_fg = if action.destructive {
950                    colors.danger
951                } else {
952                    colors.foreground
953                };
954                let hi_bg = if action.destructive {
955                    oklab_mix(colors.danger, colors.surface, 0.08)
956                } else {
957                    colors.surface_muted
958                };
959
960                div()
961                    .id(item_id)
962                    .test_support()
963                    .role(Role::MenuItem)
964                    .aria_label(action.label.clone())
965                    .flex()
966                    .flex_row()
967                    .items_center()
968                    .gap(T::ITEM_GAP)
969                    .min_h(ControlHeights::SM)
970                    .px(T::ITEM_PADDING)
971                    .rounded(Radii::PANEL - Spacing::S1 - px(2.0))
972                    .text_size(Typography::TEXT_SM)
973                    .text_color(item_fg)
974                    .bg(if is_hi && !item_disabled {
975                        hi_bg
976                    } else {
977                        Hsla::transparent_black()
978                    })
979                    .opacity(if item_disabled { 0.45 } else { item_op })
980                    .when(!item_disabled, |this| this.cursor_pointer())
981                    .on_hover(move |hovered, window, cx| {
982                        if item_inert {
983                            return;
984                        }
985                        int_hi.update(cx, |s, _| {
986                            if *hovered {
987                                s.highlighted = Some(idx);
988                            } else if s.highlighted == Some(idx) {
989                                s.highlighted = None;
990                            }
991                        });
992                        window.refresh();
993                    })
994                    .on_click(move |_, window, cx| {
995                        if item_inert {
996                            return;
997                        }
998                        int_sel.update(cx, |s, _| {
999                            s.open = false;
1000                            s.highlighted = None;
1001                        });
1002                        window.focus(&item_return_focus, cx);
1003                        if let Some(cb) = &on_select {
1004                            cb(&(), window, cx);
1005                        }
1006                        cx.stop_propagation();
1007                        window.refresh();
1008                    })
1009                    .when(has_icons, |this| {
1010                        this.child(div().flex_none().size(Spacing::S4).when_some(
1011                            action.icon,
1012                            |this, icon| {
1013                                this.child(svg().path(icon.path()).size_full().text_color(item_fg))
1014                            },
1015                        ))
1016                    })
1017                    .child(action.label)
1018            });
1019
1020            Some(
1021                deferred(
1022                    layer.child(
1023                        div()
1024                            .id(menu_id)
1025                            .test_support()
1026                            .track_focus(&focus_handle)
1027                            .role(Role::Menu)
1028                            .w(menu_width)
1029                            .max_h((viewport.height - Spacing::S3 * 2.0).max(ControlHeights::SM))
1030                            .overflow_y_scroll()
1031                            .p(T::MENU_PADDING)
1032                            .rounded(Radii::PANEL)
1033                            .border_1()
1034                            .border_color(colors.border)
1035                            .bg(colors.surface_raised)
1036                            .shadow(Shadows::floating(theme.mode))
1037                            .opacity(p)
1038                            .flex()
1039                            .flex_col()
1040                            .on_key_down(move |event: &KeyDownEvent, window, cx| {
1041                                if !int_key.read(cx).open {
1042                                    return;
1043                                }
1044                                let key = event.keystroke.key.as_str();
1045                                if matches!(key, "escape" | "down" | "up" | "enter" | "space") {
1046                                    cx.stop_propagation();
1047                                }
1048                                match key {
1049                                    "escape" => {
1050                                        window.focus(&return_focus, cx);
1051                                        int_key.update(cx, |s, _| {
1052                                            s.open = false;
1053                                            s.highlighted = None;
1054                                        });
1055                                        window.refresh();
1056                                    }
1057                                    "down" => {
1058                                        int_key.update(cx, |s, _| {
1059                                            s.highlighted =
1060                                                next_enabled_index(&actions_key, s.highlighted, 1);
1061                                        });
1062                                        window.refresh();
1063                                    }
1064                                    "up" => {
1065                                        int_key.update(cx, |s, _| {
1066                                            s.highlighted =
1067                                                next_enabled_index(&actions_key, s.highlighted, -1);
1068                                        });
1069                                        window.refresh();
1070                                    }
1071                                    "enter" | "space" => {
1072                                        let sel = int_key.read(cx).highlighted;
1073                                        if let Some(idx) = sel
1074                                            && let Some(act) = actions_key.get(idx)
1075                                            && !act.disabled
1076                                        {
1077                                            int_key.update(cx, |s, _| {
1078                                                s.open = false;
1079                                                s.highlighted = None;
1080                                            });
1081                                            window.focus(&return_focus, cx);
1082                                            if let Some(cb) = &act.on_select {
1083                                                cb(&(), window, cx);
1084                                            }
1085                                            window.refresh();
1086                                        }
1087                                    }
1088                                    _ => {}
1089                                }
1090                            })
1091                            .child(menu_probe)
1092                            .children(item_rows),
1093                    ),
1094                )
1095                .with_priority(1),
1096            )
1097        } else {
1098            None
1099        };
1100
1101        div()
1102            .id(self.id)
1103            .relative()
1104            .flex()
1105            .flex_row()
1106            .items_stretch()
1107            .flex_none()
1108            .rounded(radius)
1109            // 外轮廓画在容器上,而不是画在垫底的画布上:画布与两半同尺寸,
1110            // 描边会被按钮自己的底色覆盖,次按钮就看不到边界。
1111            .border_1()
1112            .border_color(border_color)
1113            // 禁用态整块降透明度:只降文字会让黑色主按钮看起来仍然可用。
1114            .when(self.disabled, |this| this.opacity(0.52))
1115            .child(backdrop)
1116            .child(primary_btn)
1117            .child(trigger_btn)
1118            .when_some(menu_el, |this, menu| this.child(menu))
1119    }
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124    use std::{cell::Cell, rc::Rc};
1125
1126    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1127    use gpui_kit::{
1128        Context, MouseButton, Render, Role, TestAppContext, div,
1129        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
1130    };
1131
1132    use super::*;
1133
1134    struct SplitHost {
1135        primary_clicks: Rc<Cell<usize>>,
1136        menu_clicks: Rc<Cell<usize>>,
1137    }
1138
1139    impl Render for SplitHost {
1140        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1141            let p_clicks = self.primary_clicks.clone();
1142            let m_clicks = self.menu_clicks.clone();
1143            div().p(Spacing::S6).child(
1144                SplitButton::new("merge-split", "Merge pull request")
1145                    .on_click(cx.listener(move |_, _, _, _| {
1146                        p_clicks.set(p_clicks.get() + 1);
1147                    }))
1148                    .actions([
1149                        SplitButtonAction::new("Squash and merge").on_select(cx.listener(
1150                            move |_, _, _, _| {
1151                                m_clicks.set(m_clicks.get() + 1);
1152                            },
1153                        )),
1154                        SplitButtonAction::new("Rebase and merge").disabled(true),
1155                    ]),
1156            )
1157        }
1158    }
1159
1160    #[test]
1161    fn split_button_character_identity_and_navigation() {
1162        assert_eq!(shared_edges("Copy page", "Copied"), (3, 0));
1163        assert_eq!(shared_edges("压缩合并", "变基合并"), (0, 2));
1164        let actions = [
1165            SplitButtonAction::new("a"),
1166            SplitButtonAction::new("b").disabled(true),
1167            SplitButtonAction::new("close").destructive(true),
1168        ];
1169        assert_eq!(next_enabled_index(&actions, Some(0), -1), Some(2));
1170        assert_eq!(next_enabled_index(&actions, Some(2), 1), Some(0));
1171        assert_eq!(next_enabled_index(&actions, Some(0), 1), Some(2));
1172    }
1173
1174    #[gpui_kit::test]
1175    fn split_button_keyboard_escape_returns_to_trigger(cx: &mut TestAppContext) {
1176        cx.update(|cx| {
1177            gpui_kit::init(cx);
1178            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1179        });
1180        let menu_clicks = Rc::new(Cell::new(0));
1181        let (_, cx) = cx.add_window_view(|_, _| SplitHost {
1182            primary_clicks: Rc::new(Cell::new(0)),
1183            menu_clicks: menu_clicks.clone(),
1184        });
1185        cx.update(|window, cx| {
1186            window.render_frame(cx);
1187            let t = window
1188                .find_by_label("Merge pull request more actions")
1189                .bounds()
1190                .center();
1191            window.pointer_down(t, MouseButton::Left, cx);
1192            window.pointer_up(t, MouseButton::Left, cx);
1193            window.render_frame(cx);
1194        });
1195        cx.simulate_keystrokes("escape");
1196        cx.update(|window, cx| {
1197            window.render_frame(cx);
1198        });
1199        // Escape 后再次以箭头键展开,只有焦点归还 trigger 才能工作。
1200        cx.simulate_keystrokes("down");
1201        cx.update(|window, cx| {
1202            window.render_frame(cx);
1203            assert_eq!(
1204                window.find_by_label("Squash and merge").role(),
1205                Some(Role::MenuItem)
1206            );
1207        });
1208        cx.simulate_keystrokes("down enter");
1209        cx.run_until_parked();
1210        assert_eq!(menu_clicks.get(), 1, "跳过禁用项并循环回首项,只执行一次");
1211    }
1212
1213    struct EdgeHost {
1214        disabled: bool,
1215    }
1216    impl Render for EdgeHost {
1217        fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1218            div()
1219                .w(window.viewport_size().width)
1220                .h(window.viewport_size().height)
1221                .flex()
1222                .items_end()
1223                .justify_end()
1224                .p(Spacing::S1)
1225                .child(
1226                    SplitButton::new("edge-split", "Edge")
1227                        .disabled(self.disabled)
1228                        .actions([
1229                            SplitButtonAction::new("Alternative"),
1230                            SplitButtonAction::new("Close").destructive(true),
1231                        ]),
1232                )
1233        }
1234    }
1235
1236    #[gpui_kit::test]
1237    fn split_button_menu_avoids_edges_and_can_reenable(cx: &mut TestAppContext) {
1238        cx.update(|cx| {
1239            gpui_kit::init(cx);
1240            install_arc_theme(ThemeMode::Dark, Accent::Violet, cx);
1241        });
1242        let (view, cx) = cx.add_window_view(|_, _| EdgeHost { disabled: false });
1243        cx.update(|window, cx| {
1244            window.render_frame(cx);
1245            let t = window.find_by_label("Edge more actions").bounds().center();
1246            window.pointer_down(t, MouseButton::Left, cx);
1247            window.pointer_up(t, MouseButton::Left, cx);
1248            window.render_frame(cx);
1249            let item = window.find_by_label("Alternative").bounds();
1250            assert!(
1251                item.bottom() <= t.y,
1252                "底部空间不足时应向上打开: item={item:?}, trigger={t:?}, viewport={:?}",
1253                window.viewport_size()
1254            );
1255            assert!(item.left() >= Spacing::S3);
1256            assert!(item.right() <= window.viewport_size().width - Spacing::S3);
1257            view.update(cx, |this, cx| {
1258                this.disabled = true;
1259                cx.notify();
1260            });
1261            window.render_frame(cx);
1262            view.update(cx, |this, cx| {
1263                this.disabled = false;
1264                cx.notify();
1265            });
1266            window.render_frame(cx);
1267            let t = window.find_by_label("Edge more actions").bounds().center();
1268            window.pointer_down(t, MouseButton::Left, cx);
1269            window.pointer_up(t, MouseButton::Left, cx);
1270            window.render_frame(cx);
1271            assert!(window.find_by_label("Alternative").bounds().bottom() <= t.y);
1272        });
1273    }
1274
1275    #[gpui_kit::test]
1276    fn split_button_primary_and_menu_selection_work(cx: &mut TestAppContext) {
1277        cx.update(|cx| {
1278            gpui_kit::init(cx);
1279            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1280        });
1281        let primary_clicks = Rc::new(Cell::new(0usize));
1282        let menu_clicks = Rc::new(Cell::new(0usize));
1283        let (_view, cx) = cx.add_window_view(|_, _| SplitHost {
1284            primary_clicks: primary_clicks.clone(),
1285            menu_clicks: menu_clicks.clone(),
1286        });
1287
1288        cx.update(|window, cx| {
1289            window.render_frame(cx);
1290            let primary = window.find_by_label("Merge pull request");
1291            assert_eq!(primary.role(), Some(Role::Button));
1292            let pos = primary.bounds().center();
1293            window.pointer_down(pos, MouseButton::Left, cx);
1294            window.pointer_up(pos, MouseButton::Left, cx);
1295            assert_eq!(primary_clicks.get(), 1);
1296
1297            // Open menu via chevron trigger
1298            let trigger = window.find_by_label("Merge pull request more actions");
1299            let t_pos = trigger.bounds().center();
1300            window.pointer_down(t_pos, MouseButton::Left, cx);
1301            window.pointer_up(t_pos, MouseButton::Left, cx);
1302            window.render_frame(cx);
1303
1304            let item = window.find_by_label("Squash and merge");
1305            assert_eq!(item.role(), Some(Role::MenuItem));
1306            let i_pos = item.bounds().center();
1307            window.pointer_down(i_pos, MouseButton::Left, cx);
1308            window.pointer_up(i_pos, MouseButton::Left, cx);
1309            assert_eq!(menu_clicks.get(), 1);
1310        });
1311    }
1312}