use std::{cell::RefCell, collections::HashMap, rc::Rc};
use arc_motion::{
LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion, layout::layout_scope_key,
sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, ThemeMode, Typography};
use gpui_kit::{
App, BorderStyle, Bounds, Edges, ElementId, Hsla, IntoElement, MouseButton, ParentElement,
Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
base::Button as BaseButton, bounds, canvas, deferred, div, point, prelude::*, px, quad, size,
};
use crate::overlay::tooltip::TooltipSide;
fn with_alpha(color: Hsla, alpha: f32) -> Hsla {
Hsla {
a: (color.a * alpha).clamp(0.0, 1.0),
..color
}
}
type SelectHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
type ActionHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
pub const FBG_PRESS_SCALE: f32 = 0.965;
pub const FBG_APPEAR_SCALE: f32 = 0.94;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum FloatingButtonGroupVariant {
#[default]
Muted,
Floating,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum FloatingButtonGroupSize {
Sm,
#[default]
Md,
}
impl FloatingButtonGroupSize {
pub const fn item_height(self) -> Pixels {
match self {
Self::Sm => px(28.0),
Self::Md => px(32.0),
}
}
pub const fn tray_pad(self) -> Pixels {
match self {
Self::Sm => px(3.0),
Self::Md => px(3.0),
}
}
pub const fn item_gap(self) -> Pixels {
match self {
Self::Sm => px(2.0),
Self::Md => px(3.0),
}
}
pub const fn item_pad_x(self) -> Pixels {
match self {
Self::Sm => px(8.0),
Self::Md => px(10.0),
}
}
pub fn outer_radius(self) -> Pixels {
match self {
Self::Sm => Radii::CONTROL,
Self::Md => Radii::PANEL,
}
}
pub fn inner_radius(self) -> Pixels {
(self.outer_radius() - self.tray_pad()).max(px(5.0))
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum FloatingButtonGroupOrientation {
#[default]
Horizontal,
Vertical,
}
#[derive(Clone)]
pub struct FloatingButtonGroupAction {
pub id: SharedString,
pub label: SharedString,
pub icon: Option<IconName>,
pub icon_only: Option<bool>,
pub disabled: bool,
pub pressed: Option<bool>,
pub shortcut: Option<SharedString>,
pub reserve_labels: Vec<SharedString>,
pub on_select: Option<SelectHandler>,
}
impl FloatingButtonGroupAction {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
icon: None,
icon_only: None,
disabled: false,
pressed: None,
shortcut: None,
reserve_labels: Vec::new(),
on_select: None,
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn icon_only(mut self, icon_only: bool) -> Self {
self.icon_only = Some(icon_only);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn pressed(mut self, pressed: bool) -> Self {
self.pressed = Some(pressed);
self
}
pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
pub fn reserve_labels<I, S>(mut self, labels: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.reserve_labels = labels.into_iter().map(Into::into).collect();
self
}
pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_select = Some(Rc::new(handler));
self
}
}
#[derive(Clone)]
pub enum FloatingButtonGroupItem {
Action(FloatingButtonGroupAction),
Separator(Option<SharedString>),
}
impl FloatingButtonGroupItem {
pub fn action(action: FloatingButtonGroupAction) -> Self {
Self::Action(action)
}
pub fn separator() -> Self {
Self::Separator(None)
}
pub fn separator_with_id(id: impl Into<SharedString>) -> Self {
Self::Separator(Some(id.into()))
}
}
impl From<FloatingButtonGroupAction> for FloatingButtonGroupItem {
fn from(action: FloatingButtonGroupAction) -> Self {
Self::Action(action)
}
}
pub fn fbg_highlight_target_scale(has_active: bool, pressing: bool) -> f32 {
if has_active && pressing {
FBG_PRESS_SCALE
} else {
1.0
}
}
pub fn fbg_reserved_content_width(
label: &str,
reserve_labels: &[SharedString],
has_icon: bool,
icon_only: bool,
size: FloatingButtonGroupSize,
) -> f32 {
if icon_only {
return 16.0;
}
let char_adv = match size {
FloatingButtonGroupSize::Sm => 6.8,
FloatingButtonGroupSize::Md => 7.6,
};
let max_chars = std::iter::once(label)
.chain(reserve_labels.iter().map(|s| s.as_ref()))
.map(|s| {
s.chars()
.map(|c| if c.is_ascii() { 1.0_f32 } else { 1.75_f32 })
.sum::<f32>()
})
.fold(0.0_f32, f32::max);
let icon_part = if has_icon { 16.0 + 6.0 } else { 0.0 };
(max_chars * char_adv + icon_part).ceil()
}
pub fn scale_bounds_around_center(rect: Bounds<Pixels>, factor: f32) -> Bounds<Pixels> {
let w = f32::from(rect.size.width);
let h = f32::from(rect.size.height);
let nw = (w * factor).max(0.0);
let nh = (h * factor).max(0.0);
let dx = (w - nw) * 0.5;
let dy = (h - nh) * 0.5;
bounds(
point(rect.origin.x + px(dx), rect.origin.y + px(dy)),
size(px(nw), px(nh)),
)
}
#[derive(Clone, Default)]
struct FloatingButtonGroupInternal {
hovered_id: Option<SharedString>,
pressed_id: Option<SharedString>,
item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
tray_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}
#[derive(IntoElement)]
pub struct FloatingButtonGroup {
id: ElementId,
label: SharedString,
items: Vec<FloatingButtonGroupItem>,
variant: FloatingButtonGroupVariant,
size: FloatingButtonGroupSize,
orientation: FloatingButtonGroupOrientation,
icon_only: bool,
tooltip_side: Option<TooltipSide>,
on_action: Option<ActionHandler>,
}
impl FloatingButtonGroup {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
items: Vec::new(),
variant: FloatingButtonGroupVariant::Muted,
size: FloatingButtonGroupSize::Md,
orientation: FloatingButtonGroupOrientation::Horizontal,
icon_only: false,
tooltip_side: None,
on_action: None,
}
}
pub fn item(mut self, item: impl Into<FloatingButtonGroupItem>) -> Self {
self.items.push(item.into());
self
}
pub fn items(mut self, items: impl IntoIterator<Item = FloatingButtonGroupItem>) -> Self {
self.items.extend(items);
self
}
pub fn variant(mut self, variant: FloatingButtonGroupVariant) -> Self {
self.variant = variant;
self
}
pub fn size(mut self, size: FloatingButtonGroupSize) -> Self {
self.size = size;
self
}
pub fn orientation(mut self, orientation: FloatingButtonGroupOrientation) -> Self {
self.orientation = orientation;
self
}
pub fn icon_only(mut self, icon_only: bool) -> Self {
self.icon_only = icon_only;
self
}
pub fn tooltip_side(mut self, side: TooltipSide) -> Self {
self.tooltip_side = Some(side);
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 FloatingButtonGroup {
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 dark = theme.mode == ThemeMode::Dark;
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-fbg-state".into());
let internal =
window.use_keyed_state(state_id, cx, |_, _| FloatingButtonGroupInternal::default());
let snap = internal.read(cx).clone();
let vertical = self.orientation == FloatingButtonGroupOrientation::Vertical;
let resolved_tip_side = self.tooltip_side.unwrap_or(if vertical {
TooltipSide::Right
} else {
TooltipSide::Top
});
let enabled_action = |id: &SharedString| -> bool {
self.items.iter().any(|it| {
matches!(
it,
FloatingButtonGroupItem::Action(a) if &a.id == id && !a.disabled
)
})
};
let active_id: Option<SharedString> = snap
.hovered_id
.as_ref()
.filter(|id| enabled_action(id))
.cloned()
.or_else(|| {
snap.pressed_id
.as_ref()
.filter(|id| enabled_action(id))
.cloned()
});
let pressing = active_id.is_some() && active_id == snap.pressed_id;
let highlight_opacity = arc_transition(
(self.id.clone(), "fbg-hi-op"),
if active_id.is_some() { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if active_id.is_some() {
motion.duration.fast
} else {
motion.duration.standard
},
motion.ease.standard,
window,
cx,
);
let target_scale = fbg_highlight_target_scale(active_id.is_some(), pressing);
let highlight_scale = if reduced {
target_scale
} else {
arc_spring(
(self.id.clone(), "fbg-hi-scale"),
if active_id.is_some() {
target_scale
} else {
FBG_APPEAR_SCALE
},
motion.spring.snappy,
window,
cx,
)
};
let hi_alpha = if pressing {
if dark { 0.15 } else { 0.12 }
} else if dark {
0.09
} else {
0.07
};
let hi_color = with_alpha(colors.foreground, hi_alpha * highlight_opacity);
let on_tint = with_alpha(colors.control_on, if dark { 0.16 } else { 0.12 });
let rule_color = with_alpha(colors.foreground, 0.12);
let (tray_bg, tray_border) = match self.variant {
FloatingButtonGroupVariant::Muted => (
with_alpha(colors.foreground, if dark { 0.06 } else { 0.045 }),
with_alpha(colors.foreground, if dark { 0.05 } else { 0.03 }),
),
FloatingButtonGroupVariant::Floating => (colors.surface_raised, colors.border),
};
let item_h = self.size.item_height();
let tray_pad = self.size.tray_pad();
let item_gap = self.size.item_gap();
let item_pad_x = self.size.item_pad_x();
let outer_radius = self.size.outer_radius();
let inner_radius = self.size.inner_radius();
let scope = layout_scope_key(&self.id);
let item_bounds_ref = snap.item_bounds.clone();
let tray_bounds_ref = snap.tray_bounds.clone();
let active_for_hi = active_id.clone();
let morph_spring = motion.spring.morph;
let highlight_canvas = canvas(
move |rect, _, _| {
*tray_bounds_ref.borrow_mut() = Some(rect);
},
move |tray_rect, _, window, cx| {
if let Some(key) = &active_for_hi
&& highlight_opacity > 0.01
&& let Some(item_rect) = item_bounds_ref.borrow().get(key).copied()
{
let local_rect = bounds(
point(
item_rect.origin.x - tray_rect.origin.x,
item_rect.origin.y - tray_rect.origin.y,
),
item_rect.size,
);
let target = LayoutSnapshot::uniform_radius(local_rect, inner_radius);
let flip = sample_shared_layout(
scope.clone(),
"fbg-highlight",
target,
if reduced { None } else { Some(morph_spring) },
window,
cx,
);
let world_rect =
bounds(tray_rect.origin + flip.bounds.origin, flip.bounds.size);
let scaled_rect = scale_bounds_around_center(world_rect, highlight_scale);
window.paint_quad(quad(
scaled_rect,
flip.corner_radii,
hi_color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
},
)
.absolute()
.inset_0();
let mut children = Vec::with_capacity(self.items.len());
let mut active_tip_overlay = None;
for (pos, item) in self.items.iter().enumerate() {
match item {
FloatingButtonGroupItem::Separator(sep_id) => {
let sep_key = sep_id
.clone()
.unwrap_or_else(|| SharedString::from(format!("sep-{pos}")));
let sep_len = item_h * 0.5;
let sep = if vertical {
div()
.id(ElementId::NamedChild(self.id.clone().into(), sep_key))
.flex_none()
.self_center()
.w(sep_len)
.h(px(1.0))
.my(px(2.0))
.rounded(px(1.0))
.bg(rule_color)
} else {
div()
.id(ElementId::NamedChild(self.id.clone().into(), sep_key))
.flex_none()
.self_center()
.w(px(1.0))
.h(sep_len)
.mx(px(2.0))
.rounded(px(1.0))
.bg(rule_color)
};
children.push(sep.into_any_element());
}
FloatingButtonGroupItem::Action(action) => {
let id = action.id.clone();
let is_icon_only =
action.icon.is_some() && action.icon_only.unwrap_or(self.icon_only);
let is_active = active_id.as_ref() == Some(&id);
let is_pressed_mode = action.pressed.unwrap_or(false);
let is_disabled = action.disabled;
let reserved_w = fbg_reserved_content_width(
action.label.as_ref(),
&action.reserve_labels,
action.icon.is_some(),
is_icon_only,
self.size,
);
let item_bounds = snap.item_bounds.clone();
let id_measure = id.clone();
let probe = canvas(
move |rect, _, _| {
item_bounds.borrow_mut().insert(id_measure.clone(), rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let fg_color = if is_disabled {
colors.text_muted
} else if is_active || is_pressed_mode {
colors.foreground
} else {
colors.text_secondary
};
let btn_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("item-{}", action.id)),
);
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let id_hover = id.clone();
let id_down = id.clone();
let id_click = id.clone();
let on_select = action.on_select.clone();
let on_action = self.on_action.clone();
let pad_left = if action.icon.is_some() && !is_icon_only {
(item_pad_x - px(2.0)).max(px(6.0))
} else {
item_pad_x
};
let btn = BaseButton::new(btn_id)
.disabled(is_disabled)
.accessibility_label(action.label.clone())
.on_click(move |_, window, cx| {
if is_disabled {
return;
}
if let Some(cb) = &on_select {
cb(&(), window, cx);
}
if let Some(cb) = &on_action {
cb(&id_click, window, cx);
}
window.refresh();
})
.relative()
.flex_none()
.flex()
.flex_row()
.items_center()
.when(vertical && !is_icon_only, |this| {
this.w_full().justify_start()
})
.when(!vertical || is_icon_only, |this| this.justify_center())
.when(vertical && is_icon_only, |this| this.self_center())
.h(item_h)
.when(is_icon_only, |this| this.w(item_h))
.when(!is_icon_only, |this| {
this.min_w(item_h).pl(pad_left).pr(item_pad_x)
})
.rounded(inner_radius)
.when(is_pressed_mode, |this| this.bg(on_tint))
.text_size(match self.size {
FloatingButtonGroupSize::Sm => Typography::TEXT_XS,
FloatingButtonGroupSize::Md => Typography::TEXT_SM,
})
.text_color(fg_color)
.when(is_disabled, |this| this.opacity(0.5))
.when(!is_disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
if is_disabled {
return;
}
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.hovered_id = Some(id_down.clone());
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();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed_id = None);
window.refresh();
})
.child(probe)
.child(
div()
.flex()
.flex_row()
.items_center()
.when(!vertical || is_icon_only, |this| this.justify_center())
.when(vertical && !is_icon_only, |this| this.justify_start())
.when(!is_icon_only, |this| this.min_w(px(reserved_w)))
.gap(px(6.0))
.when_some(action.icon, |this, icon| this.child(icon))
.when(!is_icon_only, |this| this.child(action.label.clone())),
);
if is_active && (is_icon_only || action.shortcut.is_some()) {
let tip_label = action.label.clone();
let tip_shortcut = action.shortcut.clone();
let kbd_fg = with_alpha(colors.background, 0.58);
let tip_border = with_alpha(colors.background, 0.14);
let tip_bubble = div()
.px(Spacing::S3)
.py(Spacing::S2)
.rounded(Radii::CONTROL)
.border_1()
.border_color(tip_border)
.bg(colors.foreground)
.text_color(colors.background)
.text_size(Typography::TEXT_XS)
.shadow(Shadows::raised(theme.mode))
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.whitespace_nowrap()
.child(tip_label)
.when_some(tip_shortcut, |this, kbd| {
this.child(div().text_color(kbd_fg).child(kbd))
});
let positioned_tip = match resolved_tip_side {
TooltipSide::Top => div()
.absolute()
.bottom(item_h + tray_pad * 2.0 + px(8.0))
.left_0()
.child(tip_bubble),
TooltipSide::Bottom => div()
.absolute()
.top(item_h + tray_pad * 2.0 + px(8.0))
.left_0()
.child(tip_bubble),
TooltipSide::Right => div()
.absolute()
.left(item_h + tray_pad * 2.0 + px(8.0))
.top(px(pos as f32 * f32::from(item_h + item_gap)))
.child(tip_bubble),
TooltipSide::Left => div()
.absolute()
.right(item_h + tray_pad * 2.0 + px(8.0))
.top(px(pos as f32 * f32::from(item_h + item_gap)))
.child(tip_bubble),
};
active_tip_overlay = Some(deferred(positioned_tip).with_priority(2));
}
children.push(btn.into_any_element());
}
}
}
div()
.id(self.id)
.test_support()
.role(Role::Toolbar)
.aria_label(self.label)
.relative()
.self_start()
.flex_none()
.flex()
.when(vertical, |this| this.flex_col().items_stretch())
.when(!vertical, |this| this.flex_row().items_center())
.gap(item_gap)
.p(tray_pad)
.rounded(outer_radius)
.border_1()
.border_color(tray_border)
.bg(tray_bg)
.when(
self.variant == FloatingButtonGroupVariant::Floating,
|this| this.shadow(Shadows::floating(theme.mode)),
)
.child(highlight_canvas)
.children(children)
.when_some(active_tip_overlay, |this, tip| this.child(tip))
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
#[test]
fn highlight_scale_and_reserved_width_behave_as_expected() {
assert!((fbg_highlight_target_scale(true, false) - 1.0).abs() < 1e-5);
assert!((fbg_highlight_target_scale(true, true) - FBG_PRESS_SCALE).abs() < 1e-5);
assert!((fbg_highlight_target_scale(false, true) - 1.0).abs() < 1e-5);
let w_short =
fbg_reserved_content_width("Share", &[], true, false, FloatingButtonGroupSize::Md);
let w_reserved = fbg_reserved_content_width(
"Share",
&[SharedString::from("Copied link")],
true,
false,
FloatingButtonGroupSize::Md,
);
assert!(w_reserved > w_short);
let w_same_after_swap = fbg_reserved_content_width(
"Copied link",
&[SharedString::from("Share")],
true,
false,
FloatingButtonGroupSize::Md,
);
assert!((w_reserved - w_same_after_swap).abs() < 1e-4);
}
struct Host {
count: Rc<Cell<usize>>,
last_action: Rc<RefCell<Option<SharedString>>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let count = self.count.clone();
let last_action = self.last_action.clone();
div().p(Spacing::S6).child(
FloatingButtonGroup::new("board-toolbar", "Board actions")
.variant(FloatingButtonGroupVariant::Floating)
.items([
FloatingButtonGroupItem::action(
FloatingButtonGroupAction::new("comment", "Comment").on_select(
cx.listener(move |_, _, _, _| {
count.set(count.get() + 1);
}),
),
),
FloatingButtonGroupItem::separator(),
FloatingButtonGroupItem::action(
FloatingButtonGroupAction::new("share", "Share")
.reserve_labels(["Copied"])
.shortcut("⌘L"),
),
])
.on_action(cx.listener(move |_, id: &SharedString, _, _| {
*last_action.borrow_mut() = Some(id.clone());
})),
)
}
}
#[gpui_kit::test]
fn floating_button_group_fires_item_and_group_callbacks(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let count = Rc::new(Cell::new(0usize));
let last_action = Rc::new(RefCell::new(None));
let (_view, cx) = cx.add_window_view(|_, _| Host {
count: count.clone(),
last_action: last_action.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let comment = window.find_by_label("Comment");
assert_eq!(comment.role(), Some(Role::Button));
let pos = comment.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(count.get(), 1);
assert_eq!(last_action.borrow().as_deref(), Some("comment"));
});
}
}