1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AnyElement, App, Axis, Bounds, ClickEvent, Div, Element, ElementId, FocusHandle,
5 GlobalElementId, InspectorElementId, InteractiveElement, Interactivity, IntoElement,
6 KeyDownEvent, KeyboardClickEvent, LayoutId, ParentElement, Pixels, RenderOnce, Role, Stateful,
7 StatefulInteractiveElement, StyleRefinement, Styled, Window, accesskit, div,
8};
9use smallvec::SmallVec;
10
11use crate::{LayoutDirection, StyledExt as _};
12
13pub(crate) type ChangeHandler = Rc<dyn Fn(bool, &ClickEvent, &mut Window, &mut App)>;
14
15#[derive(IntoElement)]
34pub struct RadioGroup {
35 id: ElementId,
36 base: Stateful<Div>,
37 style: StyleRefinement,
38 axis: Axis,
39 children: SmallVec<[AnyElement; 4]>,
40}
41
42impl RadioGroup {
43 pub fn new(id: impl Into<ElementId>) -> Self {
44 let id = id.into();
45 Self {
46 base: div().id(id.clone()),
47 id,
48 style: StyleRefinement::default(),
49 axis: Axis::Vertical,
50 children: SmallVec::new(),
51 }
52 }
53
54 pub fn axis(mut self, axis: Axis) -> Self {
59 self.axis = axis;
60 self
61 }
62}
63
64pub(crate) struct RadioEntry {
66 pub(crate) focus_handle: FocusHandle,
67 pub(crate) checked: bool,
68 pub(crate) disabled: bool,
69 pub(crate) on_change: Option<ChangeHandler>,
70}
71
72#[derive(Default)]
73pub(crate) struct RadioRegistry {
74 entries: Vec<RadioEntry>,
75 stop: Option<FocusHandle>,
78}
79
80impl RadioRegistry {
81 pub(crate) fn current() -> Option<RadioRegistryRef> {
83 RADIO_GROUP_STACK.with(|stack| stack.borrow().last().cloned())
84 }
85
86 pub(crate) fn is_stop(&self, focus_handle: &FocusHandle) -> bool {
87 self.stop.as_ref() == Some(focus_handle)
88 }
89
90 pub(crate) fn register(&mut self, entry: RadioEntry) {
91 self.entries.push(entry);
92 }
93}
94
95pub(crate) type RadioRegistryRef = Rc<RefCell<RadioRegistry>>;
96
97thread_local! {
98 static RADIO_GROUP_STACK: RefCell<Vec<RadioRegistryRef>> = const { RefCell::new(Vec::new()) };
99}
100
101struct RadioGroupScope {
105 registry: RadioRegistryRef,
106 inner: AnyElement,
107}
108
109impl Element for RadioGroupScope {
110 type RequestLayoutState = ();
111 type PrepaintState = ();
112
113 fn id(&self) -> Option<ElementId> {
114 None
115 }
116
117 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
118 None
119 }
120
121 fn request_layout(
122 &mut self,
123 _: Option<&GlobalElementId>,
124 _: Option<&InspectorElementId>,
125 window: &mut Window,
126 cx: &mut App,
127 ) -> (LayoutId, ()) {
128 self.registry.borrow_mut().entries.clear();
129 RADIO_GROUP_STACK.with(|stack| stack.borrow_mut().push(self.registry.clone()));
130 let layout_id = self.inner.request_layout(window, cx);
131 RADIO_GROUP_STACK.with(|stack| stack.borrow_mut().pop());
132 (layout_id, ())
133 }
134
135 fn prepaint(
136 &mut self,
137 _: Option<&GlobalElementId>,
138 _: Option<&InspectorElementId>,
139 _: Bounds<Pixels>,
140 _: &mut (),
141 window: &mut Window,
142 cx: &mut App,
143 ) {
144 sync_tab_stop(&self.registry, window);
145 self.inner.prepaint(window, cx);
146 }
147
148 fn paint(
149 &mut self,
150 _: Option<&GlobalElementId>,
151 _: Option<&InspectorElementId>,
152 _: Bounds<Pixels>,
153 _: &mut (),
154 _: &mut (),
155 window: &mut Window,
156 cx: &mut App,
157 ) {
158 self.inner.paint(window, cx);
159 }
160}
161
162fn sync_tab_stop(registry: &RadioRegistryRef, window: &mut Window) {
165 let mut registry = registry.borrow_mut();
166 let enabled = |entry: &&RadioEntry| !entry.disabled;
167 let stop = registry
168 .entries
169 .iter()
170 .filter(enabled)
171 .find(|entry| entry.focus_handle.is_focused(window))
172 .or_else(|| registry.entries.iter().filter(enabled).find(|e| e.checked))
173 .or_else(|| registry.entries.iter().find(|entry| !entry.disabled))
174 .map(|entry| entry.focus_handle.clone());
175
176 if registry.stop != stop {
177 registry.stop = stop;
178 window.refresh();
180 }
181}
182
183enum Step {
184 Next,
185 Previous,
186}
187
188fn handle_key_down(
189 registry: &RadioRegistryRef,
190 event: &KeyDownEvent,
191 window: &mut Window,
192 cx: &mut App,
193) {
194 if event.keystroke.modifiers.modified() || window.default_prevented() {
197 return;
198 }
199 let rtl = LayoutDirection::global(cx).is_rtl();
200 let step = match event.keystroke.key.as_str() {
201 "down" => Step::Next,
202 "up" => Step::Previous,
203 "right" if rtl => Step::Previous,
204 "right" => Step::Next,
205 "left" if rtl => Step::Next,
206 "left" => Step::Previous,
207 _ => return,
208 };
209
210 let (target, on_change) = {
211 let entries = ®istry.borrow().entries;
212 let Some(current) = entries
213 .iter()
214 .position(|entry| entry.focus_handle.is_focused(window))
215 else {
216 return;
217 };
218 let enabled: Vec<usize> = (0..entries.len())
219 .filter(|&ix| !entries[ix].disabled)
220 .collect();
221 let (Some(&first), Some(&last)) = (enabled.first(), enabled.last()) else {
222 return;
223 };
224 let target = match step {
225 Step::Next => enabled
226 .iter()
227 .copied()
228 .find(|&ix| ix > current)
229 .unwrap_or(first),
230 Step::Previous => enabled
231 .iter()
232 .rev()
233 .copied()
234 .find(|&ix| ix < current)
235 .unwrap_or(last),
236 };
237 let entry = &entries[target];
238 let on_change = (!entry.checked).then(|| entry.on_change.clone()).flatten();
239 (entry.focus_handle.clone(), on_change)
240 };
241
242 cx.stop_propagation();
243 window.prevent_default();
244 window.focus(&target, cx);
245 sync_tab_stop(registry, window);
246 if let Some(on_change) = on_change {
249 let event = ClickEvent::Keyboard(KeyboardClickEvent::default());
250 on_change(true, &event, window, cx);
251 }
252}
253
254impl Styled for RadioGroup {
255 fn style(&mut self) -> &mut StyleRefinement {
256 &mut self.style
257 }
258}
259
260impl ParentElement for RadioGroup {
261 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
262 self.children.extend(elements);
263 }
264}
265
266impl InteractiveElement for RadioGroup {
267 fn interactivity(&mut self) -> &mut Interactivity {
268 self.base.interactivity()
269 }
270}
271
272impl StatefulInteractiveElement for RadioGroup {}
273
274impl RenderOnce for RadioGroup {
275 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
276 let Self {
277 id,
278 base,
279 style,
280 axis,
281 children,
282 } = self;
283
284 let registry = window
287 .use_keyed_state(id, cx, |_, _| RadioRegistryRef::default())
288 .read(cx)
289 .clone();
290 let key_handler = {
291 let registry = registry.clone();
292 move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
293 handle_key_down(®istry, event, window, cx);
294 }
295 };
296
297 RadioGroupScope {
298 registry,
299 inner: radio_group(base, axis)
300 .on_key_down(key_handler)
301 .children(children)
302 .refine_style(&style)
303 .into_any_element(),
304 }
305 }
306}
307
308fn radio_group(base: Stateful<Div>, axis: Axis) -> Stateful<Div> {
310 base.role(Role::RadioGroup).aria_orientation(match axis {
311 Axis::Horizontal => accesskit::Orientation::Horizontal,
312 Axis::Vertical => accesskit::Orientation::Vertical,
313 })
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319 use crate::Radio;
320 use gpui::{Context, Render, TestAppContext, VisualTestContext, px};
321
322 struct Harness {
324 axis: Axis,
325 checked: Option<usize>,
326 changes: Rc<RefCell<Vec<usize>>>,
327 before: FocusHandle,
328 after: FocusHandle,
329 }
330
331 impl Render for Harness {
332 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
333 let radios = (0..4).map(|ix| {
334 let changes = self.changes.clone();
335 let entity = cx.entity();
336 Radio::new(("radio", ix))
337 .size(px(20.))
338 .checked(self.checked == Some(ix))
339 .disabled(ix == 2)
340 .tab_index(5)
342 .tab_stop(true)
343 .on_change(move |checked, _, _, cx| {
344 assert!(checked);
345 changes.borrow_mut().push(ix);
346 entity.update(cx, |this, cx| {
347 this.checked = Some(ix);
348 cx.notify();
349 });
350 })
351 });
352 div()
353 .child(div().id("before").size(px(10.)).track_focus(&self.before))
354 .child(RadioGroup::new("group").axis(self.axis).children(radios))
355 .child(div().id("after").size(px(10.)).track_focus(&self.after))
356 }
357 }
358
359 struct Fixture<'a> {
360 cx: &'a mut VisualTestContext,
361 view: gpui::Entity<Harness>,
362 changes: Rc<RefCell<Vec<usize>>>,
363 after: FocusHandle,
364 }
365
366 impl Fixture<'_> {
367 fn draw(&mut self) {
368 self.cx.update(|window, cx| window.draw(cx).clear(cx));
369 }
370
371 fn checked(&mut self) -> Option<usize> {
372 self.cx.run_until_parked();
373 self.view.read_with(self.cx, |this, _| this.checked)
374 }
375
376 fn focused(&mut self) -> Option<usize> {
378 self.draw();
379 self.changes.borrow_mut().clear();
380 self.view.update(self.cx, |this, cx| {
382 this.checked = None;
383 cx.notify();
384 });
385 self.draw();
386 self.cx.simulate_keystrokes("space");
387 self.cx.simulate_event(gpui::KeyUpEvent {
388 keystroke: gpui::Keystroke::parse("space").unwrap(),
389 });
390 self.changes.borrow().last().copied()
391 }
392 }
393
394 fn fixture(cx: &mut TestAppContext, axis: Axis, checked: Option<usize>) -> Fixture<'_> {
395 let changes: Rc<RefCell<Vec<usize>>> = Rc::default();
396 let (view, cx) = cx.add_window_view({
397 let changes = changes.clone();
398 move |window, cx| {
399 let before = cx.focus_handle().tab_stop(true);
400 before.focus(window, cx);
401 Harness {
402 axis,
403 checked,
404 changes,
405 before,
406 after: cx.focus_handle().tab_stop(true),
407 }
408 }
409 });
410 let after = view.read_with(cx, |this, _| this.after.clone());
411 cx.update(|window, cx| window.draw(cx).clear(cx));
413 cx.update(|window, cx| window.draw(cx).clear(cx));
414 cx.update(|window, cx| window.focus_next(cx));
415 Fixture {
416 cx,
417 view,
418 changes,
419 after,
420 }
421 }
422
423 #[gpui::test]
424 fn tab_enters_on_the_checked_radio_and_leaves_with_one_press(cx: &mut TestAppContext) {
425 let mut f = fixture(cx, Axis::Vertical, Some(1));
426 assert_eq!(f.focused(), Some(1));
427 f.cx.update(|window, cx| window.focus_next(cx));
428 f.cx.update(|window, _| assert!(f.after.is_focused(window)));
429 }
430
431 #[gpui::test]
432 fn without_a_checked_radio_the_first_enabled_radio_is_the_stop(cx: &mut TestAppContext) {
433 let mut f = fixture(cx, Axis::Vertical, None);
434 assert_eq!(f.focused(), Some(0));
435 }
436
437 #[gpui::test]
438 fn arrows_move_check_skip_disabled_radios_and_wrap(cx: &mut TestAppContext) {
439 let mut f = fixture(cx, Axis::Vertical, Some(0));
440
441 f.cx.simulate_keystrokes("down");
442 assert_eq!(*f.changes.borrow(), vec![1], "moving checks the radio");
443 assert_eq!(f.checked(), Some(1));
444
445 f.draw();
446 f.cx.simulate_keystrokes("down");
447 assert_eq!(f.checked(), Some(3), "the disabled radio is skipped");
448 f.draw();
449 f.cx.simulate_keystrokes("right");
450 assert_eq!(f.checked(), Some(0), "wraps past the last radio");
451 f.draw();
452 f.cx.simulate_keystrokes("left");
453 assert_eq!(f.checked(), Some(3), "wraps before the first radio");
454 f.draw();
455 f.cx.simulate_keystrokes("up");
456 assert_eq!(f.checked(), Some(1), "skips the disabled radio back");
457 assert_eq!(f.focused(), Some(1), "focus moved with the selection");
458
459 f.cx.update(|window, cx| window.focus_next(cx));
461 f.cx.update(|window, _| assert!(f.after.is_focused(window)));
462 }
463
464 #[gpui::test]
465 fn a_horizontal_group_uses_all_four_arrows(cx: &mut TestAppContext) {
466 let mut f = fixture(cx, Axis::Horizontal, Some(0));
467 f.cx.simulate_keystrokes("right");
468 assert_eq!(f.checked(), Some(1));
469 f.draw();
470 f.cx.simulate_keystrokes("up");
471 assert_eq!(f.checked(), Some(0));
472 }
473
474 #[gpui::test]
475 fn left_and_right_follow_the_global_rtl_direction(cx: &mut TestAppContext) {
476 let mut f = fixture(cx, Axis::Horizontal, Some(0));
477 f.cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
478 f.cx.simulate_keystrokes("left");
479 assert_eq!(f.checked(), Some(1), "the next radio sits to the left");
480 f.draw();
481 f.cx.simulate_keystrokes("right");
482 assert_eq!(f.checked(), Some(0));
483 }
484
485 #[gpui::test]
486 fn only_one_radio_is_a_tab_stop(cx: &mut TestAppContext) {
487 let f = fixture(cx, Axis::Vertical, Some(3));
488 f.cx.update(|window, cx| {
489 window.focus_next(cx);
490 assert!(f.after.is_focused(window), "one stop: Tab leaves at once");
491 window.focus_prev(cx);
492 window.focus_prev(cx);
493 let before = f.view.read(cx).before.clone();
494 assert!(before.is_focused(window), "and one stop going back");
495 });
496 }
497}