use std::rc::Rc;
use arc_motion::{
CubicBezier, PathPoint, PolylinePath, arc_spring, arc_transition, is_reduced_motion, motion_now,
};
use arc_tokens::{ActiveArcTheme as _, Radii, ThemeMode, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
Styled, TestSupportExt as _, Window, assets::IconName, base::Button as BaseButton, canvas, div,
prelude::*, px,
};
type SelectHandler = Rc<dyn Fn(&(), &mut Window, &mut App) -> bool>;
type ActionHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
pub const EBG_DEFAULT_CONFIRM_SECS: f64 = 1.4;
pub const EBG_HYSTERESIS_PX: f32 = 4.0;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ExpandingButtonGroupSize {
Sm,
#[default]
Md,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ExpandingButtonMetrics {
pub height: f32,
pub icon: f32,
pub start: f32,
pub gap: f32,
pub end: f32,
}
impl ExpandingButtonGroupSize {
pub const fn metrics(self) -> ExpandingButtonMetrics {
match self {
Self::Sm => ExpandingButtonMetrics {
height: 26.0,
icon: 14.0,
start: 6.0,
gap: 5.0,
end: 10.0,
},
Self::Md => ExpandingButtonMetrics {
height: 32.0,
icon: 15.0,
start: 8.5,
gap: 6.0,
end: 12.0,
},
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ExpandingButtonGroupTone {
#[default]
Neutral,
Danger,
}
pub fn ebg_slot_text_width(
label: &str,
done_label: Option<&str>,
size: ExpandingButtonGroupSize,
) -> f32 {
let char_adv = match size {
ExpandingButtonGroupSize::Sm => 6.7,
ExpandingButtonGroupSize::Md => 7.5,
};
let measure = |s: &str| -> f32 {
s.chars()
.map(|c| if c.is_ascii() { 1.0_f32 } else { 1.75_f32 })
.sum::<f32>()
* char_adv
};
let w1 = measure(label);
let w2 = done_label.map_or(0.0, measure);
w1.max(w2).ceil()
}
pub fn ebg_item_target_width(
expanded: bool,
label: &str,
done_label: Option<&str>,
size: ExpandingButtonGroupSize,
) -> f32 {
let m = size.metrics();
if expanded {
let text_w = ebg_slot_text_width(label, done_label, size);
m.start + m.icon + m.gap + text_w + m.end
} else {
m.height
}
}
pub fn ebg_resolve_expanded_id(
items: &[ExpandingButtonGroupItem],
default_expanded: Option<&str>,
intent_id: Option<&str>,
done_id: Option<&str>,
) -> Option<SharedString> {
let exists = |id: &str| items.iter().any(|it| it.id.as_ref() == id);
if let Some(id) = intent_id.filter(|id| exists(id)) {
return Some(SharedString::from(id.to_owned()));
}
if let Some(id) = done_id.filter(|id| exists(id)) {
return Some(SharedString::from(id.to_owned()));
}
if let Some(id) = default_expanded.filter(|id| exists(id)) {
return Some(SharedString::from(id.to_owned()));
}
items
.iter()
.find(|it| !it.disabled)
.or_else(|| items.first())
.map(|it| it.id.clone())
}
#[derive(Clone)]
pub struct ExpandingButtonGroupItem {
pub id: SharedString,
pub label: SharedString,
pub icon: IconName,
pub done_label: Option<SharedString>,
pub tone: ExpandingButtonGroupTone,
pub disabled: bool,
pub on_select: Option<SelectHandler>,
}
impl ExpandingButtonGroupItem {
pub fn new(
id: impl Into<SharedString>,
label: impl Into<SharedString>,
icon: IconName,
) -> Self {
Self {
id: id.into(),
label: label.into(),
icon,
done_label: None,
tone: ExpandingButtonGroupTone::Neutral,
disabled: false,
on_select: None,
}
}
pub fn done_label(mut self, label: impl Into<SharedString>) -> Self {
self.done_label = Some(label.into());
self
}
pub fn tone(mut self, tone: ExpandingButtonGroupTone) -> Self {
self.tone = tone;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_select = Some(Rc::new(move |ev, w, cx| {
handler(ev, w, cx);
true
}));
self
}
pub fn on_select_confirm(
mut self,
handler: impl Fn(&(), &mut Window, &mut App) -> bool + 'static,
) -> Self {
self.on_select = Some(Rc::new(handler));
self
}
}
#[derive(Clone, Default)]
struct ExpandingButtonGroupInternal {
hovered_id: Option<SharedString>,
pressed_id: Option<SharedString>,
done: Option<(SharedString, f64)>,
}
fn check_path_for(icon_px: f32) -> PolylinePath {
let s = icon_px / 24.0;
PolylinePath::new(vec![
PathPoint::new(4.0 * s, 12.5 * s),
PathPoint::new(9.0 * s, 17.5 * s),
PathPoint::new(20.0 * s, 6.5 * s),
])
}
#[derive(IntoElement)]
pub struct ExpandingButtonGroup {
id: ElementId,
label: SharedString,
items: Vec<ExpandingButtonGroupItem>,
size: ExpandingButtonGroupSize,
default_expanded: Option<SharedString>,
confirm_duration_secs: f64,
on_action: Option<ActionHandler>,
}
impl ExpandingButtonGroup {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
items: Vec::new(),
size: ExpandingButtonGroupSize::Md,
default_expanded: None,
confirm_duration_secs: EBG_DEFAULT_CONFIRM_SECS,
on_action: None,
}
}
pub fn item(mut self, item: ExpandingButtonGroupItem) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = ExpandingButtonGroupItem>) -> Self {
self.items.extend(items);
self
}
pub fn size(mut self, size: ExpandingButtonGroupSize) -> Self {
self.size = size;
self
}
pub fn default_expanded(mut self, id: impl Into<SharedString>) -> Self {
self.default_expanded = Some(id.into());
self
}
pub fn confirm_duration_ms(mut self, ms: u64) -> Self {
self.confirm_duration_secs = (ms as f64) / 1000.0;
self
}
pub fn on_action(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_action = Some(Rc::new(handler));
self
}
}
impl RenderOnce for ExpandingButtonGroup {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let dark = theme.mode == ThemeMode::Dark;
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-ebg-state".into());
let internal =
window.use_keyed_state(state_id, cx, |_, _| ExpandingButtonGroupInternal::default());
let mut snap = internal.read(cx).clone();
if let Some((_, started_at)) = &snap.done {
let elapsed = (now - *started_at).max(0.0);
if elapsed >= self.confirm_duration_secs {
internal.update(cx, |s, _| {
s.done = None;
});
snap.done = None;
} else {
window.request_animation_frame();
}
}
let active_done_id = snap.done.as_ref().map(|(id, _)| id.as_ref());
let expanded_id = ebg_resolve_expanded_id(
&self.items,
self.default_expanded.as_deref(),
snap.hovered_id.as_deref(),
active_done_id,
);
let m = self.size.metrics();
let mut item_els = Vec::with_capacity(self.items.len());
for item in &self.items {
let id = item.id.clone();
let is_expanded = expanded_id.as_ref() == Some(&id);
let done_info = snap.done.as_ref().filter(|(d_id, _)| d_id == &id);
let show_done = done_info.is_some() && item.done_label.is_some();
let is_danger = item.tone == ExpandingButtonGroupTone::Danger;
let is_disabled = item.disabled;
let target_w = ebg_item_target_width(
is_expanded,
item.label.as_ref(),
item.done_label.as_deref(),
self.size,
);
let current_w = if reduced {
target_w
} else {
arc_spring(
(
self.id.clone(),
SharedString::from(format!("ebg-w-{}", item.id)),
),
target_w,
motion.spring.morph,
window,
cx,
)
};
let label_op = arc_transition(
(
self.id.clone(),
SharedString::from(format!("ebg-lbl-op-{}", item.id)),
),
if is_expanded { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if is_expanded {
motion.duration.standard
} else {
motion.duration.instant
},
if is_expanded {
motion.ease.enter
} else {
motion.ease.standard
},
window,
cx,
);
let label_x = if reduced {
0.0
} else {
-6.0 * (1.0 - label_op)
};
let (item_bg, item_fg, icon_fg) = if is_disabled {
let bg = if is_expanded {
colors.surface_muted
} else {
Hsla::transparent_black()
};
let fg = if is_expanded {
colors.text_secondary
} else {
colors.text_muted
};
(bg, fg, fg)
} else if show_done && !is_danger {
let bg = oklab_mix(
colors.success,
colors.surface,
if dark { 0.14 } else { 0.10 },
);
let fg = if is_expanded {
colors.foreground
} else {
colors.text_secondary
};
(bg, fg, colors.success)
} else if is_expanded && is_danger {
let bg = oklab_mix(
colors.danger,
colors.surface,
if dark { 0.14 } else { 0.10 },
);
(bg, colors.danger, colors.danger)
} else if is_expanded {
(colors.surface_muted, colors.foreground, colors.foreground)
} else {
(
Hsla::transparent_black(),
colors.text_secondary,
colors.text_secondary,
)
};
let word = if show_done {
item.done_label
.clone()
.unwrap_or_else(|| item.label.clone())
} else {
item.label.clone()
};
let check_progress = if let Some((_, started_at)) = done_info {
if reduced {
1.0
} else {
let elapsed = (now - *started_at - 0.06).max(0.0);
let t =
(elapsed / motion.duration.standard.as_secs_f64()).clamp(0.0, 1.0) as f32;
CubicBezier::from_spec(motion.ease.enter).sample(t)
}
} else {
0.0
};
let icon_el = if show_done {
let path = check_path_for(m.icon);
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let sliced = path.slice(0.0, check_progress);
if let Some(builder) =
sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(2.0))
&& let Ok(built) = builder.build()
{
window.paint_path(built, icon_fg);
}
},
)
.size(px(m.icon))
.into_any_element()
} else {
div()
.size(px(m.icon))
.flex_none()
.flex()
.items_center()
.justify_center()
.text_color(icon_fg)
.child(item.icon)
.into_any_element()
};
let btn_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("ebg-item-{}", item.id)),
);
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_click = internal.clone();
let id_hover = id.clone();
let id_down = id.clone();
let id_click = id.clone();
let has_done_label = item.done_label.is_some();
let on_select = item.on_select.clone();
let on_action = self.on_action.clone();
let btn = BaseButton::new(btn_id)
.disabled(is_disabled)
.accessibility_label(item.label.clone())
.on_click(move |_, window, cx| {
if is_disabled {
return;
}
let already_done = int_click
.read(cx)
.done
.as_ref()
.is_some_and(|(d_id, _)| d_id == &id_click);
if already_done {
return;
}
int_click.update(cx, |s, _| {
s.hovered_id = Some(id_click.clone());
});
if let Some(cb) = &on_action {
cb(&id_click, window, cx);
}
let should_confirm = on_select.as_ref().is_none_or(|cb| cb(&(), window, cx));
if should_confirm && has_done_label {
let t_now = motion_now(cx);
int_click.update(cx, |s, _| {
s.done = Some((id_click.clone(), t_now));
});
}
window.refresh();
})
.relative()
.flex_none()
.overflow_hidden()
.flex()
.flex_row()
.items_center()
.justify_start()
.h(px(m.height))
.w(px(current_w.max(m.height)))
.min_w(px(m.height))
.pl(px(m.start))
.gap(px(m.gap))
.rounded(Radii::PILL)
.bg(item_bg)
.text_size(match self.size {
ExpandingButtonGroupSize::Sm => Typography::TEXT_XS,
ExpandingButtonGroupSize::Md => Typography::TEXT_SM,
})
.text_color(item_fg)
.when(is_disabled, |this| this.opacity(0.5))
.when(!is_disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
if *hovered {
s.hovered_id = Some(id_hover.clone());
} else if s.hovered_id.as_ref() == Some(&id_hover) {
s.hovered_id = None;
s.pressed_id = None;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if is_disabled {
return;
}
int_down.update(cx, |s, _| {
s.pressed_id = Some(id_down.clone());
});
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed_id = None);
window.refresh();
})
.child(icon_el)
.child(
div()
.flex_none()
.ml(px(label_x))
.opacity(label_op)
.whitespace_nowrap()
.child(word),
);
item_els.push(btn.into_any_element());
}
div()
.id(self.id)
.test_support()
.role(Role::Toolbar)
.aria_label(self.label)
.relative()
.self_start()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(px(2.0))
.p(px(3.0))
.rounded(Radii::PILL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.children(item_els)
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
#[test]
fn expanded_resolution_and_width_targets_follow_rules() {
let items = vec![
ExpandingButtonGroupItem::new("reply", "Reply", IconName::MessageSquare),
ExpandingButtonGroupItem::new("archive", "Archive", IconName::Archive)
.done_label("Archived"),
ExpandingButtonGroupItem::new("delete", "Delete", IconName::Trash)
.tone(ExpandingButtonGroupTone::Danger),
];
assert_eq!(
ebg_resolve_expanded_id(&items, None, None, None).as_deref(),
Some("reply")
);
assert_eq!(
ebg_resolve_expanded_id(&items, Some("archive"), None, None).as_deref(),
Some("archive")
);
assert_eq!(
ebg_resolve_expanded_id(&items, Some("reply"), Some("delete"), None).as_deref(),
Some("delete")
);
let collapsed_w = ebg_item_target_width(
false,
"Archive",
Some("Archived"),
ExpandingButtonGroupSize::Md,
);
let expanded_w = ebg_item_target_width(
true,
"Archive",
Some("Archived"),
ExpandingButtonGroupSize::Md,
);
assert!((collapsed_w - ExpandingButtonGroupSize::Md.metrics().height).abs() < 1e-4);
assert!(expanded_w > collapsed_w + 30.0);
let w_swapped = ebg_item_target_width(
true,
"Archived",
Some("Archive"),
ExpandingButtonGroupSize::Md,
);
assert!((expanded_w - w_swapped).abs() < 1e-4);
}
struct Host {
archived_count: Rc<Cell<usize>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let count = self.archived_count.clone();
div().p(Spacing::S6).child(
ExpandingButtonGroup::new("msg-actions", "Message actions").items([
ExpandingButtonGroupItem::new("reply", "Reply", IconName::MessageSquare),
ExpandingButtonGroupItem::new("archive", "Archive", IconName::Archive)
.done_label("Archived")
.on_select(cx.listener(move |_, _, _, _| {
count.set(count.get() + 1);
})),
]),
)
}
}
#[gpui_kit::test]
fn expanding_button_group_triggers_action_and_confirmation(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let archived_count = Rc::new(Cell::new(0usize));
let (_view, cx) = cx.add_window_view(|_, _| Host {
archived_count: archived_count.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let archive = window.find_by_label("Archive");
assert_eq!(archive.role(), Some(Role::Button));
let pos = archive.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(archived_count.get(), 1);
});
}
}