Skip to main content

arc_ui/actions/
expanding_button_group.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/expanding-button-group/expanding-button-group.tsx` & `.module.css`
3//!
4//! P3 Component #16: `expanding-button-group`
5//!
6//! - A compact pill of icon buttons where one action always shows its label (`default_expanded`,
7//!   or the first enabled action).
8//! - Pointing at or focusing another action moves the expansion there; each item's width rides
9//!   `motion.spring.morph` between its square collapsed width (`height`) and expanded width
10//!   (`start + icon + gap + text_width + end`) while neighbors slide aside.
11//! - Sizes: `Sm` (28px height, 14px icon, start 7, gap 5, end 11) | `Md` (36px height, 16px icon, start 10, gap 7, end 14).
12//! - Tones: `Neutral` | `Danger` (tints expanded background with `danger`).
13//! - In-place confirmation (`done_label`): clicking an action with `done_label` draws a progressive
14//!   check icon (`slice_polyline`, `60ms` delay) and crossfades the label to the past-tense word
15//!   for `confirm_duration` (default `1400ms`), holding the button expanded until confirmation ends.
16
17use std::rc::Rc;
18
19use arc_motion::{
20    CubicBezier, PathPoint, PolylinePath, arc_spring, arc_transition, is_reduced_motion, motion_now,
21};
22use arc_tokens::{ActiveArcTheme as _, Radii, ThemeMode, Typography, oklab_mix};
23use gpui_kit::{
24    App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
25    Styled, TestSupportExt as _, Window, assets::IconName, base::Button as BaseButton, canvas, div,
26    prelude::*, px,
27};
28
29type SelectHandler = Rc<dyn Fn(&(), &mut Window, &mut App) -> bool>;
30type ActionHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
31
32/// Default confirmation hold duration in seconds (`1400ms`).
33pub const EBG_DEFAULT_CONFIRM_SECS: f64 = 1.4;
34
35/// Hysteresis margin in pixels before a neighbor takes over pointer expansion.
36pub const EBG_HYSTERESIS_PX: f32 = 4.0;
37
38#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
39pub enum ExpandingButtonGroupSize {
40    Sm,
41    #[default]
42    Md,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct ExpandingButtonMetrics {
47    pub height: f32,
48    pub icon: f32,
49    pub start: f32,
50    pub gap: f32,
51    pub end: f32,
52}
53
54impl ExpandingButtonGroupSize {
55    pub const fn metrics(self) -> ExpandingButtonMetrics {
56        match self {
57            Self::Sm => ExpandingButtonMetrics {
58                height: 26.0,
59                icon: 14.0,
60                start: 6.0,
61                gap: 5.0,
62                end: 10.0,
63            },
64            Self::Md => ExpandingButtonMetrics {
65                height: 32.0,
66                icon: 15.0,
67                start: 8.5,
68                gap: 6.0,
69                end: 12.0,
70            },
71        }
72    }
73}
74
75#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
76pub enum ExpandingButtonGroupTone {
77    #[default]
78    Neutral,
79    Danger,
80}
81
82/// Estimates the max text slot width across `label` and optional `done_label` so confirmation swaps
83/// never change the expanded width.
84pub fn ebg_slot_text_width(
85    label: &str,
86    done_label: Option<&str>,
87    size: ExpandingButtonGroupSize,
88) -> f32 {
89    let char_adv = match size {
90        ExpandingButtonGroupSize::Sm => 6.7,
91        ExpandingButtonGroupSize::Md => 7.5,
92    };
93    let measure = |s: &str| -> f32 {
94        s.chars()
95            .map(|c| if c.is_ascii() { 1.0_f32 } else { 1.75_f32 })
96            .sum::<f32>()
97            * char_adv
98    };
99    let w1 = measure(label);
100    let w2 = done_label.map_or(0.0, measure);
101    w1.max(w2).ceil()
102}
103
104/// Target button width in pixels when collapsed vs expanded.
105pub fn ebg_item_target_width(
106    expanded: bool,
107    label: &str,
108    done_label: Option<&str>,
109    size: ExpandingButtonGroupSize,
110) -> f32 {
111    let m = size.metrics();
112    if expanded {
113        let text_w = ebg_slot_text_width(label, done_label, size);
114        m.start + m.icon + m.gap + text_w + m.end
115    } else {
116        m.height
117    }
118}
119
120/// Resolves which action ID should currently be expanded (`intent` wins over `done`, then `default_expanded`, then first enabled).
121pub fn ebg_resolve_expanded_id(
122    items: &[ExpandingButtonGroupItem],
123    default_expanded: Option<&str>,
124    intent_id: Option<&str>,
125    done_id: Option<&str>,
126) -> Option<SharedString> {
127    let exists = |id: &str| items.iter().any(|it| it.id.as_ref() == id);
128    if let Some(id) = intent_id.filter(|id| exists(id)) {
129        return Some(SharedString::from(id.to_owned()));
130    }
131    if let Some(id) = done_id.filter(|id| exists(id)) {
132        return Some(SharedString::from(id.to_owned()));
133    }
134    if let Some(id) = default_expanded.filter(|id| exists(id)) {
135        return Some(SharedString::from(id.to_owned()));
136    }
137    items
138        .iter()
139        .find(|it| !it.disabled)
140        .or_else(|| items.first())
141        .map(|it| it.id.clone())
142}
143
144#[derive(Clone)]
145pub struct ExpandingButtonGroupItem {
146    pub id: SharedString,
147    pub label: SharedString,
148    pub icon: IconName,
149    pub done_label: Option<SharedString>,
150    pub tone: ExpandingButtonGroupTone,
151    pub disabled: bool,
152    pub on_select: Option<SelectHandler>,
153}
154
155impl ExpandingButtonGroupItem {
156    pub fn new(
157        id: impl Into<SharedString>,
158        label: impl Into<SharedString>,
159        icon: IconName,
160    ) -> Self {
161        Self {
162            id: id.into(),
163            label: label.into(),
164            icon,
165            done_label: None,
166            tone: ExpandingButtonGroupTone::Neutral,
167            disabled: false,
168            on_select: None,
169        }
170    }
171
172    pub fn done_label(mut self, label: impl Into<SharedString>) -> Self {
173        self.done_label = Some(label.into());
174        self
175    }
176
177    pub fn tone(mut self, tone: ExpandingButtonGroupTone) -> Self {
178        self.tone = tone;
179        self
180    }
181
182    pub fn disabled(mut self, disabled: bool) -> Self {
183        self.disabled = disabled;
184        self
185    }
186
187    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
188        self.on_select = Some(Rc::new(move |ev, w, cx| {
189            handler(ev, w, cx);
190            true
191        }));
192        self
193    }
194
195    pub fn on_select_confirm(
196        mut self,
197        handler: impl Fn(&(), &mut Window, &mut App) -> bool + 'static,
198    ) -> Self {
199        self.on_select = Some(Rc::new(handler));
200        self
201    }
202}
203
204#[derive(Clone, Default)]
205struct ExpandingButtonGroupInternal {
206    hovered_id: Option<SharedString>,
207    pressed_id: Option<SharedString>,
208    done: Option<(SharedString, f64)>,
209}
210
211fn check_path_for(icon_px: f32) -> PolylinePath {
212    let s = icon_px / 24.0;
213    PolylinePath::new(vec![
214        PathPoint::new(4.0 * s, 12.5 * s),
215        PathPoint::new(9.0 * s, 17.5 * s),
216        PathPoint::new(20.0 * s, 6.5 * s),
217    ])
218}
219
220/// Arc `ExpandingButtonGroup`: compact pill toolbar where one item is always expanded to reveal
221/// its label, neighbors slide smoothly on `motion.spring.morph`, and actions with `done_label`
222/// confirm in place with a drawn checkmark.
223#[derive(IntoElement)]
224pub struct ExpandingButtonGroup {
225    id: ElementId,
226    label: SharedString,
227    items: Vec<ExpandingButtonGroupItem>,
228    size: ExpandingButtonGroupSize,
229    default_expanded: Option<SharedString>,
230    confirm_duration_secs: f64,
231    on_action: Option<ActionHandler>,
232}
233
234impl ExpandingButtonGroup {
235    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
236        Self {
237            id: id.into(),
238            label: label.into(),
239            items: Vec::new(),
240            size: ExpandingButtonGroupSize::Md,
241            default_expanded: None,
242            confirm_duration_secs: EBG_DEFAULT_CONFIRM_SECS,
243            on_action: None,
244        }
245    }
246
247    pub fn item(mut self, item: ExpandingButtonGroupItem) -> Self {
248        self.items.push(item);
249        self
250    }
251
252    pub fn items(mut self, items: impl IntoIterator<Item = ExpandingButtonGroupItem>) -> Self {
253        self.items.extend(items);
254        self
255    }
256
257    pub fn size(mut self, size: ExpandingButtonGroupSize) -> Self {
258        self.size = size;
259        self
260    }
261
262    pub fn default_expanded(mut self, id: impl Into<SharedString>) -> Self {
263        self.default_expanded = Some(id.into());
264        self
265    }
266
267    pub fn confirm_duration_ms(mut self, ms: u64) -> Self {
268        self.confirm_duration_secs = (ms as f64) / 1000.0;
269        self
270    }
271
272    pub fn on_action(
273        mut self,
274        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
275    ) -> Self {
276        self.on_action = Some(Rc::new(handler));
277        self
278    }
279}
280
281impl RenderOnce for ExpandingButtonGroup {
282    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
283        let theme = cx.arc_theme().clone();
284        let colors = theme.colors;
285        let motion = theme.motion;
286        let reduced = is_reduced_motion(cx);
287        let now = motion_now(cx);
288        let dark = theme.mode == ThemeMode::Dark;
289
290        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-ebg-state".into());
291        let internal =
292            window.use_keyed_state(state_id, cx, |_, _| ExpandingButtonGroupInternal::default());
293
294        // Check if active confirmation timer has expired
295        let mut snap = internal.read(cx).clone();
296        if let Some((_, started_at)) = &snap.done {
297            let elapsed = (now - *started_at).max(0.0);
298            if elapsed >= self.confirm_duration_secs {
299                internal.update(cx, |s, _| {
300                    s.done = None;
301                });
302                snap.done = None;
303            } else {
304                window.request_animation_frame();
305            }
306        }
307
308        let active_done_id = snap.done.as_ref().map(|(id, _)| id.as_ref());
309        let expanded_id = ebg_resolve_expanded_id(
310            &self.items,
311            self.default_expanded.as_deref(),
312            snap.hovered_id.as_deref(),
313            active_done_id,
314        );
315
316        let m = self.size.metrics();
317        let mut item_els = Vec::with_capacity(self.items.len());
318
319        for item in &self.items {
320            let id = item.id.clone();
321            let is_expanded = expanded_id.as_ref() == Some(&id);
322            let done_info = snap.done.as_ref().filter(|(d_id, _)| d_id == &id);
323            let show_done = done_info.is_some() && item.done_label.is_some();
324            let is_danger = item.tone == ExpandingButtonGroupTone::Danger;
325            let is_disabled = item.disabled;
326
327            let target_w = ebg_item_target_width(
328                is_expanded,
329                item.label.as_ref(),
330                item.done_label.as_deref(),
331                self.size,
332            );
333
334            let current_w = if reduced {
335                target_w
336            } else {
337                arc_spring(
338                    (
339                        self.id.clone(),
340                        SharedString::from(format!("ebg-w-{}", item.id)),
341                    ),
342                    target_w,
343                    motion.spring.morph,
344                    window,
345                    cx,
346                )
347            };
348
349            let label_op = arc_transition(
350                (
351                    self.id.clone(),
352                    SharedString::from(format!("ebg-lbl-op-{}", item.id)),
353                ),
354                if is_expanded { 1.0 } else { 0.0 },
355                if reduced {
356                    motion.duration.instant
357                } else if is_expanded {
358                    motion.duration.standard
359                } else {
360                    motion.duration.instant
361                },
362                if is_expanded {
363                    motion.ease.enter
364                } else {
365                    motion.ease.standard
366                },
367                window,
368                cx,
369            );
370
371            let label_x = if reduced {
372                0.0
373            } else {
374                -6.0 * (1.0 - label_op)
375            };
376
377            let (item_bg, item_fg, icon_fg) = if is_disabled {
378                let bg = if is_expanded {
379                    colors.surface_muted
380                } else {
381                    Hsla::transparent_black()
382                };
383                let fg = if is_expanded {
384                    colors.text_secondary
385                } else {
386                    colors.text_muted
387                };
388                (bg, fg, fg)
389            } else if show_done && !is_danger {
390                let bg = oklab_mix(
391                    colors.success,
392                    colors.surface,
393                    if dark { 0.14 } else { 0.10 },
394                );
395                let fg = if is_expanded {
396                    colors.foreground
397                } else {
398                    colors.text_secondary
399                };
400                (bg, fg, colors.success)
401            } else if is_expanded && is_danger {
402                let bg = oklab_mix(
403                    colors.danger,
404                    colors.surface,
405                    if dark { 0.14 } else { 0.10 },
406                );
407                (bg, colors.danger, colors.danger)
408            } else if is_expanded {
409                (colors.surface_muted, colors.foreground, colors.foreground)
410            } else {
411                (
412                    Hsla::transparent_black(),
413                    colors.text_secondary,
414                    colors.text_secondary,
415                )
416            };
417
418            let word = if show_done {
419                item.done_label
420                    .clone()
421                    .unwrap_or_else(|| item.label.clone())
422            } else {
423                item.label.clone()
424            };
425
426            let check_progress = if let Some((_, started_at)) = done_info {
427                if reduced {
428                    1.0
429                } else {
430                    let elapsed = (now - *started_at - 0.06).max(0.0);
431                    let t =
432                        (elapsed / motion.duration.standard.as_secs_f64()).clamp(0.0, 1.0) as f32;
433                    CubicBezier::from_spec(motion.ease.enter).sample(t)
434                }
435            } else {
436                0.0
437            };
438
439            let icon_el = if show_done {
440                let path = check_path_for(m.icon);
441                canvas(
442                    |_, _, _| {},
443                    move |rect, _, window, _| {
444                        let sliced = path.slice(0.0, check_progress);
445                        if let Some(builder) =
446                            sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(2.0))
447                            && let Ok(built) = builder.build()
448                        {
449                            window.paint_path(built, icon_fg);
450                        }
451                    },
452                )
453                .size(px(m.icon))
454                .into_any_element()
455            } else {
456                div()
457                    .size(px(m.icon))
458                    .flex_none()
459                    .flex()
460                    .items_center()
461                    .justify_center()
462                    .text_color(icon_fg)
463                    .child(item.icon)
464                    .into_any_element()
465            };
466
467            let btn_id = ElementId::NamedChild(
468                self.id.clone().into(),
469                SharedString::from(format!("ebg-item-{}", item.id)),
470            );
471
472            let int_hover = internal.clone();
473            let int_down = internal.clone();
474            let int_up = internal.clone();
475            let int_click = internal.clone();
476            let id_hover = id.clone();
477            let id_down = id.clone();
478            let id_click = id.clone();
479            let has_done_label = item.done_label.is_some();
480            let on_select = item.on_select.clone();
481            let on_action = self.on_action.clone();
482
483            let btn = BaseButton::new(btn_id)
484                .disabled(is_disabled)
485                .accessibility_label(item.label.clone())
486                .on_click(move |_, window, cx| {
487                    if is_disabled {
488                        return;
489                    }
490                    let already_done = int_click
491                        .read(cx)
492                        .done
493                        .as_ref()
494                        .is_some_and(|(d_id, _)| d_id == &id_click);
495                    if already_done {
496                        return;
497                    }
498                    int_click.update(cx, |s, _| {
499                        s.hovered_id = Some(id_click.clone());
500                    });
501                    if let Some(cb) = &on_action {
502                        cb(&id_click, window, cx);
503                    }
504                    let should_confirm = on_select.as_ref().is_none_or(|cb| cb(&(), window, cx));
505                    if should_confirm && has_done_label {
506                        let t_now = motion_now(cx);
507                        int_click.update(cx, |s, _| {
508                            s.done = Some((id_click.clone(), t_now));
509                        });
510                    }
511                    window.refresh();
512                })
513                .relative()
514                .flex_none()
515                .overflow_hidden()
516                .flex()
517                .flex_row()
518                .items_center()
519                .justify_start()
520                .h(px(m.height))
521                .w(px(current_w.max(m.height)))
522                .min_w(px(m.height))
523                .pl(px(m.start))
524                .gap(px(m.gap))
525                .rounded(Radii::PILL)
526                .bg(item_bg)
527                .text_size(match self.size {
528                    ExpandingButtonGroupSize::Sm => Typography::TEXT_XS,
529                    ExpandingButtonGroupSize::Md => Typography::TEXT_SM,
530                })
531                .text_color(item_fg)
532                .when(is_disabled, |this| this.opacity(0.5))
533                .when(!is_disabled, |this| this.cursor_pointer())
534                .on_hover(move |hovered, window, cx| {
535                    int_hover.update(cx, |s, _| {
536                        if *hovered {
537                            s.hovered_id = Some(id_hover.clone());
538                        } else if s.hovered_id.as_ref() == Some(&id_hover) {
539                            s.hovered_id = None;
540                            s.pressed_id = None;
541                        }
542                    });
543                    window.refresh();
544                })
545                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
546                    if is_disabled {
547                        return;
548                    }
549                    int_down.update(cx, |s, _| {
550                        s.pressed_id = Some(id_down.clone());
551                    });
552                    window.refresh();
553                })
554                .on_mouse_up(MouseButton::Left, move |_, window, cx| {
555                    int_up.update(cx, |s, _| s.pressed_id = None);
556                    window.refresh();
557                })
558                .child(icon_el)
559                .child(
560                    div()
561                        .flex_none()
562                        .ml(px(label_x))
563                        .opacity(label_op)
564                        .whitespace_nowrap()
565                        .child(word),
566                );
567
568            item_els.push(btn.into_any_element());
569        }
570
571        div()
572            .id(self.id)
573            .test_support()
574            .role(Role::Toolbar)
575            .aria_label(self.label)
576            .relative()
577            .self_start()
578            .flex_none()
579            .flex()
580            .flex_row()
581            .items_center()
582            .gap(px(2.0))
583            .p(px(3.0))
584            .rounded(Radii::PILL)
585            .border_1()
586            .border_color(colors.border)
587            .bg(colors.surface)
588            .children(item_els)
589    }
590}
591
592#[cfg(test)]
593mod tests {
594    use std::{cell::Cell, rc::Rc};
595
596    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
597    use gpui_kit::{
598        Context, MouseButton, Render, Role, TestAppContext, div,
599        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
600    };
601
602    use super::*;
603
604    #[test]
605    fn expanded_resolution_and_width_targets_follow_rules() {
606        let items = vec![
607            ExpandingButtonGroupItem::new("reply", "Reply", IconName::MessageSquare),
608            ExpandingButtonGroupItem::new("archive", "Archive", IconName::Archive)
609                .done_label("Archived"),
610            ExpandingButtonGroupItem::new("delete", "Delete", IconName::Trash)
611                .tone(ExpandingButtonGroupTone::Danger),
612        ];
613
614        // Defaults to first enabled item when default_expanded is None
615        assert_eq!(
616            ebg_resolve_expanded_id(&items, None, None, None).as_deref(),
617            Some("reply")
618        );
619        // Uses default_expanded at rest
620        assert_eq!(
621            ebg_resolve_expanded_id(&items, Some("archive"), None, None).as_deref(),
622            Some("archive")
623        );
624        // Intent overrides default_expanded
625        assert_eq!(
626            ebg_resolve_expanded_id(&items, Some("reply"), Some("delete"), None).as_deref(),
627            Some("delete")
628        );
629
630        let collapsed_w = ebg_item_target_width(
631            false,
632            "Archive",
633            Some("Archived"),
634            ExpandingButtonGroupSize::Md,
635        );
636        let expanded_w = ebg_item_target_width(
637            true,
638            "Archive",
639            Some("Archived"),
640            ExpandingButtonGroupSize::Md,
641        );
642        assert!((collapsed_w - ExpandingButtonGroupSize::Md.metrics().height).abs() < 1e-4);
643        assert!(expanded_w > collapsed_w + 30.0);
644
645        // Slot width matches regardless of whether "Archive" or "Archived" is primary
646        let w_swapped = ebg_item_target_width(
647            true,
648            "Archived",
649            Some("Archive"),
650            ExpandingButtonGroupSize::Md,
651        );
652        assert!((expanded_w - w_swapped).abs() < 1e-4);
653    }
654
655    struct Host {
656        archived_count: Rc<Cell<usize>>,
657    }
658
659    impl Render for Host {
660        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
661            let count = self.archived_count.clone();
662            div().p(Spacing::S6).child(
663                ExpandingButtonGroup::new("msg-actions", "Message actions").items([
664                    ExpandingButtonGroupItem::new("reply", "Reply", IconName::MessageSquare),
665                    ExpandingButtonGroupItem::new("archive", "Archive", IconName::Archive)
666                        .done_label("Archived")
667                        .on_select(cx.listener(move |_, _, _, _| {
668                            count.set(count.get() + 1);
669                        })),
670                ]),
671            )
672        }
673    }
674
675    #[gpui_kit::test]
676    fn expanding_button_group_triggers_action_and_confirmation(cx: &mut TestAppContext) {
677        cx.update(|cx| {
678            gpui_kit::init(cx);
679            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
680        });
681        let archived_count = Rc::new(Cell::new(0usize));
682        let (_view, cx) = cx.add_window_view(|_, _| Host {
683            archived_count: archived_count.clone(),
684        });
685
686        cx.update(|window, cx| {
687            window.render_frame(cx);
688            let archive = window.find_by_label("Archive");
689            assert_eq!(archive.role(), Some(Role::Button));
690            let pos = archive.bounds().center();
691            window.pointer_down(pos, MouseButton::Left, cx);
692            window.pointer_up(pos, MouseButton::Left, cx);
693            assert_eq!(archived_count.get(), 1);
694        });
695    }
696}