Skip to main content

waft_material/
radio.rs

1//! Flutter counterpart: material_ui's `radio.dart` (with `generated/radio_defaults_m3.g.dart`).
2//!
3//! [`Radio`] builds a [`RawRadio`], whose builder hands `_RadioPaint` the radio's state as an
4//! [`AnyToggleableState`]; the paint state keeps its arena [`ToggleablePainter`] for its
5//! lifetime, as Dart's `_painter` field is. The deprecated `groupValue` and `onChanged` reach
6//! the radio through `_RadioRegistry`, an arena object the state creates on first use.
7//! [`Radio::adaptive`] builds a [`CupertinoRadio`] on iOS and macOS.
8
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use waft_cupertino::CupertinoRadio;
13use waft_embedder::{Canvas, Color, Offset, Paint, PaintStyle, Size, TargetPlatform};
14use waft_foundation::{
15    App, ChangeNotifier, ChangeNotifierData, Handle, OptionRetained, Ref, ValueChanged,
16};
17use waft_painting::{AnyBorderSide, BorderSide, CircleBorder, ShapeBorder};
18use waft_services::MouseCursorRef;
19use waft_widgets::{
20    AnyRadioClient, AnyToggleableState, BuildContext, CustomPaint, FocusNode, FocusNodeLeaf,
21    FocusNodeRef, IntoWidget, KeyRef, RadioBuilder, RadioGroup, RadioGroupRegistry,
22    RadioGroupRegistryRef, RawRadio, State, StateData, StatefulWidget, ToggleablePainter,
23    ToggleablePainterData, ToggleablePainterRef, WidgetRef, WidgetState, WidgetStateBorderSide,
24    WidgetStateMouseCursor, WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
25};
26
27use crate::colors::Colors;
28use crate::constants::{
29    K_MIN_INTERACTIVE_DIMENSION, K_RADIAL_REACTION_ALPHA, K_RADIAL_REACTION_RADIUS,
30};
31use crate::debug::debug_check_has_material;
32use crate::generated::radio_defaults_m3::RadioDefaultsM3;
33use crate::radio_theme::{RadioTheme, RadioThemeData, RadioThemeDataGetters};
34use crate::theme::Theme;
35use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
36use crate::theme_data_getters::DefaultsContext;
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39enum RadioType {
40    Material,
41    Adaptive,
42}
43
44const K_OUTER_RADIUS: f64 = 8.0;
45const K_INNER_RADIUS: f64 = 4.5;
46
47/// A Material Design radio button.
48///
49/// This widget builds a [`RawRadio`] with a material UI.
50///
51/// Used to select between a number of mutually exclusive values. When one radio
52/// button in a group is selected, the other radio buttons in the group cease to
53/// be selected. The values are of type `T`, the type parameter of the [`Radio`]
54/// class. Enums are commonly used for this purpose.
55///
56/// This widget typically has a [`RadioGroup`] ancestor, which takes in a
57/// [`RadioGroup::group_value`], and the [`Radio`] under it with matching [`value`](Self::value)
58/// will be selected.
59///
60/// Requires one of its ancestors to be a `Material` widget.
61///
62/// See also:
63///
64///  * `RadioListTile`, which combines this widget with a `ListTile` so that
65///    you can give the radio button a label.
66///  * `Slider`, for selecting a value in a range.
67///  * `Checkbox` and `Switch`, for toggling a particular value on or off.
68///  * <https://material.io/design/components/selection-controls.html#radio-buttons>
69#[derive(Clone)]
70pub struct Radio<T: Clone + PartialEq + 'static> {
71    pub key: Option<KeyRef>,
72    /// The value represented by this radio button.
73    pub value: T,
74    /// The currently selected value for a group of radio buttons.
75    ///
76    /// This radio button is considered selected if its [`value`](Self::value) matches the
77    /// [`group_value`](Self::group_value).
78    ///
79    /// This is deprecated, use [`RadioGroup`] to manage group value instead.
80    pub group_value: Option<T>,
81    /// Called when the user selects this radio button.
82    ///
83    /// The radio button passes [`value`](Self::value) as a parameter to this callback. The
84    /// radio button does not actually change state until the parent widget rebuilds the radio
85    /// button with the new [`group_value`](Self::group_value).
86    ///
87    /// If null, the radio button will be displayed as disabled.
88    ///
89    /// The provided callback will not be invoked if this radio button is already selected and
90    /// [`toggleable`](Self::toggleable) is not set to true.
91    ///
92    /// If the [`toggleable`](Self::toggleable) is set to true, tapping a already selected radio
93    /// will invoke this callback with `null` as value.
94    ///
95    /// The callback provided to [`on_changed`](Self::on_changed) should update the state of the
96    /// parent `StatefulWidget` using the `State::set_state` method, so that the parent gets
97    /// rebuilt.
98    ///
99    /// This is deprecated, use [`RadioGroup`] to handle value change instead.
100    pub on_changed: Option<ValueChanged<Option<T>>>,
101    /// The cursor for a mouse pointer when it enters or is hovering over the widget.
102    ///
103    /// If [`mouse_cursor`](Self::mouse_cursor) is a [`WidgetStateMouseCursor`],
104    /// `WidgetStateProperty::resolve` is used for the following [`WidgetState`]s:
105    ///
106    ///  * [`WidgetState::Selected`].
107    ///  * [`WidgetState::Hovered`].
108    ///  * [`WidgetState::Focused`].
109    ///  * [`WidgetState::Disabled`].
110    ///
111    /// If null, the value of [`RadioThemeData::mouse_cursor`] is used. If that is
112    /// also null, [`WidgetStateMouseCursor::adaptive_clickable`] is used.
113    pub mouse_cursor: Option<MouseCursorRef>,
114    /// Set to true if this radio button is allowed to be returned to an indeterminate state by
115    /// selecting it again when selected.
116    ///
117    /// To indicate returning to an indeterminate state, [`RadioGroup::on_changed`] of the
118    /// [`RadioGroup`] above the widget tree will be called with null.
119    ///
120    /// If true, [`RadioGroup::on_changed`] is called with [`value`](Self::value) when selected
121    /// while [`RadioGroup::group_value`] != [`value`](Self::value), and with null when selected
122    /// again while [`RadioGroup::group_value`] == [`value`](Self::value).
123    ///
124    /// If false, [`RadioGroup::on_changed`] will be called with [`value`](Self::value) when it
125    /// is selected while [`RadioGroup::group_value`] != [`value`](Self::value), and only by
126    /// selecting another radio button in the group (i.e. changing the value of
127    /// [`RadioGroup::group_value`]) can this radio button be unselected.
128    ///
129    /// The default is false.
130    pub toggleable: bool,
131    /// The color to use when this radio button is selected.
132    ///
133    /// Defaults to `ColorScheme::secondary`.
134    ///
135    /// If [`fill_color`](Self::fill_color) returns a non-null color in the
136    /// [`WidgetState::Selected`] state, it will be used instead of this color.
137    pub active_color: Option<Color>,
138    /// The color that fills the radio button, in all [`WidgetState`]s.
139    ///
140    /// Resolves in the following states:
141    ///  * [`WidgetState::Selected`].
142    ///  * [`WidgetState::Hovered`].
143    ///  * [`WidgetState::Focused`].
144    ///  * [`WidgetState::Disabled`].
145    ///
146    /// If null, then the value of [`active_color`](Self::active_color) is used in the selected
147    /// state. If that is also null, then the value of [`RadioThemeData::fill_color`] is used.
148    /// If that is also null and `ThemeData::use_material3` is false, then
149    /// `ThemeData::disabled_color` is used in the disabled state, `ColorScheme::secondary`
150    /// is used in the selected state, and `ThemeData::unselected_widget_color` is used in the
151    /// default state; if `ThemeData::use_material3` is true, then `ColorScheme::on_surface`
152    /// is used in the disabled state, `ColorScheme::primary` is used in the
153    /// selected state and `ColorScheme::on_surface_variant` is used in the default state.
154    pub fill_color: Option<WidgetStatePropertyRef<Option<Color>>>,
155    /// Configures the minimum size of the tap target.
156    ///
157    /// If null, then the value of [`RadioThemeData::material_tap_target_size`] is used.
158    /// If that is also null, then the value of `ThemeData::material_tap_target_size`
159    /// is used.
160    ///
161    /// See also:
162    ///
163    ///  * [`MaterialTapTargetSize`], for a description of how this affects tap targets.
164    pub material_tap_target_size: Option<MaterialTapTargetSize>,
165    /// Defines how compact the radio's layout will be.
166    ///
167    /// If null, then the value of [`RadioThemeData::visual_density`] is used. If that
168    /// is also null, then the value of `ThemeData::visual_density` is used.
169    ///
170    /// See also:
171    ///
172    ///  * `ThemeData::visual_density`, which specifies the [`visual_density`](Self::visual_density)
173    ///    for all widgets within a `Theme`.
174    pub visual_density: Option<VisualDensity>,
175    /// The color for the radio's `Material` when it has the input focus.
176    ///
177    /// If [`overlay_color`](Self::overlay_color) returns a non-null color in the
178    /// [`WidgetState::Focused`] state, it will be used instead.
179    ///
180    /// If null, then the value of [`RadioThemeData::overlay_color`] is used in the
181    /// focused state. If that is also null, then the value of
182    /// `ThemeData::focus_color` is used.
183    pub focus_color: Option<Color>,
184    /// The color for the radio's `Material` when a pointer is hovering over it.
185    ///
186    /// If [`overlay_color`](Self::overlay_color) returns a non-null color in the
187    /// [`WidgetState::Hovered`] state, it will be used instead.
188    ///
189    /// If null, then the value of [`RadioThemeData::overlay_color`] is used in the
190    /// hovered state. If that is also null, then the value of
191    /// `ThemeData::hover_color` is used.
192    pub hover_color: Option<Color>,
193    /// The color for the radio's `Material`.
194    ///
195    /// Resolves in the following states:
196    ///  * [`WidgetState::Pressed`].
197    ///  * [`WidgetState::Selected`].
198    ///  * [`WidgetState::Hovered`].
199    ///  * [`WidgetState::Focused`].
200    ///
201    /// If null, then the value of [`active_color`](Self::active_color) with alpha
202    /// `K_RADIAL_REACTION_ALPHA`, [`focus_color`](Self::focus_color) and
203    /// [`hover_color`](Self::hover_color) is used in the pressed, focused and hovered state. If
204    /// that is also null, the value of [`RadioThemeData::overlay_color`] is used. If that is
205    /// also null, then in Material 2, the value of `ColorScheme::secondary` with alpha
206    /// `K_RADIAL_REACTION_ALPHA`, `ThemeData::focus_color` and `ThemeData::hover_color`
207    /// is used in the pressed, focused and hovered state. In Material3, the default
208    /// values are:
209    ///   * selected
210    ///     * pressed - Theme.colorScheme.onSurface(0.1)
211    ///     * hovered - Theme.colorScheme.primary(0.08)
212    ///     * focused - Theme.colorScheme.primary(0.1)
213    ///   * pressed - Theme.colorScheme.primary(0.1)
214    ///   * hovered - Theme.colorScheme.onSurface(0.08)
215    ///   * focused - Theme.colorScheme.onSurface(0.1)
216    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
217    /// The splash radius of the circular `Material` ink response.
218    ///
219    /// If null, then the value of [`RadioThemeData::splash_radius`] is used. If that
220    /// is also null, then `K_RADIAL_REACTION_RADIUS` is used.
221    pub splash_radius: Option<f64>,
222    /// An optional focus node to use as the focus node for this widget.
223    ///
224    /// If one is not supplied, then one will be automatically allocated, owned, and managed by
225    /// this widget. The widget will be focusable even if a `focus_node` is not supplied. If
226    /// supplied, the given `focus_node` will be _hosted_ by this widget, but not owned.
227    pub focus_node: Option<FocusNodeRef>,
228    /// True if this widget will be selected as the initial focus when no other node in its
229    /// scope is currently focused.
230    pub autofocus: bool,
231    /// Controls whether the checkmark style is used in an iOS-style radio.
232    ///
233    /// Only usable under the [`Radio::adaptive`] constructor. If set to true, on
234    /// Apple platforms the radio button will appear as an iOS styled checkmark.
235    /// Controls the [`CupertinoRadio`] through [`CupertinoRadio::use_checkmark_style`].
236    ///
237    /// Defaults to false.
238    pub use_cupertino_checkmark_style: bool,
239    /// The registry this radio registers to.
240    ///
241    /// Unless provided, the [`BuildContext`] will be used to look up the ancestor
242    /// [`RadioGroupRegistry`].
243    pub group_registry: Option<RadioGroupRegistryRef<T>>,
244    radio_type: RadioType,
245    /// Whether this widget is interactive.
246    ///
247    /// If not provided, this widget will be interactable if one of the following is true:
248    ///
249    /// * A [`on_changed`](Self::on_changed) is provided.
250    /// * Having a [`RadioGroup`] with the same type T above this widget.
251    /// * A [`group_registry`](Self::group_registry) is provided.
252    ///
253    /// If this is set to true, one of the above condition must also be true. Otherwise, an
254    /// assertion error is thrown.
255    pub enabled: Option<bool>,
256    /// The color of the background of the radio button, in all [`WidgetState`]s.
257    ///
258    /// Resolves in the following states:
259    ///  * [`WidgetState::Selected`].
260    ///  * [`WidgetState::Hovered`].
261    ///  * [`WidgetState::Focused`].
262    ///  * [`WidgetState::Disabled`].
263    ///
264    /// If null, then the ambient [`RadioThemeData::background_color`] is used.
265    /// If that is also null the default value is transparent in all states.
266    pub background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
267    /// The side for the circular border of the radio button, in all
268    /// [`WidgetState`]s.
269    ///
270    /// This property can be a [`BorderSide`] or a [`WidgetStateBorderSide`] to leverage
271    /// widget state resolution.
272    ///
273    /// Resolves in the following states:
274    ///  * [`WidgetState::Selected`].
275    ///  * [`WidgetState::Hovered`].
276    ///  * [`WidgetState::Focused`].
277    ///  * [`WidgetState::Disabled`].
278    ///
279    /// If null, then the ambient [`RadioThemeData::side`] is used. If that is
280    /// also null, the default value is a border using the fill color.
281    pub side: Option<AnyBorderSide>,
282    /// The radius of the inner circle of the radio button, in all [`WidgetState`]s.
283    ///
284    /// Resolves in the following states:
285    ///  * [`WidgetState::Hovered`].
286    ///  * [`WidgetState::Focused`].
287    ///  * [`WidgetState::Disabled`].
288    ///
289    /// If null, then the ambient [`RadioThemeData::inner_radius`] is used.
290    /// If that is also null, the default value is `4.5` in all states.
291    pub inner_radius: Option<WidgetStatePropertyRef<Option<f64>>>,
292}
293
294impl<T: Clone + PartialEq + 'static> Radio<T> {
295    /// Creates a Material Design radio button.
296    ///
297    /// This widget typically has a [`RadioGroup`] ancestor, which takes in a
298    /// [`RadioGroup::group_value`], and the [`Radio`] under it with matching
299    /// [`value`](Self::value) will be selected.
300    ///
301    /// The [`value`](Self::value) is required.
302    pub fn new(value: T) -> Radio<T> {
303        Radio::with_type(value, RadioType::Material)
304    }
305
306    /// Creates an adaptive [`Radio`] based on whether the target platform is iOS
307    /// or macOS, following Material design's
308    /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
309    ///
310    /// On iOS and macOS, this constructor creates a [`CupertinoRadio`], which has
311    /// matching functionality and presentation as Material checkboxes, and are the
312    /// graphics expected on iOS. On other platforms, this creates a Material
313    /// design [`Radio`].
314    ///
315    /// If a [`CupertinoRadio`] is created, the following parameters are ignored:
316    /// [`mouse_cursor`](Self::mouse_cursor), [`fill_color`](Self::fill_color),
317    /// [`hover_color`](Self::hover_color), [`overlay_color`](Self::overlay_color),
318    /// [`splash_radius`](Self::splash_radius),
319    /// [`material_tap_target_size`](Self::material_tap_target_size),
320    /// [`visual_density`](Self::visual_density).
321    ///
322    /// [`use_cupertino_checkmark_style`](Self::use_cupertino_checkmark_style) is used only if a
323    /// [`CupertinoRadio`] is created.
324    ///
325    /// The target platform is based on the current `Theme`: `ThemeData::platform`.
326    pub fn adaptive(value: T) -> Radio<T> {
327        Radio::with_type(value, RadioType::Adaptive)
328    }
329
330    fn with_type(value: T, radio_type: RadioType) -> Radio<T> {
331        Radio {
332            key: None,
333            value,
334            group_value: None,
335            on_changed: None,
336            mouse_cursor: None,
337            toggleable: false,
338            active_color: None,
339            fill_color: None,
340            material_tap_target_size: None,
341            visual_density: None,
342            focus_color: None,
343            hover_color: None,
344            overlay_color: None,
345            splash_radius: None,
346            focus_node: None,
347            autofocus: false,
348            use_cupertino_checkmark_style: false,
349            group_registry: None,
350            radio_type,
351            enabled: None,
352            background_color: None,
353            side: None,
354            inner_radius: None,
355        }
356    }
357
358    /// Dart `Radio(key:)`.
359    pub fn key(mut self, key: KeyRef) -> Radio<T> {
360        self.key = Some(key);
361        self
362    }
363
364    /// Dart `Radio(groupValue:)`.
365    #[deprecated(
366        note = "Use a RadioGroup ancestor to manage group value instead. This feature was \
367                deprecated after v3.32.0-0.0.pre."
368    )]
369    pub fn group_value(mut self, group_value: T) -> Radio<T> {
370        self.group_value = Some(group_value);
371        self
372    }
373
374    /// Dart `Radio(onChanged:)`.
375    #[deprecated(
376        note = "Use RadioGroup to handle value change instead. This feature was deprecated \
377                after v3.32.0-0.0.pre."
378    )]
379    pub fn on_changed(mut self, on_changed: ValueChanged<Option<T>>) -> Radio<T> {
380        self.on_changed = Some(on_changed);
381        self
382    }
383
384    /// Dart `Radio(mouseCursor:)`.
385    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> Radio<T> {
386        self.mouse_cursor = Some(mouse_cursor);
387        self
388    }
389
390    /// Dart `Radio(toggleable:)`.
391    pub fn toggleable(mut self, toggleable: bool) -> Radio<T> {
392        self.toggleable = toggleable;
393        self
394    }
395
396    /// Dart `Radio(activeColor:)`.
397    pub fn active_color(mut self, active_color: Color) -> Radio<T> {
398        self.active_color = Some(active_color);
399        self
400    }
401
402    /// Dart `Radio(fillColor:)`.
403    pub fn fill_color(mut self, fill_color: WidgetStatePropertyRef<Option<Color>>) -> Radio<T> {
404        self.fill_color = Some(fill_color);
405        self
406    }
407
408    /// Dart `Radio(focusColor:)`.
409    pub fn focus_color(mut self, focus_color: Color) -> Radio<T> {
410        self.focus_color = Some(focus_color);
411        self
412    }
413
414    /// Dart `Radio(hoverColor:)`.
415    pub fn hover_color(mut self, hover_color: Color) -> Radio<T> {
416        self.hover_color = Some(hover_color);
417        self
418    }
419
420    /// Dart `Radio(overlayColor:)`.
421    pub fn overlay_color(
422        mut self,
423        overlay_color: WidgetStatePropertyRef<Option<Color>>,
424    ) -> Radio<T> {
425        self.overlay_color = Some(overlay_color);
426        self
427    }
428
429    /// Dart `Radio(splashRadius:)`.
430    pub fn splash_radius(mut self, splash_radius: f64) -> Radio<T> {
431        self.splash_radius = Some(splash_radius);
432        self
433    }
434
435    /// Dart `Radio(materialTapTargetSize:)`.
436    pub fn material_tap_target_size(
437        mut self,
438        material_tap_target_size: MaterialTapTargetSize,
439    ) -> Radio<T> {
440        self.material_tap_target_size = Some(material_tap_target_size);
441        self
442    }
443
444    /// Dart `Radio(visualDensity:)`.
445    pub fn visual_density(mut self, visual_density: VisualDensity) -> Radio<T> {
446        self.visual_density = Some(visual_density);
447        self
448    }
449
450    /// Dart `Radio(focusNode:)`.
451    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Radio<T> {
452        self.focus_node = Some(focus_node);
453        self
454    }
455
456    /// Dart `Radio(autofocus:)`.
457    pub fn autofocus(mut self, autofocus: bool) -> Radio<T> {
458        self.autofocus = autofocus;
459        self
460    }
461
462    /// Dart `Radio.adaptive(useCupertinoCheckmarkStyle:)`; only a radio made by
463    /// [`Radio::adaptive`] reads it.
464    pub fn use_cupertino_checkmark_style(
465        mut self,
466        use_cupertino_checkmark_style: bool,
467    ) -> Radio<T> {
468        self.use_cupertino_checkmark_style = use_cupertino_checkmark_style;
469        self
470    }
471
472    /// Dart `Radio(enabled:)`.
473    pub fn enabled(mut self, enabled: bool) -> Radio<T> {
474        self.enabled = Some(enabled);
475        self
476    }
477
478    /// Dart `Radio(groupRegistry:)`.
479    pub fn group_registry(mut self, group_registry: RadioGroupRegistryRef<T>) -> Radio<T> {
480        self.group_registry = Some(group_registry);
481        self
482    }
483
484    /// Dart `Radio(backgroundColor:)`.
485    pub fn background_color(
486        mut self,
487        background_color: WidgetStatePropertyRef<Option<Color>>,
488    ) -> Radio<T> {
489        self.background_color = Some(background_color);
490        self
491    }
492
493    /// Dart `Radio(side:)`.
494    pub fn side(mut self, side: impl Into<AnyBorderSide>) -> Radio<T> {
495        self.side = Some(side.into());
496        self
497    }
498
499    /// Dart `Radio(innerRadius:)`.
500    pub fn inner_radius(mut self, inner_radius: WidgetStatePropertyRef<Option<f64>>) -> Radio<T> {
501        self.inner_radius = Some(inner_radius);
502        self
503    }
504}
505
506impl<T: Clone + PartialEq + 'static> Debug for Radio<T> {
507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508        f.debug_struct("Radio")
509            .field("radio_type", &self.radio_type)
510            .field("toggleable", &self.toggleable)
511            .field("enabled", &self.enabled)
512            .field("group_registry", &self.group_registry)
513            .finish_non_exhaustive()
514    }
515}
516
517impl<T: Clone + PartialEq + 'static> StatefulWidget for Radio<T> {
518    type State = RadioState<T>;
519
520    fn key(&self) -> Option<&KeyRef> {
521        self.key.as_ref()
522    }
523
524    fn create_state(&self) -> RadioState<T> {
525        RadioState {
526            state: StateData::new(),
527            internal_focus_node: None,
528            internal_radio_registry: None,
529        }
530    }
531}
532
533/// Dart's `_RadioState`; public because [`Radio`]'s `StatefulWidget::State` names it.
534pub struct RadioState<T: Clone + PartialEq + 'static> {
535    state: StateData<Radio<T>>,
536    internal_focus_node: Option<Ref<FocusNode>>,
537    internal_radio_registry: Option<Ref<RadioRegistry<T>>>,
538}
539
540impl<T: Clone + PartialEq + 'static> RadioState<T> {
541    fn focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
542        if let Some(focus_node) = self.widget(app).focus_node.clone() {
543            return focus_node;
544        }
545        if let Some(focus_node) = app.get(self).internal_focus_node.as_ref() {
546            return focus_node.erase();
547        }
548        let focus_node = FocusNode::new(app);
549        app.get_mut(self).internal_focus_node = Some(focus_node.clone());
550        focus_node.into_erased()
551    }
552
553    fn enabled(self: Handle<Self>, app: &mut App) -> bool {
554        let widget = self.widget(app);
555        if let Some(enabled) = widget.enabled {
556            return enabled;
557        }
558        if widget.on_changed.is_some() || widget.group_registry.is_some() {
559            return true;
560        }
561        let context = self.context(app);
562        RadioGroup::<T>::maybe_of(app, context).is_some()
563    }
564
565    fn effective_registry(self: Handle<Self>, app: &mut App) -> RadioGroupRegistryRef<T> {
566        if let Some(group_registry) = self.widget(app).group_registry.clone() {
567            return group_registry;
568        }
569
570        let context = self.context(app);
571        if let Some(inherited_registry) = RadioGroup::<T>::maybe_of(app, context) {
572            return inherited_registry;
573        }
574
575        // Handles deprecated API.
576        let registry = match app.get(self).internal_radio_registry.as_ref().cloned() {
577            Some(registry) => registry,
578            None => {
579                let registry = app.create(RadioRegistry { state: self });
580                app.get_mut(self).internal_radio_registry = Some(registry.clone());
581                registry
582            }
583        };
584        registry.erase()
585    }
586
587    /// Dart's `CupertinoRadio<T>(...)` that [`Radio::adaptive`] builds on iOS and macOS.
588    #[allow(deprecated)]
589    fn build_cupertino_radio(self: Handle<Self>, app: &mut App) -> WidgetRef {
590        let widget = self.widget(app);
591        let mut radio = CupertinoRadio::new(widget.value.clone())
592            .toggleable(widget.toggleable)
593            .autofocus(widget.autofocus)
594            .use_checkmark_style(widget.use_cupertino_checkmark_style);
595        if let Some(group_value) = widget.group_value.clone() {
596            radio = radio.group_value(group_value);
597        }
598        if let Some(on_changed) = widget.on_changed.clone() {
599            radio = radio.on_changed(on_changed);
600        }
601        if let Some(mouse_cursor) = widget.mouse_cursor.clone() {
602            radio = radio.mouse_cursor(mouse_cursor);
603        }
604        if let Some(active_color) = widget.active_color {
605            radio = radio.active_color(active_color);
606        }
607        if let Some(focus_color) = widget.focus_color {
608            radio = radio.focus_color(focus_color);
609        }
610        let focus_node = self.focus_node(app);
611        let group_registry = self.effective_registry(app);
612        let enabled = self.enabled(app);
613        radio
614            .focus_node(focus_node)
615            .group_registry(group_registry)
616            .enabled(enabled)
617            .into_widget()
618    }
619
620    /// Dart's `effectiveMouseCursor`, built from the widget's cursor and the theme's.
621    fn effective_mouse_cursor(
622        mouse_cursor: Option<MouseCursorRef>,
623        radio_theme: &RadioThemeData,
624    ) -> WidgetStatePropertyRef<MouseCursorRef> {
625        let theme_mouse_cursor = radio_theme.mouse_cursor.clone();
626        let adaptive_clickable: MouseCursorRef =
627            WidgetStateMouseCursor::adaptive_clickable().into();
628        <dyn WidgetStateProperty<MouseCursorRef>>::resolve_with(move |states: &WidgetStates| {
629            <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, states)
630                .or_else(|| {
631                    theme_mouse_cursor
632                        .as_ref()
633                        .and_then(|mouse_cursor| mouse_cursor.resolve(states))
634                })
635                .unwrap_or_else(|| {
636                    <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
637                        &adaptive_clickable,
638                        states,
639                    )
640                })
641        })
642    }
643
644    /// The `builder` Dart passes `RawRadio`: it reads the state's widget when the raw radio
645    /// builds, as the Dart closure does.
646    fn radio_builder(self: Handle<Self>) -> RadioBuilder {
647        Rc::new(move |app: &mut App, _context, state: AnyToggleableState| {
648            let widget = self.widget(app);
649            RadioPaint {
650                toggleable_state: state,
651                active_color: widget.active_color,
652                fill_color: widget.fill_color.clone(),
653                hover_color: widget.hover_color,
654                focus_color: widget.focus_color,
655                overlay_color: widget.overlay_color.clone(),
656                splash_radius: widget.splash_radius,
657                visual_density: widget.visual_density,
658                material_tap_target_size: widget.material_tap_target_size,
659                background_color: widget.background_color.clone(),
660                side: widget.side.clone(),
661                inner_radius: widget.inner_radius.clone(),
662            }
663            .into_widget()
664        })
665    }
666}
667
668impl<T: Clone + PartialEq + 'static> State for RadioState<T> {
669    type Widget = Radio<T>;
670    waft_widgets::state_accessors!();
671
672    fn dispose(self: Handle<Self>, app: &mut App) {
673        if let Some(focus_node) = app.get(self).internal_focus_node.handle() {
674            focus_node.dispose(app);
675        }
676        // The raw radio below has unregistered already: children dispose first.
677    }
678
679    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
680        debug_assert!(
681            !self.widget(app).enabled.unwrap_or(false)
682                || self.widget(app).on_changed.is_some()
683                || self.widget(app).group_registry.is_some()
684                || RadioGroup::<T>::maybe_of(app, context).is_some(),
685            "Radio is enabled but has no Radio.onChange or registry above"
686        );
687        debug_assert!(debug_check_has_material(app, context));
688        match self.widget(app).radio_type {
689            RadioType::Material => {}
690
691            RadioType::Adaptive => {
692                let theme = Theme::of(app, context);
693                match theme.platform {
694                    TargetPlatform::Android
695                    | TargetPlatform::Fuchsia
696                    | TargetPlatform::Linux
697                    | TargetPlatform::Windows => {}
698                    TargetPlatform::IOS | TargetPlatform::MacOS => {
699                        return self.build_cupertino_radio(app);
700                    }
701                }
702            }
703        }
704
705        let radio_theme = RadioTheme::of(app, context);
706        let effective_mouse_cursor =
707            Self::effective_mouse_cursor(self.widget(app).mouse_cursor.clone(), &radio_theme);
708        let value = self.widget(app).value.clone();
709        let toggleable = self.widget(app).toggleable;
710        let focus_node = self.focus_node(app);
711        let autofocus = self.widget(app).autofocus;
712        let group_registry = self.effective_registry(app);
713        let enabled = self.enabled(app);
714        RawRadio::new(
715            value,
716            effective_mouse_cursor,
717            toggleable,
718            focus_node,
719            autofocus,
720            Some(group_registry),
721            enabled,
722            self.radio_builder(),
723        )
724        .into_widget()
725    }
726}
727
728/// A registry for deprecated API.
729// TODO(chunhtai): Remove this once deprecated API is removed.
730struct RadioRegistry<T: Clone + PartialEq + 'static> {
731    state: Handle<RadioState<T>>,
732}
733
734impl<T: Clone + PartialEq + 'static> RadioGroupRegistry<T> for RadioRegistry<T> {
735    fn group_value(self: Handle<Self>, app: &App) -> Option<T> {
736        let state = app.get(self).state;
737        state.widget(app).group_value.clone()
738    }
739
740    fn register_client(self: Handle<Self>, _app: &mut App, _radio: AnyRadioClient<T>) {}
741
742    fn unregister_client(self: Handle<Self>, _app: &mut App, _radio: AnyRadioClient<T>) {}
743
744    fn on_changed(self: Handle<Self>, app: &mut App, value: Option<T>) {
745        let state = app.get(self).state;
746        let on_changed = Rc::clone(
747            state
748                .widget(app)
749                .on_changed
750                .as_ref()
751                .expect("a registry of a radio with onChanged"),
752        );
753        on_changed(app, value);
754    }
755}
756
757/// Dart's `_RadioPaint`.
758#[derive(Clone)]
759struct RadioPaint {
760    toggleable_state: AnyToggleableState,
761    active_color: Option<Color>,
762    fill_color: Option<WidgetStatePropertyRef<Option<Color>>>,
763    hover_color: Option<Color>,
764    focus_color: Option<Color>,
765    overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
766    splash_radius: Option<f64>,
767    visual_density: Option<VisualDensity>,
768    material_tap_target_size: Option<MaterialTapTargetSize>,
769    background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
770    side: Option<AnyBorderSide>,
771    inner_radius: Option<WidgetStatePropertyRef<Option<f64>>>,
772}
773
774impl Debug for RadioPaint {
775    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776        f.debug_struct("RadioPaint")
777            .field("toggleable_state", &self.toggleable_state)
778            .finish_non_exhaustive()
779    }
780}
781
782impl StatefulWidget for RadioPaint {
783    type State = RadioPaintState;
784
785    fn create_state(&self) -> RadioPaintState {
786        RadioPaintState {
787            state: StateData::new(),
788            painter: None,
789        }
790    }
791}
792
793/// Dart's `_RadioPaintState`.
794struct RadioPaintState {
795    state: StateData<RadioPaint>,
796    /// Dart's `final _RadioPainter _painter = _RadioPainter()`, created in `init_state` because
797    /// a painter is an arena object and a state is created without the `App`.
798    painter: Option<Ref<RadioPainter>>,
799}
800
801impl RadioPaintState {
802    fn painter(self: Handle<Self>, app: &App) -> Handle<RadioPainter> {
803        app.get(self)
804            .painter
805            .handle()
806            .expect("created in init_state")
807    }
808
809    fn widget_fill_color(self: Handle<Self>, app: &App) -> WidgetStatePropertyRef<Option<Color>> {
810        let active_color = self.widget(app).active_color;
811        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
812            if states.contains(&WidgetState::Disabled) {
813                return None;
814            }
815            if states.contains(&WidgetState::Selected) {
816                return active_color;
817            }
818            None
819        })
820    }
821
822    /// Dart's `_resolveSide`: Dart's `side is WidgetStateProperty` asks whether the side is a
823    /// [`WidgetStateBorderSide`].
824    fn resolve_side(side: &Option<AnyBorderSide>, states: &WidgetStates) -> Option<BorderSide> {
825        if side
826            .as_ref()
827            .is_some_and(|side| side.extension::<WidgetStateBorderSide>().is_some())
828        {
829            return <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(side, states)
830                .map(|side| *side);
831        }
832        if !states.contains(&WidgetState::Selected) {
833            return side.as_ref().map(|side| **side);
834        }
835        None
836    }
837}
838
839/// Dart's `property?.resolve(states)` for a nullable property of a nullable value.
840fn resolve<T: 'static>(
841    property: &Option<WidgetStatePropertyRef<Option<T>>>,
842    states: &WidgetStates,
843) -> Option<T> {
844    property
845        .as_ref()
846        .and_then(|property| property.resolve(states))
847}
848
849impl State for RadioPaintState {
850    type Widget = RadioPaint;
851    waft_widgets::state_accessors!();
852
853    fn init_state(self: Handle<Self>, app: &mut App) {
854        let painter = RadioPainter::new(app);
855        app.get_mut(self).painter = Some(painter);
856    }
857
858    fn dispose(self: Handle<Self>, app: &mut App) {
859        let painter = self.painter(app);
860        ToggleablePainter::dispose(painter, app);
861    }
862
863    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
864        let radio_theme = RadioTheme::of(app, context);
865        let defaults: Box<dyn RadioThemeDataGetters> = if Theme::of(app, context).use_material3 {
866            Box::new(RadioDefaultsM3::new(context))
867        } else {
868            Box::new(RadioDefaultsM2::new(context))
869        };
870        let widget = self.widget(app).clone();
871        let toggleable_state = widget.toggleable_state;
872        let widget_fill_color = self.widget_fill_color(app);
873
874        // Colors need to be resolved in selected and non selected states separately
875        // so that they can be lerped between.
876        let mut active_states = toggleable_state.states(app);
877        active_states.insert(WidgetState::Selected);
878        let mut inactive_states = toggleable_state.states(app);
879        inactive_states.remove(&WidgetState::Selected);
880        let active_color = resolve(&widget.fill_color, &active_states)
881            .or_else(|| widget_fill_color.resolve(&active_states))
882            .or_else(|| resolve(&radio_theme.fill_color, &active_states));
883        let effective_active_color = active_color.unwrap_or_else(|| {
884            defaults
885                .fill_color(app)
886                .expect("the defaults' fill color")
887                .resolve(&active_states)
888                .expect("the defaults resolve a fill color")
889        });
890        let inactive_color = resolve(&widget.fill_color, &inactive_states)
891            .or_else(|| widget_fill_color.resolve(&inactive_states))
892            .or_else(|| resolve(&radio_theme.fill_color, &inactive_states));
893        let effective_inactive_color = inactive_color.unwrap_or_else(|| {
894            defaults
895                .fill_color(app)
896                .expect("the defaults' fill color")
897                .resolve(&inactive_states)
898                .expect("the defaults resolve a fill color")
899        });
900        let active_background_color = resolve(&widget.background_color, &active_states)
901            .or_else(|| resolve(&radio_theme.background_color, &active_states))
902            .unwrap_or_else(|| {
903                defaults
904                    .background_color(app)
905                    .expect("the defaults' background color")
906                    .resolve(&active_states)
907                    .expect("the defaults resolve a background color")
908            });
909        let inactive_background_color = resolve(&widget.background_color, &inactive_states)
910            .or_else(|| resolve(&radio_theme.background_color, &inactive_states))
911            .unwrap_or_else(|| {
912                defaults
913                    .background_color(app)
914                    .expect("the defaults' background color")
915                    .resolve(&inactive_states)
916                    .expect("the defaults resolve a background color")
917            });
918
919        let mut focused_states = toggleable_state.states(app);
920        focused_states.insert(WidgetState::Focused);
921        let mut effective_focus_overlay_color = resolve(&widget.overlay_color, &focused_states)
922            .or(widget.focus_color)
923            .or_else(|| resolve(&radio_theme.overlay_color, &focused_states))
924            .unwrap_or_else(|| {
925                defaults
926                    .overlay_color(app)
927                    .expect("the defaults' overlay color")
928                    .resolve(&focused_states)
929                    .expect("the defaults resolve an overlay color")
930            });
931
932        let mut hovered_states = toggleable_state.states(app);
933        hovered_states.insert(WidgetState::Hovered);
934        let mut effective_hover_overlay_color = resolve(&widget.overlay_color, &hovered_states)
935            .or(widget.hover_color)
936            .or_else(|| resolve(&radio_theme.overlay_color, &hovered_states))
937            .unwrap_or_else(|| {
938                defaults
939                    .overlay_color(app)
940                    .expect("the defaults' overlay color")
941                    .resolve(&hovered_states)
942                    .expect("the defaults resolve an overlay color")
943            });
944
945        // Dart's `activeStates..add(WidgetState.pressed)` adds to the set itself, which the
946        // active side and the inner radius below resolve in.
947        active_states.insert(WidgetState::Pressed);
948        let active_pressed_states = &active_states;
949        let effective_active_pressed_overlay_color =
950            resolve(&widget.overlay_color, active_pressed_states)
951                .or_else(|| resolve(&radio_theme.overlay_color, active_pressed_states))
952                .or_else(|| active_color.map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA)))
953                .unwrap_or_else(|| {
954                    defaults
955                        .overlay_color(app)
956                        .expect("the defaults' overlay color")
957                        .resolve(active_pressed_states)
958                        .expect("the defaults resolve an overlay color")
959                });
960
961        inactive_states.insert(WidgetState::Pressed);
962        let inactive_pressed_states = &inactive_states;
963        let effective_inactive_pressed_overlay_color =
964            resolve(&widget.overlay_color, inactive_pressed_states)
965                .or_else(|| resolve(&radio_theme.overlay_color, inactive_pressed_states))
966                .or_else(|| inactive_color.map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA)))
967                .unwrap_or_else(|| {
968                    defaults
969                        .overlay_color(app)
970                        .expect("the defaults' overlay color")
971                        .resolve(inactive_pressed_states)
972                        .expect("the defaults resolve an overlay color")
973                });
974
975        if toggleable_state.down_position(app).is_some() {
976            effective_hover_overlay_color = if toggleable_state
977                .states(app)
978                .contains(&WidgetState::Selected)
979            {
980                effective_active_pressed_overlay_color
981            } else {
982                effective_inactive_pressed_overlay_color
983            };
984            effective_focus_overlay_color = if toggleable_state
985                .states(app)
986                .contains(&WidgetState::Selected)
987            {
988                effective_active_pressed_overlay_color
989            } else {
990                effective_inactive_pressed_overlay_color
991            };
992        }
993
994        let effective_material_tap_target_size = widget
995            .material_tap_target_size
996            .or(radio_theme.material_tap_target_size)
997            .or_else(|| defaults.material_tap_target_size(app))
998            .expect("the defaults' tap target size");
999        let effective_visual_density = widget
1000            .visual_density
1001            .or(radio_theme.visual_density)
1002            .or_else(|| defaults.visual_density(app))
1003            .expect("the defaults' visual density");
1004        let mut size = match effective_material_tap_target_size {
1005            MaterialTapTargetSize::Padded => {
1006                Size::new(K_MIN_INTERACTIVE_DIMENSION, K_MIN_INTERACTIVE_DIMENSION)
1007            }
1008            MaterialTapTargetSize::ShrinkWrap => Size::new(
1009                K_MIN_INTERACTIVE_DIMENSION - 8.0,
1010                K_MIN_INTERACTIVE_DIMENSION - 8.0,
1011            ),
1012        };
1013        size = size + effective_visual_density.base_size_adjustment();
1014        let active_side = Self::resolve_side(&widget.side, &active_states)
1015            .or_else(|| Self::resolve_side(&radio_theme.side, &active_states))
1016            .unwrap_or(BorderSide {
1017                color: effective_active_color,
1018                width: 2.0,
1019                stroke_align: BorderSide::STROKE_ALIGN_CENTER,
1020                ..BorderSide::default()
1021            });
1022        let inactive_side = Self::resolve_side(&widget.side, &inactive_states)
1023            .or_else(|| Self::resolve_side(&radio_theme.side, &inactive_states))
1024            .unwrap_or(BorderSide {
1025                color: effective_inactive_color,
1026                width: 2.0,
1027                stroke_align: BorderSide::STROKE_ALIGN_CENTER,
1028                ..BorderSide::default()
1029            });
1030
1031        let inner_radius = resolve(&widget.inner_radius, &active_states)
1032            .or_else(|| resolve(&radio_theme.inner_radius, &active_states))
1033            .unwrap_or(K_INNER_RADIUS);
1034
1035        let splash_radius = widget
1036            .splash_radius
1037            .or(radio_theme.splash_radius)
1038            .unwrap_or(K_RADIAL_REACTION_RADIUS);
1039        let current_states = toggleable_state.states(app);
1040        let painter = app
1041            .get(self)
1042            .painter
1043            .clone()
1044            .expect("created in init_state");
1045        painter.set_position(app, toggleable_state.position(app).erase());
1046        painter.set_reaction(app, toggleable_state.reaction(app).erase());
1047        painter.set_reaction_focus_fade(app, toggleable_state.reaction_focus_fade(app).erase());
1048        painter.set_reaction_hover_fade(app, toggleable_state.reaction_hover_fade(app).erase());
1049        painter.set_inactive_reaction_color(app, effective_inactive_pressed_overlay_color);
1050        painter.set_reaction_color(app, effective_active_pressed_overlay_color);
1051        painter.set_hover_color(app, effective_hover_overlay_color);
1052        painter.set_focus_color(app, effective_focus_overlay_color);
1053        painter.set_splash_radius(app, splash_radius);
1054        painter.set_down_position(app, toggleable_state.down_position(app));
1055        painter.set_is_focused(app, Some(current_states.contains(&WidgetState::Focused)));
1056        painter.set_is_hovered(app, Some(current_states.contains(&WidgetState::Hovered)));
1057        painter.set_active_color(app, effective_active_color);
1058        painter.set_inactive_color(app, effective_inactive_color);
1059        painter.set_active_background_color(app, Some(active_background_color));
1060        painter.set_inactive_background_color(app, Some(inactive_background_color));
1061        painter.set_active_side(app, Some(active_side));
1062        painter.set_inactive_side(app, Some(inactive_side));
1063        painter.set_inner_radius(app, Some(inner_radius));
1064
1065        CustomPaint::new()
1066            .size(size)
1067            .painter(ToggleablePainterRef::new(painter))
1068            .into_widget()
1069    }
1070}
1071
1072/// Dart's `_RadioPainter`.
1073struct RadioPainter {
1074    change_notifier: ChangeNotifierData,
1075    toggleable_painter: ToggleablePainterData,
1076    inactive_background_color: Option<Color>,
1077    active_background_color: Option<Color>,
1078    inactive_side: Option<BorderSide>,
1079    active_side: Option<BorderSide>,
1080    inner_radius: Option<f64>,
1081}
1082
1083impl RadioPainter {
1084    fn new(app: &mut App) -> Ref<RadioPainter> {
1085        app.create(RadioPainter {
1086            change_notifier: ChangeNotifierData::new(),
1087            toggleable_painter: ToggleablePainterData::new(),
1088            inactive_background_color: None,
1089            active_background_color: None,
1090            inactive_side: None,
1091            active_side: None,
1092            inner_radius: None,
1093        })
1094    }
1095
1096    fn inactive_background_color(self: Handle<Self>, app: &App) -> Color {
1097        app.get(self)
1098            .inactive_background_color
1099            .expect("set before painting")
1100    }
1101
1102    fn set_inactive_background_color(self: Handle<Self>, app: &mut App, value: Option<Color>) {
1103        if app.get(self).inactive_background_color == value {
1104            return;
1105        }
1106        app.get_mut(self).inactive_background_color = value;
1107        self.notify_listeners(app);
1108    }
1109
1110    fn active_background_color(self: Handle<Self>, app: &App) -> Color {
1111        app.get(self)
1112            .active_background_color
1113            .expect("set before painting")
1114    }
1115
1116    fn set_active_background_color(self: Handle<Self>, app: &mut App, value: Option<Color>) {
1117        if app.get(self).active_background_color == value {
1118            return;
1119        }
1120        app.get_mut(self).active_background_color = value;
1121        self.notify_listeners(app);
1122    }
1123
1124    fn inactive_side(self: Handle<Self>, app: &App) -> BorderSide {
1125        app.get(self).inactive_side.expect("set before painting")
1126    }
1127
1128    fn set_inactive_side(self: Handle<Self>, app: &mut App, value: Option<BorderSide>) {
1129        if app.get(self).inactive_side == value {
1130            return;
1131        }
1132        app.get_mut(self).inactive_side = value;
1133        self.notify_listeners(app);
1134    }
1135
1136    fn active_side(self: Handle<Self>, app: &App) -> BorderSide {
1137        app.get(self).active_side.expect("set before painting")
1138    }
1139
1140    fn set_active_side(self: Handle<Self>, app: &mut App, value: Option<BorderSide>) {
1141        if app.get(self).active_side == value {
1142            return;
1143        }
1144        app.get_mut(self).active_side = value;
1145        self.notify_listeners(app);
1146    }
1147
1148    fn inner_radius(self: Handle<Self>, app: &App) -> f64 {
1149        app.get(self).inner_radius.expect("set before painting")
1150    }
1151
1152    fn set_inner_radius(self: Handle<Self>, app: &mut App, value: Option<f64>) {
1153        if app.get(self).inner_radius == value {
1154            return;
1155        }
1156        app.get_mut(self).inner_radius = value;
1157        self.notify_listeners(app);
1158    }
1159}
1160
1161impl ChangeNotifier for RadioPainter {
1162    fn change_notifier_data(&self) -> &ChangeNotifierData {
1163        &self.change_notifier
1164    }
1165
1166    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1167        &mut self.change_notifier
1168    }
1169}
1170
1171impl ToggleablePainter for RadioPainter {
1172    fn toggleable_painter_data(self: Handle<Self>, app: &App) -> &ToggleablePainterData {
1173        &app.get(self).toggleable_painter
1174    }
1175
1176    fn toggleable_painter_data_mut(
1177        self: Handle<Self>,
1178        app: &mut App,
1179    ) -> &mut ToggleablePainterData {
1180        &mut app.get_mut(self).toggleable_painter
1181    }
1182
1183    fn paint(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
1184        self.paint_radial_reaction(app, canvas, Offset::ZERO, size.center(Offset::ZERO));
1185
1186        let rect = Offset::ZERO & size;
1187        let center = rect.center();
1188        let effective_rect = (center & Size::square(K_OUTER_RADIUS * 2.0))
1189            .translate(-K_OUTER_RADIUS, -K_OUTER_RADIUS);
1190        let position = self.position(app).value(app);
1191
1192        // Background
1193        let background_paint = Paint {
1194            color: Color::lerp(
1195                Some(self.inactive_background_color(app)),
1196                Some(self.active_background_color(app)),
1197                position,
1198            )
1199            .expect("lerping non-null colors")
1200            .into(),
1201            style: PaintStyle::Fill,
1202            ..Paint::default()
1203        };
1204        canvas.draw_circle(center, K_OUTER_RADIUS as f32, &background_paint);
1205
1206        // Outer circle
1207        let side = BorderSide::lerp(self.inactive_side(app), self.active_side(app), position);
1208        CircleBorder::new(side, 0.0).paint(canvas, effective_rect, None);
1209
1210        // Inner circle
1211        if !self.position(app).is_dismissed(app) {
1212            let inner_circle_paint = Paint {
1213                style: PaintStyle::Fill,
1214                color: Color::lerp(
1215                    Some(self.inactive_color(app)),
1216                    Some(self.active_color(app)),
1217                    position,
1218                )
1219                .expect("lerping non-null colors")
1220                .into(),
1221                ..Paint::default()
1222            };
1223            canvas.draw_circle(
1224                center,
1225                (self.inner_radius(app) * position) as f32,
1226                &inner_circle_paint,
1227            );
1228        }
1229    }
1230}
1231
1232/// Hand coded defaults based on Material Design 2: Dart's `_RadioDefaultsM2`.
1233struct RadioDefaultsM2 {
1234    /// Dart's `super(..)` arguments.
1235    radio_theme_data: RadioThemeData,
1236    context: DefaultsContext,
1237}
1238
1239impl RadioDefaultsM2 {
1240    fn new(context: BuildContext) -> RadioDefaultsM2 {
1241        RadioDefaultsM2 {
1242            radio_theme_data: RadioThemeData::new(),
1243            context: DefaultsContext::new(context),
1244        }
1245    }
1246}
1247
1248impl RadioThemeDataGetters for RadioDefaultsM2 {
1249    fn radio_theme_data(&self) -> &RadioThemeData {
1250        &self.radio_theme_data
1251    }
1252
1253    fn fill_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
1254        let theme = self.context.theme(app);
1255        let disabled_color = theme.disabled_color;
1256        let secondary = theme.color_scheme.secondary();
1257        let unselected_widget_color = theme.unselected_widget_color;
1258        let fill_color = move |states: &WidgetStates| -> Color {
1259            if states.contains(&WidgetState::Disabled) {
1260                return disabled_color;
1261            }
1262            if states.contains(&WidgetState::Selected) {
1263                return secondary;
1264            }
1265            unselected_widget_color
1266        };
1267        Some(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
1268            move |states| Some(fill_color(states)),
1269        ))
1270    }
1271
1272    fn overlay_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
1273        let theme = self.context.theme(app);
1274        let disabled_color = theme.disabled_color;
1275        let secondary = theme.color_scheme.secondary();
1276        let unselected_widget_color = theme.unselected_widget_color;
1277        let hover_color = theme.hover_color;
1278        let focus_color = theme.focus_color;
1279        let fill_color = move |states: &WidgetStates| -> Color {
1280            if states.contains(&WidgetState::Disabled) {
1281                return disabled_color;
1282            }
1283            if states.contains(&WidgetState::Selected) {
1284                return secondary;
1285            }
1286            unselected_widget_color
1287        };
1288        Some(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
1289            move |states| {
1290                if states.contains(&WidgetState::Pressed) {
1291                    return Some(fill_color(states).with_alpha(K_RADIAL_REACTION_ALPHA));
1292                }
1293                if states.contains(&WidgetState::Hovered) {
1294                    return Some(hover_color);
1295                }
1296                if states.contains(&WidgetState::Focused) {
1297                    return Some(focus_color);
1298                }
1299                Some(Colors::TRANSPARENT)
1300            },
1301        ))
1302    }
1303
1304    fn material_tap_target_size(&self, app: &mut App) -> Option<MaterialTapTargetSize> {
1305        let theme = self.context.theme(app);
1306        Some(theme.material_tap_target_size)
1307    }
1308
1309    fn visual_density(&self, app: &mut App) -> Option<VisualDensity> {
1310        let theme = self.context.theme(app);
1311        Some(theme.visual_density)
1312    }
1313
1314    fn background_color(&self, _app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
1315        Some(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
1316            Colors::TRANSPARENT,
1317        )))
1318    }
1319}
1320
1321#[cfg(test)]
1322#[allow(deprecated)]
1323pub(crate) mod tests {
1324    use std::cell::{Cell, RefCell};
1325    use std::time::Duration;
1326
1327    use waft_embedder::{PointerChange, Rect};
1328    use waft_gestures::{K_LONG_PRESS_TIMEOUT, K_PRIMARY_BUTTON};
1329    use waft_painting::AlignmentGeometry;
1330    use waft_rendering::{AnyRenderObject, RenderBox};
1331    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey, SystemMouseCursors};
1332    use waft_widgets::{
1333        Align, AnyElement, Center, Container, FocusHighlightStrategy, GlobalKey, LookupBoundary,
1334        MouseRegion, Row, SizedBox, StatefulBuilder, TooltipTriggerMode, WidgetStateColor,
1335    };
1336
1337    use waft_rendering::testing::{PaintCall, PaintedStyle};
1338    use waft_widgets::testing::{
1339        TestPointer, WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
1340    };
1341
1342    use super::*;
1343    use crate::material::{Material, RenderInkFeatures};
1344    use crate::scaffold::Scaffold;
1345    use crate::test_support::{PaintInspection, material_app};
1346    use crate::theme_data::ThemeData;
1347    use crate::tooltip::Tooltip;
1348
1349    /// Where a 100x100 `Container` centred in the 800x600 view lies.
1350    pub(crate) const CENTER_RECT: Rect = Rect::from_ltrb(350.0, 250.0, 450.0, 350.0);
1351
1352    /// Dart's `ThemeData()`.
1353    pub(crate) fn m3(tester: &WidgetTester) -> ThemeData {
1354        ThemeData::new(&tester.cell.borrow())
1355    }
1356
1357    /// Dart's `ThemeData(useMaterial3: false)`.
1358    pub(crate) fn m2(tester: &WidgetTester) -> ThemeData {
1359        ThemeData::builder()
1360            .use_material3(false)
1361            .build(&tester.cell.borrow())
1362    }
1363
1364    pub(crate) fn no_op<T: 'static>() -> ValueChanged<Option<T>> {
1365        Rc::new(|_app, _value| {})
1366    }
1367
1368    fn log_into(log: &Rc<RefCell<Vec<Option<i32>>>>) -> ValueChanged<Option<i32>> {
1369        let log = Rc::clone(log);
1370        Rc::new(move |_app, value| log.borrow_mut().push(value))
1371    }
1372
1373    /// A `WidgetStateProperty<Color>` given where Dart's `WidgetStateProperty<Color?>` goes:
1374    /// Dart's `WidgetStateColor.resolveWith(resolve)`.
1375    pub(crate) fn colors(
1376        resolve: impl Fn(&WidgetStates) -> Color + 'static,
1377    ) -> WidgetStatePropertyRef<Option<Color>> {
1378        let color = WidgetStateColor::resolve_with(resolve);
1379        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
1380            Some(color.resolve(states))
1381        })
1382    }
1383
1384    /// Dart's `Container(width: 100, height: 100, color: Colors.white, child: child)`.
1385    fn white_box<K>(child: impl IntoWidget<K>) -> WidgetRef {
1386        Container::new()
1387            .width(100.0)
1388            .height(100.0)
1389            .color(Colors::WHITE)
1390            .child(child)
1391            .into_widget()
1392    }
1393
1394    /// Dart's `MaterialApp(theme: theme, home: Material(child: Center(child: child)))`.
1395    fn centered_app<K>(theme: ThemeData, child: impl IntoWidget<K>) -> WidgetRef {
1396        material_app(
1397            theme,
1398            Material::new()
1399                .child(Center::new().child(child))
1400                .into_widget(),
1401        )
1402    }
1403
1404    /// Dart's `MaterialApp(theme: theme, home: Scaffold(body: child))`.
1405    pub(crate) fn scaffold_app<K>(theme: ThemeData, child: impl IntoWidget<K>) -> WidgetRef {
1406        material_app(theme, Scaffold::new().body(child).into_widget())
1407    }
1408
1409    /// Dart's `find.byType(Radio<T>)`: the one radio of that type.
1410    pub(crate) fn find_radio<T: Clone + PartialEq + 'static>(tester: &WidgetTester) -> AnyElement {
1411        let found = find::by_type::<Radio<T>>().evaluate(tester);
1412        assert_eq!(found.len(), 1, "one Radio");
1413        found[0]
1414    }
1415
1416    pub(crate) fn center_of_radio<T: Clone + PartialEq + 'static>(tester: &WidgetTester) -> Offset {
1417        let render = tester.render_box_of(find_radio::<T>(tester));
1418        tester.global_rect(render).center()
1419    }
1420
1421    /// Dart's `Material.of(tester.element(find.byType(Radio<T>)))`: the ink features of the
1422    /// material the radio paints into, which Dart's `paints` matcher paints with its subtree.
1423    pub(crate) fn radio_material<T: Clone + PartialEq + 'static>(
1424        tester: &WidgetTester,
1425    ) -> AnyRenderObject {
1426        let radio = find_radio::<T>(tester);
1427        let app = tester.cell.borrow();
1428        let ink =
1429            LookupBoundary::find_ancestor_render_object_of_type::<RenderInkFeatures>(&app, radio)
1430                .expect("a Material above the radio");
1431        RenderBox::as_object(ink)
1432    }
1433
1434    /// Dart's `createGesture(kind: mouse)`, `addPointer()` and `moveTo(at)`.
1435    pub(crate) fn hover_at(tester: &mut WidgetTester, at: Offset) {
1436        let mut mouse = TestPointer::mouse(1, K_PRIMARY_BUTTON);
1437        tester.add_pointer(&mut mouse, Offset::ZERO);
1438        tester.move_to(&mut mouse, at, false);
1439    }
1440
1441    /// Dart's `tester.press(finder)`: a touch pointer `id` down at `at`, left down.
1442    pub(crate) fn press_at(tester: &mut WidgetTester, at: Offset, id: i64) {
1443        let mut touch = TestPointer::touch(id);
1444        tester.down(&mut touch, at);
1445    }
1446
1447    /// Dart's `..rect(color:, rect:)`.
1448    pub(crate) fn rect(color: Color, rect: Rect) -> PaintCall {
1449        PaintCall::rect_at(rect, Some(color))
1450    }
1451
1452    /// Dart's `..rect()`: a rect of any colour.
1453    pub(crate) fn any_rect() -> PaintCall {
1454        PaintCall::rect(None)
1455    }
1456
1457    /// Dart's `..circle(color:)`.
1458    pub(crate) fn circle(color: Color) -> PaintCall {
1459        PaintCall::circle(Some(color))
1460    }
1461
1462    /// Dart's `radius:` and `strokeWidth:` arguments of `..circle`, the latter with or
1463    /// without `style: stroke`.
1464    pub(crate) trait CircleArguments {
1465        fn radius(self, radius: f64) -> PaintCall;
1466        fn stroke_width(self, stroke_width: f64) -> PaintCall;
1467    }
1468
1469    impl CircleArguments for PaintCall {
1470        fn radius(self, radius: f64) -> PaintCall {
1471            match self {
1472                PaintCall::Circle {
1473                    x, y, color, style, ..
1474                } => PaintCall::Circle {
1475                    x,
1476                    y,
1477                    radius: Some(radius),
1478                    color,
1479                    style,
1480                },
1481                other => other,
1482            }
1483        }
1484
1485        fn stroke_width(self, stroke_width: f64) -> PaintCall {
1486            match self {
1487                PaintCall::Circle {
1488                    x,
1489                    y,
1490                    radius,
1491                    color,
1492                    ..
1493                } => PaintCall::Circle {
1494                    x,
1495                    y,
1496                    radius,
1497                    color,
1498                    style: Some(PaintedStyle::Stroke(Some(stroke_width))),
1499                },
1500                other => other,
1501            }
1502        }
1503    }
1504
1505    /// Dart's `expect(render, paints..a()..b())` on what `render` and its subtree draw.
1506    pub(crate) fn assert_paints(
1507        tester: &WidgetTester,
1508        render: AnyRenderObject,
1509        expected: &[PaintCall],
1510    ) {
1511        waft_rendering::testing::assert_paints(&tester.painted_ops(render), expected);
1512    }
1513
1514    /// The first `T` at or below `node`, depth first.
1515    fn find_below<T: waft_rendering::RenderObject>(
1516        app: &App,
1517        node: AnyRenderObject,
1518    ) -> Option<waft_rendering::RenderHandle<T>> {
1519        if let Some(found) = node.downcast::<T>(app) {
1520            return Some(found);
1521        }
1522        let mut found = None;
1523        node.visit_children(app, &mut |child| {
1524            if found.is_none() {
1525                found = find_below::<T>(app, child);
1526            }
1527        });
1528        found
1529    }
1530
1531    /// The radio's painter, for what valo records no draw of.
1532    fn painter<T: Clone + PartialEq + 'static>(tester: &WidgetTester) -> Handle<RadioPainter> {
1533        let radio = tester.render_box_of(find_radio::<T>(tester)).as_object();
1534        let app = tester.cell.borrow();
1535        let custom = find_below::<waft_rendering::RenderCustomPaint>(&app, radio)
1536            .expect("the radio's paint");
1537        let painter = custom.painter(&app).expect("the radio's painter");
1538        painter
1539            .as_any()
1540            .downcast_ref::<ToggleablePainterRef<RadioPainter>>()
1541            .expect("a radio painter")
1542            .painter()
1543    }
1544
1545    #[test]
1546    fn a_radio_reports_its_value_when_tapped_unless_selected_or_without_on_changed() {
1547        test_widgets(|tester| {
1548            let theme = m3(tester);
1549            let key = GlobalKey::new();
1550            let log: Rc<RefCell<Vec<Option<i32>>>> = Rc::default();
1551            let wrap = |radio: Radio<i32>| {
1552                Theme::new(
1553                    theme.clone(),
1554                    Material::new().child(Center::new().child(radio.key(key.clone().into()))),
1555                )
1556                .into_widget()
1557            };
1558
1559            tester.pump_widget(wrap(
1560                Radio::new(1).group_value(2).on_changed(log_into(&log)),
1561            ));
1562            tester.tap_at(tester.get_center(&key), 1);
1563            assert_eq!(*log.borrow(), [Some(1)]);
1564            log.borrow_mut().clear();
1565
1566            tester.pump_widget(wrap(
1567                Radio::new(1)
1568                    .group_value(1)
1569                    .on_changed(log_into(&log))
1570                    .active_color(Colors::GREEN.shade500()),
1571            ));
1572            tester.tap_at(tester.get_center(&key), 2);
1573            assert!(log.borrow().is_empty());
1574
1575            tester.pump_widget(wrap(Radio::new(1).group_value(2)));
1576            tester.tap_at(tester.get_center(&key), 3);
1577            assert!(log.borrow().is_empty());
1578        });
1579    }
1580
1581    #[test]
1582    fn a_disabled_radio_does_not_report_a_tap() {
1583        test_widgets(|tester| {
1584            let theme = m3(tester);
1585            let key = GlobalKey::new();
1586            let log: Rc<RefCell<Vec<Option<i32>>>> = Rc::default();
1587
1588            tester.pump_widget(
1589                Theme::new(
1590                    theme,
1591                    Material::new().child(
1592                        Center::new().child(
1593                            Radio::new(1)
1594                                .key(key.clone().into())
1595                                .group_value(2)
1596                                .enabled(false)
1597                                .on_changed(log_into(&log)),
1598                        ),
1599                    ),
1600                )
1601                .into_widget(),
1602            );
1603            tester.tap_at(tester.get_center(&key), 1);
1604            assert!(log.borrow().is_empty());
1605        });
1606    }
1607
1608    #[test]
1609    fn a_toggleable_radio_reports_null_when_tapped_while_selected() {
1610        test_widgets(|tester| {
1611            let theme = m3(tester);
1612            let key = GlobalKey::new();
1613            let log: Rc<RefCell<Vec<Option<i32>>>> = Rc::default();
1614            let wrap = |radio: Radio<i32>| {
1615                Theme::new(
1616                    theme.clone(),
1617                    Material::new().child(Center::new().child(radio.key(key.clone().into()))),
1618                )
1619                .into_widget()
1620            };
1621
1622            tester.pump_widget(wrap(
1623                Radio::new(1)
1624                    .group_value(2)
1625                    .on_changed(log_into(&log))
1626                    .toggleable(true),
1627            ));
1628            tester.tap_at(tester.get_center(&key), 1);
1629            assert_eq!(*log.borrow(), [Some(1)]);
1630            log.borrow_mut().clear();
1631
1632            tester.pump_widget(wrap(
1633                Radio::new(1)
1634                    .group_value(1)
1635                    .on_changed(log_into(&log))
1636                    .toggleable(true),
1637            ));
1638            tester.tap_at(tester.get_center(&key), 2);
1639            assert_eq!(*log.borrow(), [None]);
1640            log.borrow_mut().clear();
1641
1642            tester.pump_widget(wrap(
1643                Radio::new(1).on_changed(log_into(&log)).toggleable(true),
1644            ));
1645            tester.tap_at(tester.get_center(&key), 3);
1646            assert_eq!(*log.borrow(), [Some(1)]);
1647        });
1648    }
1649
1650    #[test]
1651    fn the_radio_size_is_configurable_by_the_theme_tap_target_size() {
1652        test_widgets(|tester| {
1653            let theme = m3(tester);
1654            let size_of = |tester: &mut WidgetTester, tap_target_size: MaterialTapTargetSize| {
1655                let key = GlobalKey::new();
1656                tester.pump_widget(
1657                    Theme::new(
1658                        theme
1659                            .copy_with()
1660                            .material_tap_target_size(tap_target_size)
1661                            .build(),
1662                        waft_widgets::Directionality::new(
1663                            waft_embedder::TextDirection::Ltr,
1664                            Material::new().child(
1665                                Center::new().child(
1666                                    Radio::new(true)
1667                                        .key(key.clone().into())
1668                                        .group_value(true)
1669                                        .on_changed(no_op()),
1670                                ),
1671                            ),
1672                        ),
1673                    )
1674                    .into_widget(),
1675                );
1676                let render = tester.render_object(&key).as_box().expect("a box");
1677                render.size(&tester.cell.borrow())
1678            };
1679
1680            assert_eq!(
1681                size_of(tester, MaterialTapTargetSize::Padded),
1682                Size::new(48.0, 48.0)
1683            );
1684            assert_eq!(
1685                size_of(tester, MaterialTapTargetSize::ShrinkWrap),
1686                Size::new(40.0, 40.0)
1687            );
1688        });
1689    }
1690
1691    #[test]
1692    fn a_radio_with_a_splash_radius_paints_its_focus_reaction_that_large() {
1693        test_widgets(|tester| {
1694            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1695            const SPLASH_RADIUS: f64 = 30.0;
1696            let theme = m3(tester);
1697            tester.pump_widget(centered_app(
1698                theme,
1699                white_box(
1700                    Radio::new(0)
1701                        .on_changed(no_op())
1702                        .focus_color(Colors::ORANGE.shade500())
1703                        .autofocus(true)
1704                        .group_value(0)
1705                        .splash_radius(SPLASH_RADIUS),
1706                ),
1707            ));
1708            tester.pump_and_settle();
1709            assert_paints(
1710                tester,
1711                radio_material::<i32>(tester),
1712                &[circle(Colors::ORANGE.shade500()).radius(SPLASH_RADIUS)],
1713            );
1714        });
1715    }
1716
1717    /// Dart's `buildApp({enabled})` of the focus and hover cases: a `Radio<int>` of value 0 in
1718    /// a white box, enabled through `onChanged`.
1719    fn focus_and_hover_app(
1720        theme: ThemeData,
1721        group_value: i32,
1722        enabled: bool,
1723        configure: impl FnOnce(Radio<i32>) -> Radio<i32>,
1724    ) -> WidgetRef {
1725        let mut radio = Radio::new(0).group_value(group_value);
1726        if enabled {
1727            radio = radio.on_changed(no_op());
1728        }
1729        centered_app(theme, white_box(configure(radio)))
1730    }
1731
1732    #[test]
1733    fn material2_a_radio_is_focusable_and_has_the_focus_color() {
1734        test_widgets(|tester| {
1735            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1736            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
1737                .into_erased::<waft_widgets::AnyFocusNode>();
1738            let theme = m2(tester);
1739            let configure = {
1740                let focus_node = focus_node.clone();
1741                move |radio: Radio<i32>| {
1742                    radio
1743                        .focus_color(Colors::ORANGE.shade500())
1744                        .autofocus(true)
1745                        .focus_node(focus_node.clone())
1746                }
1747            };
1748
1749            tester.pump_widget(focus_and_hover_app(
1750                theme.clone(),
1751                0,
1752                true,
1753                configure.clone(),
1754            ));
1755            tester.pump_and_settle();
1756            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1757            assert_paints(
1758                tester,
1759                radio_material::<i32>(tester),
1760                &[
1761                    rect(Color::new(0xffffffff), CENTER_RECT),
1762                    circle(Colors::ORANGE.shade500()),
1763                    circle(Color::new(0xff2196f3)),
1764                    circle(Color::new(0xff2196f3)),
1765                ],
1766            );
1767
1768            // Check when the radio isn't selected.
1769            tester.pump_widget(focus_and_hover_app(
1770                theme.clone(),
1771                1,
1772                true,
1773                configure.clone(),
1774            ));
1775            tester.pump_and_settle();
1776            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1777            assert_paints(
1778                tester,
1779                radio_material::<i32>(tester),
1780                &[
1781                    rect(Color::new(0xffffffff), CENTER_RECT),
1782                    circle(Colors::ORANGE.shade500()),
1783                    circle(Color::new(0x8a000000)).stroke_width(2.0),
1784                ],
1785            );
1786
1787            // Check when the radio is selected, but disabled.
1788            tester.pump_widget(focus_and_hover_app(theme, 0, false, configure));
1789            tester.pump_and_settle();
1790            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
1791            assert_paints(
1792                tester,
1793                radio_material::<i32>(tester),
1794                &[
1795                    rect(Color::new(0xffffffff), CENTER_RECT),
1796                    circle(Color::new(0x61000000)),
1797                    circle(Color::new(0x61000000)),
1798                ],
1799            );
1800        });
1801    }
1802
1803    #[test]
1804    fn material3_a_radio_is_focusable_and_has_the_focus_color() {
1805        test_widgets(|tester| {
1806            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1807            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
1808                .into_erased::<waft_widgets::AnyFocusNode>();
1809            let theme = m3(tester);
1810            let colors = theme.color_scheme.clone();
1811            let configure = {
1812                let focus_node = focus_node.clone();
1813                move |radio: Radio<i32>| {
1814                    radio
1815                        .focus_color(Colors::ORANGE.shade500())
1816                        .autofocus(true)
1817                        .focus_node(focus_node.clone())
1818                }
1819            };
1820
1821            tester.pump_widget(focus_and_hover_app(
1822                theme.clone(),
1823                0,
1824                true,
1825                configure.clone(),
1826            ));
1827            tester.pump_and_settle();
1828            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1829            assert_paints(
1830                tester,
1831                radio_material::<i32>(tester),
1832                &[
1833                    rect(Color::new(0xffffffff), CENTER_RECT),
1834                    circle(Colors::ORANGE.shade500()),
1835                    circle(colors.primary()),
1836                    circle(colors.primary()),
1837                ],
1838            );
1839
1840            // Check when the radio isn't selected.
1841            tester.pump_widget(focus_and_hover_app(
1842                theme.clone(),
1843                1,
1844                true,
1845                configure.clone(),
1846            ));
1847            tester.pump_and_settle();
1848            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
1849            assert_paints(
1850                tester,
1851                radio_material::<i32>(tester),
1852                &[
1853                    any_rect(),
1854                    circle(Colors::ORANGE.shade500()),
1855                    circle(colors.on_surface()),
1856                ],
1857            );
1858
1859            // Check when the radio is selected, but disabled.
1860            tester.pump_widget(focus_and_hover_app(theme, 0, false, configure));
1861            tester.pump_and_settle();
1862            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
1863            assert_paints(
1864                tester,
1865                radio_material::<i32>(tester),
1866                &[
1867                    rect(Color::new(0xffffffff), CENTER_RECT),
1868                    circle(colors.on_surface().with_opacity(0.38)),
1869                    circle(colors.on_surface().with_opacity(0.38)),
1870                ],
1871            );
1872        });
1873    }
1874
1875    #[test]
1876    fn material2_a_radio_can_be_hovered_and_has_the_hover_color() {
1877        test_widgets(|tester| {
1878            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1879            let theme = m2(tester);
1880            let configure = |radio: Radio<i32>| radio.hover_color(Colors::ORANGE.shade500());
1881
1882            tester.pump_widget(focus_and_hover_app(theme.clone(), 0, true, configure));
1883            tester.pump();
1884            tester.pump_and_settle();
1885            assert_paints(
1886                tester,
1887                radio_material::<i32>(tester),
1888                &[
1889                    rect(Color::new(0xffffffff), CENTER_RECT),
1890                    circle(Color::new(0xff2196f3)),
1891                    circle(Color::new(0xff2196f3)),
1892                ],
1893            );
1894
1895            // Start hovering
1896            let mut mouse = TestPointer::mouse(1, K_PRIMARY_BUTTON);
1897            let center = center_of_radio::<i32>(tester);
1898            tester.move_to(&mut mouse, center, false);
1899
1900            // Check when the radio isn't selected.
1901            tester.pump_widget(focus_and_hover_app(theme.clone(), 1, true, configure));
1902            tester.pump();
1903            tester.pump_and_settle();
1904            assert_paints(
1905                tester,
1906                radio_material::<i32>(tester),
1907                &[
1908                    rect(Color::new(0xffffffff), CENTER_RECT),
1909                    circle(Colors::ORANGE.shade500()),
1910                    circle(Color::new(0x8a000000)).stroke_width(2.0),
1911                ],
1912            );
1913
1914            // Check when the radio is selected, but disabled.
1915            tester.pump_widget(focus_and_hover_app(theme, 0, false, configure));
1916            tester.pump();
1917            tester.pump_and_settle();
1918            assert_paints(
1919                tester,
1920                radio_material::<i32>(tester),
1921                &[
1922                    rect(Color::new(0xffffffff), CENTER_RECT),
1923                    circle(Color::new(0x61000000)),
1924                    circle(Color::new(0x61000000)),
1925                ],
1926            );
1927        });
1928    }
1929
1930    #[test]
1931    fn material3_a_radio_can_be_hovered_and_has_the_hover_color() {
1932        test_widgets(|tester| {
1933            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1934            let theme = m3(tester);
1935            let colors = theme.color_scheme.clone();
1936            let configure = |radio: Radio<i32>| radio.hover_color(Colors::ORANGE.shade500());
1937
1938            tester.pump_widget(focus_and_hover_app(theme.clone(), 0, true, configure));
1939            tester.pump();
1940            tester.pump_and_settle();
1941            assert_paints(
1942                tester,
1943                radio_material::<i32>(tester),
1944                &[
1945                    rect(Color::new(0xffffffff), CENTER_RECT),
1946                    circle(colors.primary()),
1947                    circle(colors.primary()),
1948                ],
1949            );
1950
1951            // Start hovering
1952            let mut mouse = TestPointer::mouse(1, K_PRIMARY_BUTTON);
1953            let center = center_of_radio::<i32>(tester);
1954            tester.move_to(&mut mouse, center, false);
1955
1956            // Check when the radio isn't selected.
1957            tester.pump_widget(focus_and_hover_app(theme.clone(), 1, true, configure));
1958            tester.pump();
1959            tester.pump_and_settle();
1960            assert_paints(
1961                tester,
1962                radio_material::<i32>(tester),
1963                &[
1964                    rect(Color::new(0xffffffff), CENTER_RECT),
1965                    circle(Colors::ORANGE.shade500()),
1966                    circle(colors.on_surface()).stroke_width(2.0),
1967                ],
1968            );
1969
1970            // Check when the radio is selected, but disabled.
1971            tester.pump_widget(focus_and_hover_app(theme, 0, false, configure));
1972            tester.pump();
1973            tester.pump_and_settle();
1974            assert_paints(
1975                tester,
1976                radio_material::<i32>(tester),
1977                &[
1978                    rect(Color::new(0xffffffff), CENTER_RECT),
1979                    circle(colors.on_surface().with_opacity(0.38)),
1980                    circle(colors.on_surface().with_opacity(0.38)),
1981                ],
1982            );
1983        });
1984    }
1985
1986    #[test]
1987    fn a_radio_can_be_controlled_by_keyboard_shortcuts() {
1988        test_widgets(|tester| {
1989            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
1990            let group_value = Rc::new(Cell::new(Some(1)));
1991            let focus_node2 = FocusNode::new(&mut tester.cell.borrow_mut())
1992                .into_erased::<waft_widgets::AnyFocusNode>();
1993            focus_node2.set_debug_label(&mut tester.cell.borrow_mut(), Some("radio2".into()));
1994            let theme = m3(tester);
1995
1996            let builder_value = Rc::clone(&group_value);
1997            tester.pump_widget(centered_app(
1998                theme,
1999                StatefulBuilder::new({
2000                    let focus_node2 = focus_node2.clone();
2001                    move |_app, _context, set_state| {
2002                        let radio = |value: i32| {
2003                            let group_value = Rc::clone(&builder_value);
2004                            let set_state = Rc::clone(&set_state);
2005                            let mut radio = Radio::new(value)
2006                                .on_changed(Rc::new(
2007                                    move |app: &mut App, new_value: Option<i32>| {
2008                                        set_state(app, &mut |_app| group_value.set(new_value));
2009                                    },
2010                                ))
2011                                .hover_color(Colors::ORANGE.shade500());
2012                            if let Some(group_value) = builder_value.get() {
2013                                radio = radio.group_value(group_value);
2014                            }
2015                            radio
2016                        };
2017                        Container::new()
2018                            .width(200.0)
2019                            .height(100.0)
2020                            .color(Colors::WHITE)
2021                            .child(Row::new().children([
2022                                radio(0).autofocus(true).into_widget(),
2023                                radio(1).into_widget(),
2024                                radio(2).focus_node(focus_node2.clone()).into_widget(),
2025                            ]))
2026                            .into_widget()
2027                    }
2028                }),
2029            ));
2030            tester.pump_and_settle();
2031
2032            tester.send_key_event(PhysicalKeyboardKey::ENTER, LogicalKeyboardKey::ENTER);
2033            tester.pump_and_settle();
2034            // On web, radios don't respond to the enter key.
2035            assert_eq!(
2036                group_value.get(),
2037                if waft_foundation::K_IS_WEB {
2038                    Some(1)
2039                } else {
2040                    Some(0)
2041                }
2042            );
2043
2044            focus_node2.request_focus(&mut tester.cell.borrow_mut(), None);
2045            tester.pump_and_settle();
2046
2047            tester.send_key_event(PhysicalKeyboardKey::SPACE, LogicalKeyboardKey::SPACE);
2048            tester.pump_and_settle();
2049            assert_eq!(group_value.get(), Some(2));
2050        });
2051    }
2052
2053    /// widgets' radio_group_test 'Radio group can use arrow key', with Material radios.
2054    #[test]
2055    fn arrow_keys_move_the_selection_through_a_radio_group() {
2056        test_widgets(|tester| {
2057            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2058                .into_erased::<waft_widgets::AnyFocusNode>();
2059            let group_value: Rc<Cell<Option<i32>>> = Rc::default();
2060            let theme = m3(tester);
2061            let key0 = GlobalKey::new();
2062
2063            let builder_value = Rc::clone(&group_value);
2064            let builder_key = key0.clone();
2065            tester.pump_widget(centered_app(
2066                theme,
2067                StatefulBuilder::new({
2068                    let focus_node = focus_node.clone();
2069                    move |_app, _context, set_state| {
2070                        let group_value = Rc::clone(&builder_value);
2071                        let mut group = RadioGroup::<i32>::new(
2072                            Rc::new(move |app: &mut App, value: Option<i32>| {
2073                                set_state(app, &mut |_app| group_value.set(value));
2074                            }),
2075                            waft_widgets::Column::new().children([
2076                                Radio::new(0)
2077                                    .key(builder_key.clone().into())
2078                                    .focus_node(focus_node.clone())
2079                                    .into_widget(),
2080                                Radio::new(1).into_widget(),
2081                                Radio::new(2).into_widget(),
2082                            ]),
2083                        );
2084                        if let Some(value) = builder_value.get() {
2085                            group = group.group_value(value);
2086                        }
2087                        group.into_widget()
2088                    }
2089                }),
2090            ));
2091
2092            tester.tap_at(tester.get_center(&key0), 1);
2093            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2094            tester.pump_and_settle();
2095            assert_eq!(group_value.get(), Some(0));
2096            assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
2097
2098            let press = |tester: &mut WidgetTester,
2099                         physical: PhysicalKeyboardKey,
2100                         logical: LogicalKeyboardKey| {
2101                tester.send_key_event(physical, logical);
2102                tester.pump_and_settle();
2103                group_value.get()
2104            };
2105            assert_eq!(
2106                press(
2107                    tester,
2108                    PhysicalKeyboardKey::ARROW_DOWN,
2109                    LogicalKeyboardKey::ARROW_DOWN
2110                ),
2111                Some(1)
2112            );
2113            assert_eq!(
2114                press(
2115                    tester,
2116                    PhysicalKeyboardKey::ARROW_RIGHT,
2117                    LogicalKeyboardKey::ARROW_RIGHT
2118                ),
2119                Some(2)
2120            );
2121            // Wrap around
2122            assert_eq!(
2123                press(
2124                    tester,
2125                    PhysicalKeyboardKey::ARROW_RIGHT,
2126                    LogicalKeyboardKey::ARROW_RIGHT
2127                ),
2128                Some(0)
2129            );
2130            // Wrap around
2131            assert_eq!(
2132                press(
2133                    tester,
2134                    PhysicalKeyboardKey::ARROW_LEFT,
2135                    LogicalKeyboardKey::ARROW_LEFT
2136                ),
2137                Some(2)
2138            );
2139            assert_eq!(
2140                press(
2141                    tester,
2142                    PhysicalKeyboardKey::ARROW_UP,
2143                    LogicalKeyboardKey::ARROW_UP
2144                ),
2145                Some(1)
2146            );
2147        });
2148    }
2149
2150    #[test]
2151    fn a_radio_responds_to_density_changes() {
2152        test_widgets(|tester| {
2153            let theme = m3(tester);
2154            let key = GlobalKey::new();
2155            let build_test = |tester: &mut WidgetTester, visual_density: VisualDensity| {
2156                tester.pump_widget(centered_app(
2157                    theme.clone(),
2158                    Radio::new(0)
2159                        .visual_density(visual_density)
2160                        .key(key.clone().into())
2161                        .on_changed(no_op())
2162                        .group_value(0),
2163                ));
2164                tester.pump_and_settle();
2165                let render = tester.render_object(&key).as_box().expect("a box");
2166                render.size(&tester.cell.borrow())
2167            };
2168
2169            assert_eq!(
2170                build_test(tester, VisualDensity::STANDARD),
2171                Size::new(48.0, 48.0)
2172            );
2173            assert_eq!(
2174                build_test(tester, VisualDensity::new(3.0, 3.0)),
2175                Size::new(60.0, 60.0)
2176            );
2177            assert_eq!(
2178                build_test(tester, VisualDensity::new(-3.0, -3.0)),
2179                Size::new(36.0, 36.0)
2180            );
2181            assert_eq!(
2182                build_test(tester, VisualDensity::new(3.0, -3.0)),
2183                Size::new(60.0, 36.0)
2184            );
2185        });
2186    }
2187
2188    #[test]
2189    fn a_radio_changes_the_mouse_cursor_when_hovered() {
2190        test_widgets(|tester| {
2191            let theme = m3(tester);
2192            let app_with = |radio: Radio<i32>| {
2193                scaffold_app(
2194                    theme.clone(),
2195                    Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
2196                        Material::new().child(
2197                            MouseRegion::new()
2198                                .cursor(SystemMouseCursors::FORBIDDEN.into())
2199                                .child(radio),
2200                        ),
2201                    ),
2202                )
2203            };
2204
2205            // Test Radio() constructor
2206            tester.pump_widget(app_with(
2207                Radio::new(1)
2208                    .mouse_cursor(SystemMouseCursors::TEXT.into())
2209                    .on_changed(no_op())
2210                    .group_value(2),
2211            ));
2212            let mut mouse = TestPointer::mouse(1, K_PRIMARY_BUTTON);
2213            let center = center_of_radio::<i32>(tester);
2214            tester.add_pointer(&mut mouse, center);
2215            tester.pump();
2216            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
2217
2218            // Test default cursor
2219            tester.pump_widget(app_with(Radio::new(1).on_changed(no_op()).group_value(2)));
2220            assert_eq!(
2221                tester.active_cursor(1),
2222                if waft_foundation::K_IS_WEB {
2223                    SystemMouseCursors::CLICK.into()
2224                } else {
2225                    SystemMouseCursors::BASIC.into()
2226                }
2227            );
2228
2229            // Test default cursor when disabled
2230            tester.pump_widget(app_with(Radio::new(1).group_value(2)));
2231            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
2232        });
2233    }
2234
2235    #[test]
2236    fn the_fill_color_resolves_in_enabled_and_disabled_states() {
2237        test_widgets(|tester| {
2238            const ACTIVE_ENABLED_FILL_COLOR: Color = Color::new(0xFF000001);
2239            const ACTIVE_DISABLED_FILL_COLOR: Color = Color::new(0xFF000002);
2240            const INACTIVE_ENABLED_FILL_COLOR: Color = Color::new(0xFF000003);
2241            const INACTIVE_DISABLED_FILL_COLOR: Color = Color::new(0xFF000004);
2242            let fill_color = colors(|states| {
2243                if states.contains(&WidgetState::Disabled) {
2244                    if states.contains(&WidgetState::Selected) {
2245                        return ACTIVE_DISABLED_FILL_COLOR;
2246                    }
2247                    return INACTIVE_DISABLED_FILL_COLOR;
2248                }
2249                if states.contains(&WidgetState::Selected) {
2250                    return ACTIVE_ENABLED_FILL_COLOR;
2251                }
2252                INACTIVE_ENABLED_FILL_COLOR
2253            });
2254            let theme = m3(tester);
2255            let mut check = |group_value: i32, enabled: bool, expected: &[PaintCall]| {
2256                let fill_color = Rc::clone(&fill_color);
2257                tester.pump_widget(focus_and_hover_app(
2258                    theme.clone(),
2259                    group_value,
2260                    enabled,
2261                    move |radio| radio.fill_color(fill_color),
2262                ));
2263                tester.pump_and_settle();
2264                assert_paints(tester, radio_material::<i32>(tester), expected);
2265            };
2266
2267            // Selected and enabled.
2268            check(
2269                0,
2270                true,
2271                &[
2272                    rect(Color::new(0xffffffff), CENTER_RECT),
2273                    circle(ACTIVE_ENABLED_FILL_COLOR),
2274                    circle(ACTIVE_ENABLED_FILL_COLOR),
2275                ],
2276            );
2277            // Check when the radio isn't selected.
2278            check(
2279                1,
2280                true,
2281                &[
2282                    rect(Color::new(0xffffffff), CENTER_RECT),
2283                    circle(INACTIVE_ENABLED_FILL_COLOR).stroke_width(2.0),
2284                ],
2285            );
2286            // Check when the radio is selected, but disabled.
2287            check(
2288                0,
2289                false,
2290                &[
2291                    rect(Color::new(0xffffffff), CENTER_RECT),
2292                    circle(ACTIVE_DISABLED_FILL_COLOR),
2293                    circle(ACTIVE_DISABLED_FILL_COLOR),
2294                ],
2295            );
2296            // Check when the radio is unselected and disabled.
2297            check(
2298                1,
2299                false,
2300                &[
2301                    rect(Color::new(0xffffffff), CENTER_RECT),
2302                    circle(INACTIVE_DISABLED_FILL_COLOR).stroke_width(2.0),
2303                ],
2304            );
2305        });
2306    }
2307
2308    /// The fill colour of the hovered and focused cases.
2309    fn hovered_or_focused_fill_color() -> WidgetStatePropertyRef<Option<Color>> {
2310        colors(|states| {
2311            if states.contains(&WidgetState::Hovered) {
2312                return Color::new(0xFF000001);
2313            }
2314            if states.contains(&WidgetState::Focused) {
2315                return Color::new(0xFF000002);
2316            }
2317            Colors::TRANSPARENT
2318        })
2319    }
2320
2321    fn fill_color_in_hovered_and_focused_states(
2322        tester: &mut WidgetTester,
2323        m3_theme: bool,
2324        focus: Color,
2325        hover: Color,
2326    ) {
2327        tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2328        let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2329            .into_erased::<waft_widgets::AnyFocusNode>();
2330        focus_node.set_debug_label(&mut tester.cell.borrow_mut(), Some("radio".into()));
2331        let theme = if m3_theme { m3(tester) } else { m2(tester) };
2332        let fill_color = hovered_or_focused_fill_color();
2333
2334        tester.pump_widget(focus_and_hover_app(theme, 0, true, {
2335            let focus_node = focus_node.clone();
2336            move |radio| {
2337                radio
2338                    .autofocus(true)
2339                    .focus_node(focus_node.clone())
2340                    .fill_color(fill_color)
2341            }
2342        }));
2343        tester.pump_and_settle();
2344        assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2345        assert_paints(
2346            tester,
2347            radio_material::<i32>(tester),
2348            &[
2349                if m3_theme {
2350                    any_rect()
2351                } else {
2352                    rect(Color::new(0xffffffff), CENTER_RECT)
2353                },
2354                circle(focus),
2355                circle(Color::new(0xFF000002)),
2356            ],
2357        );
2358
2359        // Start hovering
2360        let center = center_of_radio::<i32>(tester);
2361        hover_at(tester, center);
2362        tester.pump_and_settle();
2363        assert_paints(
2364            tester,
2365            radio_material::<i32>(tester),
2366            &[
2367                rect(Color::new(0xffffffff), CENTER_RECT),
2368                circle(hover),
2369                circle(Color::new(0xFF000001)),
2370            ],
2371        );
2372    }
2373
2374    #[test]
2375    fn material2_the_fill_color_resolves_in_hovered_and_focused_states() {
2376        test_widgets(|tester| {
2377            let hover_color = m2(tester).hover_color;
2378            fill_color_in_hovered_and_focused_states(tester, false, Colors::BLACK12, hover_color);
2379        });
2380    }
2381
2382    #[test]
2383    fn material3_the_fill_color_resolves_in_hovered_and_focused_states() {
2384        test_widgets(|tester| {
2385            let primary = m3(tester).color_scheme.primary();
2386            fill_color_in_hovered_and_focused_states(
2387                tester,
2388                true,
2389                primary.with_opacity(0.1),
2390                primary.with_opacity(0.08),
2391            );
2392        });
2393    }
2394
2395    #[test]
2396    fn the_overlay_color_resolves_in_active_pressed_focused_and_hovered_states() {
2397        test_widgets(|tester| {
2398            const FILL_COLOR: Color = Color::new(0xFF000000);
2399            const ACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000001);
2400            const INACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000002);
2401            const HOVER_OVERLAY_COLOR: Color = Color::new(0xFF000003);
2402            const FOCUS_OVERLAY_COLOR: Color = Color::new(0xFF000004);
2403            const HOVER_COLOR: Color = Color::new(0xFF000005);
2404            const FOCUS_COLOR: Color = Color::new(0xFF000006);
2405            const SPLASH_RADIUS: f64 = 24.0;
2406            let get_overlay_color = |states: &WidgetStates| -> Option<Color> {
2407                if states.contains(&WidgetState::Pressed) {
2408                    if states.contains(&WidgetState::Selected) {
2409                        return Some(ACTIVE_PRESSED_OVERLAY_COLOR);
2410                    }
2411                    return Some(INACTIVE_PRESSED_OVERLAY_COLOR);
2412                }
2413                if states.contains(&WidgetState::Hovered) {
2414                    return Some(HOVER_OVERLAY_COLOR);
2415                }
2416                if states.contains(&WidgetState::Focused) {
2417                    return Some(FOCUS_OVERLAY_COLOR);
2418                }
2419                None
2420            };
2421            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2422            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2423                .into_erased::<waft_widgets::AnyFocusNode>();
2424            let theme = m3(tester);
2425            let build_radio = |active: bool, focused: bool, use_overlay: bool| {
2426                let mut radio = Radio::new(active)
2427                    .focus_node(focus_node.clone())
2428                    .autofocus(focused)
2429                    .group_value(true)
2430                    .on_changed(no_op())
2431                    .fill_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
2432                        FILL_COLOR,
2433                    )))
2434                    .hover_color(HOVER_COLOR)
2435                    .focus_color(FOCUS_COLOR)
2436                    .splash_radius(SPLASH_RADIUS);
2437                if use_overlay {
2438                    radio = radio.overlay_color(
2439                        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(get_overlay_color),
2440                    );
2441                }
2442                scaffold_app(theme.clone(), radio)
2443            };
2444            let reaction = |color: Color| [circle(color).radius(SPLASH_RADIUS)];
2445
2446            tester.pump_widget(build_radio(false, false, false));
2447            let center = center_of_radio::<bool>(tester);
2448            press_at(tester, center, 1);
2449            tester.pump_and_settle();
2450            // Default inactive pressed Radio should have overlay color from fillColor
2451            assert_paints(
2452                tester,
2453                radio_material::<bool>(tester),
2454                &reaction(FILL_COLOR.with_alpha(K_RADIAL_REACTION_ALPHA)),
2455            );
2456
2457            tester.pump_widget(build_radio(true, false, false));
2458            let center = center_of_radio::<bool>(tester);
2459            press_at(tester, center, 2);
2460            tester.pump_and_settle();
2461            // Default active pressed Radio should have overlay color from fillColor
2462            assert_paints(
2463                tester,
2464                radio_material::<bool>(tester),
2465                &reaction(FILL_COLOR.with_alpha(K_RADIAL_REACTION_ALPHA)),
2466            );
2467
2468            tester.pump_widget(build_radio(false, false, true));
2469            let center = center_of_radio::<bool>(tester);
2470            press_at(tester, center, 3);
2471            tester.pump_and_settle();
2472            assert_paints(
2473                tester,
2474                radio_material::<bool>(tester),
2475                &reaction(INACTIVE_PRESSED_OVERLAY_COLOR),
2476            );
2477
2478            tester.pump_widget(build_radio(true, false, true));
2479            let center = center_of_radio::<bool>(tester);
2480            press_at(tester, center, 4);
2481            tester.pump_and_settle();
2482            assert_paints(
2483                tester,
2484                radio_material::<bool>(tester),
2485                &reaction(ACTIVE_PRESSED_OVERLAY_COLOR),
2486            );
2487
2488            tester.pump_widget(Container::new().into_widget());
2489            tester.pump_widget(build_radio(false, true, true));
2490            tester.pump_and_settle();
2491            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2492            // Focused Radio should use overlay color FOCUS_OVERLAY_COLOR over FOCUS_COLOR
2493            assert_paints(
2494                tester,
2495                radio_material::<bool>(tester),
2496                &reaction(FOCUS_OVERLAY_COLOR),
2497            );
2498
2499            // Start hovering
2500            let center = center_of_radio::<bool>(tester);
2501            hover_at(tester, center);
2502            tester.pump_and_settle();
2503            // Hovered Radio should use overlay color HOVER_OVERLAY_COLOR over HOVER_COLOR
2504            assert_paints(
2505                tester,
2506                radio_material::<bool>(tester),
2507                &reaction(HOVER_OVERLAY_COLOR),
2508            );
2509        });
2510    }
2511
2512    #[test]
2513    fn a_radio_that_disappears_while_the_pointer_is_down_does_not_crash() {
2514        test_widgets(|tester| {
2515            let theme = m3(tester);
2516            let key = GlobalKey::new();
2517            let build_radio = |show: bool| {
2518                if show {
2519                    centered_app(
2520                        theme.clone(),
2521                        Radio::new(true)
2522                            .key(key.clone().into())
2523                            .group_value(false)
2524                            .on_changed(no_op()),
2525                    )
2526                } else {
2527                    centered_app(theme.clone(), Container::new())
2528                }
2529            };
2530
2531            tester.pump_widget(build_radio(true));
2532            let center = tester.get_center(&key);
2533            // Put a pointer down on the screen.
2534            let mut gesture = TestPointer::touch(1);
2535            tester.down(&mut gesture, center);
2536            tester.pump();
2537            // While the pointer is down, the widget disappears.
2538            tester.pump_widget(build_radio(false));
2539            assert!(key.current_context(&tester.cell.borrow_mut()).is_none());
2540            // Release pointer after widget disappeared.
2541            tester.up(&gesture);
2542        });
2543    }
2544
2545    #[test]
2546    fn a_disabled_radio_shows_a_tooltip() {
2547        test_widgets(|tester| {
2548            const LONG_PRESS_TOOLTIP: &str = "long press tooltip";
2549            const TAP_TOOLTIP: &str = "tap tooltip";
2550            let theme = m3(tester);
2551            let tooltip_center = |tester: &WidgetTester| {
2552                let tooltip = find::by_type::<Tooltip>().evaluate(tester)[0];
2553                tester.get_rect(tooltip).center()
2554            };
2555            tester.pump_widget(material_app(
2556                theme.clone(),
2557                Material::new()
2558                    .child(
2559                        Tooltip::new()
2560                            .message(LONG_PRESS_TOOLTIP)
2561                            .child(Radio::new(true).group_value(false)),
2562                    )
2563                    .into_widget(),
2564            ));
2565
2566            // Default tooltip shows up after long pressed.
2567            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
2568
2569            tester.tap_at(tooltip_center(tester), 1);
2570            tester.pump_by(Duration::from_millis(10));
2571            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
2572
2573            let mut gesture_long_press = TestPointer::touch(2);
2574            tester.down(&mut gesture_long_press, tooltip_center(tester));
2575            tester.pump();
2576            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2577            tester.up(&gesture_long_press);
2578            tester.pump();
2579
2580            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_one_widget());
2581
2582            // Tooltip shows up after tapping when set triggerMode to TooltipTriggerMode.tap.
2583            tester.pump_widget(material_app(
2584                theme,
2585                Material::new()
2586                    .child(
2587                        Tooltip::new()
2588                            .trigger_mode(TooltipTriggerMode::Tap)
2589                            .message(TAP_TOOLTIP)
2590                            .child(Radio::new(true).group_value(false)),
2591                    )
2592                    .into_widget(),
2593            ));
2594
2595            tester.pump_by(Duration::from_secs(24 * 60 * 60));
2596            tester.pump_and_settle();
2597            expect(tester, &find::text(TAP_TOOLTIP), finds_nothing());
2598            expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
2599
2600            tester.tap_at(tooltip_center(tester), 3);
2601            tester.pump_by(Duration::from_millis(10));
2602            expect(tester, &find::text(TAP_TOOLTIP), finds_one_widget());
2603        });
2604    }
2605
2606    fn default_colors(tester: &mut WidgetTester, m3_theme: bool) {
2607        let theme = if m3_theme { m3(tester) } else { m2(tester) };
2608        let selected = if m3_theme {
2609            theme.color_scheme.primary()
2610        } else {
2611            Color::new(0xFF2196F3)
2612        };
2613        let disabled = if m3_theme {
2614            theme.color_scheme.on_surface().with_opacity(0.38)
2615        } else {
2616            Colors::BLACK38
2617        };
2618        let build_radio = |enabled: bool| {
2619            let mut radio = Radio::new(true).group_value(true);
2620            if enabled {
2621                radio = radio.on_changed(no_op());
2622            }
2623            scaffold_app(theme.clone(), radio)
2624        };
2625
2626        tester.pump_widget(build_radio(true));
2627        tester.pump_and_settle();
2628        assert_paints(
2629            tester,
2630            radio_material::<bool>(tester),
2631            &[
2632                // Outer circle - primary value
2633                circle(selected),
2634                // Inner circle - primary value
2635                circle(selected),
2636                PaintCall::Restore,
2637            ],
2638        );
2639
2640        tester.pump_widget(Container::new().into_widget());
2641        tester.pump_widget(build_radio(true));
2642        tester.pump_and_settle();
2643        assert_paints(
2644            tester,
2645            radio_material::<bool>(tester),
2646            &[PaintCall::Save, circle(selected), PaintCall::Restore],
2647        );
2648
2649        tester.pump_widget(Container::new().into_widget());
2650        tester.pump_widget(build_radio(false));
2651        tester.pump_and_settle();
2652        assert_paints(tester, radio_material::<bool>(tester), &[circle(disabled)]);
2653    }
2654
2655    #[test]
2656    fn material2_a_radio_has_the_default_colors() {
2657        test_widgets(|tester| default_colors(tester, false));
2658    }
2659
2660    #[test]
2661    fn material3_a_radio_has_the_default_colors() {
2662        test_widgets(|tester| default_colors(tester, true));
2663    }
2664
2665    #[test]
2666    fn material2_a_radio_has_the_default_overlay_colors_in_hover_focus_and_press_states() {
2667        test_widgets(|tester| {
2668            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2669            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2670                .into_erased::<waft_widgets::AnyFocusNode>();
2671            let theme = m2(tester);
2672            let colors = theme.color_scheme.clone();
2673            let build_radio = |focused: bool, selected: bool| {
2674                scaffold_app(
2675                    theme.clone(),
2676                    Radio::new(true)
2677                        .focus_node(focus_node.clone())
2678                        .autofocus(focused)
2679                        .group_value(selected)
2680                        .on_changed(no_op()),
2681                )
2682            };
2683
2684            // default selected radio
2685            tester.pump_widget(build_radio(false, true));
2686            tester.pump_and_settle();
2687            assert_paints(
2688                tester,
2689                radio_material::<bool>(tester),
2690                &[circle(colors.secondary())],
2691            );
2692
2693            // selected radio in pressed state
2694            tester.pump_widget(build_radio(false, true));
2695            let center = center_of_radio::<bool>(tester);
2696            press_at(tester, center, 1);
2697            tester.pump_and_settle();
2698            assert_paints(
2699                tester,
2700                radio_material::<bool>(tester),
2701                &[
2702                    circle(colors.secondary().with_alpha(0x1F)),
2703                    circle(colors.secondary()),
2704                ],
2705            );
2706
2707            // unselected radio in pressed state
2708            tester.pump_widget(build_radio(false, false));
2709            let center = center_of_radio::<bool>(tester);
2710            press_at(tester, center, 2);
2711            tester.pump_and_settle();
2712            assert_paints(
2713                tester,
2714                radio_material::<bool>(tester),
2715                &[
2716                    circle(theme.unselected_widget_color.with_alpha(0x1F)),
2717                    circle(theme.unselected_widget_color),
2718                ],
2719            );
2720
2721            // selected radio in focused state
2722            tester.pump_widget(Container::new().into_widget()); // reset test
2723            tester.pump_widget(build_radio(true, true));
2724            tester.pump_and_settle();
2725            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2726            assert_paints(
2727                tester,
2728                radio_material::<bool>(tester),
2729                &[circle(theme.focus_color), circle(colors.secondary())],
2730            );
2731
2732            // unselected radio in focused state
2733            tester.pump_widget(Container::new().into_widget()); // reset test
2734            tester.pump_widget(build_radio(true, false));
2735            tester.pump_and_settle();
2736            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2737            assert_paints(
2738                tester,
2739                radio_material::<bool>(tester),
2740                &[
2741                    circle(theme.focus_color),
2742                    circle(theme.unselected_widget_color),
2743                ],
2744            );
2745
2746            // selected radio in hovered state
2747            tester.pump_widget(Container::new().into_widget()); // reset test
2748            tester.pump_widget(build_radio(false, true));
2749            let center = center_of_radio::<bool>(tester);
2750            hover_at(tester, center);
2751            tester.pump_and_settle();
2752            assert_paints(
2753                tester,
2754                radio_material::<bool>(tester),
2755                &[circle(theme.hover_color), circle(colors.secondary())],
2756            );
2757        });
2758    }
2759
2760    #[test]
2761    fn material3_a_radio_has_the_default_overlay_colors_in_hover_focus_and_press_states() {
2762        test_widgets(|tester| {
2763            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2764            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2765                .into_erased::<waft_widgets::AnyFocusNode>();
2766            let theme = m3(tester);
2767            let colors = theme.color_scheme.clone();
2768            let build_radio = |focused: bool, selected: bool| {
2769                scaffold_app(
2770                    theme.clone(),
2771                    Radio::new(true)
2772                        .focus_node(focus_node.clone())
2773                        .autofocus(focused)
2774                        .group_value(selected)
2775                        .on_changed(no_op()),
2776                )
2777            };
2778
2779            // default selected radio
2780            tester.pump_widget(build_radio(false, true));
2781            tester.pump_and_settle();
2782            assert_paints(
2783                tester,
2784                radio_material::<bool>(tester),
2785                &[circle(colors.primary().with_opacity(1.0))],
2786            );
2787
2788            // selected radio in pressed state
2789            tester.pump_widget(build_radio(false, true));
2790            let center = center_of_radio::<bool>(tester);
2791            press_at(tester, center, 1);
2792            tester.pump_and_settle();
2793            assert_paints(
2794                tester,
2795                radio_material::<bool>(tester),
2796                &[
2797                    circle(colors.on_surface().with_opacity(0.1)),
2798                    circle(colors.primary().with_opacity(1.0)),
2799                ],
2800            );
2801
2802            // unselected radio in pressed state
2803            tester.pump_widget(build_radio(false, false));
2804            let center = center_of_radio::<bool>(tester);
2805            press_at(tester, center, 2);
2806            tester.pump_and_settle();
2807            assert_paints(
2808                tester,
2809                radio_material::<bool>(tester),
2810                &[
2811                    circle(colors.primary().with_opacity(0.1)),
2812                    circle(colors.on_surface_variant().with_opacity(1.0)),
2813                ],
2814            );
2815
2816            // selected radio in focused state
2817            tester.pump_widget(Container::new().into_widget()); // reset test
2818            tester.pump_widget(build_radio(true, true));
2819            tester.pump_and_settle();
2820            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2821            assert_paints(
2822                tester,
2823                radio_material::<bool>(tester),
2824                &[
2825                    circle(colors.primary().with_opacity(0.1)),
2826                    circle(colors.primary().with_opacity(1.0)),
2827                ],
2828            );
2829
2830            // unselected radio in focused state
2831            tester.pump_widget(Container::new().into_widget()); // reset test
2832            tester.pump_widget(build_radio(true, false));
2833            tester.pump_and_settle();
2834            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2835            assert_paints(
2836                tester,
2837                radio_material::<bool>(tester),
2838                &[
2839                    circle(colors.on_surface().with_opacity(0.1)),
2840                    circle(colors.on_surface().with_opacity(1.0)),
2841                ],
2842            );
2843
2844            // selected radio in hovered state
2845            tester.pump_widget(Container::new().into_widget()); // reset test
2846            tester.pump_widget(build_radio(false, true));
2847            let center = center_of_radio::<bool>(tester);
2848            hover_at(tester, center);
2849            tester.pump_and_settle();
2850            assert_paints(
2851                tester,
2852                radio_material::<bool>(tester),
2853                &[
2854                    circle(colors.primary().with_opacity(0.08)),
2855                    circle(colors.primary().with_opacity(1.0)),
2856                ],
2857            );
2858        });
2859    }
2860
2861    #[test]
2862    fn radio_adaptive_shows_the_widget_of_the_platform() {
2863        test_widgets(|tester| {
2864            let build_app = |tester: &WidgetTester, platform: TargetPlatform| {
2865                let theme = ThemeData::builder()
2866                    .platform(platform)
2867                    .build(&tester.cell.borrow());
2868                centered_app(theme, Radio::adaptive(1).group_value(2).on_changed(no_op()))
2869            };
2870
2871            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
2872                let app = build_app(tester, platform);
2873                tester.pump_widget(app);
2874                tester.pump_and_settle();
2875                expect(
2876                    tester,
2877                    &find::by_type::<CupertinoRadio<i32>>(),
2878                    finds_one_widget(),
2879                );
2880            }
2881
2882            for platform in [
2883                TargetPlatform::Android,
2884                TargetPlatform::Fuchsia,
2885                TargetPlatform::Linux,
2886                TargetPlatform::Windows,
2887            ] {
2888                let app = build_app(tester, platform);
2889                tester.pump_widget(app);
2890                tester.pump_and_settle();
2891                assert!(
2892                    find::by_type::<CupertinoRadio<i32>>()
2893                        .evaluate(tester)
2894                        .is_empty(),
2895                    "{platform:?}"
2896                );
2897            }
2898        });
2899    }
2900
2901    fn default_overlay_and_fill_colors_resolve_the_pressed_state(
2902        tester: &mut WidgetTester,
2903        m3_theme: bool,
2904        hover: impl Fn(&ThemeData) -> Color,
2905        pressed: impl Fn(&ThemeData) -> Color,
2906        focus: impl Fn(&ThemeData) -> Color,
2907        fill: impl Fn(&ThemeData) -> Color,
2908    ) {
2909        tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
2910        let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
2911            .into_erased::<waft_widgets::AnyFocusNode>();
2912        let theme = if m3_theme { m3(tester) } else { m2(tester) };
2913
2914        tester.pump_widget(scaffold_app(
2915            theme.clone(),
2916            Radio::new(true)
2917                .focus_node(focus_node.clone())
2918                .group_value(true)
2919                .on_changed(no_op()),
2920        ));
2921
2922        // Hover
2923        let center = center_of_radio::<bool>(tester);
2924        let mut gesture = TestPointer::mouse(1, K_PRIMARY_BUTTON);
2925        tester.add_pointer(&mut gesture, Offset::ZERO);
2926        tester.move_to(&mut gesture, center, false);
2927        tester.pump_and_settle();
2928        assert_paints(
2929            tester,
2930            radio_material::<bool>(tester),
2931            &[circle(hover(&theme)), circle(fill(&theme))],
2932        );
2933
2934        // Highlighted (pressed).
2935        tester.send(&gesture, PointerChange::Down);
2936        tester.pump_and_settle();
2937        assert_paints(
2938            tester,
2939            radio_material::<bool>(tester),
2940            &[circle(pressed(&theme)), circle(fill(&theme))],
2941        );
2942        // Remove pressed and hovered states
2943        tester.up(&gesture);
2944        tester.pump_and_settle();
2945        tester.move_to(&mut gesture, Offset::new(0.0, 50.0), false);
2946        tester.pump_and_settle();
2947
2948        // Focused.
2949        focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2950        tester.pump_and_settle();
2951        assert_paints(
2952            tester,
2953            radio_material::<bool>(tester),
2954            &[circle(focus(&theme)), circle(fill(&theme))],
2955        );
2956    }
2957
2958    #[test]
2959    fn material2_the_default_overlay_and_fill_colors_resolve_the_pressed_state() {
2960        test_widgets(|tester| {
2961            default_overlay_and_fill_colors_resolve_the_pressed_state(
2962                tester,
2963                false,
2964                |theme| theme.hover_color,
2965                |theme| {
2966                    theme
2967                        .color_scheme
2968                        .secondary()
2969                        .with_alpha(K_RADIAL_REACTION_ALPHA)
2970                },
2971                |theme| theme.focus_color,
2972                |theme| theme.color_scheme.secondary(),
2973            );
2974        });
2975    }
2976
2977    #[test]
2978    fn material3_the_default_overlay_and_fill_colors_resolve_the_pressed_state() {
2979        test_widgets(|tester| {
2980            default_overlay_and_fill_colors_resolve_the_pressed_state(
2981                tester,
2982                true,
2983                |theme| theme.color_scheme.primary().with_opacity(0.08),
2984                |theme| theme.color_scheme.on_surface().with_opacity(0.1),
2985                |theme| theme.color_scheme.primary().with_opacity(0.1),
2986                |theme| theme.color_scheme.primary(),
2987            );
2988        });
2989    }
2990
2991    /// Dart's `buildApp` of the cases on `backgroundColor`, `side` and `innerRadius`: a
2992    /// `Radio<int>` of value 0 under a `RadioGroup<int>` in a white box.
2993    fn group_app(
2994        theme: ThemeData,
2995        group_value: i32,
2996        configure: impl FnOnce(Radio<i32>) -> Radio<i32>,
2997    ) -> WidgetRef {
2998        centered_app(
2999            theme,
3000            white_box(
3001                RadioGroup::<i32>::new(no_op(), configure(Radio::new(0))).group_value(group_value),
3002            ),
3003        )
3004    }
3005
3006    #[test]
3007    fn the_background_color_resolves_in_enabled_and_disabled_states() {
3008        test_widgets(|tester| {
3009            const ACTIVE_ENABLED_BACKGROUND_COLOR: Color = Color::new(0xFF000001);
3010            const ACTIVE_DISABLED_BACKGROUND_COLOR: Color = Color::new(0xFF000002);
3011            const INACTIVE_ENABLED_BACKGROUND_COLOR: Color = Color::new(0xFF000003);
3012            const INACTIVE_DISABLED_BACKGROUND_COLOR: Color = Color::new(0xFF000004);
3013            let background_color = colors(|states| {
3014                if states.contains(&WidgetState::Disabled) {
3015                    if states.contains(&WidgetState::Selected) {
3016                        return ACTIVE_DISABLED_BACKGROUND_COLOR;
3017                    }
3018                    return INACTIVE_DISABLED_BACKGROUND_COLOR;
3019                }
3020                if states.contains(&WidgetState::Selected) {
3021                    return ACTIVE_ENABLED_BACKGROUND_COLOR;
3022                }
3023                INACTIVE_ENABLED_BACKGROUND_COLOR
3024            });
3025            let theme = m3(tester);
3026            let mut check = |group_value: i32, enabled: bool, expected: Color| {
3027                let background_color = Rc::clone(&background_color);
3028                tester.pump_widget(group_app(theme.clone(), group_value, move |radio| {
3029                    radio.background_color(background_color).enabled(enabled)
3030                }));
3031                tester.pump_and_settle();
3032                assert_paints(
3033                    tester,
3034                    radio_material::<i32>(tester),
3035                    &[rect(Color::new(0xffffffff), CENTER_RECT), circle(expected)],
3036                );
3037            };
3038
3039            // Selected and enabled.
3040            check(0, true, ACTIVE_ENABLED_BACKGROUND_COLOR);
3041            // Check when the radio isn't selected.
3042            check(1, true, INACTIVE_ENABLED_BACKGROUND_COLOR);
3043            // Check when the radio is selected, but disabled.
3044            check(0, false, ACTIVE_DISABLED_BACKGROUND_COLOR);
3045            // Check when the radio is unselected and disabled.
3046            check(1, false, INACTIVE_DISABLED_BACKGROUND_COLOR);
3047        });
3048    }
3049
3050    /// The focused-then-hovered cases on `backgroundColor`, `side` and `innerRadius`: what the
3051    /// radio paints after its overlay when focused, and when hovered too.
3052    fn resolves_in_hovered_and_focused_states(
3053        tester: &mut WidgetTester,
3054        configure: impl FnOnce(Radio<i32>) -> Radio<i32>,
3055        focused: &[PaintCall],
3056        hovered: &[PaintCall],
3057    ) {
3058        tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
3059        let focus_node = FocusNode::new(&mut tester.cell.borrow_mut())
3060            .into_erased::<waft_widgets::AnyFocusNode>();
3061        focus_node.set_debug_label(&mut tester.cell.borrow_mut(), Some("radio".into()));
3062        let theme = m3(tester);
3063        let primary = theme.color_scheme.primary();
3064
3065        tester.pump_widget(group_app(theme, 0, {
3066            let focus_node = focus_node.clone();
3067            move |radio| configure(radio.autofocus(true).focus_node(focus_node.clone()))
3068        }));
3069        tester.pump_and_settle();
3070        assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
3071        let mut expected = vec![
3072            any_rect(),
3073            circle(primary.with_values(Some(0.1), None, None, None, None)),
3074        ];
3075        expected.extend_from_slice(focused);
3076        assert_paints(tester, radio_material::<i32>(tester), &expected);
3077
3078        // Start hovering
3079        let center = center_of_radio::<i32>(tester);
3080        hover_at(tester, center);
3081        tester.pump_and_settle();
3082        let mut expected = vec![
3083            rect(Color::new(0xffffffff), CENTER_RECT),
3084            circle(primary.with_values(Some(0.08), None, None, None, None)),
3085        ];
3086        expected.extend_from_slice(hovered);
3087        assert_paints(tester, radio_material::<i32>(tester), &expected);
3088    }
3089
3090    #[test]
3091    fn the_background_color_resolves_in_hovered_and_focused_states() {
3092        test_widgets(|tester| {
3093            const HOVERED_BACKGROUND_COLOR: Color = Color::new(0xFF000001);
3094            const FOCUSED_BACKGROUND_COLOR: Color = Color::new(0xFF000002);
3095            let background_color = colors(|states| {
3096                if states.contains(&WidgetState::Hovered) {
3097                    return HOVERED_BACKGROUND_COLOR;
3098                }
3099                if states.contains(&WidgetState::Focused) {
3100                    return FOCUSED_BACKGROUND_COLOR;
3101                }
3102                Colors::TRANSPARENT
3103            });
3104            resolves_in_hovered_and_focused_states(
3105                tester,
3106                move |radio| radio.background_color(background_color),
3107                &[circle(FOCUSED_BACKGROUND_COLOR)],
3108                &[circle(HOVERED_BACKGROUND_COLOR)],
3109            );
3110        });
3111    }
3112
3113    #[test]
3114    fn the_side_resolves_in_enabled_and_disabled_states() {
3115        test_widgets(|tester| {
3116            let active_enabled_side = BorderSide {
3117                color: Color::new(0xFF000001),
3118                ..BorderSide::default()
3119            };
3120            let active_disabled_side = BorderSide {
3121                color: Color::new(0xFF000002),
3122                width: 2.0,
3123                ..BorderSide::default()
3124            };
3125            let inactive_enabled_side = BorderSide {
3126                color: Color::new(0xFF000003),
3127                width: 3.0,
3128                ..BorderSide::default()
3129            };
3130            let inactive_disabled_side = BorderSide {
3131                color: Color::new(0xFF000004),
3132                width: 4.0,
3133                ..BorderSide::default()
3134            };
3135            let theme = m3(tester);
3136            let mut check = |group_value: i32, enabled: bool, expected: BorderSide| {
3137                let side = WidgetStateBorderSide::resolve_with(move |states| {
3138                    if states.contains(&WidgetState::Disabled) {
3139                        if states.contains(&WidgetState::Selected) {
3140                            return Some(active_disabled_side);
3141                        }
3142                        return Some(inactive_disabled_side);
3143                    }
3144                    if states.contains(&WidgetState::Selected) {
3145                        return Some(active_enabled_side);
3146                    }
3147                    Some(inactive_enabled_side)
3148                });
3149                tester.pump_widget(group_app(theme.clone(), group_value, move |radio| {
3150                    radio.side(side).enabled(enabled)
3151                }));
3152                tester.pump_and_settle();
3153                assert_paints(
3154                    tester,
3155                    radio_material::<i32>(tester),
3156                    &[
3157                        rect(Color::new(0xffffffff), CENTER_RECT),
3158                        circle(expected.color).stroke_width(expected.width),
3159                    ],
3160                );
3161            };
3162
3163            // Selected and enabled.
3164            check(0, true, active_enabled_side);
3165            // Check when the radio isn't selected.
3166            check(1, true, inactive_enabled_side);
3167            // Check when the radio is selected, but disabled.
3168            check(0, false, active_disabled_side);
3169            // Check when the radio is unselected and disabled.
3170            check(1, false, inactive_disabled_side);
3171        });
3172    }
3173
3174    #[test]
3175    fn the_side_resolves_in_hovered_and_focused_states() {
3176        test_widgets(|tester| {
3177            let hovered_side = BorderSide {
3178                color: Color::new(0xFF000001),
3179                ..BorderSide::default()
3180            };
3181            let focused_side = BorderSide {
3182                color: Color::new(0xFF000002),
3183                width: 2.0,
3184                ..BorderSide::default()
3185            };
3186            let side = WidgetStateBorderSide::resolve_with(move |states| {
3187                if states.contains(&WidgetState::Hovered) {
3188                    return Some(hovered_side);
3189                }
3190                if states.contains(&WidgetState::Focused) {
3191                    return Some(focused_side);
3192                }
3193                None
3194            });
3195            resolves_in_hovered_and_focused_states(
3196                tester,
3197                move |radio| radio.side(side),
3198                &[circle(focused_side.color).stroke_width(focused_side.width)],
3199                &[circle(hovered_side.color).stroke_width(hovered_side.width)],
3200            );
3201        });
3202    }
3203
3204    #[test]
3205    fn the_inner_radius_resolves_in_enabled_and_disabled_states() {
3206        test_widgets(|tester| {
3207            const ENABLED_INNER_RADIUS: f64 = 1.0;
3208            const DISABLED_INNER_RADIUS: f64 = 2.0;
3209            let inner_radius = <dyn WidgetStateProperty<Option<f64>>>::resolve_with(|states| {
3210                if states.contains(&WidgetState::Disabled) {
3211                    return Some(DISABLED_INNER_RADIUS);
3212                }
3213                Some(ENABLED_INNER_RADIUS)
3214            });
3215            let theme = m3(tester);
3216            let colors = theme.color_scheme.clone();
3217            let mut check = |enabled: bool, expected: &[PaintCall]| {
3218                let inner_radius = Rc::clone(&inner_radius);
3219                tester.pump_widget(group_app(theme.clone(), 0, move |radio| {
3220                    radio.inner_radius(inner_radius).enabled(enabled)
3221                }));
3222                tester.pump_and_settle();
3223                assert_paints(tester, radio_material::<i32>(tester), expected);
3224            };
3225
3226            // Enabled.
3227            check(
3228                true,
3229                &[
3230                    rect(Color::new(0xffffffff), CENTER_RECT),
3231                    circle(colors.primary()),
3232                    circle(colors.primary()).radius(ENABLED_INNER_RADIUS),
3233                ],
3234            );
3235            // Disabled.
3236            check(
3237                false,
3238                &[
3239                    rect(Color::new(0xffffffff), CENTER_RECT),
3240                    circle(colors.on_surface().with_alpha(97)),
3241                    circle(colors.on_surface().with_alpha(97)).radius(DISABLED_INNER_RADIUS),
3242                ],
3243            );
3244        });
3245    }
3246
3247    #[test]
3248    fn the_inner_radius_resolves_in_hovered_and_focused_states() {
3249        test_widgets(|tester| {
3250            const HOVERED_INNER_RADIUS: f64 = 1.0;
3251            const FOCUSED_INNER_RADIUS: f64 = 2.0;
3252            let inner_radius = <dyn WidgetStateProperty<Option<f64>>>::resolve_with(|states| {
3253                if states.contains(&WidgetState::Hovered) {
3254                    return Some(HOVERED_INNER_RADIUS);
3255                }
3256                if states.contains(&WidgetState::Focused) {
3257                    return Some(FOCUSED_INNER_RADIUS);
3258                }
3259                None
3260            });
3261            let primary = m3(tester).color_scheme.primary();
3262            resolves_in_hovered_and_focused_states(
3263                tester,
3264                move |radio| radio.inner_radius(inner_radius),
3265                &[
3266                    circle(primary),
3267                    circle(primary).radius(FOCUSED_INNER_RADIUS),
3268                ],
3269                &[
3270                    circle(primary),
3271                    circle(primary).radius(HOVERED_INNER_RADIUS),
3272                ],
3273            );
3274        });
3275    }
3276
3277    #[test]
3278    fn a_radio_takes_a_string_value_compared_with_eq() {
3279        test_widgets(|tester| {
3280            let theme = m3(tester);
3281            let key = GlobalKey::new();
3282            let changes: Rc<RefCell<Vec<Option<String>>>> = Rc::default();
3283            let build = |group_value: Option<&str>| {
3284                let changes = Rc::clone(&changes);
3285                let mut group = RadioGroup::<String>::new(
3286                    Rc::new(move |_app, value| changes.borrow_mut().push(value)),
3287                    Radio::new(String::from("jefferson"))
3288                        .key(key.clone().into())
3289                        .toggleable(true),
3290                );
3291                if let Some(group_value) = group_value {
3292                    group = group.group_value(String::from(group_value));
3293                }
3294                centered_app(theme.clone(), group)
3295            };
3296
3297            tester.pump_widget(build(Some("lafayette")));
3298            tester.tap_at(tester.get_center(&key), 1);
3299            assert_eq!(*changes.borrow(), [Some(String::from("jefferson"))]);
3300
3301            // An equal string that is another object selects the radio.
3302            tester.pump_widget(build(Some("jefferson")));
3303            tester.pump_and_settle();
3304            assert_eq!(
3305                painter::<String>(tester)
3306                    .position(&tester.cell.borrow())
3307                    .value(&tester.cell.borrow()),
3308                1.0
3309            );
3310
3311            // Selecting a toggleable radio again unselects it.
3312            tester.tap_at(tester.get_center(&key), 2);
3313            assert_eq!(*changes.borrow(), [Some(String::from("jefferson")), None]);
3314        });
3315    }
3316
3317    #[test]
3318    fn a_radio_does_not_crash_at_zero_area() {
3319        test_widgets(|tester| {
3320            let theme = m3(tester);
3321            tester.pump_widget(scaffold_app(
3322                theme,
3323                Center::new().child(SizedBox::shrink().child(Radio::new(true))),
3324            ));
3325            let render = tester.render_box_of(find_radio::<bool>(tester));
3326            assert_eq!(render.size(&tester.cell.borrow()), Size::ZERO);
3327        });
3328    }
3329}