use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
use arc_motion::{
LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion, layout::layout_scope_key,
sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, BorderStyle, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, KeyDownEvent,
MouseButton, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
assets::IconName,
base::{Button as BaseButton, StyledExt as _},
bounds, canvas,
component::Icon,
div,
prelude::*,
px, quad,
};
type ValuesChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToggleGroupType {
#[default]
Single,
Multiple,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToggleGroupSize {
Sm,
#[default]
Md,
}
#[derive(Clone)]
pub struct ToggleGroupItem {
pub value: SharedString,
pub label: SharedString,
pub text: Option<SharedString>,
pub icon: Option<IconName>,
pub disabled: bool,
}
impl ToggleGroupItem {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
let label = label.into();
Self {
value: value.into(),
text: Some(label.clone()),
label,
icon: None,
disabled: false,
}
}
pub fn icon_only(
value: impl Into<SharedString>,
label: impl Into<SharedString>,
icon: IconName,
) -> Self {
Self {
value: value.into(),
label: label.into(),
text: None,
icon: Some(icon),
disabled: false,
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
#[derive(Clone)]
struct ToggleGroupInternal {
uncontrolled: Vec<SharedString>,
pressed_item: Option<SharedString>,
item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
}
#[derive(IntoElement)]
pub struct ToggleGroup {
id: ElementId,
label: SharedString,
kind: ToggleGroupType,
size: ToggleGroupSize,
items: Vec<ToggleGroupItem>,
values: Option<Vec<SharedString>>,
default_values: Vec<SharedString>,
disabled: bool,
on_values_change: Option<ValuesChangeHandler>,
}
impl ToggleGroup {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
kind: ToggleGroupType::Single,
size: ToggleGroupSize::Md,
items: Vec::new(),
values: None,
default_values: Vec::new(),
disabled: false,
on_values_change: None,
}
}
pub fn kind(mut self, kind: ToggleGroupType) -> Self {
self.kind = kind;
self
}
pub fn size(mut self, size: ToggleGroupSize) -> Self {
self.size = size;
self
}
pub fn item(mut self, item: ToggleGroupItem) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = ToggleGroupItem>) -> Self {
self.items.extend(items);
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.values = Some(vec![value.into()]);
self
}
pub fn values(mut self, values: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.values = Some(values.into_iter().map(Into::into).collect());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_values = vec![value.into()];
self
}
pub fn default_values(
mut self,
values: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_values = values.into_iter().map(Into::into).collect();
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_values_change(
mut self,
handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
) -> Self {
self.on_values_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for ToggleGroup {
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 is_dark = theme.mode.is_dark();
let is_controlled = self.values.is_some();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-toggle-group-state".into());
let default_vals = self.default_values.clone();
let internal = window.use_keyed_state(state_id, cx, |_, _| ToggleGroupInternal {
uncontrolled: default_vals,
pressed_item: None,
item_bounds: Rc::new(RefCell::new(HashMap::new())),
});
let snap = internal.read(cx).clone();
let active_values: Vec<SharedString> = self
.values
.clone()
.unwrap_or_else(|| snap.uncontrolled.clone());
let fill_color = oklab_mix(
colors.control_on,
colors.surface,
if is_dark { 0.14 } else { 0.11 },
);
let item_h = match self.size {
ToggleGroupSize::Sm => px(28.0),
ToggleGroupSize::Md => px(36.0),
};
let item_pad = match self.size {
ToggleGroupSize::Sm => px(8.0),
ToggleGroupSize::Md => px(10.0),
};
let icon_sz = match self.size {
ToggleGroupSize::Sm => px(14.0),
ToggleGroupSize::Md => px(16.0),
};
let text_sz = match self.size {
ToggleGroupSize::Sm => Typography::TEXT_XS,
ToggleGroupSize::Md => Typography::TEXT_SM,
};
let item_radius = px(15.0);
let is_single = self.kind == ToggleGroupType::Single;
let scope = layout_scope_key(&self.id);
let bounds_for_fill = snap.item_bounds.clone();
let active_first = active_values.first().cloned();
let morph_spec = motion.spring.morph;
let single_fill_canvas = if is_single {
Some(
canvas(
|_, _, _| {},
move |group_rect, _, window, cx| {
let Some(val) = active_first.as_ref() else {
return;
};
let Some(btn_rect) = bounds_for_fill.borrow().get(val).copied() else {
window.request_animation_frame();
return;
};
let local = bounds(btn_rect.origin - group_rect.origin, btn_rect.size);
let target = LayoutSnapshot::uniform_radius(local, item_radius);
let flip = sample_shared_layout(
scope.clone(),
"fill",
target,
Some(morph_spec),
window,
cx,
);
let paint =
bounds(group_rect.origin + flip.bounds.origin, flip.bounds.size);
window.paint_quad(quad(
paint,
flip.corner_radii,
fill_color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0(),
)
} else {
None
};
let on_flags: Vec<bool> = self
.items
.iter()
.map(|it| active_values.contains(&it.value))
.collect();
let enabled_values: Vec<SharedString> = self
.items
.iter()
.filter(|it| !self.disabled && !it.disabled)
.map(|it| it.value.clone())
.collect();
let mut row = div()
.relative()
.p(px(3.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.when(self.disabled, |this| this.opacity(0.52))
.flex()
.flex_row()
.items_center()
.gap(px(2.0))
.when_some(single_fill_canvas, |this, c| this.child(c));
let count = self.items.len();
for (idx, item) in self.items.into_iter().enumerate() {
let val = item.value.clone();
let on = on_flags[idx];
let off = self.disabled || item.disabled;
let prev_on = !is_single && idx > 0 && on_flags[idx - 1];
let next_on = !is_single && idx + 1 < count && on_flags[idx + 1];
let multi_op = if !is_single {
arc_transition(
(self.id.clone(), format!("tg-op-{val}")),
if on { 1.0 } else { 0.0 },
if reduced {
Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
)
} else {
0.0
};
let is_pressed = !off && snap.pressed_item.as_ref() == Some(&val);
let content_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), format!("tg-press-{val}")),
if is_pressed { 0.92 } else { 1.0 },
motion.spring.snappy,
window,
cx,
)
};
let bounds_measure = snap.item_bounds.clone();
let val_measure = val.clone();
let probe = canvas(
move |rect, _, _| {
bounds_measure
.borrow_mut()
.insert(val_measure.clone(), rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let multi_bg = if !is_single && multi_op > 0.01 {
let bg = Hsla {
a: fill_color.a * multi_op,
..fill_color
};
let left_r = if on && prev_on { px(0.0) } else { item_radius };
let right_r = if on && next_on { px(0.0) } else { item_radius };
let extend_right = if on && next_on { px(2.0) } else { px(0.0) };
Some(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let paint_rect = bounds(
rect.origin,
gpui_kit::size(rect.size.width + extend_right, rect.size.height),
);
window.paint_quad(quad(
paint_rect,
Corners {
top_left: left_r,
bottom_left: left_r,
top_right: right_r,
bottom_right: right_r,
},
bg,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0(),
)
} else {
None
};
let int_click = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_key = internal.clone();
let on_change = self.on_values_change.clone();
let on_change_key = self.on_values_change.clone();
let current_active = active_values.clone();
let val_click = val.clone();
let val_down = val.clone();
let val_key = val.clone();
let enabled_for_key = enabled_values.clone();
let hover_bg = colors.surface_muted;
let hover_fg = colors.foreground;
let btn = BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tg-{val}")),
))
.disabled(off)
.accessibility_label(item.label)
.on_click(move |_, window, cx| {
if off {
return;
}
let next = if is_single {
if current_active.first() == Some(&val_click) {
return;
}
vec![val_click.clone()]
} else if current_active.contains(&val_click) {
current_active
.iter()
.filter(|v| *v != &val_click)
.cloned()
.collect()
} else {
let mut v = current_active.clone();
v.push(val_click.clone());
v
};
if !is_controlled {
int_click.update(cx, |s, _| s.uncontrolled = next.clone());
}
if let Some(cb) = &on_change {
cb(&next, window, cx);
}
window.refresh();
})
.relative()
.min_w(item_h)
.h(item_h)
.px(item_pad)
.rounded(item_radius)
.flex()
.items_center()
.justify_center()
.text_size(text_sz)
.font_medium()
.text_color(if on {
colors.foreground
} else {
colors.text_secondary
})
.when(off, |this| this.opacity(0.45))
.when(!off && !on, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(hover_bg).text_color(hover_fg))
})
.when(!off && on, |this| this.cursor_pointer())
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !off {
int_down.update(cx, |s, _| s.pressed_item = Some(val_down.clone()));
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed_item = None);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed_item = None);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if !is_single || enabled_for_key.len() < 2 {
return;
}
let cur = enabled_for_key
.iter()
.position(|v| v == &val_key)
.unwrap_or(0);
let next_idx = match event.keystroke.key.as_str() {
"right" | "down" => Some((cur + 1) % enabled_for_key.len()),
"left" | "up" => {
Some((cur + enabled_for_key.len() - 1) % enabled_for_key.len())
}
"home" => Some(0),
"end" => Some(enabled_for_key.len() - 1),
_ => None,
};
if let Some(ni) = next_idx {
let next = vec![enabled_for_key[ni].clone()];
if !is_controlled {
int_key.update(cx, |s, _| s.uncontrolled = next.clone());
}
if let Some(cb) = &on_change_key {
cb(&next, window, cx);
}
window.refresh();
}
})
.child(probe)
.when_some(multi_bg, |this, bg| this.child(bg))
.child(
div()
.flex()
.items_center()
.gap(px(6.0))
.when((content_scale - 1.0).abs() > 0.005, |this| {
this.mt(px((1.0 - content_scale) * 10.0))
})
.when_some(item.icon, |this, ic| {
this.child(Icon::new(ic).text_size(icon_sz))
})
.when_some(item.text, |this, txt| this.child(txt)),
);
row = row.child(btn);
}
div()
.id(self.id)
.flex()
.flex_col()
.items_start()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(self.label),
)
.child(row)
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct ToggleHost {
align: SharedString,
styles: Vec<SharedString>,
}
impl Render for ToggleHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.w(px(460.0))
.p(Spacing::S4)
.flex()
.flex_col()
.gap(Spacing::S4)
.child(
ToggleGroup::new("align-tg", "Alignment")
.kind(ToggleGroupType::Single)
.value(self.align.clone())
.items([
ToggleGroupItem::new("left", "Left"),
ToggleGroupItem::new("center", "Center"),
ToggleGroupItem::new("right", "Right"),
])
.on_values_change(cx.listener(|this, vals: &[SharedString], _, cx| {
if let Some(first) = vals.first() {
this.align = first.clone();
cx.notify();
}
})),
)
.child(
ToggleGroup::new("fmt-tg", "Format")
.kind(ToggleGroupType::Multiple)
.values(self.styles.clone())
.items([
ToggleGroupItem::new("bold", "Bold"),
ToggleGroupItem::new("italic", "Italic"),
ToggleGroupItem::new("underline", "Underline"),
])
.on_values_change(cx.listener(|this, vals: &[SharedString], _, cx| {
this.styles = vals.to_vec();
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn toggle_group_handles_single_and_multiple_modes(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|_, _| ToggleHost {
align: "left".into(),
styles: vec!["bold".into()],
});
cx.update(|window, cx| {
window.render_frame(cx);
let center = window.find_by_label("Center");
assert_eq!(center.role(), Some(Role::Button));
let pos = center.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
let italic = window.find_by_label("Italic");
let ipos = italic.bounds().center();
window.pointer_down(ipos, MouseButton::Left, cx);
window.pointer_up(ipos, MouseButton::Left, cx);
});
assert_eq!(view.read_with(cx, |v, _| v.align.clone()), "center");
assert_eq!(
view.read_with(cx, |v, _| v.styles.clone()),
vec![SharedString::from("bold"), SharedString::from("italic")]
);
}
}