Skip to main content

arc_ui/actions/
button_group.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/button-group/button-group.tsx` & `.module.css`
3//!
4//! P2 Component #5: `button-group`
5//!
6//! - Joins related actions into one bordered surface with hairline dividers and zero gaps.
7//! - One travelling highlight pill (`inset = 3px`, `motion.spring.snappy`) glides between segments
8//!   under pointer hover, press, or open menu chevron; adjacent dividers fade away (`quiet`).
9//! - Variants: `Outline` | `Solid`; sizes: `Sm` (36px) | `Md` (44px); orientations: `Horizontal` | `Vertical`.
10//! - Optional trailing chevron menu anchored to the group edge (`deferred` overlay, `ArcPresence`,
11//!   35ms staggered items, Escape & outside-click dismiss).
12
13use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
14
15use arc_motion::{
16    ArcPresence, ArcPresenceConfig, CubicBezier, LayoutSnapshot, arc_spring, arc_transition,
17    is_reduced_motion, layout::layout_scope_key, motion_now, sample_shared_layout,
18};
19use arc_tokens::{
20    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
21};
22use gpui_kit::{
23    App, BorderStyle, Bounds, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
24    MouseButton, MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
25    SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
26    base::Button as BaseButton, bounds, canvas, deferred, div, point, prelude::*, px, quad, size,
27};
28
29type SelectHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
30
31const MENU_KEY: &str = "__button-group-menu";
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
34pub enum ButtonGroupVariant {
35    #[default]
36    Outline,
37    Solid,
38}
39
40#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
41pub enum ButtonGroupSize {
42    Sm,
43    #[default]
44    Md,
45}
46
47impl ButtonGroupSize {
48    pub const fn height(self) -> Pixels {
49        match self {
50            Self::Sm => ControlHeights::SM,
51            Self::Md => ControlHeights::MD,
52        }
53    }
54
55    pub const fn pad_x(self) -> Pixels {
56        match self {
57            Self::Sm => px(10.0),
58            Self::Md => px(12.0),
59        }
60    }
61
62    pub const fn divider_inset(self) -> Pixels {
63        match self {
64            Self::Sm => px(7.0),
65            Self::Md => px(8.0),
66        }
67    }
68}
69
70#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
71pub enum ButtonGroupOrientation {
72    #[default]
73    Horizontal,
74    Vertical,
75}
76
77#[derive(Clone)]
78pub struct ButtonGroupItem {
79    pub id: SharedString,
80    pub label: SharedString,
81    pub icon: Option<IconName>,
82    pub icon_only: bool,
83    pub disabled: bool,
84    pub on_select: Option<SelectHandler>,
85}
86
87impl ButtonGroupItem {
88    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
89        Self {
90            id: id.into(),
91            label: label.into(),
92            icon: None,
93            icon_only: false,
94            disabled: false,
95            on_select: None,
96        }
97    }
98
99    pub fn icon(mut self, icon: IconName) -> Self {
100        self.icon = Some(icon);
101        self
102    }
103
104    pub fn icon_only(mut self, icon_only: bool) -> Self {
105        self.icon_only = icon_only;
106        self
107    }
108
109    pub fn disabled(mut self, disabled: bool) -> Self {
110        self.disabled = disabled;
111        self
112    }
113
114    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
115        self.on_select = Some(Rc::new(handler));
116        self
117    }
118}
119
120#[derive(Clone)]
121pub struct ButtonGroupMenuItem {
122    pub id: SharedString,
123    pub label: SharedString,
124    pub icon: Option<IconName>,
125    pub disabled: bool,
126    pub destructive: bool,
127    pub on_select: Option<SelectHandler>,
128}
129
130impl ButtonGroupMenuItem {
131    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
132        Self {
133            id: id.into(),
134            label: label.into(),
135            icon: None,
136            disabled: false,
137            destructive: false,
138            on_select: None,
139        }
140    }
141
142    pub fn icon(mut self, icon: IconName) -> Self {
143        self.icon = Some(icon);
144        self
145    }
146
147    pub fn disabled(mut self, disabled: bool) -> Self {
148        self.disabled = disabled;
149        self
150    }
151
152    pub fn destructive(mut self, destructive: bool) -> Self {
153        self.destructive = destructive;
154        self
155    }
156
157    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
158        self.on_select = Some(Rc::new(handler));
159        self
160    }
161}
162
163#[derive(Clone)]
164pub struct ButtonGroupMenu {
165    pub label: SharedString,
166    pub items: Vec<ButtonGroupMenuItem>,
167}
168
169impl ButtonGroupMenu {
170    pub fn new(
171        label: impl Into<SharedString>,
172        items: impl IntoIterator<Item = ButtonGroupMenuItem>,
173    ) -> Self {
174        Self {
175            label: label.into(),
176            items: items.into_iter().collect(),
177        }
178    }
179}
180
181#[derive(Clone)]
182struct ButtonGroupInternal {
183    hovered_key: Option<SharedString>,
184    pressed_key: Option<SharedString>,
185    menu_open: bool,
186    opened_at_secs: f64,
187    highlighted_menu_idx: Option<usize>,
188    segment_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
189    group_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
190    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
191    menu_focus: FocusHandle,
192}
193
194impl ButtonGroupInternal {
195    fn new(now: f64, menu_focus: FocusHandle) -> Self {
196        Self {
197            hovered_key: None,
198            pressed_key: None,
199            menu_open: false,
200            opened_at_secs: now - 10.0,
201            highlighted_menu_idx: None,
202            segment_bounds: Rc::new(RefCell::new(HashMap::new())),
203            group_bounds: Rc::new(RefCell::new(None)),
204            menu_bounds: Rc::new(RefCell::new(None)),
205            menu_focus,
206        }
207    }
208}
209
210/// Arc `ButtonGroup` joining segments into one surface with a travelling highlight pill,
211/// quiet hairline dividers, and optional trailing dropdown menu.
212#[derive(IntoElement)]
213pub struct ButtonGroup {
214    id: ElementId,
215    label: SharedString,
216    items: Vec<ButtonGroupItem>,
217    menu: Option<ButtonGroupMenu>,
218    variant: ButtonGroupVariant,
219    size: ButtonGroupSize,
220    orientation: ButtonGroupOrientation,
221    disabled: bool,
222}
223
224impl ButtonGroup {
225    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
226        Self {
227            id: id.into(),
228            label: label.into(),
229            items: Vec::new(),
230            menu: None,
231            variant: ButtonGroupVariant::Outline,
232            size: ButtonGroupSize::Md,
233            orientation: ButtonGroupOrientation::Horizontal,
234            disabled: false,
235        }
236    }
237
238    pub fn item(mut self, item: ButtonGroupItem) -> Self {
239        self.items.push(item);
240        self
241    }
242
243    pub fn items(mut self, items: impl IntoIterator<Item = ButtonGroupItem>) -> Self {
244        self.items.extend(items);
245        self
246    }
247
248    pub fn menu(mut self, menu: ButtonGroupMenu) -> Self {
249        self.menu = Some(menu);
250        self
251    }
252
253    pub fn variant(mut self, variant: ButtonGroupVariant) -> Self {
254        self.variant = variant;
255        self
256    }
257
258    pub fn size(mut self, size: ButtonGroupSize) -> Self {
259        self.size = size;
260        self
261    }
262
263    pub fn orientation(mut self, orientation: ButtonGroupOrientation) -> Self {
264        self.orientation = orientation;
265        self
266    }
267
268    pub fn disabled(mut self, disabled: bool) -> Self {
269        self.disabled = disabled;
270        self
271    }
272}
273
274fn paint_chevron(cx: f32, cy: f32, deg: f32, color: Hsla, window: &mut Window) {
275    let rad = deg.to_radians();
276    let (c, s) = (rad.cos(), rad.sin());
277    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
278    let mut b = PathBuilder::stroke(px(1.75));
279    for (i, (lx, ly)) in pts.iter().enumerate() {
280        let p = point(px(cx + lx * c - ly * s), px(cy + lx * s + ly * c));
281        if i == 0 {
282            b.move_to(p);
283        } else {
284            b.line_to(p);
285        }
286    }
287    if let Ok(path) = b.build() {
288        window.paint_path(path, color);
289    }
290}
291
292impl RenderOnce for ButtonGroup {
293    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
294        let theme = cx.arc_theme().clone();
295        let colors = theme.colors;
296        let motion = theme.motion;
297        let reduced = is_reduced_motion(cx);
298        let now = motion_now(cx);
299
300        let state_id =
301            ElementId::NamedChild(self.id.clone().into(), "__arc-button-group-state".into());
302        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
303            ButtonGroupInternal::new(now, cx.focus_handle())
304        });
305
306        let snap = internal.read(cx).clone();
307        let is_open = snap.menu_open && !self.disabled;
308        let vertical = self.orientation == ButtonGroupOrientation::Vertical;
309        let solid = self.variant == ButtonGroupVariant::Solid;
310
311        let active_key: Option<SharedString> = if self.disabled {
312            None
313        } else {
314            snap.hovered_key
315                .clone()
316                .or_else(|| snap.pressed_key.clone())
317                .or_else(|| is_open.then(|| SharedString::from(MENU_KEY)))
318        };
319
320        let all_keys: Vec<SharedString> = self
321            .items
322            .iter()
323            .map(|i| i.id.clone())
324            .chain(self.menu.as_ref().map(|_| SharedString::from(MENU_KEY)))
325            .collect();
326        let active_index = active_key
327            .as_ref()
328            .and_then(|k| all_keys.iter().position(|x| x == k));
329
330        let highlight_opacity = arc_transition(
331            (self.id.clone(), "highlight-op"),
332            if active_key.is_some() { 1.0 } else { 0.0 },
333            if reduced {
334                motion.duration.instant
335            } else {
336                motion.duration.fast
337            },
338            motion.ease.standard,
339            window,
340            cx,
341        );
342
343        let chevron_deg = if reduced {
344            if is_open { 180.0 } else { 0.0 }
345        } else {
346            arc_spring(
347                (self.id.clone(), "chevron-deg"),
348                if is_open { 180.0 } else { 0.0 },
349                motion.spring.snappy,
350                window,
351                cx,
352            )
353        };
354
355        let (group_bg, group_border, group_fg, divider_color, hi_bg, hi_pressed_bg, muted_ink) =
356            if solid {
357                (
358                    colors.foreground,
359                    colors.foreground,
360                    colors.background,
361                    oklab_mix(colors.background, colors.foreground, 0.20),
362                    oklab_mix(colors.background, colors.foreground, 0.13),
363                    oklab_mix(colors.background, colors.foreground, 0.22),
364                    oklab_mix(colors.background, colors.foreground, 0.72),
365                )
366            } else {
367                (
368                    colors.surface,
369                    colors.border,
370                    colors.foreground,
371                    colors.border,
372                    colors.surface_muted,
373                    oklab_mix(colors.border_strong, colors.surface_muted, 0.30),
374                    colors.text_secondary,
375                )
376            };
377
378        let is_active_pressed =
379            active_key.is_some() && active_key == snap.pressed_key && !self.disabled;
380        let active_hi_color = {
381            let base_c = if is_active_pressed {
382                hi_pressed_bg
383            } else {
384                hi_bg
385            };
386            Hsla {
387                a: base_c.a * highlight_opacity,
388                ..base_c
389            }
390        };
391
392        // Travelling highlight pill rendered in backdrop canvas (group-local FLIP coordinates).
393        let scope = layout_scope_key(&self.id);
394        let seg_bounds_ref = snap.segment_bounds.clone();
395        let group_bounds_ref = snap.group_bounds.clone();
396        let group_bounds_out = snap.group_bounds.clone();
397        let menu_bounds_out = snap.menu_bounds.clone();
398        let internal_out = internal.clone();
399        let active_for_hi = active_key.clone();
400        let snappy = motion.spring.snappy;
401
402        let highlight_canvas = canvas(
403            move |rect, _, _| {
404                *group_bounds_ref.borrow_mut() = Some(rect);
405            },
406            move |group_rect, _, window, cx| {
407                if let Some(key) = &active_for_hi
408                    && highlight_opacity > 0.01
409                    && let Some(seg_rect) = seg_bounds_ref.borrow().get(key).copied()
410                {
411                    let inset = px(3.0);
412                    let local_rect = bounds(
413                        point(
414                            seg_rect.origin.x - group_rect.origin.x + inset,
415                            seg_rect.origin.y - group_rect.origin.y + inset,
416                        ),
417                        size(
418                            (seg_rect.size.width - inset * 2.0).max(px(0.0)),
419                            (seg_rect.size.height - inset * 2.0).max(px(0.0)),
420                        ),
421                    );
422                    let target = LayoutSnapshot::uniform_radius(local_rect, px(6.0));
423                    let flip = sample_shared_layout(
424                        scope.clone(),
425                        "highlight",
426                        target,
427                        Some(snappy),
428                        window,
429                        cx,
430                    );
431                    let paint_rect =
432                        bounds(group_rect.origin + flip.bounds.origin, flip.bounds.size);
433                    window.paint_quad(quad(
434                        paint_rect,
435                        flip.corner_radii,
436                        active_hi_color,
437                        Edges::default(),
438                        Hsla::transparent_black(),
439                        BorderStyle::Solid,
440                    ));
441                }
442
443                if is_open {
444                    let g_ref = group_bounds_out.clone();
445                    let m_ref = menu_bounds_out.clone();
446                    let st = internal_out.clone();
447                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
448                        if !phase.bubble() {
449                            return;
450                        }
451                        let in_g = g_ref.borrow().is_some_and(|b| b.contains(&event.position));
452                        let in_m = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
453                        if !in_g && !in_m {
454                            st.update(cx, |s, _| {
455                                s.menu_open = false;
456                                s.highlighted_menu_idx = None;
457                            });
458                            window.refresh();
459                        }
460                    });
461                }
462            },
463        )
464        .absolute()
465        .inset_0();
466
467        let seg_h = self.size.height() - px(2.0);
468        let pad_x = self.size.pad_x();
469        let div_inset = if vertical {
470            px(10.0)
471        } else {
472            self.size.divider_inset()
473        };
474
475        let quiet_divider =
476            |idx: usize| -> bool { active_index.is_some_and(|ai| idx == ai || idx == ai + 1) };
477
478        let mut segment_elements = Vec::with_capacity(self.items.len() + 1);
479        for (idx, item) in self.items.iter().enumerate() {
480            let item_disabled = self.disabled || item.disabled;
481            let key = item.id.clone();
482            let seg_id = ElementId::NamedChild(
483                self.id.clone().into(),
484                SharedString::from(format!("seg-{}", item.id)),
485            );
486            let seg_bounds = snap.segment_bounds.clone();
487            let key_measure = key.clone();
488            let probe = canvas(
489                move |rect, _, _| {
490                    seg_bounds.borrow_mut().insert(key_measure.clone(), rect);
491                },
492                |_, _, _, _| {},
493            )
494            .absolute()
495            .inset_0();
496
497            let int_hover = internal.clone();
498            let int_down = internal.clone();
499            let int_up = internal.clone();
500            let int_out = internal.clone();
501            let key_hover = key.clone();
502            let key_down = key.clone();
503            let on_select = item.on_select.clone();
504
505            let show_divider = idx > 0 && !quiet_divider(idx);
506            let divider_el = if show_divider {
507                Some(if vertical {
508                    div()
509                        .absolute()
510                        .top_0()
511                        .left(div_inset)
512                        .right(div_inset)
513                        .h(px(1.0))
514                        .bg(divider_color)
515                } else {
516                    div()
517                        .absolute()
518                        .left_0()
519                        .top(div_inset)
520                        .bottom(div_inset)
521                        .w(px(1.0))
522                        .bg(divider_color)
523                })
524            } else {
525                None
526            };
527
528            let seg = BaseButton::new(seg_id)
529                .disabled(item_disabled)
530                .accessibility_label(item.label.clone())
531                .on_click(move |_, window, cx| {
532                    if item_disabled {
533                        return;
534                    }
535                    if let Some(cb) = &on_select {
536                        cb(&(), window, cx);
537                    }
538                    window.refresh();
539                })
540                .relative()
541                .flex_none()
542                .flex()
543                .flex_row()
544                .items_center()
545                .when(vertical && !item.icon_only, |this| {
546                    this.w_full().justify_start()
547                })
548                .when(!vertical || item.icon_only, |this| this.justify_center())
549                .h(seg_h)
550                .when(item.icon_only, |this| this.w(seg_h))
551                .when(!item.icon_only, |this| this.min_w(seg_h).px(pad_x))
552                .gap(if self.size == ButtonGroupSize::Sm {
553                    px(6.0)
554                } else {
555                    Spacing::S2
556                })
557                .text_size(Typography::TEXT_SM)
558                .text_color(group_fg)
559                .when(!item_disabled, |this| this.cursor_pointer())
560                .on_hover(move |hovered, window, cx| {
561                    if item_disabled {
562                        return;
563                    }
564                    int_hover.update(cx, |s, _| {
565                        if *hovered {
566                            s.hovered_key = Some(key_hover.clone());
567                        } else if s.hovered_key.as_ref() == Some(&key_hover) {
568                            s.hovered_key = None;
569                            s.pressed_key = None;
570                        }
571                    });
572                    window.refresh();
573                })
574                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
575                    if item_disabled {
576                        return;
577                    }
578                    int_down.update(cx, |s, _| s.pressed_key = Some(key_down.clone()));
579                    window.refresh();
580                })
581                .on_mouse_up(MouseButton::Left, move |_, window, cx| {
582                    int_up.update(cx, |s, _| s.pressed_key = None);
583                    window.refresh();
584                })
585                .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
586                    int_out.update(cx, |s, _| s.pressed_key = None);
587                    window.refresh();
588                })
589                .child(probe)
590                .when_some(divider_el, |this, d| this.child(d))
591                .child(
592                    div()
593                        .flex()
594                        .flex_row()
595                        .items_center()
596                        .gap(if self.size == ButtonGroupSize::Sm {
597                            px(6.0)
598                        } else {
599                            Spacing::S2
600                        })
601                        .when(item.disabled && !self.disabled, |this| this.opacity(0.4))
602                        .when_some(item.icon, |this, icon| this.child(icon))
603                        .when(!item.icon_only, |this| this.child(item.label.clone())),
604                );
605
606            segment_elements.push(seg.into_any_element());
607        }
608
609        // Optional trailing chevron trigger segment + floating menu.
610        let mut menu_overlay = None;
611        if let Some(menu) = self.menu {
612            let trigger_idx = self.items.len();
613            let trigger_id = ElementId::NamedChild(self.id.clone().into(), "menu-trigger".into());
614            let seg_bounds = snap.segment_bounds.clone();
615            let probe = canvas(
616                move |rect, _, _| {
617                    seg_bounds
618                        .borrow_mut()
619                        .insert(SharedString::from(MENU_KEY), rect);
620                },
621                |_, _, _, _| {},
622            )
623            .absolute()
624            .inset_0();
625
626            let int_hover = internal.clone();
627            let int_click = internal.clone();
628            let is_disabled = self.disabled;
629            let focus_open = snap.menu_focus.clone();
630            let show_divider = trigger_idx > 0 && !quiet_divider(trigger_idx);
631            let divider_el = if show_divider {
632                Some(if vertical {
633                    div()
634                        .absolute()
635                        .top_0()
636                        .left(div_inset)
637                        .right(div_inset)
638                        .h(px(1.0))
639                        .bg(divider_color)
640                } else {
641                    div()
642                        .absolute()
643                        .left_0()
644                        .top(div_inset)
645                        .bottom(div_inset)
646                        .w(px(1.0))
647                        .bg(divider_color)
648                })
649            } else {
650                None
651            };
652
653            let chevron_color = if is_open { group_fg } else { muted_ink };
654            let trigger_w = self.size.height() - px(6.0);
655            let trigger = BaseButton::new(trigger_id)
656                .disabled(self.disabled)
657                .accessibility_label(menu.label.clone())
658                .on_click(move |_, window, cx| {
659                    if is_disabled {
660                        return;
661                    }
662                    let t_now = motion_now(cx);
663                    let mut opened = false;
664                    int_click.update(cx, |s, _| {
665                        s.menu_open = !s.menu_open;
666                        opened = s.menu_open;
667                        if s.menu_open {
668                            s.opened_at_secs = t_now;
669                            s.highlighted_menu_idx = Some(0);
670                        } else {
671                            s.highlighted_menu_idx = None;
672                        }
673                    });
674                    if opened {
675                        window.focus(&focus_open, cx);
676                    }
677                    window.refresh();
678                })
679                .relative()
680                .flex_none()
681                .flex()
682                .items_center()
683                .justify_center()
684                .h(seg_h)
685                .when(vertical, |this| this.w_full())
686                .when(!vertical, |this| this.w(trigger_w))
687                .when(!self.disabled, |this| this.cursor_pointer())
688                .on_hover(move |hovered, window, cx| {
689                    if is_disabled {
690                        return;
691                    }
692                    int_hover.update(cx, |s, _| {
693                        if *hovered {
694                            s.hovered_key = Some(SharedString::from(MENU_KEY));
695                        } else if s.hovered_key.as_deref() == Some(MENU_KEY) {
696                            s.hovered_key = None;
697                        }
698                    });
699                    window.refresh();
700                })
701                .child(probe)
702                .when_some(divider_el, |this, d| this.child(d))
703                .child(
704                    canvas(
705                        |_, _, _| {},
706                        move |rect, _, window, _| {
707                            let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
708                            let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
709                            paint_chevron(cx, cy, chevron_deg, chevron_color, window);
710                        },
711                    )
712                    .size(px(16.0)),
713                );
714            segment_elements.push(trigger.into_any_element());
715
716            let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
717                .animate_initial(false)
718                .config(ArcPresenceConfig {
719                    enter_duration: motion.duration.fast,
720                    exit_duration: Duration::from_millis(130),
721                    enter_ease: motion.ease.enter,
722                    exit_ease: motion.ease.standard,
723                    fade_on_reduced_motion: true,
724                })
725                .sample(window, cx);
726
727            if menu_presence.should_render() && !menu.items.is_empty() {
728                let p = menu_presence.progress.clamp(0.0, 1.0);
729                let menu_y = if reduced { 0.0 } else { -5.0 * (1.0 - p) };
730                let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
731                let menu_bounds_ref = snap.menu_bounds.clone();
732                let menu_probe = canvas(
733                    move |rect, _, _| {
734                        *menu_bounds_ref.borrow_mut() = Some(rect);
735                    },
736                    |_, _, _, _| {},
737                )
738                .absolute()
739                .inset_0();
740                let int_key = internal.clone();
741                let items_key = menu.items.clone();
742                let menu_focus = snap.menu_focus.clone();
743                let hi_idx = snap.highlighted_menu_idx;
744
745                let rows = menu.items.into_iter().enumerate().map(|(i, act)| {
746                    let item_id = ElementId::NamedChild(
747                        self.id.clone().into(),
748                        SharedString::from(format!("bg-menu-{}", act.id)),
749                    );
750                    let delay = if reduced {
751                        0.0
752                    } else {
753                        (i.min(4) as f64) * 0.035
754                    };
755                    let op = if reduced || !is_open {
756                        1.0
757                    } else {
758                        let t = ((menu_elapsed - delay) / motion.duration.standard.as_secs_f64())
759                            .clamp(0.0, 1.0) as f32;
760                        if t < 1.0 {
761                            window.request_animation_frame();
762                        }
763                        CubicBezier::from_spec(motion.ease.enter).sample(t)
764                    };
765                    let item_fg = if act.destructive {
766                        colors.danger
767                    } else {
768                        colors.foreground
769                    };
770                    let hi_row_bg = if act.destructive {
771                        oklab_mix(colors.danger, colors.surface, 0.08)
772                    } else {
773                        colors.surface_muted
774                    };
775                    let int_hi = internal.clone();
776                    let int_sel = internal.clone();
777                    let on_select = act.on_select.clone();
778                    let act_disabled = act.disabled;
779
780                    div()
781                        .id(item_id)
782                        .test_support()
783                        .role(Role::MenuItem)
784                        .aria_label(act.label.clone())
785                        .flex()
786                        .flex_row()
787                        .items_center()
788                        .gap(px(10.0))
789                        .min_h(ControlHeights::SM)
790                        .px(px(10.0))
791                        .rounded(px(6.0))
792                        .text_size(Typography::TEXT_SM)
793                        .text_color(item_fg)
794                        .bg(if hi_idx == Some(i) && !act_disabled {
795                            hi_row_bg
796                        } else {
797                            Hsla::transparent_black()
798                        })
799                        .opacity(if act_disabled { 0.45 } else { op })
800                        .when(!act_disabled, |this| this.cursor_pointer())
801                        .on_hover(move |hovered, window, cx| {
802                            if act_disabled {
803                                return;
804                            }
805                            int_hi.update(cx, |s, _| {
806                                if *hovered {
807                                    s.highlighted_menu_idx = Some(i);
808                                } else if s.highlighted_menu_idx == Some(i) {
809                                    s.highlighted_menu_idx = None;
810                                }
811                            });
812                            window.refresh();
813                        })
814                        .on_click(move |_, window, cx| {
815                            if act_disabled {
816                                return;
817                            }
818                            int_sel.update(cx, |s, _| {
819                                s.menu_open = false;
820                                s.highlighted_menu_idx = None;
821                            });
822                            if let Some(cb) = &on_select {
823                                cb(&(), window, cx);
824                            }
825                            window.refresh();
826                        })
827                        .when_some(act.icon, |this, icon| this.child(icon))
828                        .child(act.label)
829                });
830
831                let menu_top = if vertical {
832                    seg_h * (self.items.len() + 1) as f32 + px(8.0 + menu_y)
833                } else {
834                    self.size.height() + px(6.0 + menu_y)
835                };
836
837                menu_overlay = Some(
838                    deferred(
839                        div()
840                            .id(ElementId::NamedChild(self.id.clone().into(), "menu".into()))
841                            .test_support()
842                            .track_focus(&menu_focus)
843                            .role(Role::Menu)
844                            .absolute()
845                            .top(menu_top)
846                            .when(vertical, |this| this.left_0())
847                            .when(!vertical, |this| this.right_0())
848                            .min_w(px(208.0))
849                            .p(px(5.0))
850                            .rounded(Radii::PANEL)
851                            .border_1()
852                            .border_color(colors.border)
853                            .bg(colors.surface_raised)
854                            .shadow(Shadows::floating(theme.mode))
855                            .opacity(p)
856                            .flex()
857                            .flex_col()
858                            .on_key_down(move |event: &KeyDownEvent, window, cx| {
859                                match event.keystroke.key.as_str() {
860                                    "escape" => {
861                                        int_key.update(cx, |s, _| {
862                                            s.menu_open = false;
863                                            s.highlighted_menu_idx = None;
864                                        });
865                                        window.refresh();
866                                    }
867                                    "down" => {
868                                        int_key.update(cx, |s, _| {
869                                            let next = s
870                                                .highlighted_menu_idx
871                                                .map_or(0, |v| (v + 1) % items_key.len());
872                                            s.highlighted_menu_idx = Some(next);
873                                        });
874                                        window.refresh();
875                                    }
876                                    "up" => {
877                                        int_key.update(cx, |s, _| {
878                                            let next = s
879                                                .highlighted_menu_idx
880                                                .map_or(items_key.len().saturating_sub(1), |v| {
881                                                    (v + items_key.len() - 1) % items_key.len()
882                                                });
883                                            s.highlighted_menu_idx = Some(next);
884                                        });
885                                        window.refresh();
886                                    }
887                                    "enter" | "space" => {
888                                        if let Some(idx) = int_key.read(cx).highlighted_menu_idx
889                                            && let Some(act) = items_key.get(idx)
890                                            && !act.disabled
891                                        {
892                                            int_key.update(cx, |s, _| {
893                                                s.menu_open = false;
894                                                s.highlighted_menu_idx = None;
895                                            });
896                                            if let Some(cb) = &act.on_select {
897                                                cb(&(), window, cx);
898                                            }
899                                            window.refresh();
900                                        }
901                                    }
902                                    _ => {}
903                                }
904                            })
905                            .child(menu_probe)
906                            .children(rows),
907                    )
908                    .with_priority(1),
909                );
910            }
911        }
912
913        div()
914            .id(self.id)
915            .test_support()
916            .role(Role::Group)
917            .aria_label(self.label)
918            .relative()
919            .self_start()
920            .flex()
921            .when(vertical, |this| this.flex_col())
922            .when(!vertical, |this| this.flex_row())
923            .items_stretch()
924            .border_1()
925            .border_color(group_border)
926            .rounded(Radii::CONTROL)
927            .bg(group_bg)
928            .when(self.disabled, |this| this.opacity(0.52))
929            .child(highlight_canvas)
930            .children(segment_elements)
931            .when_some(menu_overlay, |this, m| this.child(m))
932    }
933}
934
935#[cfg(test)]
936mod tests {
937    use std::{cell::Cell, rc::Rc};
938
939    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
940    use gpui_kit::{
941        Context, MouseButton, Render, Role, TestAppContext, div,
942        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
943    };
944
945    use super::*;
946
947    struct GroupHost {
948        selected: Rc<Cell<usize>>,
949        menu_selected: Rc<Cell<usize>>,
950    }
951
952    impl Render for GroupHost {
953        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
954            let selected = self.selected.clone();
955            let menu_selected = self.menu_selected.clone();
956            div().p(Spacing::S6).child(
957                ButtonGroup::new("doc-actions", "Document actions")
958                    .items([
959                        ButtonGroupItem::new("edit", "Edit").on_select(cx.listener(
960                            move |_, _, _, _| {
961                                selected.set(selected.get() + 1);
962                            },
963                        )),
964                        ButtonGroupItem::new("share", "Share"),
965                    ])
966                    .menu(ButtonGroupMenu::new(
967                        "More actions",
968                        [ButtonGroupMenuItem::new("delete", "Delete")
969                            .destructive(true)
970                            .on_select(cx.listener(move |_, _, _, _| {
971                                menu_selected.set(menu_selected.get() + 1);
972                            }))],
973                    )),
974            )
975        }
976    }
977
978    #[gpui_kit::test]
979    fn button_group_segments_and_menu_trigger_work(cx: &mut TestAppContext) {
980        cx.update(|cx| {
981            gpui_kit::init(cx);
982            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
983        });
984        let selected = Rc::new(Cell::new(0usize));
985        let menu_selected = Rc::new(Cell::new(0usize));
986        let (_view, cx) = cx.add_window_view(|_, _| GroupHost {
987            selected: selected.clone(),
988            menu_selected: menu_selected.clone(),
989        });
990
991        cx.update(|window, cx| {
992            window.render_frame(cx);
993            let edit = window.find_by_label("Edit");
994            assert_eq!(edit.role(), Some(Role::Button));
995            let pos = edit.bounds().center();
996            window.pointer_down(pos, MouseButton::Left, cx);
997            window.pointer_up(pos, MouseButton::Left, cx);
998            assert_eq!(selected.get(), 1);
999
1000            let more = window.find_by_label("More actions");
1001            let mpos = more.bounds().center();
1002            window.pointer_down(mpos, MouseButton::Left, cx);
1003            window.pointer_up(mpos, MouseButton::Left, cx);
1004            window.render_frame(cx);
1005
1006            let del = window.find_by_label("Delete");
1007            let dpos = del.bounds().center();
1008            window.pointer_down(dpos, MouseButton::Left, cx);
1009            window.pointer_up(dpos, MouseButton::Left, cx);
1010            assert_eq!(menu_selected.get(), 1);
1011        });
1012    }
1013}