Skip to main content

waft_widgets/widgets/
raw_radio.rs

1//! Flutter counterpart: `widgets/raw_radio.dart`.
2//!
3//! [`RawRadioState`] is a [`ToggleableStateMixin`] and a [`RadioClient`]: the toggle's
4//! animations and gestures come from the mixin, the selection from the [`RadioGroupRegistry`]
5//! it registers with. A design system draws the radio in [`RawRadio::builder`], which receives
6//! the state as an [`AnyToggleableState`].
7
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10
11use waft_embedder::TargetPlatform;
12use waft_foundation::{App, Handle, Ref, ValueChanged};
13use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
14use waft_services::MouseCursorRef;
15
16use crate::framework::{
17    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
18};
19use crate::widgets::basic::Semantics;
20use crate::widgets::focus_manager::{AnyFocusNode, FocusNodeRef};
21use crate::widgets::localizations::WidgetsLocalizations;
22use crate::widgets::radio_group::{RadioClient, RadioClientData, RadioGroupRegistryRef};
23use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
24use crate::widgets::toggleable::{
25    AnyToggleableState, ToggleableStateMixin, ToggleableStateMixinData,
26};
27use crate::widgets::widget_state::WidgetStatePropertyRef;
28
29/// Signature for [`RawRadio::builder`].
30///
31/// The builder can use `state` to determine the state of the radio and build
32/// the visual.
33///
34/// See [`ToggleableStateMixin::build_toggleable_with_child`].
35pub type RadioBuilder = Rc<dyn Fn(&mut App, BuildContext, AnyToggleableState) -> WidgetRef>;
36
37/// A Radio button that provides basic radio functionalities.
38///
39/// Provide the `builder` to draw UI for radio.
40///
41/// See [`ToggleableStateMixin::build_toggleable_with_child`].
42///
43/// This widget allows selection between a number of mutually exclusive values.
44/// When one radio button in a group is selected, the other radio buttons in the
45/// group cease to be selected. The values are of type `T`, the type parameter
46/// of the radio class. Enums are commonly used for this purpose.
47///
48/// The radio relies on [`group_registry`](Self::group_registry) to maintains the state for
49/// selection. If use in conjunction with a `RadioGroup` widget, use `RadioGroup::maybe_of` to
50/// get the group registry from the context.
51///
52/// If [`enabled`](Self::enabled) is false, the radio will not be interactive.
53///
54/// See also:
55///
56///  * `Radio`, which uses this widget to build a Material styled radio button.
57///  * `CupertinoRadio`, which uses this widget to build a Cupertino styled radio button.
58#[derive(Clone)]
59pub struct RawRadio<T: Clone + PartialEq + 'static> {
60    pub key: Option<KeyRef>,
61    /// The value represented by this radio button.
62    pub value: T,
63    /// The cursor for a mouse pointer when it enters or is hovering over the
64    /// widget.
65    ///
66    /// If [`mouse_cursor`](Self::mouse_cursor) is a `WidgetStateMouseCursor`,
67    /// `WidgetStateProperty::resolve` is used for the following `WidgetState`s:
68    ///
69    ///  * `WidgetState::Selected`.
70    ///  * `WidgetState::Hovered`.
71    ///  * `WidgetState::Focused`.
72    ///  * `WidgetState::Disabled`.
73    pub mouse_cursor: WidgetStatePropertyRef<MouseCursorRef>,
74    /// Set to true if this radio button is allowed to be returned to an
75    /// indeterminate state by selecting it again when selected.
76    ///
77    /// To indicate returning to an indeterminate state, `RadioGroup::on_changed`
78    /// of the `RadioGroup` above the widget tree will be called with null.
79    ///
80    /// If true, `RadioGroup::on_changed` is called with [`value`](Self::value) when selected
81    /// while `RadioGroup::group_value` != [`value`](Self::value), and with null when selected
82    /// again while `RadioGroup::group_value` == [`value`](Self::value).
83    ///
84    /// If false, `RadioGroup::on_changed` will be called with [`value`](Self::value) when it is
85    /// selected while `RadioGroup::group_value` != [`value`](Self::value), and only by
86    /// selecting another radio button in the group (i.e. changing the value of
87    /// `RadioGroup::group_value`) can this radio button be unselected.
88    ///
89    /// The default is false.
90    pub toggleable: bool,
91    /// The focus node of the radio.
92    pub focus_node: FocusNodeRef,
93    /// True if this widget will be selected as the initial focus when no other node in its
94    /// scope is currently focused.
95    pub autofocus: bool,
96    /// The builder for the radio button visual.
97    ///
98    /// Use the input `state` to determine the current state of the radio.
99    ///
100    /// See [`ToggleableStateMixin::build_toggleable_with_child`].
101    pub builder: RadioBuilder,
102    /// Whether this widget is enabled.
103    pub enabled: bool,
104    /// The registry this radio registers to.
105    ///
106    /// The radio relies on [`group_registry`](Self::group_registry) to maintains the state for
107    /// selection. If use in conjunction with a `RadioGroup` widget, use
108    /// `RadioGroup::maybe_of` to get the group registry from the context.
109    pub group_registry: Option<RadioGroupRegistryRef<T>>,
110}
111
112impl<T: Clone + PartialEq + 'static> RawRadio<T> {
113    /// Creates a radio button.
114    ///
115    /// If [`enabled`](Self::enabled) is true, the [`group_registry`](Self::group_registry) must
116    /// not be null.
117    #[allow(clippy::too_many_arguments)]
118    pub fn new(
119        value: T,
120        mouse_cursor: WidgetStatePropertyRef<MouseCursorRef>,
121        toggleable: bool,
122        focus_node: FocusNodeRef,
123        autofocus: bool,
124        group_registry: Option<RadioGroupRegistryRef<T>>,
125        enabled: bool,
126        builder: RadioBuilder,
127    ) -> RawRadio<T> {
128        debug_assert!(
129            !enabled || group_registry.is_some(),
130            "an enabled raw radio must have a registry"
131        );
132        RawRadio {
133            key: None,
134            value,
135            mouse_cursor,
136            toggleable,
137            focus_node,
138            autofocus,
139            builder,
140            enabled,
141            group_registry,
142        }
143    }
144
145    /// Dart `RawRadio(key:)`.
146    pub fn key(mut self, key: KeyRef) -> RawRadio<T> {
147        self.key = Some(key);
148        self
149    }
150}
151
152impl<T: Clone + PartialEq + 'static> Debug for RawRadio<T> {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.debug_struct("RawRadio")
155            .field("enabled", &self.enabled)
156            .field("toggleable", &self.toggleable)
157            .field("autofocus", &self.autofocus)
158            .field("group_registry", &self.group_registry)
159            .finish_non_exhaustive()
160    }
161}
162
163impl<T: Clone + PartialEq + 'static> StatefulWidget for RawRadio<T> {
164    type State = RawRadioState<T>;
165
166    fn key(&self) -> Option<&KeyRef> {
167        self.key.as_ref()
168    }
169
170    fn create_state(&self) -> RawRadioState<T> {
171        RawRadioState {
172            state: StateData::new(),
173            ticker_provider: TickerProviderStateMixinData::new(),
174            toggleable: ToggleableStateMixinData::new(),
175            radio_client: RadioClientData::new(),
176        }
177    }
178}
179
180/// Dart's `_RawRadioState`; public because [`RawRadio`]'s `StatefulWidget::State` names it.
181pub struct RawRadioState<T: Clone + PartialEq + 'static> {
182    state: StateData<RawRadio<T>>,
183    ticker_provider: TickerProviderStateMixinData,
184    toggleable: ToggleableStateMixinData,
185    radio_client: RadioClientData<T>,
186}
187
188impl<T: Clone + PartialEq + 'static> RawRadioState<T> {
189    /// Handle selection status changed.
190    ///
191    /// if `selected` is false, nothing happens.
192    ///
193    /// if `selected` is true, select this radio. i.e. `Radio::on_changed` is called
194    /// with `Radio::value`. This also updates the group value in `RadioGroup` if it
195    /// is in use.
196    ///
197    /// if `selected` is null, unselect this radio. Same as `selected` is true
198    /// except group value is set to null.
199    fn handle_changed(self: Handle<Self>, app: &mut App, selected: Option<bool>) {
200        let registry = RadioClient::registry(self, app);
201        debug_assert!(registry.is_some());
202        let Some(registry) = registry else {
203            return;
204        };
205        if !selected.unwrap_or(true) {
206            return;
207        }
208        if selected.unwrap_or(false) {
209            let value = self.widget(app).value.clone();
210            registry.on_changed(app, Some(value));
211        } else {
212            registry.on_changed(app, None);
213        }
214    }
215}
216
217impl<T: Clone + PartialEq + 'static> TickerProviderStateMixin for RawRadioState<T> {
218    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
219        &app.get(self).ticker_provider
220    }
221
222    fn ticker_provider_data_mut(
223        self: Handle<Self>,
224        app: &mut App,
225    ) -> &mut TickerProviderStateMixinData {
226        &mut app.get_mut(self).ticker_provider
227    }
228}
229
230/// Dart's `vsync: this`.
231impl<T: Clone + PartialEq + 'static> TickerProviderObject for RawRadioState<T> {
232    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
233        TickerProviderStateMixin::create_ticker(self, app, on_tick)
234    }
235}
236
237impl<T: Clone + PartialEq + 'static> RadioClient<T> for RawRadioState<T> {
238    crate::radio_client_accessors!(T);
239
240    fn tristate(self: Handle<Self>, app: &App) -> bool {
241        self.widget(app).toggleable
242    }
243
244    fn radio_value(self: Handle<Self>, app: &App) -> T {
245        self.widget(app).value.clone()
246    }
247
248    fn enabled(self: Handle<Self>, app: &App) -> bool {
249        ToggleableStateMixin::is_interactive(self, app)
250    }
251
252    fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode {
253        self.widget(app).focus_node.handle()
254    }
255}
256
257impl<T: Clone + PartialEq + 'static> ToggleableStateMixin for RawRadioState<T> {
258    fn toggleable_data(self: Handle<Self>, app: &App) -> &ToggleableStateMixinData {
259        &app.get(self).toggleable
260    }
261
262    fn toggleable_data_mut(self: Handle<Self>, app: &mut App) -> &mut ToggleableStateMixinData {
263        &mut app.get_mut(self).toggleable
264    }
265
266    fn on_changed(self: Handle<Self>, app: &App) -> Option<ValueChanged<Option<bool>>> {
267        RadioClient::registry(self, app)?;
268        Some(Rc::new(move |app: &mut App, selected| {
269            self.handle_changed(app, selected)
270        }))
271    }
272
273    fn tristate(self: Handle<Self>, app: &App) -> bool {
274        self.widget(app).toggleable
275    }
276
277    fn value(self: Handle<Self>, app: &App) -> Option<bool> {
278        let registry = RadioClient::registry(self, app);
279        let group_value = registry.and_then(|registry| registry.group_value(app));
280        Some(group_value.as_ref() == Some(&self.widget(app).value))
281    }
282
283    fn is_interactive(self: Handle<Self>, app: &App) -> bool {
284        self.widget(app).enabled
285    }
286}
287
288impl<T: Clone + PartialEq + 'static> State for RawRadioState<T> {
289    type Widget = RawRadio<T>;
290    crate::state_accessors!();
291
292    fn init_state(self: Handle<Self>, app: &mut App) {
293        // This has to be before the init state because the [ToggleableStateMixin]
294        // expect the [value] is up-to-date when init its state.
295        let registry = self.widget(app).group_registry.clone();
296        self.set_registry(app, registry);
297        ToggleableStateMixin::init_state(self, app);
298    }
299
300    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RawRadio<T>) {
301        let registry = self.widget(app).group_registry.clone();
302        self.set_registry(app, registry);
303        self.animate_to_value(app); // The registry's group value may have changed
304    }
305
306    fn activate(self: Handle<Self>, app: &mut App) {
307        TickerProviderStateMixin::activate(self, app);
308    }
309
310    fn dispose(self: Handle<Self>, app: &mut App) {
311        ToggleableStateMixin::dispose(self, app);
312        TickerProviderStateMixin::dispose(self, app);
313        self.set_registry(app, None);
314    }
315
316    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
317        let accessibility_selected: Option<bool>;
318        let mut semantics_hint: Option<String> = None;
319
320        match app.platform().target_platform() {
321            TargetPlatform::Android
322            | TargetPlatform::Fuchsia
323            | TargetPlatform::Linux
324            | TargetPlatform::Windows => {
325                accessibility_selected = None;
326                semantics_hint = None;
327            }
328            TargetPlatform::IOS | TargetPlatform::MacOS => {
329                accessibility_selected = self.value(app);
330                // Only provide hint for unselected radio buttons to avoid duplication
331                // of the selected state announcement.
332                // Selected state is already announced by iOS via the 'selected' property.
333                if !self.value(app).unwrap_or(false) {
334                    let localizations = <dyn WidgetsLocalizations>::of(app, context);
335                    semantics_hint = Some(localizations.radio_button_unselected_label());
336                }
337            }
338        }
339
340        let widget = self.widget(app);
341        let focus_node = widget.focus_node.clone();
342        let autofocus = widget.autofocus;
343        let mouse_cursor = Rc::clone(&widget.mouse_cursor);
344        let builder = Rc::clone(&widget.builder);
345        let child = builder(app, context, self.as_toggleable_state());
346        let mut semantics = Semantics::new().in_mutually_exclusive_group(true);
347        if let Some(checked) = self.value(app) {
348            semantics = semantics.checked(checked);
349        }
350        if let Some(selected) = accessibility_selected {
351            semantics = semantics.selected(selected);
352        }
353        if let Some(hint) = semantics_hint {
354            semantics = semantics.hint(hint);
355        }
356        semantics
357            .child(self.build_toggleable_with_child(
358                app,
359                Some(focus_node),
360                None,
361                autofocus,
362                Some(mouse_cursor),
363                child,
364            ))
365            .into_widget()
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use std::any::Any;
372    use std::cell::{Cell, RefCell};
373    use std::time::Duration;
374    use waft_foundation::Ref;
375
376    use waft_embedder::{Canvas, Size};
377    use waft_rendering::CustomPainter;
378    use waft_services::SystemMouseCursors;
379
380    use super::*;
381    use crate::framework::IntoWidget;
382    use crate::testing::{WidgetTester, find, test_widgets};
383    use crate::widgets::basic::{Builder, Center, CustomPaint, Directionality, SizedBox};
384    use crate::widgets::focus_manager::FocusNode;
385    use crate::widgets::radio_group::{AnyRadioClient, RadioGroup, RadioGroupRegistry};
386    use crate::widgets::widget_state::WidgetStateProperty;
387    use waft_embedder::TextDirection;
388
389    /// Dart's `TestRegistry<int>`: the group value is whatever `on_changed` last set.
390    struct TestRegistry {
391        group_value: Option<u32>,
392        clients: Vec<AnyRadioClient<u32>>,
393    }
394
395    impl RadioGroupRegistry<u32> for TestRegistry {
396        fn group_value(self: Handle<Self>, app: &App) -> Option<u32> {
397            app.get(self).group_value
398        }
399
400        fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<u32>) {
401            app.get_mut(self).clients.push(radio);
402        }
403
404        fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<u32>) {
405            app.get_mut(self).clients.retain(|client| *client != radio);
406        }
407
408        fn on_changed(self: Handle<Self>, app: &mut App, value: Option<u32>) {
409            app.get_mut(self).group_value = value;
410        }
411    }
412
413    fn registry(app: &mut App) -> Ref<TestRegistry> {
414        app.create(TestRegistry {
415            group_value: None,
416            clients: Vec::new(),
417        })
418    }
419
420    fn raw_radio(
421        node: FocusNodeRef,
422        registry: Option<RadioGroupRegistryRef<u32>>,
423        enabled: bool,
424        toggleable: bool,
425        captured: Rc<Cell<Option<AnyToggleableState>>>,
426        child: impl Fn() -> WidgetRef + 'static,
427    ) -> RawRadio<u32> {
428        RawRadio::new(
429            0,
430            <dyn WidgetStateProperty<MouseCursorRef>>::all(SystemMouseCursors::CLICK.into()),
431            toggleable,
432            node,
433            false,
434            registry,
435            enabled,
436            Rc::new(move |_app, _context, state| {
437                captured.set(Some(state));
438                child()
439            }),
440        )
441    }
442
443    /// Dart's `TestPainter`: a painter makes the `CustomPaint` hit-testable.
444    struct TestPainter;
445
446    impl CustomPainter for TestPainter {
447        fn paint(&self, _app: &mut App, _canvas: &mut Canvas, _size: Size) {}
448
449        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
450            true
451        }
452
453        fn as_any(&self) -> &dyn Any {
454            self
455        }
456    }
457
458    fn painted_box() -> WidgetRef {
459        CustomPaint::new()
460            .size(Size::new(40.0, 40.0))
461            .painter(TestPainter)
462            .into_widget()
463    }
464
465    fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
466        tester.update(|app| FocusNode::new(app).erase())
467    }
468
469    #[test]
470    fn a_tap_selects_the_radio_in_its_registry() {
471        test_widgets(|tester| {
472            let node = focus_node(tester);
473            let registry = tester.update(registry);
474            let captured = Rc::new(Cell::new(None));
475            let build = |captured: &Rc<Cell<Option<AnyToggleableState>>>| {
476                raw_radio(
477                    node.clone(),
478                    Some(registry.erase()),
479                    true,
480                    true,
481                    Rc::clone(captured),
482                    painted_box,
483                )
484            };
485
486            tester.pump_widget(build(&captured));
487            let actual_state = captured.get().expect("the builder ran");
488            {
489                let app = tester.cell.borrow();
490                assert!(actual_state.tristate(&app));
491                assert_eq!(actual_state.value(&app), Some(false));
492                assert_eq!(app.get(&registry).group_value, None);
493
494                let state = app
495                    .handle::<RawRadioState<u32>>(actual_state.id())
496                    .expect("the radio's state");
497                assert!(
498                    app.get(&registry)
499                        .clients
500                        .contains(&state.as_radio_client())
501                );
502            }
503
504            tester.tap(find::by_type::<RawRadio<u32>>());
505            // Rebuilds with new group value
506            tester.pump_widget(build(&captured));
507
508            let app = tester.cell.borrow();
509            assert_eq!(app.get(&registry).group_value, Some(0));
510            assert_eq!(actual_state.value(&app), Some(true));
511        });
512    }
513
514    #[test]
515    fn a_disabled_radio_does_not_report_a_tap() {
516        test_widgets(|tester| {
517            let node = focus_node(tester);
518            let registry = tester.update(registry);
519            let captured = Rc::new(Cell::new(None));
520
521            tester.pump_widget(raw_radio(
522                node,
523                Some(registry.erase()),
524                false,
525                true,
526                captured,
527                painted_box,
528            ));
529            tester.tap(find::by_type::<RawRadio<u32>>());
530
531            // onChanged won't fire
532            assert_eq!(tester.cell.borrow().get(&registry).group_value, None);
533        });
534    }
535
536    #[test]
537    #[should_panic(expected = "an enabled raw radio must have a registry")]
538    fn an_enabled_radio_without_a_registry_is_rejected() {
539        test_widgets(|tester| {
540            let node = focus_node(tester);
541
542            raw_radio(
543                node,
544                None,
545                true,
546                true,
547                Rc::new(Cell::new(None)),
548                painted_box,
549            );
550        });
551    }
552
553    /// A `RawRadio<String>` under a `RadioGroup<String>`, as Material's `Radio<String>` builds
554    /// one: the radio takes its registry from the group above it.
555    fn string_radio_group(
556        node: FocusNodeRef,
557        group_value: Option<String>,
558        changes: Rc<RefCell<Vec<Option<String>>>>,
559        captured: Rc<Cell<Option<AnyToggleableState>>>,
560    ) -> WidgetRef {
561        let mut group = RadioGroup::<String>::new(
562            Rc::new(move |_app, value| changes.borrow_mut().push(value)),
563            Builder::new(move |app, context| {
564                let captured = Rc::clone(&captured);
565                RawRadio::new(
566                    String::from("lafayette"),
567                    <dyn WidgetStateProperty<MouseCursorRef>>::all(
568                        SystemMouseCursors::CLICK.into(),
569                    ),
570                    true,
571                    node.clone(),
572                    false,
573                    RadioGroup::<String>::maybe_of(app, context),
574                    true,
575                    Rc::new(move |_app, _context, state| {
576                        captured.set(Some(state));
577                        painted_box()
578                    }),
579                )
580                .into_widget()
581            }),
582        );
583        if let Some(group_value) = group_value {
584            group = group.group_value(group_value);
585        }
586        group.into_widget()
587    }
588
589    #[test]
590    fn a_radio_takes_a_string_value_compared_with_eq() {
591        test_widgets(|tester| {
592            let node = focus_node(tester);
593            let changes: Rc<RefCell<Vec<Option<String>>>> = Rc::default();
594            let captured = Rc::new(Cell::new(None));
595
596            tester.pump_widget(string_radio_group(
597                node.clone(),
598                None,
599                Rc::clone(&changes),
600                Rc::clone(&captured),
601            ));
602            let state = captured.get().expect("the builder ran");
603            assert_eq!(state.value(&tester.cell.borrow()), Some(false));
604
605            tester.tap(find::by_type::<RawRadio<String>>());
606            assert_eq!(*changes.borrow(), [Some(String::from("lafayette"))]);
607
608            // An equal string that is another object selects the radio.
609            tester.pump_widget(string_radio_group(
610                node,
611                Some(String::from("lafayette")),
612                Rc::clone(&changes),
613                Rc::clone(&captured),
614            ));
615            assert_eq!(state.value(&tester.cell.borrow()), Some(true));
616
617            // Selecting a toggleable radio again unselects it.
618            tester.tap(find::by_type::<RawRadio<String>>());
619            assert_eq!(*changes.borrow(), [Some(String::from("lafayette")), None]);
620        });
621    }
622
623    #[test]
624    #[should_panic(expected = "No WidgetsLocalizations found")]
625    fn an_unselected_radio_on_ios_reads_the_widgets_localizations() {
626        let mut tester = WidgetTester::on(TargetPlatform::IOS);
627        let node = focus_node(&tester);
628        let registry = tester.update(registry);
629
630        tester.pump_widget(raw_radio(
631            node,
632            Some(registry.erase()),
633            true,
634            false,
635            Rc::new(Cell::new(None)),
636            painted_box,
637        ));
638    }
639
640    #[test]
641    fn a_radio_at_zero_area_does_not_crash() {
642        test_widgets(|tester| {
643            let node = focus_node(tester);
644            let registry = tester.update(registry);
645            let captured = Rc::new(Cell::new(None));
646            let radio = raw_radio(
647                node,
648                Some(registry.erase()),
649                true,
650                false,
651                captured.clone(),
652                || SizedBox::square(Some(24.0)).into_widget(),
653            );
654
655            tester.pump_widget(Directionality::new(
656                TextDirection::Ltr,
657                Center::new().child(SizedBox::shrink().child(radio)),
658            ));
659            tester.pump_by(Duration::from_millis(16));
660
661            let app = tester.cell.borrow();
662            let state = captured.get().expect("the builder ran");
663            let size = state.context(&app).size(&app);
664            assert_eq!(size, Some(Size::ZERO));
665        });
666    }
667}