use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{
BlurFallback, CubicBezier, PathPoint, PolylinePath, arc_spring, arc_transition,
is_reduced_motion, motion_now,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, ParentElement,
Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
base::{Button as BaseButton, StyledExt as _},
canvas, div,
prelude::*,
px,
};
type ChipGroupChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
pub const CHIP_CHECK_SLOT_PX: f32 = 18.0;
pub const CHIP_REVEAL_STAGGER_SECS: f64 = 0.035;
pub const CHIP_REVEAL_MAX_DELAY_SECS: f64 = 0.30;
pub fn chip_check_metrics(grown: f32, reduced: bool) -> (f32, f32, f32, f32) {
let g = grown.clamp(0.0, 1.15);
let slot_w = (g * CHIP_CHECK_SLOT_PX).clamp(0.0, CHIP_CHECK_SLOT_PX);
let scale = g.min(1.1);
let raw_op = (g * 1.4).clamp(0.0, 1.0);
let blur = BlurFallback::evaluate(px(((1.0 - g).max(0.0)) * 2.0), reduced);
let opacity = (raw_op * blur.opacity_multiplier).clamp(0.0, 1.0);
let path_len = g.clamp(0.0, 1.0);
(slot_w, scale, opacity, path_len)
}
pub fn chip_reveal_progress(elapsed: f64, index: usize, max_visible: usize, reduced: bool) -> f32 {
if reduced || index < max_visible {
return 1.0;
}
let delay =
((index - max_visible) as f64 * CHIP_REVEAL_STAGGER_SECS).min(CHIP_REVEAL_MAX_DELAY_SECS);
if elapsed <= delay {
return 0.0;
}
let t = ((elapsed - delay) / 0.16).clamp(0.0, 1.0) as f32;
CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t)
}
pub fn chip_more_swap_sample(elapsed: f64, reduced: bool) -> (f32, f32, f32, f32) {
if reduced {
let t = (elapsed / 0.15).clamp(0.0, 1.0) as f32;
return (t, 0.0, 1.0 - t, 0.0);
}
let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
let blur_in = BlurFallback::evaluate(px(4.0 * (1.0 - e_in)), false);
let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
let enter_y = 4.2 * (1.0 - e_in);
let t_out = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
let exit_y = -4.2 * e_out;
(enter_op, enter_y, exit_op, exit_y)
}
pub fn toggle_chip_group_value(
options: &[ChipOption],
selected: &[SharedString],
target: &SharedString,
multiple: bool,
) -> Vec<SharedString> {
let is_on = selected.iter().any(|v| v == target);
if !multiple {
return if is_on {
Vec::new()
} else {
vec![target.clone()]
};
}
options
.iter()
.filter(|opt| {
if &opt.value == target {
!is_on
} else {
selected.iter().any(|v| v == &opt.value)
}
})
.map(|opt| opt.value.clone())
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChipOption {
pub value: SharedString,
pub label: SharedString,
}
impl ChipOption {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
}
}
}
#[derive(Clone)]
struct ChipGroupInternal {
uncontrolled_value: Vec<SharedString>,
expanded: bool,
expanded_changed_at_secs: f64,
previous_more_text: Option<SharedString>,
pinned: Vec<SharedString>,
active_focus_key: Option<SharedString>,
hovered_chip: Option<SharedString>,
pressed_chip: Option<SharedString>,
measured_frame_h: Rc<RefCell<Option<f32>>>,
focus_handle: FocusHandle,
}
impl ChipGroupInternal {
fn new(default_value: Vec<SharedString>, now: f64, focus_handle: FocusHandle) -> Self {
Self {
pinned: default_value.clone(),
uncontrolled_value: default_value,
expanded: false,
expanded_changed_at_secs: now - 10.0,
previous_more_text: None,
active_focus_key: None,
hovered_chip: None,
pressed_chip: None,
measured_frame_h: Rc::new(RefCell::new(None)),
focus_handle,
}
}
}
fn paint_chip_check(
origin_x: Pixels,
origin_y: Pixels,
scale: f32,
path_length: f32,
opacity: f32,
color: Hsla,
window: &mut Window,
) {
let len = path_length.clamp(0.0, 1.0);
let alpha = opacity.clamp(0.0, 1.0);
if len <= 0.01 || alpha <= 0.01 || scale <= 0.05 {
return;
}
let s = 14.0 / 24.0;
let cy = 7.0_f32;
let transform_pt = |vx: f32, vy: f32| -> PathPoint {
let bx = vx * s;
let by = vy * s;
PathPoint::new(bx * scale, cy + (by - cy) * scale)
};
let poly = PolylinePath::new(vec![
transform_pt(4.0, 12.5),
transform_pt(9.5, 18.0),
transform_pt(20.0, 6.5),
]);
let sliced = poly.slice(0.0, len);
let stroke_color = Hsla {
a: color.a * alpha,
..color
};
if let Some(b) = sliced.to_stroke_builder(origin_x, origin_y, px(2.1))
&& let Ok(path) = b.build()
{
window.paint_path(path, stroke_color);
}
}
#[derive(IntoElement)]
pub struct ChipGroup {
id: ElementId,
label: SharedString,
show_label: bool,
options: Vec<ChipOption>,
value: Option<Vec<SharedString>>,
default_value: Vec<SharedString>,
multiple: bool,
max_visible: Option<usize>,
disabled: bool,
width: Option<Pixels>,
on_value_change: Option<ChipGroupChangeHandler>,
}
impl ChipGroup {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
show_label: false,
options: Vec::new(),
value: None,
default_value: Vec::new(),
multiple: true,
max_visible: None,
disabled: false,
width: None,
on_value_change: None,
}
}
pub fn show_label(mut self, show: bool) -> Self {
self.show_label = show;
self
}
pub fn option(mut self, option: ChipOption) -> Self {
self.options.push(option);
self
}
pub fn options(mut self, options: impl IntoIterator<Item = ChipOption>) -> Self {
self.options.extend(options);
self
}
pub fn value<I, S>(mut self, value: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.value = Some(value.into_iter().map(Into::into).collect());
self
}
pub fn default_value<I, S>(mut self, value: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.default_value = value.into_iter().map(Into::into).collect();
self
}
pub fn multiple(mut self, multiple: bool) -> Self {
self.multiple = multiple;
self
}
pub fn max_visible(mut self, max_visible: usize) -> Self {
self.max_visible = Some(max_visible.max(1));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for ChipGroup {
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 initial_vals = self
.value
.clone()
.unwrap_or_else(|| self.default_value.clone());
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-chip-group-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
ChipGroupInternal::new(initial_vals.clone(), now, cx.focus_handle())
});
let selected: Vec<SharedString> = self
.value
.clone()
.unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
let snap = internal.read(cx).clone();
let max_vis = self.max_visible.unwrap_or(usize::MAX);
let foldable = self.options.len() > max_vis;
let visible_options: Vec<(usize, ChipOption)> = if !foldable || snap.expanded {
self.options.iter().cloned().enumerate().collect()
} else {
self.options
.iter()
.cloned()
.enumerate()
.filter(|(idx, opt)| {
*idx < max_vis
|| snap.pinned.contains(&opt.value)
|| selected.contains(&opt.value)
})
.collect()
};
let hidden_count = self.options.len().saturating_sub(visible_options.len());
let show_more = foldable && (snap.expanded || hidden_count > 0);
let measured_h = snap.measured_frame_h.borrow().map(|h| h.max(36.0));
let frame_h = arc_motion::arc_measured_spring(
(self.id.clone(), "frame-h"),
measured_h,
36.0,
motion.spring.smooth,
window,
cx,
)
.max(36.0);
let frame_h_ref = snap.measured_frame_h.clone();
let frame_probe = canvas(
move |rect, window, _| {
let h = f32::from(rect.size.height).max(36.0);
let prev = *frame_h_ref.borrow();
*frame_h_ref.borrow_mut() = Some(h);
if prev.is_none_or(|prev| (prev - h).abs() > 0.5) {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let expand_elapsed = (now - snap.expanded_changed_at_secs).max(0.0);
let disabled = self.disabled;
let multiple = self.multiple;
let mut chip_els = Vec::with_capacity(visible_options.len() + 1);
for (orig_idx, option) in &visible_options {
let is_selected = selected.contains(&option.value);
let is_hovered = snap.hovered_chip.as_ref() == Some(&option.value) && !disabled;
let is_pressed = snap.pressed_chip.as_ref() == Some(&option.value) && !disabled;
let is_focused = snap.active_focus_key.as_ref() == Some(&option.value);
let grown = if reduced {
if is_selected { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), format!("grown-{}", option.value)),
if is_selected { 1.0 } else { 0.0 },
motion.spring.morph,
window,
cx,
)
};
let (slot_w, check_scale, check_op, check_path_len) =
chip_check_metrics(grown, reduced);
let reveal_p = if snap.expanded && foldable && *orig_idx >= max_vis {
let rp = chip_reveal_progress(expand_elapsed, *orig_idx, max_vis, reduced);
if rp < 0.999 {
window.request_animation_frame();
}
rp
} else {
1.0
};
let hover_p = arc_transition(
(self.id.clone(), format!("hover-{}", option.value)),
if is_hovered || is_focused { 1.0 } else { 0.0 },
if reduced {
Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let sel_p = grown.clamp(0.0, 1.0);
let resting_unsel_bg = colors.surface;
let resting_sel_bg = oklab_mix(colors.accent, colors.surface, 0.11);
let hover_sel_bg = oklab_mix(colors.accent, colors.surface, 0.16);
let sel_bg = oklab_mix(hover_sel_bg, resting_sel_bg, hover_p);
let chip_bg = oklab_mix(sel_bg, resting_unsel_bg, sel_p);
let resting_unsel_border = oklab_mix(colors.border_strong, colors.border, hover_p);
let resting_sel_border = oklab_mix(colors.accent, colors.border, 0.42);
let hover_sel_border = oklab_mix(colors.accent, colors.border, 0.60);
let sel_border = oklab_mix(hover_sel_border, resting_sel_border, hover_p);
let chip_border = oklab_mix(sel_border, resting_unsel_border, sel_p);
let text_fg = if is_selected || is_hovered || is_focused {
colors.foreground
} else {
colors.text_secondary
};
let check_color = colors.accent_strong;
let body_h = if is_pressed && !reduced { 35.0 } else { 36.0 };
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_click = internal.clone();
let all_opts = self.options.clone();
let cur_selected = selected.clone();
let on_change = self.on_value_change.clone();
let val_hover = option.value.clone();
let val_down = option.value.clone();
let val_up = option.value.clone();
let val_out = option.value.clone();
let val_click = option.value.clone();
let focus_for_click = snap.focus_handle.clone();
chip_els.push(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("chip-{}", option.value)),
))
.accessibility_label(option.label.clone())
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
window.focus(&focus_for_click, cx);
let next_vals =
toggle_chip_group_value(&all_opts, &cur_selected, &val_click, multiple);
int_click.update(cx, |s, _| {
s.uncontrolled_value = next_vals.clone();
s.active_focus_key = Some(val_click.clone());
s.pressed_chip = None;
});
if let Some(cb) = &on_change {
cb(&next_vals, window, cx);
}
window.refresh();
})
.relative()
.h(px(body_h))
.px(px(14.0))
.flex()
.flex_row()
.items_center()
.rounded(Radii::PILL)
.border_1()
.border_color(chip_border)
.bg(chip_bg)
.opacity(if disabled { 0.5 } else { reveal_p })
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(text_fg)
.when(!disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
if *hovered {
s.hovered_chip = Some(val_hover.clone());
} else if s.hovered_chip.as_ref() == Some(&val_hover) {
s.hovered_chip = None;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !disabled {
int_down.update(cx, |s, _| s.pressed_chip = Some(val_down.clone()));
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
if int_up.read(cx).pressed_chip.as_ref() == Some(&val_up) {
int_up.update(cx, |s, _| s.pressed_chip = None);
window.refresh();
}
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
if int_out.read(cx).pressed_chip.as_ref() == Some(&val_out) {
int_out.update(cx, |s, _| s.pressed_chip = None);
window.refresh();
}
})
.when(check_op > 0.01, |this| {
this.child(
div()
.absolute()
.left(px(12.0))
.top(px((body_h - 14.0) * 0.5))
.size(px(14.0))
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
paint_chip_check(
rect.origin.x,
rect.origin.y,
check_scale,
check_path_len,
check_op,
check_color,
window,
);
},
)
.size_full(),
),
)
})
.child(div().w(px(slot_w)).flex_none())
.child(div().truncate().child(option.label.clone()))
.into_any_element(),
);
}
if show_more {
let more_key: SharedString = "__more__".into();
let more_text: SharedString = if snap.expanded {
"Show less".into()
} else {
SharedString::from(format!("+{hidden_count} more"))
};
let is_more_hovered = snap.hovered_chip.as_ref() == Some(&more_key) && !disabled;
let is_more_focused = snap.active_focus_key.as_ref() == Some(&more_key);
let more_border = if is_more_hovered || is_more_focused {
colors.border_strong
} else {
colors.border
};
let more_fg = if is_more_hovered || is_more_focused {
colors.foreground
} else {
colors.text_muted
};
let (in_op, in_y, out_op, out_y) = if expand_elapsed < 0.25 {
window.request_animation_frame();
chip_more_swap_sample(expand_elapsed, reduced)
} else {
(1.0, 0.0, 0.0, 0.0)
};
let mut more_label_slot = div()
.relative()
.h(px(20.0))
.overflow_hidden()
.flex()
.items_center()
.justify_center()
.child(div().mt(px(in_y)).opacity(in_op).child(more_text.clone()));
if out_op > 0.01
&& let Some(prev_txt) = snap.previous_more_text.clone()
{
more_label_slot = more_label_slot.child(
div()
.absolute()
.top_0()
.left_0()
.mt(px(out_y))
.opacity(out_op)
.child(prev_txt),
);
}
let int_more_hover = internal.clone();
let int_more_click = internal.clone();
let cur_selected_for_pin = selected.clone();
let cur_more_text = more_text.clone();
let focus_for_more = snap.focus_handle.clone();
chip_els.push(
BaseButton::new(ElementId::NamedChild(self.id.clone().into(), "more".into()))
.accessibility_label(more_text)
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
window.focus(&focus_for_more, cx);
let t_now = motion_now(cx);
int_more_click.update(cx, |s, _| {
if s.expanded {
s.pinned = cur_selected_for_pin.clone();
}
s.expanded = !s.expanded;
s.expanded_changed_at_secs = t_now;
s.previous_more_text = Some(cur_more_text.clone());
s.active_focus_key = Some("__more__".into());
});
window.refresh();
})
.h(ControlHeights::SM)
.px(px(14.0))
.flex()
.flex_row()
.items_center()
.rounded(Radii::PILL)
.border_1()
.border_color(more_border)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(more_fg)
.when(!disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_more_hover.update(cx, |s, _| {
if *hovered {
s.hovered_chip = Some("__more__".into());
} else if s.hovered_chip.as_deref() == Some("__more__") {
s.hovered_chip = None;
}
});
window.refresh();
})
.child(more_label_slot)
.into_any_element(),
);
}
let mut focus_keys: Vec<SharedString> = visible_options
.iter()
.map(|(_, o)| o.value.clone())
.collect();
if show_more {
focus_keys.push("__more__".into());
}
let int_key = internal.clone();
let all_opts_key = self.options.clone();
let selected_for_key = selected;
let on_change_key = self.on_value_change.clone();
let focus_handle = snap.focus_handle.clone();
let group_box = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"group".into(),
))
.test_support()
.role(Role::Group)
.aria_label(self.label.clone())
.track_focus(&focus_handle)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if disabled || focus_keys.is_empty() {
return;
}
let cur_key = int_key.read(cx).active_focus_key.clone();
let cur_idx = cur_key
.as_ref()
.and_then(|k| focus_keys.iter().position(|fk| fk == k))
.unwrap_or(0);
let len = focus_keys.len();
match event.keystroke.key.as_str() {
"right" | "arrowright" | "down" | "arrowdown" => {
let next_k = focus_keys[(cur_idx + 1) % len].clone();
int_key.update(cx, |s, _| s.active_focus_key = Some(next_k));
window.refresh();
}
"left" | "arrowleft" | "up" | "arrowup" => {
let prev_k = focus_keys[(cur_idx + len - 1) % len].clone();
int_key.update(cx, |s, _| s.active_focus_key = Some(prev_k));
window.refresh();
}
"home" => {
let first_k = focus_keys[0].clone();
int_key.update(cx, |s, _| s.active_focus_key = Some(first_k));
window.refresh();
}
"end" => {
let last_k = focus_keys[len - 1].clone();
int_key.update(cx, |s, _| s.active_focus_key = Some(last_k));
window.refresh();
}
"enter" | " " | "space" => {
let target_k = focus_keys[cur_idx].clone();
if target_k.as_ref() == "__more__" {
let t_now = motion_now(cx);
int_key.update(cx, |s, _| {
if s.expanded {
s.pinned = selected_for_key.clone();
}
s.expanded = !s.expanded;
s.expanded_changed_at_secs = t_now;
});
} else {
let next_vals = toggle_chip_group_value(
&all_opts_key,
&selected_for_key,
&target_k,
multiple,
);
int_key.update(cx, |s, _| {
s.uncontrolled_value = next_vals.clone();
});
if let Some(cb) = &on_change_key {
cb(&next_vals, window, cx);
}
}
window.refresh();
}
_ => {}
}
})
.w_full()
.h(px(frame_h))
.overflow_hidden()
.child(
div()
.relative()
.w_full()
.flex()
.flex_row()
.flex_wrap()
.gap(Spacing::S2)
.child(frame_probe)
.children(chip_els),
);
div()
.id(self.id)
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.gap(Spacing::S2)
.when(self.show_label, |this| {
this.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label),
)
})
.child(group_box)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chip_check_metrics_coordinate_slot_width_and_path_length() {
let (w0, sc0, op0, len0) = chip_check_metrics(0.0, false);
assert!(w0.abs() < 1e-4);
assert!(sc0.abs() < 1e-4);
assert!(op0.abs() < 1e-4);
assert!(len0.abs() < 1e-4);
let (w1, sc1, op1, len1) = chip_check_metrics(1.0, false);
assert!((w1 - CHIP_CHECK_SLOT_PX).abs() < 1e-4);
assert!((sc1 - 1.0).abs() < 1e-4);
assert!((op1 - 1.0).abs() < 1e-4);
assert!((len1 - 1.0).abs() < 1e-4);
}
#[test]
fn toggle_chip_group_value_handles_multi_and_single_modes() {
let opts = vec![
ChipOption::new("a", "Alpha"),
ChipOption::new("b", "Beta"),
ChipOption::new("c", "Gamma"),
];
let sel: Vec<SharedString> = vec!["c".into()];
let next_multi = toggle_chip_group_value(&opts, &sel, &"a".into(), true);
assert_eq!(
next_multi,
vec![SharedString::from("a"), SharedString::from("c")]
);
let next_single = toggle_chip_group_value(&opts, &sel, &"a".into(), false);
assert_eq!(next_single, vec![SharedString::from("a")]);
let cleared = toggle_chip_group_value(&opts, &next_single, &"a".into(), false);
assert!(cleared.is_empty());
}
#[test]
fn chip_reveal_progress_staggers_items_beyond_max_visible() {
assert!((chip_reveal_progress(0.0, 2, 4, false) - 1.0).abs() < 1e-4);
assert!(chip_reveal_progress(0.02, 5, 4, false) < 1e-4);
assert!((chip_reveal_progress(0.50, 5, 4, false) - 1.0).abs() < 1e-4);
}
}