Skip to main content

waft_widgets/widgets/
radio_group.rs

1//! Flutter counterpart: `widgets/radio_group.dart`.
2//!
3//! A [`RadioGroup`] treats every [`RadioClient`] of the same value type below it as one group:
4//! it holds the group value, hands a selection change back through
5//! [`RadioGroup::on_changed`], and moves the selection with the arrow keys.
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9
10use waft_embedder::SemanticsRole;
11use waft_foundation::{
12    App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Listener, OptionRetained, Ref,
13    Retained, ValueChanged,
14};
15use waft_services::{KeyEvent, LogicalKeyboardKey};
16
17use crate::framework::{
18    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
19};
20use crate::widgets::actions::{IntentRef, VoidCallbackIntent};
21use crate::widgets::basic::Semantics;
22use crate::widgets::focus_manager::{AnyFocusNode, KeyEventResult};
23use crate::widgets::focus_traversal::{
24    DirectionalFocusTraversalPolicyMixin, DirectionalFocusTraversalPolicyMixinData,
25    FocusTraversalGroup, FocusTraversalPolicy, FocusTraversalPolicyData, FocusTraversalPolicyRef,
26    ReadingOrderTraversalPolicy,
27};
28use crate::widgets::shortcuts::{
29    ShortcutActivatorRef, ShortcutManagerBase, ShortcutManagerData, ShortcutManagerKeypress,
30    ShortcutManagerRef, ShortcutMap, Shortcuts, SingleActivator,
31};
32
33// ---------------------------------------------------------------------------------------------
34// RadioGroupRegistry
35
36/// The vtable of an erased [`AnyRadioGroupRegistry`]: one `&'static` table per leaf type.
37struct RadioGroupRegistryVTable<T: Clone + PartialEq + 'static> {
38    type_name: fn() -> &'static str,
39    group_value: fn(&App, HandleId) -> Option<T>,
40    register_client: fn(&mut App, HandleId, AnyRadioClient<T>),
41    unregister_client: fn(&mut App, HandleId, AnyRadioClient<T>),
42    on_changed: fn(&mut App, HandleId, Option<T>),
43}
44
45/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
46fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
47    Handle::from_id(id)
48}
49
50impl<T: Clone + PartialEq + 'static> RadioGroupRegistryVTable<T> {
51    const fn of<L: RadioGroupRegistry<T>>() -> RadioGroupRegistryVTable<T> {
52        RadioGroupRegistryVTable {
53            type_name: std::any::type_name::<L>,
54            group_value: |app, id| L::group_value(resolve(id), app),
55            register_client: |app, id, radio| L::register_client(resolve(id), app, radio),
56            unregister_client: |app, id, radio| L::unregister_client(resolve(id), app, radio),
57            on_changed: |app, id, value| L::on_changed(resolve(id), app, value),
58        }
59    }
60}
61
62/// An abstract interface for registering a group of radios.
63///
64/// Use [`register_client`](Self::register_client) or
65/// [`unregister_client`](Self::unregister_client) to handle registrations of radios.
66///
67/// The registry manages the group value for the radios. The radio needs to call
68/// [`on_changed`](Self::on_changed) to notify the group value needs to be changed.
69pub trait RadioGroupRegistry<T: Clone + PartialEq + 'static>: Sized + 'static {
70    /// This registry as the erased [`AnyRadioGroupRegistry`] — what to pass where a Dart API
71    /// takes a `RadioGroupRegistry<T>`.
72    fn as_radio_group_registry(self: Handle<Self>) -> AnyRadioGroupRegistry<T> {
73        AnyRadioGroupRegistry {
74            id: self.id(),
75            vtable: const { &RadioGroupRegistryVTable::<T>::of::<Self>() },
76        }
77    }
78
79    /// The group value for the group.
80    fn group_value(self: Handle<Self>, app: &App) -> Option<T>;
81
82    /// Registers a radio client.
83    ///
84    /// The implementor provides additional features, such as keyboard navigation for the
85    /// registered clients.
86    fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>);
87
88    /// Unregisters a radio client.
89    fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>);
90
91    /// Notifies the registry that a radio is selected or unselected.
92    fn on_changed(self: Handle<Self>, app: &mut App, value: Option<T>);
93}
94
95/// Erased `RadioGroupRegistry<T>`: one identity and a static vtable.
96///
97/// This is what a parameter Dart types as `RadioGroupRegistry<T>` becomes, and what a field
98/// holding one for the length of a call holds; a field Dart keeps is
99/// [`RadioGroupRegistryRef<T>`].
100pub struct AnyRadioGroupRegistry<T: Clone + PartialEq + 'static> {
101    id: HandleId,
102    vtable: &'static RadioGroupRegistryVTable<T>,
103}
104
105impl<T: Clone + PartialEq + 'static> Clone for AnyRadioGroupRegistry<T> {
106    fn clone(&self) -> AnyRadioGroupRegistry<T> {
107        *self
108    }
109}
110
111impl<T: Clone + PartialEq + 'static> From<AnyRadioGroupRegistry<T>> for HandleId {
112    fn from(registry: AnyRadioGroupRegistry<T>) -> HandleId {
113        registry.id
114    }
115}
116
117impl<T: Clone + PartialEq + 'static, Leaf: RadioGroupRegistry<T>> From<Handle<Leaf>>
118    for AnyRadioGroupRegistry<T>
119{
120    fn from(handle: Handle<Leaf>) -> AnyRadioGroupRegistry<T> {
121        handle.as_radio_group_registry()
122    }
123}
124
125/// A field or parameter Dart types as `RadioGroupRegistry<T>`, kept: the erased registry with
126/// its count.
127pub type RadioGroupRegistryRef<T> = Retained<AnyRadioGroupRegistry<T>>;
128
129impl<T: Clone + PartialEq + 'static> Copy for AnyRadioGroupRegistry<T> {}
130
131impl<T: Clone + PartialEq + 'static> PartialEq for AnyRadioGroupRegistry<T> {
132    fn eq(&self, other: &AnyRadioGroupRegistry<T>) -> bool {
133        self.id == other.id
134    }
135}
136
137impl<T: Clone + PartialEq + 'static> Eq for AnyRadioGroupRegistry<T> {}
138
139impl<T: Clone + PartialEq + 'static> Debug for AnyRadioGroupRegistry<T> {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
142    }
143}
144
145impl<T: Clone + PartialEq + 'static> AnyRadioGroupRegistry<T> {
146    /// The arena id behind this handle.
147    pub fn id(self) -> HandleId {
148        self.id
149    }
150
151    /// See [`RadioGroupRegistry::group_value`].
152    pub fn group_value(self, app: &App) -> Option<T> {
153        (self.vtable.group_value)(app, self.id)
154    }
155
156    /// See [`RadioGroupRegistry::register_client`].
157    pub fn register_client(self, app: &mut App, radio: AnyRadioClient<T>) {
158        (self.vtable.register_client)(app, self.id, radio);
159    }
160
161    /// See [`RadioGroupRegistry::unregister_client`].
162    pub fn unregister_client(self, app: &mut App, radio: AnyRadioClient<T>) {
163        (self.vtable.unregister_client)(app, self.id, radio);
164    }
165
166    /// See [`RadioGroupRegistry::on_changed`].
167    pub fn on_changed(self, app: &mut App, value: Option<T>) {
168        (self.vtable.on_changed)(app, self.id, value);
169    }
170
171    /// A reference while something still keeps the registry, `None` once it is freed or its
172    /// last keeper has let go; see [`Handle::upgrade`](waft_foundation::Handle::upgrade).
173    pub fn upgrade(self, app: &App) -> Option<RadioGroupRegistryRef<T>> {
174        Retained::upgrade(app, self)
175    }
176
177    /// A reference to a registry something is known to keep; see
178    /// [`Handle::keep`](waft_foundation::Handle::keep).
179    #[track_caller]
180    pub fn keep(self, app: &App) -> RadioGroupRegistryRef<T> {
181        Retained::keep(app, self)
182    }
183}
184
185// ---------------------------------------------------------------------------------------------
186// RadioClient
187
188/// The vtable of an erased [`AnyRadioClient`]: one `&'static` table per leaf type.
189struct RadioClientVTable<T: Clone + PartialEq + 'static> {
190    type_name: fn() -> &'static str,
191    tristate: fn(&App, HandleId) -> bool,
192    radio_value: fn(&App, HandleId) -> T,
193    enabled: fn(&App, HandleId) -> bool,
194    focus_node: fn(&App, HandleId) -> AnyFocusNode,
195}
196
197impl<T: Clone + PartialEq + 'static> RadioClientVTable<T> {
198    const fn of<L: RadioClient<T>>() -> RadioClientVTable<T> {
199        RadioClientVTable {
200            type_name: std::any::type_name::<L>,
201            tristate: |app, id| L::tristate(resolve(id), app),
202            radio_value: |app, id| L::radio_value(resolve(id), app),
203            enabled: |app, id| L::enabled(resolve(id), app),
204            focus_node: |app, id| L::focus_node(resolve(id), app),
205        }
206    }
207}
208
209/// The field Dart's `RadioClient` mixin declares; a client carries this bag under the field
210/// `radio_client` ([`radio_client_accessors!`](crate::radio_client_accessors)).
211pub struct RadioClientData<T: Clone + PartialEq + 'static> {
212    registry: Option<RadioGroupRegistryRef<T>>,
213}
214
215impl<T: Clone + PartialEq + 'static> RadioClientData<T> {
216    /// The bag of a freshly created client.
217    pub fn new() -> RadioClientData<T> {
218        RadioClientData { registry: None }
219    }
220}
221
222impl<T: Clone + PartialEq + 'static> Default for RadioClientData<T> {
223    fn default() -> RadioClientData<T> {
224        RadioClientData::new()
225    }
226}
227
228/// The accessors [`RadioClient`] asks for, for a struct whose bag is the field `radio_client`.
229///
230/// Takes the radio's value type, which the trait's own type parameter names.
231#[macro_export]
232macro_rules! radio_client_accessors {
233    ($value:ty) => {
234        fn radio_client_data(
235            self: ::waft_foundation::Handle<Self>,
236            app: &::waft_foundation::App,
237        ) -> &$crate::RadioClientData<$value> {
238            &app.get(self).radio_client
239        }
240
241        fn radio_client_data_mut(
242            self: ::waft_foundation::Handle<Self>,
243            app: &mut ::waft_foundation::App,
244        ) -> &mut $crate::RadioClientData<$value> {
245            &mut app.get_mut(self).radio_client
246        }
247    };
248}
249
250/// A client for a [`RadioGroupRegistry`].
251///
252/// This is typically mixed into a [`State`].
253///
254/// To register to a [`RadioGroupRegistry`], assign the registry with
255/// [`set_registry`](Self::set_registry).
256///
257/// To unregister from the previous [`RadioGroupRegistry`], either assign a different value or
258/// set it to `None`.
259pub trait RadioClient<T: Clone + PartialEq + 'static>: Sized + 'static {
260    /// Dart's `RadioClient` field, held under the field `radio_client`
261    /// ([`radio_client_accessors!`](crate::radio_client_accessors)).
262    fn radio_client_data(self: Handle<Self>, app: &App) -> &RadioClientData<T>;
263
264    /// See [`radio_client_data`](Self::radio_client_data).
265    fn radio_client_data_mut(self: Handle<Self>, app: &mut App) -> &mut RadioClientData<T>;
266
267    /// This client as the erased [`AnyRadioClient`] — what to pass where a Dart API takes a
268    /// `RadioClient<T>`.
269    fn as_radio_client(self: Handle<Self>) -> AnyRadioClient<T> {
270        AnyRadioClient {
271            id: self.id(),
272            vtable: const { &RadioClientVTable::<T>::of::<Self>() },
273        }
274    }
275
276    /// Whether this radio supports toggles.
277    ///
278    /// Used by the registry to provide additional features such as keyboard support.
279    fn tristate(self: Handle<Self>, app: &App) -> bool;
280
281    /// The value this radio represents.
282    ///
283    /// Used by the registry to provide additional features such as keyboard support.
284    fn radio_value(self: Handle<Self>, app: &App) -> T;
285
286    /// Whether this radio is enabled.
287    ///
288    /// If false, the registry skips this client when handling keyboard navigation.
289    fn enabled(self: Handle<Self>, app: &App) -> bool;
290
291    /// Focus node for this radio.
292    ///
293    /// Used by the registry to provide additional features such as keyboard support.
294    fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode;
295
296    /// The [`RadioGroupRegistry`] this client is registered to.
297    fn registry(self: Handle<Self>, app: &App) -> Option<AnyRadioGroupRegistry<T>> {
298        self.radio_client_data(app).registry.handle()
299    }
300
301    /// See [`registry`](Self::registry).
302    ///
303    /// Setting this property automatically registers with the new value and unregisters the old
304    /// one. This should be set to `None` on dispose.
305    fn set_registry(
306        self: Handle<Self>,
307        app: &mut App,
308        new_registry: Option<RadioGroupRegistryRef<T>>,
309    ) {
310        let registry = self.radio_client_data(app).registry.handle();
311        let new = new_registry.handle();
312        if registry != new
313            && let Some(registry) = registry
314        {
315            registry.unregister_client(app, self.as_radio_client());
316        }
317        self.radio_client_data_mut(app).registry = new_registry;
318        if let Some(new_registry) = new {
319            new_registry.register_client(app, self.as_radio_client());
320        }
321    }
322}
323
324/// Erased `RadioClient<T>`: one identity and a static vtable.
325///
326/// This is what a field or parameter Dart types as `RadioClient<T>` becomes.
327pub struct AnyRadioClient<T: Clone + PartialEq + 'static> {
328    id: HandleId,
329    vtable: &'static RadioClientVTable<T>,
330}
331
332impl<T: Clone + PartialEq + 'static> Clone for AnyRadioClient<T> {
333    fn clone(&self) -> AnyRadioClient<T> {
334        *self
335    }
336}
337
338impl<T: Clone + PartialEq + 'static> Copy for AnyRadioClient<T> {}
339
340impl<T: Clone + PartialEq + 'static> PartialEq for AnyRadioClient<T> {
341    fn eq(&self, other: &AnyRadioClient<T>) -> bool {
342        self.id == other.id
343    }
344}
345
346impl<T: Clone + PartialEq + 'static> Eq for AnyRadioClient<T> {}
347
348impl<T: Clone + PartialEq + 'static> Debug for AnyRadioClient<T> {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
351    }
352}
353
354impl<T: Clone + PartialEq + 'static> AnyRadioClient<T> {
355    /// The arena id behind this handle.
356    pub fn id(self) -> HandleId {
357        self.id
358    }
359
360    /// See [`RadioClient::tristate`].
361    pub fn tristate(self, app: &App) -> bool {
362        (self.vtable.tristate)(app, self.id)
363    }
364
365    /// See [`RadioClient::radio_value`].
366    pub fn radio_value(self, app: &App) -> T {
367        (self.vtable.radio_value)(app, self.id)
368    }
369
370    /// See [`RadioClient::enabled`].
371    pub fn enabled(self, app: &App) -> bool {
372        (self.vtable.enabled)(app, self.id)
373    }
374
375    /// See [`RadioClient::focus_node`].
376    pub fn focus_node(self, app: &App) -> AnyFocusNode {
377        (self.vtable.focus_node)(app, self.id)
378    }
379}
380
381// ---------------------------------------------------------------------------------------------
382// RadioGroup
383
384/// A group for radios.
385///
386/// This widget treats all radios in the subtree with the same type `T` as a group. Radios with
387/// different types are not included in the group.
388///
389/// This widget handles the group value for the radios in the subtree with the same value type.
390///
391/// Using this widget also provides keyboard navigation for the radio buttons that matches
392/// [APG](https://www.w3.org/WAI/ARIA/apg/patterns/radio/).
393///
394/// The keyboard behaviors are:
395/// * Tab and Shift+Tab: moves focus into and out of the radio group. When focus moves into a
396///   radio group and a radio button is selected, focus is set on the selected button.
397///   Otherwise, it focuses the first radio button in reading order.
398/// * Space: toggle the selection on the focused radio button.
399/// * Right and down arrow key: move selection to the next radio button in the group in reading
400///   order.
401/// * Left and up arrow key: move selection to the previous radio button in the group in reading
402///   order.
403///
404/// Arrow keys will wrap around if they reach the first or last radio in the group.
405pub struct RadioGroup<T: Clone + PartialEq + 'static> {
406    /// See [`Widget::key`](crate::Widget::key).
407    pub key: Option<KeyRef>,
408
409    /// The selected value under this radio group.
410    ///
411    /// A radio under this radio group whose value equals this value will be selected.
412    pub group_value: Option<T>,
413
414    /// Called when selection has changed.
415    ///
416    /// The value can be `None` when unselecting a radio with `tristate` set to true.
417    pub on_changed: ValueChanged<Option<T>>,
418
419    /// The widget below this widget in the tree.
420    pub child: WidgetRef,
421}
422
423impl<T: Clone + PartialEq + 'static> RadioGroup<T> {
424    /// Creates a radio group; Dart's optional `groupValue` argument is the setter.
425    ///
426    /// The `on_changed` callback is called when the selection has changed in the subtree
427    /// radios.
428    #[cfg_attr(debug_assertions, track_caller)]
429    pub fn new<K>(on_changed: ValueChanged<Option<T>>, child: impl IntoWidget<K>) -> RadioGroup<T> {
430        RadioGroup {
431            key: None,
432            group_value: None,
433            on_changed,
434            child: child.into_widget(),
435        }
436    }
437
438    /// Dart `RadioGroup(key:)`.
439    pub fn key(mut self, key: KeyRef) -> RadioGroup<T> {
440        self.key = Some(key);
441        self
442    }
443
444    /// Dart `RadioGroup(groupValue:)`.
445    pub fn group_value(mut self, group_value: T) -> RadioGroup<T> {
446        self.group_value = Some(group_value);
447        self
448    }
449
450    /// Gets the [`RadioGroupRegistry`] from above the context.
451    ///
452    /// This registers a dependency on the context so that it rebuilds if the registry has
453    /// changed or its [`RadioGroupRegistry::group_value`] has changed.
454    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<RadioGroupRegistryRef<T>> {
455        let state = context
456            .depend_on_inherited_widget_of_exact_type::<RadioGroupStateScope<T>>(app)
457            .map(|scope| scope.state)?;
458        state.as_radio_group_registry().upgrade(app)
459    }
460}
461
462impl<T: Clone + PartialEq + 'static> Debug for RadioGroup<T> {
463    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464        f.debug_struct("RadioGroup").finish_non_exhaustive()
465    }
466}
467
468impl<T: Clone + PartialEq + 'static> StatefulWidget for RadioGroup<T> {
469    type State = RadioGroupState<T>;
470
471    fn key(&self) -> Option<&KeyRef> {
472        self.key.as_ref()
473    }
474
475    fn create_state(&self) -> RadioGroupState<T> {
476        RadioGroupState {
477            state: StateData::new(),
478            radio_group_shortcut_manager: None,
479            policy: None,
480            radios: Vec::new(),
481        }
482    }
483}
484
485/// Dart's `_RadioGroupState`.
486pub struct RadioGroupState<T: Clone + PartialEq + 'static> {
487    state: StateData<RadioGroup<T>>,
488    radio_group_shortcut_manager: Option<Ref<RadioGroupShortcutManager<T>>>,
489    policy: Option<Ref<SkipUnselectedRadioPolicy<T>>>,
490    radios: Vec<AnyRadioClient<T>>,
491}
492
493impl<T: Clone + PartialEq + 'static> RadioGroupState<T> {
494    /// Dart's `_radioGroupShortcuts`, built once the state has an `App`.
495    fn radio_group_shortcuts(self: Handle<Self>) -> ShortcutMap {
496        let select_previous = || {
497            Rc::new(VoidCallbackIntent::new(Listener::handle_method(
498                self,
499                RadioGroupState::<T>::select_previous_radio,
500            ))) as IntentRef
501        };
502        let select_next = || {
503            Rc::new(VoidCallbackIntent::new(Listener::handle_method(
504                self,
505                RadioGroupState::<T>::select_next_radio,
506            ))) as IntentRef
507        };
508        vec![
509            (
510                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_LEFT))
511                    as ShortcutActivatorRef,
512                select_previous(),
513            ),
514            (
515                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_RIGHT))
516                    as ShortcutActivatorRef,
517                select_next(),
518            ),
519            (
520                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN))
521                    as ShortcutActivatorRef,
522                select_next(),
523            ),
524            (
525                Rc::new(SingleActivator::new(LogicalKeyboardKey::ARROW_UP)) as ShortcutActivatorRef,
526                select_previous(),
527            ),
528            (
529                Rc::new(SingleActivator::new(LogicalKeyboardKey::SPACE)) as ShortcutActivatorRef,
530                Rc::new(VoidCallbackIntent::new(Listener::handle_method(
531                    self,
532                    RadioGroupState::<T>::toggle_focused_radio,
533                ))) as IntentRef,
534            ),
535        ]
536    }
537
538    /// The radios registered with this group, in registration order.
539    pub fn radios(self: Handle<Self>, app: &App) -> Vec<AnyRadioClient<T>> {
540        app.get(self).radios.clone()
541    }
542
543    /// The first registered radio whose focus node has focus, if any.
544    fn focused_radio(self: Handle<Self>, app: &mut App) -> Option<AnyRadioClient<T>> {
545        self.radios(app)
546            .into_iter()
547            .find(|radio| radio.focus_node(app).has_focus(app))
548    }
549
550    fn toggle_focused_radio(self: Handle<Self>, app: &mut App) {
551        let Some(radio) = self.focused_radio(app) else {
552            return;
553        };
554        let value = radio.radio_value(app);
555        if Some(&value) != self.widget(app).group_value.as_ref() {
556            self.on_changed(app, Some(value));
557            return;
558        }
559
560        if radio.tristate(app) {
561            self.on_changed(app, None);
562        }
563    }
564
565    fn select_next_radio(self: Handle<Self>, app: &mut App) {
566        self.select_radio_in_direction(app, true);
567    }
568
569    fn select_previous_radio(self: Handle<Self>, app: &mut App) {
570        self.select_radio_in_direction(app, false);
571    }
572
573    fn select_radio_in_direction(self: Handle<Self>, app: &mut App, forward: bool) {
574        if self.radios(app).len() < 2 {
575            return;
576        }
577        let Some(current_focus) = self.focused_radio(app).map(|radio| radio.focus_node(app)) else {
578            // The focused node is either a non-interactive radio or another control.
579            return;
580        };
581        let enabled: Vec<AnyFocusNode> = self
582            .radios(app)
583            .into_iter()
584            .filter(|radio| radio.enabled(app))
585            .map(|radio| radio.focus_node(app))
586            .collect();
587        let sorted = ReadingOrderTraversalPolicy::sort(app, enabled);
588        debug_assert!(!sorted.is_empty());
589        let nodes_in_effective_order: Vec<AnyFocusNode> = if forward {
590            sorted
591        } else {
592            sorted.into_iter().rev().collect()
593        };
594
595        let next_focus = nodes_in_effective_order
596            .iter()
597            .position(|node| *node == current_focus)
598            .and_then(|index| nodes_in_effective_order.get(index + 1))
599            .copied()
600            // Current focus is at the end, the next focus should wrap around.
601            .or_else(|| nodes_in_effective_order.first().copied())
602            .expect("the sorted list is not empty");
603        let radio_to_select = self
604            .radios(app)
605            .into_iter()
606            .find(|radio| radio.focus_node(app) == next_focus)
607            .expect("the next node belongs to a registered radio");
608        let value = radio_to_select.radio_value(app);
609        self.on_changed(app, Some(value));
610        next_focus.request_focus(app, None);
611    }
612}
613
614impl<T: Clone + PartialEq + 'static> RadioGroupRegistry<T> for RadioGroupState<T> {
615    fn group_value(self: Handle<Self>, app: &App) -> Option<T> {
616        self.widget(app).group_value.clone()
617    }
618
619    fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>) {
620        let radios = &mut app.get_mut(self).radios;
621        if !radios.contains(&radio) {
622            radios.push(radio);
623        }
624    }
625
626    fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<T>) {
627        app.get_mut(self).radios.retain(|entry| *entry != radio);
628    }
629
630    fn on_changed(self: Handle<Self>, app: &mut App, value: Option<T>) {
631        let on_changed = Rc::clone(&self.widget(app).on_changed);
632        on_changed(app, value);
633    }
634}
635
636impl<T: Clone + PartialEq + 'static> State for RadioGroupState<T> {
637    type Widget = RadioGroup<T>;
638    crate::state_accessors!();
639
640    fn init_state(self: Handle<Self>, app: &mut App) {
641        let shortcuts = self.radio_group_shortcuts();
642        let manager = RadioGroupShortcutManager::new(app, self);
643        manager.set_shortcuts(app, shortcuts);
644        let policy = SkipUnselectedRadioPolicy::new(app, self);
645        let this = app.get_mut(self);
646        this.radio_group_shortcut_manager = Some(manager);
647        this.policy = Some(policy);
648    }
649
650    fn dispose(self: Handle<Self>, app: &mut App) {
651        if let Some(manager) = app.get(self).radio_group_shortcut_manager.handle() {
652            ChangeNotifierData::dispose(app, manager);
653        }
654    }
655
656    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
657        let manager: ShortcutManagerRef = app
658            .get(self)
659            .radio_group_shortcut_manager
660            .as_ref()
661            .expect("created in init_state")
662            .erase();
663        let policy: FocusTraversalPolicyRef = app
664            .get(self)
665            .policy
666            .as_ref()
667            .expect("created in init_state")
668            .erase();
669        let typed_policy = app
670            .get(self)
671            .policy
672            .handle()
673            .expect("created in init_state");
674        let group_value = self.widget(app).group_value.clone();
675        typed_policy.set_group_value(app, group_value.clone());
676        let child = self.widget(app).child.clone();
677        Semantics::new()
678            .container(true)
679            .role(SemanticsRole::RadioGroup)
680            .child(Shortcuts::manager(
681                manager,
682                FocusTraversalGroup::new(RadioGroupStateScope {
683                    state: self,
684                    group_value,
685                    child,
686                })
687                .policy(policy),
688            ))
689            .into_widget()
690    }
691}
692
693/// Dart's `_RadioGroupShortcutManager`: a [`ShortcutManagerBase`] that ignores a key event
694/// while no radio in its group has focus.
695pub struct RadioGroupShortcutManager<T: Clone + PartialEq + 'static> {
696    change_notifier: ChangeNotifierData,
697    shortcut_manager: ShortcutManagerData,
698    state: Handle<RadioGroupState<T>>,
699}
700
701impl<T: Clone + PartialEq + 'static> RadioGroupShortcutManager<T> {
702    fn new(app: &mut App, state: Handle<RadioGroupState<T>>) -> Ref<RadioGroupShortcutManager<T>> {
703        app.create(RadioGroupShortcutManager {
704            change_notifier: ChangeNotifierData::new(),
705            shortcut_manager: ShortcutManagerData::new(),
706            state,
707        })
708    }
709}
710
711impl<T: Clone + PartialEq + 'static> ShortcutManagerBase for RadioGroupShortcutManager<T> {
712    crate::shortcut_manager_accessors!();
713
714    fn handle_keypress(
715        self: Handle<Self>,
716        app: &mut App,
717        context: BuildContext,
718        event: &KeyEvent,
719    ) -> KeyEventResult {
720        let state = app.get(self).state;
721        let radio_has_focus = state
722            .radios(app)
723            .into_iter()
724            .any(|radio| radio.focus_node(app).has_focus(app));
725        if !radio_has_focus {
726            // Ignore the event if no radio is focused. This prevents this handler from
727            // unintentionally consuming an event meant for a non-radio widget that currently
728            // has focus.
729            return KeyEventResult::Ignored;
730        }
731        ShortcutManagerKeypress::handle_keypress(self, app, context, event)
732    }
733}
734
735impl<T: Clone + PartialEq + 'static> ChangeNotifier for RadioGroupShortcutManager<T> {
736    fn change_notifier_data(&self) -> &ChangeNotifierData {
737        &self.change_notifier
738    }
739
740    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
741        &mut self.change_notifier
742    }
743}
744
745/// Dart's `_RadioGroupStateScope`.
746pub struct RadioGroupStateScope<T: Clone + PartialEq + 'static> {
747    state: Handle<RadioGroupState<T>>,
748    /// The group value is part of the scope so that dependents are notified when it changes.
749    group_value: Option<T>,
750    child: WidgetRef,
751}
752
753impl<T: Clone + PartialEq + 'static> Debug for RadioGroupStateScope<T> {
754    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
755        f.debug_struct("RadioGroupStateScope")
756            .field("state", &self.state)
757            .finish_non_exhaustive()
758    }
759}
760
761impl<T: Clone + PartialEq + 'static> InheritedWidget for RadioGroupStateScope<T> {
762    fn child(&self) -> &WidgetRef {
763        &self.child
764    }
765
766    fn update_should_notify(&self, old_widget: &RadioGroupStateScope<T>) -> bool {
767        self.state != old_widget.state || self.group_value != old_widget.group_value
768    }
769}
770
771/// A traversal policy that is the same as [`ReadingOrderTraversalPolicy`] except that it skips
772/// the nodes of unselected radio buttons if there is a selected radio button.
773///
774/// If none of the radios is selected, this defaults to [`ReadingOrderTraversalPolicy`] for all
775/// nodes.
776///
777/// This policy ensures that tabbing into a radio group only focuses the currently selected
778/// radio button and prevents focus from reaching unselected ones.
779pub struct SkipUnselectedRadioPolicy<T: Clone + PartialEq + 'static> {
780    policy: FocusTraversalPolicyData,
781    directional: DirectionalFocusTraversalPolicyMixinData,
782    state: Handle<RadioGroupState<T>>,
783    group_value: Option<T>,
784}
785
786impl<T: Clone + PartialEq + 'static> SkipUnselectedRadioPolicy<T> {
787    fn new(app: &mut App, state: Handle<RadioGroupState<T>>) -> Ref<SkipUnselectedRadioPolicy<T>> {
788        app.create(SkipUnselectedRadioPolicy {
789            policy: FocusTraversalPolicyData::new(),
790            directional: DirectionalFocusTraversalPolicyMixinData::new(),
791            state,
792            group_value: None,
793        })
794    }
795
796    /// The group value the policy compares each radio against; Dart passes it to the
797    /// constructor of the policy it builds every frame.
798    fn set_group_value(self: Handle<Self>, app: &mut App, group_value: Option<T>) {
799        app.get_mut(self).group_value = group_value;
800    }
801
802    fn radio_selected(self: Handle<Self>, app: &App, radio: AnyRadioClient<T>) -> bool {
803        Some(&radio.radio_value(app)) == app.get(self).group_value.as_ref()
804    }
805}
806
807impl<T: Clone + PartialEq + 'static> FocusTraversalPolicy for SkipUnselectedRadioPolicy<T> {
808    crate::focus_traversal_policy_accessors!();
809    crate::directional_focus_traversal_policy_overrides!();
810
811    fn sort_descendants(
812        self: Handle<Self>,
813        app: &mut App,
814        descendants: Vec<AnyFocusNode>,
815        current_node: AnyFocusNode,
816    ) -> Vec<AnyFocusNode> {
817        let nodes_in_read_order = ReadingOrderTraversalPolicy::sort(app, descendants.clone());
818        let radios = app.get(self).state.radios(app);
819        let mut selected = radios
820            .iter()
821            .copied()
822            .find(|radio| self.radio_selected(app, *radio));
823
824        if selected.is_none() {
825            // None of the radios is selected. Select the first radio in read order.
826            for node in &nodes_in_read_order {
827                selected = radios
828                    .iter()
829                    .copied()
830                    .find(|radio| radio.focus_node(app) == *node);
831                if selected.is_some() {
832                    break;
833                }
834            }
835        }
836
837        let Some(selected) = selected else {
838            // None of the radios is selected or focusable, defaults to reading order.
839            return nodes_in_read_order;
840        };
841
842        // Nodes that are not selected AND not currently focused, since we can't remove the
843        // focused node from the sorted result.
844        let node_to_skip: Vec<AnyFocusNode> = radios
845            .iter()
846            .copied()
847            .filter(|radio| selected != *radio && radio.focus_node(app) != current_node)
848            .map(|radio| radio.focus_node(app))
849            .collect();
850        let skips_non_selected: Vec<AnyFocusNode> = descendants
851            .into_iter()
852            .filter(|node| !node_to_skip.contains(node))
853            .collect();
854        ReadingOrderTraversalPolicy::sort(app, skips_non_selected)
855    }
856}
857
858impl<T: Clone + PartialEq + 'static> DirectionalFocusTraversalPolicyMixin
859    for SkipUnselectedRadioPolicy<T>
860{
861    fn directional_data(
862        self: Handle<Self>,
863        app: &App,
864    ) -> &DirectionalFocusTraversalPolicyMixinData {
865        &app.get(self).directional
866    }
867
868    fn directional_data_mut(
869        self: Handle<Self>,
870        app: &mut App,
871    ) -> &mut DirectionalFocusTraversalPolicyMixinData {
872        &mut app.get_mut(self).directional
873    }
874}
875
876#[cfg(test)]
877mod tests {
878    use std::any::TypeId;
879    use std::cell::RefCell;
880    use std::collections::HashMap;
881    use std::time::Duration;
882
883    use waft_embedder::{Rect, TextDirection};
884    use waft_services::{HardwareKeyboard, KeyDownEvent, LogicalKeyboardKey, PhysicalKeyboardKey};
885
886    use super::*;
887    use crate::testing::{WidgetTester, test_widgets};
888    use crate::widgets::actions::{Actions, VoidCallbackAction};
889    use crate::widgets::basic::{Directionality, Positioned, SizedBox, Stack};
890    use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf, primary_focus};
891    use crate::widgets::focus_scope::Focus;
892
893    /// A radio that only registers with the group: enough to drive the registry and the arrow
894    /// keys, standing in for `RawRadio`.
895    #[derive(Debug)]
896    struct TestRadio {
897        value: u32,
898        enabled: bool,
899        rect: Rect,
900    }
901
902    impl StatefulWidget for TestRadio {
903        type State = TestRadioState;
904
905        fn create_state(&self) -> TestRadioState {
906            TestRadioState {
907                state: StateData::new(),
908                radio_client: RadioClientData::new(),
909                focus_node: None,
910            }
911        }
912    }
913
914    struct TestRadioState {
915        state: StateData<TestRadio>,
916        radio_client: RadioClientData<u32>,
917        focus_node: Option<Ref<FocusNode>>,
918    }
919
920    impl TestRadioState {
921        fn node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
922            app.get(self)
923                .focus_node
924                .handle()
925                .expect("created in init_state")
926        }
927    }
928
929    impl RadioClient<u32> for TestRadioState {
930        crate::radio_client_accessors!(u32);
931
932        fn tristate(self: Handle<Self>, _app: &App) -> bool {
933            false
934        }
935
936        fn radio_value(self: Handle<Self>, app: &App) -> u32 {
937            self.widget(app).value
938        }
939
940        fn enabled(self: Handle<Self>, app: &App) -> bool {
941            self.widget(app).enabled
942        }
943
944        fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode {
945            self.node(app).as_node()
946        }
947    }
948
949    impl State for TestRadioState {
950        type Widget = TestRadio;
951        crate::state_accessors!();
952
953        fn init_state(self: Handle<Self>, app: &mut App) {
954            let node = FocusNode::new(app);
955            let label = format!("radio {}", self.widget(app).value);
956            node.as_node().set_debug_label(app, Some(label));
957            app.get_mut(self).focus_node = Some(node);
958        }
959
960        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
961            let context = self.context(app);
962            let registry = if self.widget(app).enabled {
963                RadioGroup::<u32>::maybe_of(app, context)
964            } else {
965                None
966            };
967            self.set_registry(app, registry);
968        }
969
970        fn dispose(self: Handle<Self>, app: &mut App) {
971            self.set_registry(app, None);
972            self.node(app).as_node().dispose(app);
973        }
974
975        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
976            let node: crate::widgets::focus_manager::FocusNodeRef = app
977                .get(self)
978                .focus_node
979                .as_ref()
980                .expect("created in init_state")
981                .erase();
982            let enabled = self.widget(app).enabled;
983            let rect = self.widget(app).rect;
984            Positioned::from_rect(
985                rect,
986                Focus::new(SizedBox::expand())
987                    .focus_node(node)
988                    .can_request_focus(enabled),
989            )
990            .into_widget()
991        }
992    }
993
994    /// The group's state, reached through a `GlobalKey`, plus what `on_changed` recorded.
995    struct GroupHarness {
996        state: Handle<RadioGroupState<u32>>,
997        changes: Rc<RefCell<Vec<Option<u32>>>>,
998    }
999
1000    fn radio(value: u32, enabled: bool, rect: Rect) -> WidgetRef {
1001        TestRadio {
1002            value,
1003            enabled,
1004            rect,
1005        }
1006        .into_widget()
1007    }
1008
1009    /// Three radios side by side in reading order, under a group with `group_value`.
1010    fn mount_group(
1011        tester: &mut WidgetTester,
1012        group_value: Option<u32>,
1013        enabled: [bool; 3],
1014    ) -> GroupHarness {
1015        let mut app = tester.cell.borrow_mut();
1016        let changes: Rc<RefCell<Vec<Option<u32>>>> = Rc::default();
1017        let recorded = Rc::clone(&changes);
1018        let key = crate::framework::GlobalKey::new();
1019        let children = vec![
1020            radio(0, enabled[0], Rect::from_ltwh(0.0, 0.0, 40.0, 20.0)),
1021            radio(1, enabled[1], Rect::from_ltwh(50.0, 0.0, 40.0, 20.0)),
1022            radio(2, enabled[2], Rect::from_ltwh(100.0, 0.0, 40.0, 20.0)),
1023        ];
1024        let mut group = RadioGroup::<u32>::new(
1025            Rc::new(move |_app, value| recorded.borrow_mut().push(value)),
1026            Stack::new().children(children),
1027        )
1028        .key(key.clone().into());
1029        if let Some(value) = group_value {
1030            group = group.group_value(value);
1031        }
1032        let void_callback_action = VoidCallbackAction::new(&mut app);
1033        drop(app);
1034        tester.pump_widget(
1035            Directionality::new(
1036                TextDirection::Ltr,
1037                Actions::new(
1038                    HashMap::from([(
1039                        TypeId::of::<VoidCallbackIntent>(),
1040                        void_callback_action.erase(),
1041                    )]),
1042                    group,
1043                ),
1044            )
1045            .into_widget(),
1046        );
1047        let app = tester.cell.borrow();
1048        let state = key
1049            .current_state::<RadioGroupState<u32>>(&app)
1050            .expect("the group is mounted");
1051        drop(app);
1052        GroupHarness { state, changes }
1053    }
1054
1055    fn arrow_down(app: &mut App) -> bool {
1056        let keyboard = HardwareKeyboard::instance(app);
1057        let event = KeyEvent::Down(KeyDownEvent::new(
1058            PhysicalKeyboardKey::ARROW_DOWN,
1059            LogicalKeyboardKey::ARROW_DOWN,
1060            Duration::ZERO,
1061        ));
1062        keyboard.handle_key_event(app, &event)
1063    }
1064
1065    #[test]
1066    fn a_radio_group_registers_every_client_below_it() {
1067        test_widgets(|tester| {
1068            let harness = mount_group(tester, None, [true, true, true]);
1069            let values: Vec<u32> = harness
1070                .state
1071                .radios(&tester.cell.borrow())
1072                .into_iter()
1073                .map(|radio| radio.radio_value(&tester.cell.borrow()))
1074                .collect();
1075            assert_eq!(values, [0, 1, 2]);
1076            assert_eq!(harness.state.group_value(&tester.cell.borrow()), None);
1077
1078            // Reported selections reach the widget's callback.
1079            let registry = harness.state.as_radio_group_registry();
1080            registry.on_changed(&mut tester.cell.borrow_mut(), Some(2));
1081            assert_eq!(*harness.changes.borrow(), [Some(2)]);
1082        });
1083
1084        // A disabled radio does not register.
1085        test_widgets(|tester| {
1086            let disabled = mount_group(tester, Some(1), [true, false, true]);
1087            let values: Vec<u32> = disabled
1088                .state
1089                .radios(&tester.cell.borrow())
1090                .into_iter()
1091                .map(|radio| radio.radio_value(&tester.cell.borrow()))
1092                .collect();
1093            assert_eq!(values, [0, 2]);
1094            assert_eq!(disabled.state.group_value(&tester.cell.borrow()), Some(1));
1095        });
1096    }
1097
1098    #[test]
1099    fn an_arrow_key_moves_the_selection_to_the_next_radio() {
1100        test_widgets(|tester| {
1101            let harness = mount_group(tester, Some(0), [true, true, true]);
1102            let first =
1103                harness.state.radios(&tester.cell.borrow())[0].focus_node(&tester.cell.borrow());
1104            first.request_focus(&mut tester.cell.borrow_mut(), None);
1105            tester.cell.borrow_mut().drain_microtasks();
1106            assert_eq!(primary_focus(&mut tester.cell.borrow_mut()), Some(first));
1107
1108            assert!(
1109                arrow_down(&mut tester.cell.borrow_mut()),
1110                "the group handled the key"
1111            );
1112            tester.cell.borrow_mut().drain_microtasks();
1113            assert_eq!(*harness.changes.borrow(), [Some(1)]);
1114            let second =
1115                harness.state.radios(&tester.cell.borrow())[1].focus_node(&tester.cell.borrow());
1116            assert_eq!(primary_focus(&mut tester.cell.borrow_mut()), Some(second));
1117
1118            // The last radio wraps around to the first.
1119            let third =
1120                harness.state.radios(&tester.cell.borrow())[2].focus_node(&tester.cell.borrow());
1121            third.request_focus(&mut tester.cell.borrow_mut(), None);
1122            tester.cell.borrow_mut().drain_microtasks();
1123            assert!(arrow_down(&mut tester.cell.borrow_mut()));
1124            tester.cell.borrow_mut().drain_microtasks();
1125            assert_eq!(*harness.changes.borrow(), [Some(1), Some(0)]);
1126        });
1127    }
1128
1129    #[test]
1130    fn an_arrow_key_is_ignored_while_no_radio_has_focus() {
1131        test_widgets(|tester| {
1132            let harness = mount_group(tester, Some(0), [true, true, true]);
1133            assert!(
1134                !arrow_down(&mut tester.cell.borrow_mut()),
1135                "the manager ignores the event when the focus is elsewhere"
1136            );
1137            assert!(harness.changes.borrow().is_empty());
1138        });
1139    }
1140
1141    #[test]
1142    fn the_traversal_policy_skips_the_unselected_radios() {
1143        test_widgets(|tester| {
1144            let harness = mount_group(tester, Some(1), [true, true, true]);
1145            let nodes: Vec<AnyFocusNode> = harness
1146                .state
1147                .radios(&tester.cell.borrow())
1148                .into_iter()
1149                .map(|radio| radio.focus_node(&tester.cell.borrow()))
1150                .collect();
1151            let policy = tester
1152                .cell
1153                .borrow()
1154                .get(harness.state)
1155                .policy
1156                .handle()
1157                .expect("created in init_state");
1158            let sorted =
1159                policy.sort_descendants(&mut tester.cell.borrow_mut(), nodes.clone(), nodes[0]);
1160            assert_eq!(
1161                sorted,
1162                vec![nodes[0], nodes[1]],
1163                "only the selected radio and the currently focused one stay"
1164            );
1165        });
1166    }
1167}