1use std::{cell::RefCell, collections::HashMap, rc::Rc};
15
16use arc_motion::{
17 LayoutSnapshot, TransformOrigin, arc_spring, arc_transition, is_reduced_motion,
18 layout::layout_scope_key, sample_shared_layout, scaled_bounds,
19};
20use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
21use gpui_kit::{
22 App, Axis, BorderStyle, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, KeyDownEvent,
23 MouseButton, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
24 base::{Radio as BaseRadio, RadioGroup as BaseRadioGroup},
25 bounds, canvas, div, point,
26 prelude::*,
27 px, quad, size,
28};
29
30type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
31
32#[derive(Clone)]
34pub struct RadioOption {
35 pub value: SharedString,
36 pub label: SharedString,
37 pub description: Option<SharedString>,
38 pub disabled: bool,
39}
40
41impl RadioOption {
42 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
43 Self {
44 value: value.into(),
45 label: label.into(),
46 description: None,
47 disabled: false,
48 }
49 }
50
51 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
52 self.description = Some(description.into());
53 self
54 }
55
56 pub fn disabled(mut self, disabled: bool) -> Self {
57 self.disabled = disabled;
58 self
59 }
60}
61
62#[derive(Clone)]
63struct RadioGroupInternal {
64 uncontrolled_value: SharedString,
65 pressed_value: Option<SharedString>,
66 row_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
67}
68
69#[derive(IntoElement)]
71pub struct RadioGroup {
72 id: ElementId,
73 label: SharedString,
74 options: Vec<RadioOption>,
75 value: Option<SharedString>,
76 default_value: Option<SharedString>,
77 disabled: bool,
78 on_value_change: Option<ValueChangeHandler>,
79}
80
81impl RadioGroup {
82 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
83 Self {
84 id: id.into(),
85 label: label.into(),
86 options: Vec::new(),
87 value: None,
88 default_value: None,
89 disabled: false,
90 on_value_change: None,
91 }
92 }
93
94 pub fn option(mut self, option: RadioOption) -> Self {
95 self.options.push(option);
96 self
97 }
98
99 pub fn options(mut self, options: impl IntoIterator<Item = RadioOption>) -> Self {
100 self.options.extend(options);
101 self
102 }
103
104 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
105 self.value = Some(value.into());
106 self
107 }
108
109 pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
110 self.default_value = Some(value.into());
111 self
112 }
113
114 pub fn disabled(mut self, disabled: bool) -> Self {
115 self.disabled = disabled;
116 self
117 }
118
119 pub fn on_value_change(
120 mut self,
121 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
122 ) -> Self {
123 self.on_value_change = Some(Rc::new(handler));
124 self
125 }
126}
127
128impl RenderOnce for RadioGroup {
129 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
130 let theme = cx.arc_theme().clone();
131 let colors = theme.colors;
132 let motion = theme.motion;
133 let reduced = is_reduced_motion(cx);
134
135 let fallback = self
136 .default_value
137 .clone()
138 .or_else(|| {
139 self.options
140 .iter()
141 .find(|o| !o.disabled)
142 .map(|o| o.value.clone())
143 })
144 .unwrap_or_default();
145
146 let is_controlled = self.value.is_some();
147 let state_id =
148 ElementId::NamedChild(self.id.clone().into(), "__arc-radio-group-state".into());
149 let internal = window.use_keyed_state(state_id, cx, |_, _| RadioGroupInternal {
150 uncontrolled_value: fallback,
151 pressed_value: None,
152 row_bounds: Rc::new(RefCell::new(HashMap::new())),
153 });
154
155 let snap = internal.read(cx).clone();
156 let active = self
157 .value
158 .clone()
159 .unwrap_or_else(|| snap.uncontrolled_value.clone());
160
161 let scope = layout_scope_key(&self.id);
162 let rows_ref = snap.row_bounds.clone();
163 let active_for_hi = active.clone();
164 let morph_spec = motion.spring.morph;
165 let hi_border = colors.control_on;
166 let hi_bg = oklab_mix(colors.control_on, Hsla::transparent_black(), 0.05);
167
168 let highlight_canvas = canvas(
169 |_, _, _| {},
170 move |list_rect, _, window, cx| {
171 let Some(row_rect) = rows_ref.borrow().get(&active_for_hi).copied() else {
172 window.request_animation_frame();
173 return;
174 };
175 let local_rect = bounds(row_rect.origin - list_rect.origin, row_rect.size);
176 let target = LayoutSnapshot::uniform_radius(local_rect, Radii::CONTROL);
177 let flip = sample_shared_layout(
178 scope.clone(),
179 "selection",
180 target,
181 Some(morph_spec),
182 window,
183 cx,
184 );
185 let paint_rect = bounds(list_rect.origin + flip.bounds.origin, flip.bounds.size);
186 window.paint_quad(quad(
187 paint_rect,
188 flip.corner_radii,
189 hi_bg,
190 Edges::all(px(1.0)),
191 hi_border,
192 BorderStyle::Solid,
193 ));
194 },
195 )
196 .absolute()
197 .inset_0();
198
199 let enabled_values: Vec<SharedString> = self
200 .options
201 .iter()
202 .filter(|o| !self.disabled && !o.disabled)
203 .map(|o| o.value.clone())
204 .collect();
205
206 let mut list =
207 BaseRadioGroup::new(ElementId::NamedChild(self.id.clone().into(), "list".into()))
208 .axis(Axis::Vertical)
209 .relative()
210 .w_full()
211 .flex()
212 .flex_col()
213 .gap(Spacing::S2)
214 .child(highlight_canvas);
215
216 let total = self.options.len();
217 for (idx, option) in self.options.into_iter().enumerate() {
218 let opt_val = option.value.clone();
219 let checked = active == opt_val;
220 let opt_disabled = self.disabled || option.disabled;
221 let is_pressed = !opt_disabled && snap.pressed_value.as_ref() == Some(&opt_val);
222
223 let dot_scale = if reduced {
224 if checked { 1.0 } else { 0.4 }
225 } else {
226 arc_spring(
227 (self.id.clone(), format!("dot-scale-{opt_val}")),
228 if checked { 1.0 } else { 0.4 },
229 motion.spring.snappy,
230 window,
231 cx,
232 )
233 };
234 let dot_op = arc_transition(
235 (self.id.clone(), format!("dot-op-{opt_val}")),
236 if checked { 1.0 } else { 0.0 },
237 if reduced {
238 std::time::Duration::ZERO
239 } else if checked {
240 motion.duration.fast
241 } else {
242 motion.duration.instant
243 },
244 motion.ease.standard,
245 window,
246 cx,
247 );
248 let mark_scale = if reduced {
249 1.0
250 } else {
251 arc_spring(
252 (self.id.clone(), format!("mark-scale-{opt_val}")),
253 if is_pressed { 0.88 } else { 1.0 },
254 motion.spring.snappy,
255 window,
256 cx,
257 )
258 };
259
260 let mark_border = if checked {
261 colors.control_on
262 } else {
263 colors.border_strong
264 };
265 let mark_bg = if checked {
266 colors.control_on
267 } else {
268 Hsla::transparent_black()
269 };
270 let dot_color = if checked {
271 Hsla {
272 a: colors.control_glyph.a * dot_op,
273 ..colors.control_glyph
274 }
275 } else if is_pressed {
276 Hsla {
277 a: 0.22,
278 ..colors.foreground
279 }
280 } else {
281 Hsla::transparent_black()
282 };
283
284 let mark_el = canvas(
285 |_, _, _| {},
286 move |rect, _, window, _| {
287 let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
288 let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
289 let outer = scaled_bounds(
290 bounds(point(px(cx - 8.0), px(cy - 8.0)), size(px(16.0), px(16.0))),
291 mark_scale,
292 mark_scale,
293 TransformOrigin::CENTER,
294 );
295 window.paint_quad(quad(
296 outer,
297 Corners::all(Radii::PILL),
298 mark_bg,
299 Edges::all(px(1.0)),
300 mark_border,
301 BorderStyle::Solid,
302 ));
303 if dot_color.a > 0.01 {
304 let d_s = if checked { dot_scale } else { 1.0 };
305 let inner = scaled_bounds(
306 bounds(point(px(cx - 3.0), px(cy - 3.0)), size(px(6.0), px(6.0))),
307 d_s,
308 d_s,
309 TransformOrigin::CENTER,
310 );
311 window.paint_quad(quad(
312 inner,
313 Corners::all(Radii::PILL),
314 dot_color,
315 Edges::default(),
316 Hsla::transparent_black(),
317 BorderStyle::Solid,
318 ));
319 }
320 },
321 )
322 .w(px(16.0))
323 .h(px(16.0))
324 .flex_none();
325
326 let row_bounds = snap.row_bounds.clone();
327 let val_measure = opt_val.clone();
328 let probe = canvas(
329 move |rect, _, _| {
330 row_bounds.borrow_mut().insert(val_measure.clone(), rect);
331 },
332 |_, _, _, _| {},
333 )
334 .absolute()
335 .inset_0();
336
337 let int_change = internal.clone();
338 let int_down = internal.clone();
339 let int_up = internal.clone();
340 let int_out = internal.clone();
341 let int_key = internal.clone();
342 let on_change = self.on_value_change.clone();
343 let on_change_key = self.on_value_change.clone();
344 let val_click = opt_val.clone();
345 let val_down = opt_val.clone();
346 let val_key = opt_val.clone();
347 let enabled_for_key = enabled_values.clone();
348 let hover_bg = colors.surface_muted;
349
350 let radio = BaseRadio::new(ElementId::NamedChild(
351 self.id.clone().into(),
352 SharedString::from(format!("radio-{opt_val}")),
353 ))
354 .checked(checked)
355 .disabled(opt_disabled)
356 .accessibility_label(option.label.clone())
357 .set_position(idx + 1, total)
358 .on_change(move |_, _, window, cx| {
359 if !is_controlled {
360 int_change.update(cx, |s, _| s.uncontrolled_value = val_click.clone());
361 }
362 if let Some(cb) = &on_change {
363 cb(&val_click, window, cx);
364 }
365 window.refresh();
366 })
367 .relative()
368 .w_full()
369 .flex()
370 .flex_row()
371 .items_center()
372 .gap(Spacing::S3)
373 .p(Spacing::S3)
374 .rounded(Radii::CONTROL)
375 .border_1()
376 .border_color(if checked {
377 Hsla::transparent_black()
378 } else {
379 colors.border
380 })
381 .when(!opt_disabled, |this| {
382 this.cursor_pointer().hover(move |s| s.bg(hover_bg))
383 })
384 .when(opt_disabled, |this| this.opacity(0.5))
385 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
386 if opt_disabled {
387 return;
388 }
389 int_down.update(cx, |s, _| s.pressed_value = Some(val_down.clone()));
390 window.refresh();
391 })
392 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
393 int_up.update(cx, |s, _| s.pressed_value = None);
394 window.refresh();
395 })
396 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
397 int_out.update(cx, |s, _| s.pressed_value = None);
398 window.refresh();
399 })
400 .on_key_down(move |event: &KeyDownEvent, window, cx| {
401 if enabled_for_key.len() < 2 {
402 return;
403 }
404 let cur_pos = enabled_for_key
405 .iter()
406 .position(|v| v == &val_key)
407 .unwrap_or(0);
408 let next_idx = match event.keystroke.key.as_str() {
409 "down" | "right" => Some((cur_pos + 1) % enabled_for_key.len()),
410 "up" | "left" => {
411 Some((cur_pos + enabled_for_key.len() - 1) % enabled_for_key.len())
412 }
413 "home" => Some(0),
414 "end" => Some(enabled_for_key.len() - 1),
415 _ => None,
416 };
417 if let Some(ni) = next_idx {
418 let next_val = enabled_for_key[ni].clone();
419 if !is_controlled {
420 int_key.update(cx, |s, _| s.uncontrolled_value = next_val.clone());
421 }
422 if let Some(cb) = &on_change_key {
423 cb(&next_val, window, cx);
424 }
425 window.refresh();
426 }
427 })
428 .child(probe)
429 .child(mark_el)
430 .child(
431 div()
432 .flex_1()
433 .min_w_0()
434 .flex()
435 .flex_col()
436 .gap(px(2.0))
437 .child(
438 div()
439 .text_size(Typography::TEXT_SM)
440 .text_color(if checked {
441 colors.foreground
442 } else {
443 colors.text_secondary
444 })
445 .child(option.label),
446 )
447 .when_some(option.description, |this, desc| {
448 this.child(
449 div()
450 .text_size(Typography::TEXT_XS)
451 .text_color(colors.text_muted)
452 .child(desc),
453 )
454 }),
455 );
456
457 list = list.child(radio);
458 }
459
460 div()
461 .id(self.id)
462 .w_full()
463 .flex()
464 .flex_col()
465 .gap(Spacing::S2)
466 .child(
467 div()
468 .text_size(Typography::TEXT_SM)
469 .text_color(colors.foreground)
470 .child(self.label),
471 )
472 .child(list)
473 }
474}
475
476#[cfg(test)]
477mod tests {
478 use std::{cell::RefCell, rc::Rc};
479
480 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
481 use gpui_kit::{
482 Context, MouseButton, Render, Role, TestAppContext, div,
483 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
484 };
485
486 use super::*;
487
488 struct RadioHost {
489 selected: SharedString,
490 last: Rc<RefCell<SharedString>>,
491 }
492
493 impl Render for RadioHost {
494 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
495 let last = self.last.clone();
496 div().w(px(360.0)).p(Spacing::S4).child(
497 RadioGroup::new("delivery", "Delivery speed")
498 .value(self.selected.clone())
499 .options([
500 RadioOption::new("std", "Standard").description("3–5 business days"),
501 RadioOption::new("exp", "Express").description("Next day delivery"),
502 ])
503 .on_value_change(cx.listener(move |this, v: &SharedString, _, cx| {
504 this.selected = v.clone();
505 *last.borrow_mut() = v.clone();
506 cx.notify();
507 })),
508 )
509 }
510 }
511
512 #[gpui_kit::test]
513 fn radio_group_selects_option_on_click(cx: &mut TestAppContext) {
514 cx.update(|cx| {
515 gpui_kit::init(cx);
516 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
517 });
518 let last = Rc::new(RefCell::new(SharedString::from("std")));
519 let (view, cx) = cx.add_window_view(|_, _| RadioHost {
520 selected: "std".into(),
521 last: last.clone(),
522 });
523
524 cx.update(|window, cx| {
525 window.render_frame(cx);
526 let exp = window.find_by_label("Express");
527 assert_eq!(exp.role(), Some(Role::RadioButton));
528 let pos = exp.bounds().center();
529 window.pointer_down(pos, MouseButton::Left, cx);
530 window.pointer_up(pos, MouseButton::Left, cx);
531 });
532
533 assert_eq!(view.read_with(cx, |v, _| v.selected.clone()), "exp");
534 assert_eq!(*last.borrow(), "exp");
535 }
536}