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, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, Axis, BorderStyle, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, KeyDownEvent,
MouseButton, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
base::{Radio as BaseRadio, RadioGroup as BaseRadioGroup},
bounds, canvas, div, point,
prelude::*,
px, quad, size,
};
type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone)]
pub struct RadioOption {
pub value: SharedString,
pub label: SharedString,
pub description: Option<SharedString>,
pub disabled: bool,
}
impl RadioOption {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
description: None,
disabled: false,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
#[derive(Clone)]
struct RadioGroupInternal {
uncontrolled_value: SharedString,
pressed_value: Option<SharedString>,
row_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
}
#[derive(IntoElement)]
pub struct RadioGroup {
id: ElementId,
label: SharedString,
options: Vec<RadioOption>,
value: Option<SharedString>,
default_value: Option<SharedString>,
disabled: bool,
on_value_change: Option<ValueChangeHandler>,
}
impl RadioGroup {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
options: Vec::new(),
value: None,
default_value: None,
disabled: false,
on_value_change: None,
}
}
pub fn option(mut self, option: RadioOption) -> Self {
self.options.push(option);
self
}
pub fn options(mut self, options: impl IntoIterator<Item = RadioOption>) -> 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 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 RadioGroup {
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 fallback = self
.default_value
.clone()
.or_else(|| {
self.options
.iter()
.find(|o| !o.disabled)
.map(|o| o.value.clone())
})
.unwrap_or_default();
let is_controlled = self.value.is_some();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-radio-group-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| RadioGroupInternal {
uncontrolled_value: fallback,
pressed_value: None,
row_bounds: Rc::new(RefCell::new(HashMap::new())),
});
let snap = internal.read(cx).clone();
let active = self
.value
.clone()
.unwrap_or_else(|| snap.uncontrolled_value.clone());
let scope = layout_scope_key(&self.id);
let rows_ref = snap.row_bounds.clone();
let active_for_hi = active.clone();
let morph_spec = motion.spring.morph;
let hi_border = colors.control_on;
let hi_bg = oklab_mix(colors.control_on, Hsla::transparent_black(), 0.05);
let highlight_canvas = canvas(
|_, _, _| {},
move |list_rect, _, window, cx| {
let Some(row_rect) = rows_ref.borrow().get(&active_for_hi).copied() else {
window.request_animation_frame();
return;
};
let local_rect = bounds(row_rect.origin - list_rect.origin, row_rect.size);
let target = LayoutSnapshot::uniform_radius(local_rect, Radii::CONTROL);
let flip = sample_shared_layout(
scope.clone(),
"selection",
target,
Some(morph_spec),
window,
cx,
);
let paint_rect = bounds(list_rect.origin + flip.bounds.origin, flip.bounds.size);
window.paint_quad(quad(
paint_rect,
flip.corner_radii,
hi_bg,
Edges::all(px(1.0)),
hi_border,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let enabled_values: Vec<SharedString> = self
.options
.iter()
.filter(|o| !self.disabled && !o.disabled)
.map(|o| o.value.clone())
.collect();
let mut list =
BaseRadioGroup::new(ElementId::NamedChild(self.id.clone().into(), "list".into()))
.axis(Axis::Vertical)
.relative()
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.child(highlight_canvas);
let total = self.options.len();
for (idx, option) in self.options.into_iter().enumerate() {
let opt_val = option.value.clone();
let checked = active == opt_val;
let opt_disabled = self.disabled || option.disabled;
let is_pressed = !opt_disabled && snap.pressed_value.as_ref() == Some(&opt_val);
let dot_scale = if reduced {
if checked { 1.0 } else { 0.4 }
} else {
arc_spring(
(self.id.clone(), format!("dot-scale-{opt_val}")),
if checked { 1.0 } else { 0.4 },
motion.spring.snappy,
window,
cx,
)
};
let dot_op = arc_transition(
(self.id.clone(), format!("dot-op-{opt_val}")),
if checked { 1.0 } else { 0.0 },
if reduced {
std::time::Duration::ZERO
} else if checked {
motion.duration.fast
} else {
motion.duration.instant
},
motion.ease.standard,
window,
cx,
);
let mark_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), format!("mark-scale-{opt_val}")),
if is_pressed { 0.88 } else { 1.0 },
motion.spring.snappy,
window,
cx,
)
};
let mark_border = if checked {
colors.control_on
} else {
colors.border_strong
};
let mark_bg = if checked {
colors.control_on
} else {
Hsla::transparent_black()
};
let dot_color = if checked {
Hsla {
a: colors.control_glyph.a * dot_op,
..colors.control_glyph
}
} else if is_pressed {
Hsla {
a: 0.22,
..colors.foreground
}
} else {
Hsla::transparent_black()
};
let mark_el = 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 = scaled_bounds(
bounds(point(px(cx - 8.0), px(cy - 8.0)), size(px(16.0), px(16.0))),
mark_scale,
mark_scale,
TransformOrigin::CENTER,
);
window.paint_quad(quad(
outer,
Corners::all(Radii::PILL),
mark_bg,
Edges::all(px(1.0)),
mark_border,
BorderStyle::Solid,
));
if dot_color.a > 0.01 {
let d_s = if checked { dot_scale } else { 1.0 };
let inner = scaled_bounds(
bounds(point(px(cx - 3.0), px(cy - 3.0)), size(px(6.0), px(6.0))),
d_s,
d_s,
TransformOrigin::CENTER,
);
window.paint_quad(quad(
inner,
Corners::all(Radii::PILL),
dot_color,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
},
)
.w(px(16.0))
.h(px(16.0))
.flex_none();
let row_bounds = snap.row_bounds.clone();
let val_measure = opt_val.clone();
let probe = canvas(
move |rect, _, _| {
row_bounds.borrow_mut().insert(val_measure.clone(), rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let int_change = 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_value_change.clone();
let on_change_key = self.on_value_change.clone();
let val_click = opt_val.clone();
let val_down = opt_val.clone();
let val_key = opt_val.clone();
let enabled_for_key = enabled_values.clone();
let hover_bg = colors.surface_muted;
let radio = BaseRadio::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("radio-{opt_val}")),
))
.checked(checked)
.disabled(opt_disabled)
.accessibility_label(option.label.clone())
.set_position(idx + 1, total)
.on_change(move |_, _, window, cx| {
if !is_controlled {
int_change.update(cx, |s, _| s.uncontrolled_value = val_click.clone());
}
if let Some(cb) = &on_change {
cb(&val_click, window, cx);
}
window.refresh();
})
.relative()
.w_full()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S3)
.p(Spacing::S3)
.rounded(Radii::CONTROL)
.border_1()
.border_color(if checked {
Hsla::transparent_black()
} else {
colors.border
})
.when(!opt_disabled, |this| {
this.cursor_pointer().hover(move |s| s.bg(hover_bg))
})
.when(opt_disabled, |this| this.opacity(0.5))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if opt_disabled {
return;
}
int_down.update(cx, |s, _| s.pressed_value = Some(val_down.clone()));
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed_value = None);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed_value = None);
window.refresh();
})
.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() {
"down" | "right" => Some((cur_pos + 1) % enabled_for_key.len()),
"up" | "left" => {
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 = next_val.clone());
}
if let Some(cb) = &on_change_key {
cb(&next_val, window, cx);
}
window.refresh();
}
})
.child(probe)
.child(mark_el)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(if checked {
colors.foreground
} else {
colors.text_secondary
})
.child(option.label),
)
.when_some(option.description, |this, desc| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(desc),
)
}),
);
list = list.child(radio);
}
div()
.id(self.id)
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(self.label),
)
.child(list)
}
}
#[cfg(test)]
mod tests {
use std::{cell::RefCell, 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::*;
struct RadioHost {
selected: SharedString,
last: Rc<RefCell<SharedString>>,
}
impl Render for RadioHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let last = self.last.clone();
div().w(px(360.0)).p(Spacing::S4).child(
RadioGroup::new("delivery", "Delivery speed")
.value(self.selected.clone())
.options([
RadioOption::new("std", "Standard").description("3–5 business days"),
RadioOption::new("exp", "Express").description("Next day delivery"),
])
.on_value_change(cx.listener(move |this, v: &SharedString, _, cx| {
this.selected = v.clone();
*last.borrow_mut() = v.clone();
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn radio_group_selects_option_on_click(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let last = Rc::new(RefCell::new(SharedString::from("std")));
let (view, cx) = cx.add_window_view(|_, _| RadioHost {
selected: "std".into(),
last: last.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let exp = window.find_by_label("Express");
assert_eq!(exp.role(), Some(Role::RadioButton));
let pos = exp.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
});
assert_eq!(view.read_with(cx, |v, _| v.selected.clone()), "exp");
assert_eq!(*last.borrow(), "exp");
}
}