use std::{cell::RefCell, collections::HashMap, rc::Rc};
use arc_motion::{
LayoutSnapshot, TransformOrigin, arc_spring, arc_transition, is_reduced_motion,
layout::layout_scope_key, sample_shared_layout, scaled_bounds,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Typography, oklab_mix};
use gpui_kit::{
App, Axis, BorderStyle, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, KeyDownEvent,
ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
assets::IconName,
base::{Radio as BaseRadio, RadioGroup as BaseRadioGroup, StyledExt as _},
bounds, canvas,
component::Icon,
div, point,
prelude::*,
px, quad, size,
};
type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum RadioCardsLayout {
#[default]
Grid,
List,
}
#[derive(Clone)]
pub struct RadioCardOption {
pub value: SharedString,
pub label: SharedString,
pub description: Option<SharedString>,
pub meta: Option<SharedString>,
pub icon: Option<IconName>,
pub disabled: bool,
pub disabled_reason: Option<SharedString>,
}
impl RadioCardOption {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
description: None,
meta: None,
icon: None,
disabled: false,
disabled_reason: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
self.meta = Some(meta.into());
self
}
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
}
pub fn disabled_reason(mut self, reason: impl Into<SharedString>) -> Self {
self.disabled_reason = Some(reason.into());
self
}
}
#[derive(Clone)]
struct RadioCardsInternal {
uncontrolled_value: Option<SharedString>,
card_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
}
#[derive(IntoElement)]
pub struct RadioCards {
id: ElementId,
options: Vec<RadioCardOption>,
value: Option<SharedString>,
default_value: Option<SharedString>,
layout: RadioCardsLayout,
min_column_width: f32,
disabled: bool,
on_value_change: Option<ValueChangeHandler>,
}
impl RadioCards {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
options: Vec::new(),
value: None,
default_value: None,
layout: RadioCardsLayout::Grid,
min_column_width: 180.0,
disabled: false,
on_value_change: None,
}
}
pub fn option(mut self, option: RadioCardOption) -> Self {
self.options.push(option);
self
}
pub fn options(mut self, options: impl IntoIterator<Item = RadioCardOption>) -> Self {
self.options.extend(options);
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = Some(value.into());
self
}
pub fn layout(mut self, layout: RadioCardsLayout) -> Self {
self.layout = layout;
self
}
pub fn min_column_width(mut self, width: f32) -> Self {
self.min_column_width = width.max(120.0);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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 RadioCards {
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_controlled = self.value.is_some();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-radio-cards-state".into());
let default_val = self.default_value.clone();
let internal = window.use_keyed_state(state_id, cx, |_, _| RadioCardsInternal {
uncontrolled_value: default_val,
card_bounds: Rc::new(RefCell::new(HashMap::new())),
});
let snap = internal.read(cx).clone();
let selected = self
.value
.clone()
.or_else(|| snap.uncontrolled_value.clone());
let enabled_values: Vec<SharedString> = self
.options
.iter()
.filter(|o| !self.disabled && !o.disabled)
.map(|o| o.value.clone())
.collect();
let scope = layout_scope_key(&self.id);
let bounds_ref = snap.card_bounds.clone();
let selected_for_ring = selected.clone();
let glide_spec = motion.spring.morph.as_physical();
let ring_color = colors.control_on;
let card_radius = px(20.0);
let ring_overlay = canvas(
|_, _, _| {},
move |root_rect, _, window, cx| {
let Some(sel) = selected_for_ring.as_ref() else {
return;
};
let Some(card_rect) = bounds_ref.borrow().get(sel).copied() else {
window.request_animation_frame();
return;
};
let local_rect = bounds(card_rect.origin - root_rect.origin, card_rect.size);
let target = LayoutSnapshot::uniform_radius(local_rect, card_radius);
let flip = sample_shared_layout(
scope.clone(),
"ring",
target,
Some(glide_spec),
window,
cx,
);
let paint_rect = bounds(root_rect.origin + flip.bounds.origin, flip.bounds.size);
window.paint_quad(quad(
paint_rect,
flip.corner_radii,
Hsla::transparent_black(),
Edges::all(px(1.5)),
ring_color,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let is_list = self.layout == RadioCardsLayout::List;
let mut group = BaseRadioGroup::new(self.id.clone())
.axis(if is_list {
Axis::Vertical
} else {
Axis::Horizontal
})
.relative()
.w_full()
.flex()
.when(is_list, |this| this.flex_col().gap(px(8.0)))
.when(!is_list, |this| this.flex_row().flex_wrap().gap(px(10.0)));
let total = self.options.len();
let checked_bg = oklab_mix(colors.control_on, colors.surface, 0.04);
for (idx, option) in self.options.into_iter().enumerate() {
let opt_val = option.value.clone();
let checked = selected.as_ref() == Some(&opt_val);
let off = self.disabled || option.disabled;
let description = if off {
option.disabled_reason.or(option.description)
} else {
option.description
};
let dot_scale = if reduced {
if checked { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), format!("dot-{opt_val}")),
if checked { 1.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
)
};
let ind_border = if off {
colors.border
} else if checked {
colors.control_on
} else {
colors.border_strong
};
let ind_bg = if checked && !off {
colors.control_on
} else {
Hsla::transparent_black()
};
let dot_color = colors.control_glyph;
let surface_p = arc_transition(
(self.id.clone(), format!("surface-{opt_val}")),
if checked && !off { 1.0 } else { 0.0 },
if reduced {
std::time::Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let card_bg = if off {
colors.surface_muted
} else {
oklab_mix(checked_bg, colors.surface, surface_p.clamp(0.0, 1.0))
};
let indicator = canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
let outer = bounds(point(px(cx - 9.0), px(cy - 9.0)), size(px(18.0), px(18.0)));
window.paint_quad(quad(
outer,
Corners::all(Radii::PILL),
ind_bg,
Edges::all(px(1.5)),
ind_border,
BorderStyle::Solid,
));
if dot_scale > 0.02 {
let inner = scaled_bounds(
bounds(point(px(cx - 3.0), px(cy - 3.0)), size(px(6.0), px(6.0))),
dot_scale,
dot_scale,
TransformOrigin::CENTER,
);
window.paint_quad(quad(
inner,
Corners::all(Radii::PILL),
dot_color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
},
)
.w(px(18.0))
.h(px(18.0))
.flex_none();
let bounds_measure = snap.card_bounds.clone();
let val_measure = opt_val.clone();
let probe = canvas(
move |rect, _, _| {
bounds_measure
.borrow_mut()
.insert(val_measure.clone(), rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let label_color = if off {
colors.text_muted
} else {
colors.foreground
};
let icon_color = if off {
colors.text_muted
} else if checked {
colors.foreground
} else {
colors.text_secondary
};
let body = div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.flex()
.items_center()
.gap(px(8.0))
.when_some(option.icon, |this, icon| {
this.child(Icon::new(icon).text_size(px(16.0)).text_color(icon_color))
})
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(label_color)
.child(option.label.clone()),
),
)
.when_some(description, |this, desc| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(desc),
)
});
let int_click = internal.clone();
let int_key = internal.clone();
let on_change = self.on_value_change.clone();
let on_change_key = self.on_value_change.clone();
let val_click = opt_val.clone();
let val_key = opt_val.clone();
let enabled_for_key = enabled_values.clone();
let hover_border = colors.border_strong;
let mut card = BaseRadio::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("card-{opt_val}")),
))
.checked(checked)
.disabled(off)
.accessibility_label(option.label)
.set_position(idx + 1, total)
.on_change(move |_, _, window, cx| {
if off {
return;
}
if !is_controlled {
int_click.update(cx, |s, _| s.uncontrolled_value = Some(val_click.clone()));
}
if let Some(cb) = &on_change {
cb(&val_click, window, cx);
}
window.refresh();
})
.relative()
.rounded(card_radius)
.border_1()
.border_color(colors.border)
.bg(card_bg)
.when(!off && !checked, |this| {
this.cursor_pointer()
.hover(move |s| s.border_color(hover_border))
})
.when(!off && checked, |this| this.cursor_pointer())
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if enabled_for_key.len() < 2 {
return;
}
let cur_pos = 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_pos + 1) % enabled_for_key.len()),
"left" | "up" => {
Some((cur_pos + 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_val = enabled_for_key[ni].clone();
if !is_controlled {
int_key.update(cx, |s, _| s.uncontrolled_value = Some(next_val.clone()));
}
if let Some(cb) = &on_change_key {
cb(&next_val, window, cx);
}
window.refresh();
}
})
.child(probe);
if is_list {
card = card
.w_full()
.flex()
.flex_row()
.items_center()
.gap(px(12.0))
.py(px(13.0))
.pl(px(14.0))
.pr(px(16.0))
.child(indicator)
.child(body)
.when_some(option.meta, |this, meta| {
this.child(
div()
.flex_none()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(label_color)
.child(meta),
)
});
} else {
card = card
.flex_1()
.min_w(px(self.min_column_width))
.flex()
.flex_col()
.justify_between()
.gap(px(10.0))
.py(px(14.0))
.px(px(16.0))
.child(
div()
.w_full()
.flex()
.flex_row()
.items_start()
.justify_between()
.gap(px(12.0))
.child(body)
.child(div().pt(px(1.0)).child(indicator)),
)
.when_some(option.meta, |this, meta| {
this.child(
div()
.text_size(Typography::TEXT_LG)
.font_medium()
.text_color(label_color)
.child(meta),
)
});
}
group = group.child(card);
}
group.child(ring_overlay)
}
}
#[cfg(test)]
mod tests {
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::*;
struct CardsHost {
selected: SharedString,
}
impl Render for CardsHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(620.0)).p(Spacing::S4).child(
RadioCards::new("plan-cards")
.value(self.selected.clone())
.options([
RadioCardOption::new("starter", "Starter")
.description("For side projects")
.meta("$0 / mo"),
RadioCardOption::new("pro", "Pro")
.description("For small teams")
.meta("$24 / mo"),
RadioCardOption::new("scale", "Scale")
.meta("Custom")
.disabled(true)
.disabled_reason("Contact sales to unlock"),
])
.on_value_change(cx.listener(|this, v: &SharedString, _, cx| {
this.selected = v.clone();
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn radio_cards_selects_enabled_and_blocks_disabled(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(|_, _| CardsHost {
selected: "starter".into(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let pro = window.find_by_label("Pro");
assert_eq!(pro.role(), Some(Role::RadioButton));
let pos = pro.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
let scale = window.find_by_label("Scale");
assert_eq!(scale.disabled(), Some(true));
let spos = scale.bounds().center();
window.pointer_down(spos, MouseButton::Left, cx);
window.pointer_up(spos, MouseButton::Left, cx);
});
assert_eq!(view.read_with(cx, |v, _| v.selected.clone()), "pro");
}
}