Skip to main content

waft_material/
radio_theme.rs

1//! Flutter counterpart: material_ui's `radio_theme.dart`.
2
3use waft_embedder::{Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{AnyBorderSide, BorderSide};
6use waft_services::MouseCursorRef;
7use waft_widgets::{
8    BuildContext, InheritedWidget, IntoWidget, KeyRef, WidgetRef, WidgetStateBorderSide,
9    WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
10};
11
12use crate::theme::Theme;
13use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
14
15/// Defines default property values for descendant `Radio` widgets.
16///
17/// Descendant widgets obtain the current [`RadioThemeData`] object using
18/// [`RadioTheme::of`]. Instances of [`RadioThemeData`] can be customized
19/// with [`RadioThemeData::copy_with`].
20///
21/// Typically a [`RadioThemeData`] is specified as part of the overall `Theme`
22/// with `ThemeData::radio_theme`.
23///
24/// All [`RadioThemeData`] properties are `None` by default. When `None`, the
25/// `Radio` will use the values from `ThemeData` if they exist, otherwise it
26/// will provide its own defaults based on the overall `Theme`'s color_scheme.
27/// See the individual `Radio` properties for details.
28///
29/// See also:
30///
31///  * `ThemeData`, which describes the overall theme information for the
32///    application.
33///  * [`RadioTheme`], which is used by descendants to obtain the
34///    [`RadioThemeData`].
35#[derive(Clone, Debug, Default)]
36pub struct RadioThemeData {
37    /// The cursor for a mouse pointer when it enters or is hovering over the
38    /// widget.
39    ///
40    /// If specified, overrides the default value of `Radio::mouse_cursor`. The
41    /// default value is `WidgetStateMouseCursor::clickable`.
42    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
43
44    /// The color that fills the radio button, in all `WidgetState`s.
45    ///
46    /// If specified, overrides the default value of `Radio::fill_color`.
47    pub fill_color: Option<WidgetStatePropertyRef<Option<Color>>>,
48
49    /// The color for the radio's `Material`.
50    ///
51    /// If specified, overrides the default value of `Radio::overlay_color`.
52    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
53
54    /// The splash radius of the circular `Material` ink response.
55    ///
56    /// If specified, overrides the default value of `Radio::splash_radius`. The
57    /// default value is `K_RADIAL_REACTION_RADIUS`.
58    pub splash_radius: Option<f64>,
59
60    /// Configures the minimum size of the tap target.
61    ///
62    /// If specified, overrides the default value of
63    /// `Radio::material_tap_target_size`. The default value is the value of
64    /// `ThemeData::material_tap_target_size`.
65    pub material_tap_target_size: Option<MaterialTapTargetSize>,
66
67    /// Defines how compact the radio's layout will be.
68    ///
69    /// If specified, overrides the default value of `Radio::visual_density`. The
70    /// default value is the value of `ThemeData::visual_density`.
71    pub visual_density: Option<VisualDensity>,
72
73    /// The color of the background of the radio button, in all `WidgetState`s.
74    ///
75    /// If specified, overrides the default value of `Radio::background_color`. The
76    /// default value is transparent in all states.
77    pub background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
78
79    /// The side for the circular border of the radio button, in all
80    /// `WidgetState`s.
81    ///
82    /// If specified, overrides the default value of `Radio::side`. The default
83    /// value is a border using the fill color.
84    pub side: Option<AnyBorderSide>,
85
86    /// The radius of the inner circle of the radio button, in all `WidgetState`s.
87    ///
88    /// If specified, overrides the default value of `Radio::inner_radius`. The
89    /// default value is `4.5` in all states.
90    pub inner_radius: Option<WidgetStatePropertyRef<Option<f64>>>,
91}
92
93crate::theme_data_getters::theme_data_getters! {
94    /// Dart's getters of `RadioThemeData`: the theme data answers with its fields, and a defaults
95    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
96    /// are read.
97    pub trait RadioThemeDataGetters for RadioThemeData, fields: radio_theme_data {
98        mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
99        fill_color: Option<WidgetStatePropertyRef<Option<Color>>>,
100        overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
101        splash_radius: Option<f64>,
102        material_tap_target_size: Option<MaterialTapTargetSize>,
103        visual_density: Option<VisualDensity>,
104        background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
105        side: Option<AnyBorderSide>,
106        inner_radius: Option<WidgetStatePropertyRef<Option<f64>>>,
107    }
108}
109
110impl RadioThemeData {
111    /// Creates a theme that can be used for `ThemeData::radio_theme`.
112    pub fn new() -> RadioThemeData {
113        RadioThemeData::default()
114    }
115
116    /// Dart `RadioThemeData(mouseCursor:)`.
117    pub fn mouse_cursor(
118        mut self,
119        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
120    ) -> RadioThemeData {
121        self.mouse_cursor = Some(mouse_cursor);
122        self
123    }
124
125    /// Dart `RadioThemeData(fillColor:)`.
126    pub fn fill_color(
127        mut self,
128        fill_color: WidgetStatePropertyRef<Option<Color>>,
129    ) -> RadioThemeData {
130        self.fill_color = Some(fill_color);
131        self
132    }
133
134    /// Dart `RadioThemeData(overlayColor:)`.
135    pub fn overlay_color(
136        mut self,
137        overlay_color: WidgetStatePropertyRef<Option<Color>>,
138    ) -> RadioThemeData {
139        self.overlay_color = Some(overlay_color);
140        self
141    }
142
143    /// Dart `RadioThemeData(splashRadius:)`.
144    pub fn splash_radius(mut self, splash_radius: f64) -> RadioThemeData {
145        self.splash_radius = Some(splash_radius);
146        self
147    }
148
149    /// Dart `RadioThemeData(materialTapTargetSize:)`.
150    pub fn material_tap_target_size(
151        mut self,
152        material_tap_target_size: MaterialTapTargetSize,
153    ) -> RadioThemeData {
154        self.material_tap_target_size = Some(material_tap_target_size);
155        self
156    }
157
158    /// Dart `RadioThemeData(visualDensity:)`.
159    pub fn visual_density(mut self, visual_density: VisualDensity) -> RadioThemeData {
160        self.visual_density = Some(visual_density);
161        self
162    }
163
164    /// Dart `RadioThemeData(backgroundColor:)`.
165    pub fn background_color(
166        mut self,
167        background_color: WidgetStatePropertyRef<Option<Color>>,
168    ) -> RadioThemeData {
169        self.background_color = Some(background_color);
170        self
171    }
172
173    /// Dart `RadioThemeData(side:)`.
174    pub fn side(mut self, side: impl Into<AnyBorderSide>) -> RadioThemeData {
175        self.side = Some(side.into());
176        self
177    }
178
179    /// Dart `RadioThemeData(innerRadius:)`.
180    pub fn inner_radius(
181        mut self,
182        inner_radius: WidgetStatePropertyRef<Option<f64>>,
183    ) -> RadioThemeData {
184        self.inner_radius = Some(inner_radius);
185        self
186    }
187
188    /// Creates a copy of this object but with the given fields replaced with the
189    /// new values.
190    ///
191    /// Dart's named arguments are the fluent setters on the copy
192    /// (`data.copy_with().splash_radius(1.0)`).
193    pub fn copy_with(&self) -> RadioThemeData {
194        self.clone()
195    }
196
197    // Special case because BorderSide.lerp() doesn't support null arguments.
198    fn lerp_sides(
199        a: Option<&AnyBorderSide>,
200        b: Option<&AnyBorderSide>,
201        t: f64,
202    ) -> Option<BorderSide> {
203        if a.is_none() && b.is_none() {
204            return None;
205        }
206        let a = a.and_then(Self::resolve_side_in_no_state);
207        let b = b.and_then(Self::resolve_side_in_no_state);
208        let a = a.unwrap_or_else(|| BorderSide {
209            width: 0.0,
210            color: b.expect("one side is given").color.with_alpha(0),
211            ..BorderSide::default()
212        });
213        let b = b.unwrap_or(BorderSide {
214            width: 0.0,
215            color: a.color.with_alpha(0),
216            ..BorderSide::default()
217        });
218
219        Some(BorderSide::lerp(a, b, t))
220    }
221
222    /// Dart's `side is WidgetStateBorderSide ? side.resolve(const <WidgetState>{}) : side`.
223    fn resolve_side_in_no_state(side: &AnyBorderSide) -> Option<BorderSide> {
224        match side.extension::<WidgetStateBorderSide>() {
225            Some(side) => side.resolve(&WidgetStates::new()),
226            None => Some(**side),
227        }
228    }
229
230    /// Linearly interpolate between two [`RadioThemeData`]s.
231    ///
232    /// The argument `t` represents position on the timeline, with 0.0 meaning
233    /// that the interpolation has not started, returning `a` (or something
234    /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
235    /// returning `b` (or something equivalent to `b`), and values in between
236    /// meaning that the interpolation is at the relevant point on the timeline
237    /// between `a` and `b`.
238    pub fn lerp(a: Option<&RadioThemeData>, b: Option<&RadioThemeData>, t: f64) -> RadioThemeData {
239        if let (Some(a), Some(b)) = (a, b)
240            && std::ptr::eq(a, b)
241        {
242            return a.clone();
243        }
244        RadioThemeData {
245            mouse_cursor: pick(a, b, t, |theme| theme.mouse_cursor.clone()),
246            fill_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
247                a.and_then(|a| a.fill_color.clone()),
248                b.and_then(|b| b.fill_color.clone()),
249                t,
250                Color::lerp,
251            ),
252            material_tap_target_size: pick(a, b, t, |theme| theme.material_tap_target_size),
253            overlay_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
254                a.and_then(|a| a.overlay_color.clone()),
255                b.and_then(|b| b.overlay_color.clone()),
256                t,
257                Color::lerp,
258            ),
259            splash_radius: lerp_double(
260                a.and_then(|a| a.splash_radius),
261                b.and_then(|b| b.splash_radius),
262                t,
263            ),
264            visual_density: pick(a, b, t, |theme| theme.visual_density),
265            background_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
266                a.and_then(|a| a.background_color.clone()),
267                b.and_then(|b| b.background_color.clone()),
268                t,
269                Color::lerp,
270            ),
271            side: Self::lerp_sides(
272                a.and_then(|a| a.side.as_ref()),
273                b.and_then(|b| b.side.as_ref()),
274                t,
275            )
276            .map(AnyBorderSide::new),
277            inner_radius: <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(
278                a.and_then(|a| a.inner_radius.clone()),
279                b.and_then(|b| b.inner_radius.clone()),
280                t,
281                lerp_double,
282            ),
283        }
284    }
285}
286
287/// Dart's `t < 0.5 ? a?.field : b?.field`.
288fn pick<T>(
289    a: Option<&RadioThemeData>,
290    b: Option<&RadioThemeData>,
291    t: f64,
292    field: impl Fn(&RadioThemeData) -> Option<T>,
293) -> Option<T> {
294    if t < 0.5 {
295        a.and_then(&field)
296    } else {
297        b.and_then(&field)
298    }
299}
300
301impl PartialEq for RadioThemeData {
302    fn eq(&self, other: &RadioThemeData) -> bool {
303        if std::ptr::eq(self, other) {
304            return true;
305        }
306        other.mouse_cursor == self.mouse_cursor
307            && other.fill_color == self.fill_color
308            && other.overlay_color == self.overlay_color
309            && other.splash_radius == self.splash_radius
310            && other.material_tap_target_size == self.material_tap_target_size
311            && other.visual_density == self.visual_density
312            && other.background_color == self.background_color
313            && other.side == self.side
314            && other.inner_radius == self.inner_radius
315    }
316}
317
318/// Applies a radio theme to descendant `Radio` widgets.
319///
320/// Descendant widgets obtain the current theme's [`RadioTheme`] object using
321/// [`RadioTheme::of`]. When a widget uses [`RadioTheme::of`], it is automatically
322/// rebuilt if the theme later changes.
323///
324/// A radio theme can be specified as part of the overall Material theme using
325/// `ThemeData::radio_theme`.
326///
327/// See also:
328///
329///  * [`RadioThemeData`], which describes the actual configuration of a radio
330///    theme.
331#[derive(Debug)]
332pub struct RadioTheme {
333    pub key: Option<KeyRef>,
334    /// The properties used for all descendant `Radio` widgets.
335    pub data: RadioThemeData,
336    pub child: WidgetRef,
337}
338
339impl RadioTheme {
340    /// Constructs a radio theme that configures all descendant `Radio` widgets.
341    #[cfg_attr(debug_assertions, track_caller)]
342    pub fn new<K>(data: RadioThemeData, child: impl IntoWidget<K>) -> RadioTheme {
343        RadioTheme {
344            key: None,
345            data,
346            child: child.into_widget(),
347        }
348    }
349
350    /// Dart `RadioTheme(key:)`.
351    pub fn key(mut self, key: KeyRef) -> RadioTheme {
352        self.key = Some(key);
353        self
354    }
355
356    /// Returns the configuration [`data`](Self::data) from the closest [`RadioTheme`] ancestor.
357    /// If there is no ancestor, it returns `ThemeData::radio_theme`.
358    ///
359    /// Typical usage is as follows:
360    ///
361    /// ```text
362    /// let theme = RadioTheme::of(app, context);
363    /// ```
364    pub fn of(app: &mut App, context: BuildContext) -> RadioThemeData {
365        match context.depend_on_inherited_widget_of_exact_type::<RadioTheme>(app) {
366            Some(radio_theme) => radio_theme.data.clone(),
367            None => Theme::of(app, context).radio_theme.clone(),
368        }
369    }
370}
371
372impl InheritedWidget for RadioTheme {
373    fn key(&self) -> Option<&KeyRef> {
374        self.key.as_ref()
375    }
376
377    fn child(&self) -> &WidgetRef {
378        &self.child
379    }
380
381    fn update_should_notify(&self, old_widget: &RadioTheme) -> bool {
382        self.data != old_widget.data
383    }
384}
385
386impl waft_foundation::Diagnosticable for RadioThemeData {
387    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
388        properties.add(
389            DiagnosticsProperty::<String>::new(
390                "mouseCursor",
391                self.mouse_cursor
392                    .as_deref()
393                    .map(|property| property.to_string()),
394            )
395            .default_value(None),
396        );
397        properties.add(
398            DiagnosticsProperty::<String>::new(
399                "fillColor",
400                self.fill_color
401                    .as_deref()
402                    .map(|property| property.to_string()),
403            )
404            .default_value(None),
405        );
406        properties.add(
407            DiagnosticsProperty::<String>::new(
408                "overlayColor",
409                self.overlay_color
410                    .as_deref()
411                    .map(|property| property.to_string()),
412            )
413            .default_value(None),
414        );
415        properties.add(DoubleProperty::new("splashRadius", self.splash_radius).default_value(None));
416        properties.add(
417            DiagnosticsProperty::<waft_foundation::DartEnum<MaterialTapTargetSize>>::new(
418                "materialTapTargetSize",
419                self.material_tap_target_size.map(waft_foundation::DartEnum),
420            )
421            .default_value(None),
422        );
423        properties.add(
424            DiagnosticsProperty::<VisualDensity>::new("visualDensity", self.visual_density)
425                .default_value(None),
426        );
427        properties.add(
428            DiagnosticsProperty::<String>::new(
429                "backgroundColor",
430                self.background_color
431                    .as_deref()
432                    .map(|property| property.to_string()),
433            )
434            .default_value(None),
435        );
436        properties.add(
437            DiagnosticsProperty::<AnyBorderSide>::new("side", self.side.clone())
438                .default_value(None),
439        );
440        properties.add(
441            DiagnosticsProperty::<String>::new(
442                "innerRadius",
443                self.inner_radius
444                    .as_deref()
445                    .map(|property| property.to_string()),
446            )
447            .default_value(None),
448        );
449    }
450}
451
452impl std::fmt::Display for RadioThemeData {
453    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
455    }
456}
457
458#[cfg(test)]
459#[allow(deprecated)]
460mod tests {
461    use std::rc::Rc;
462
463    use waft_embedder::Size;
464    use waft_painting::BorderStyle;
465    use waft_services::SystemMouseCursors;
466    use waft_widgets::{FocusHighlightStrategy, SizedBox, WidgetState, WidgetStatePropertyAll};
467
468    use waft_widgets::testing::{WidgetTester, test_widgets};
469
470    use super::*;
471    use crate::radio::Radio;
472    use crate::radio::tests::{
473        CircleArguments, assert_paints, center_of_radio, circle, find_radio, hover_at, no_op,
474        press_at, radio_material, scaffold_app,
475    };
476    use crate::theme_data::ThemeData;
477
478    fn theme_with(tester: &WidgetTester, radio_theme: RadioThemeData) -> ThemeData {
479        ThemeData::builder()
480            .radio_theme(radio_theme)
481            .build(&tester.cell.borrow())
482    }
483
484    /// Dart's `_pointGestureToRadio`.
485    fn point_gesture_to_radio(tester: &mut WidgetTester) {
486        let center = center_of_radio::<i32>(tester);
487        hover_at(tester, center);
488    }
489
490    fn radio_size(tester: &WidgetTester) -> Size {
491        let render = tester.render_box_of(find_radio::<i32>(tester));
492        render.size(&tester.cell.borrow())
493    }
494
495    #[test]
496    fn radio_theme_data_copy_with_equality_basics() {
497        assert_eq!(RadioThemeData::new(), RadioThemeData::new().copy_with());
498    }
499
500    #[test]
501    fn radio_theme_data_lerp_special_cases() {
502        assert_eq!(RadioThemeData::lerp(None, None, 0.0), RadioThemeData::new());
503        let fill_color =
504            <dyn WidgetStateProperty<Option<Color>>>::all(Some(Color::new(0xff000001)));
505        let data = RadioThemeData::new().fill_color(Rc::clone(&fill_color));
506        // Dart's `identical`: the same data comes back, its properties not lerped.
507        let lerped = RadioThemeData::lerp(Some(&data), Some(&data), 0.5);
508        assert!(Rc::ptr_eq(
509            lerped.fill_color.as_ref().expect("a fill color"),
510            &fill_color
511        ));
512    }
513
514    #[test]
515    fn radio_theme_data_defaults() {
516        let theme_data = RadioThemeData::new();
517        let all_none = |data: &RadioThemeData| {
518            data.mouse_cursor.is_none()
519                && data.fill_color.is_none()
520                && data.overlay_color.is_none()
521                && data.splash_radius.is_none()
522                && data.material_tap_target_size.is_none()
523                && data.visual_density.is_none()
524                && data.background_color.is_none()
525                && data.side.is_none()
526                && data.inner_radius.is_none()
527        };
528        assert!(all_none(&theme_data));
529
530        let theme = RadioTheme::new(RadioThemeData::new(), SizedBox::new());
531        assert!(all_none(&theme.data));
532    }
533
534    #[test]
535    fn a_radio_is_themeable() {
536        test_widgets(|tester| {
537            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
538            const DEFAULT_FILL_COLOR: Color = Color::new(0xfffffff0);
539            const SELECTED_FILL_COLOR: Color = Color::new(0xfffffff1);
540            const FOCUS_OVERLAY_COLOR: Color = Color::new(0xfffffff2);
541            const HOVER_OVERLAY_COLOR: Color = Color::new(0xfffffff3);
542            const DEFAULT_BACKGROUND_COLOR: Color = Color::new(0xfffffff4);
543            const SELECTED_BACKGROUND_COLOR: Color = Color::new(0xfffffff5);
544            const SPLASH_RADIUS: f64 = 1.0;
545            const MATERIAL_TAP_TARGET_SIZE: MaterialTapTargetSize =
546                MaterialTapTargetSize::ShrinkWrap;
547            const VISUAL_DENSITY: VisualDensity = VisualDensity::new(1.0, 1.0);
548            const INNER_RADIUS: f64 = 5.0;
549            let radio_theme = RadioThemeData::new()
550                .mouse_cursor(Rc::new(WidgetStatePropertyAll::new(Some(
551                    SystemMouseCursors::TEXT.into(),
552                ))))
553                .fill_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
554                    |states| {
555                        if states.contains(&WidgetState::Selected) {
556                            return Some(SELECTED_FILL_COLOR);
557                        }
558                        Some(DEFAULT_FILL_COLOR)
559                    },
560                ))
561                .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
562                    |states| {
563                        if states.contains(&WidgetState::Focused) {
564                            return Some(FOCUS_OVERLAY_COLOR);
565                        }
566                        if states.contains(&WidgetState::Hovered) {
567                            return Some(HOVER_OVERLAY_COLOR);
568                        }
569                        None
570                    },
571                ))
572                .splash_radius(SPLASH_RADIUS)
573                .material_tap_target_size(MATERIAL_TAP_TARGET_SIZE)
574                .visual_density(VISUAL_DENSITY)
575                .background_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
576                    |states| {
577                        if states.contains(&WidgetState::Selected) {
578                            return Some(SELECTED_BACKGROUND_COLOR);
579                        }
580                        Some(DEFAULT_BACKGROUND_COLOR)
581                    },
582                ))
583                .inner_radius(Rc::new(WidgetStatePropertyAll::new(Some(INNER_RADIUS))));
584            let theme = theme_with(tester, radio_theme);
585            let build_radio = |selected: bool, autofocus: bool| {
586                scaffold_app(
587                    theme.clone(),
588                    Radio::new(if selected { 1 } else { 0 })
589                        .on_changed(no_op())
590                        .group_value(1)
591                        .autofocus(autofocus),
592                )
593            };
594
595            // Radio.
596            tester.pump_widget(build_radio(false, false));
597            tester.pump_and_settle();
598            assert_paints(
599                tester,
600                radio_material::<i32>(tester),
601                &[circle(DEFAULT_BACKGROUND_COLOR), circle(DEFAULT_FILL_COLOR)],
602            );
603            // Size from MaterialTapTargetSize.shrinkWrap with added VisualDensity.
604            assert_eq!(
605                radio_size(tester),
606                Size::new(40.0, 40.0) + VISUAL_DENSITY.base_size_adjustment()
607            );
608
609            // Selected radio.
610            tester.pump_widget(build_radio(true, false));
611            tester.pump_and_settle();
612            assert_paints(
613                tester,
614                radio_material::<i32>(tester),
615                &[
616                    circle(SELECTED_BACKGROUND_COLOR),
617                    circle(SELECTED_FILL_COLOR),
618                    circle(SELECTED_FILL_COLOR).radius(INNER_RADIUS),
619                ],
620            );
621
622            // Radio with hover.
623            tester.pump_widget(build_radio(false, false));
624            point_gesture_to_radio(tester);
625            tester.pump_and_settle();
626            assert_paints(
627                tester,
628                radio_material::<i32>(tester),
629                &[circle(HOVER_OVERLAY_COLOR)],
630            );
631            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
632
633            // Radio with focus.
634            tester.pump_widget(build_radio(false, true));
635            tester.pump_and_settle();
636            assert_paints(
637                tester,
638                radio_material::<i32>(tester),
639                &[circle(FOCUS_OVERLAY_COLOR).radius(SPLASH_RADIUS)],
640            );
641        });
642    }
643
644    /// The radio of the side cases: value 0 or 1 against a group value of `group_value`.
645    fn side_radio(tester: &mut WidgetTester, theme: &ThemeData, radio: Radio<i32>) {
646        tester.pump_widget(scaffold_app(theme.clone(), radio.on_changed(no_op())));
647    }
648
649    fn side(color: Color, width: f64) -> BorderSide {
650        BorderSide {
651            color,
652            width,
653            ..BorderSide::default()
654        }
655    }
656
657    #[test]
658    fn the_radio_side_is_themeable() {
659        test_widgets(|tester| {
660            let default_side = side(Color::new(0xfffffff0), 2.0);
661            let selected_side = side(Color::new(0xfffffff1), 3.0);
662            let theme = theme_with(
663                tester,
664                RadioThemeData::new().side(WidgetStateBorderSide::resolve_with(move |states| {
665                    if states.contains(&WidgetState::Selected) {
666                        return Some(selected_side);
667                    }
668                    Some(default_side)
669                })),
670            );
671
672            // Radio.
673            side_radio(tester, &theme, Radio::new(0).group_value(1));
674            assert_paints(
675                tester,
676                radio_material::<i32>(tester),
677                &[circle(default_side.color).stroke_width(default_side.width)],
678            );
679
680            // Selected radio.
681            side_radio(tester, &theme, Radio::new(1).group_value(1));
682            tester.pump_and_settle();
683            assert_paints(
684                tester,
685                radio_material::<i32>(tester),
686                &[circle(selected_side.color).stroke_width(selected_side.width)],
687            );
688        });
689    }
690
691    #[test]
692    fn radio_properties_are_taken_over_the_theme_values() {
693        test_widgets(|tester| {
694            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
695            const THEME_DEFAULT_FILL_COLOR: Color = Color::new(0xfffffff0);
696            const THEME_SELECTED_FILL_COLOR: Color = Color::new(0xfffffff1);
697            const THEME_FOCUS_OVERLAY_COLOR: Color = Color::new(0xfffffff2);
698            const THEME_HOVER_OVERLAY_COLOR: Color = Color::new(0xfffffff3);
699            const THEME_DEFAULT_BACKGROUND_COLOR: Color = Color::new(0xfffffff4);
700            const THEME_SELECTED_BACKGROUND_COLOR: Color = Color::new(0xfffffff5);
701            const THEME_SPLASH_RADIUS: f64 = 1.0;
702            const THEME_INNER_RADIUS: f64 = 5.0;
703
704            const DEFAULT_FILL_COLOR: Color = Color::new(0xeffffff0);
705            const SELECTED_FILL_COLOR: Color = Color::new(0xeffffff1);
706            const FOCUS_COLOR: Color = Color::new(0xeffffff2);
707            const HOVER_COLOR: Color = Color::new(0xeffffff3);
708            const DEFAULT_BACKGROUND_COLOR: Color = Color::new(0xeffffff4);
709            const SELECTED_BACKGROUND_COLOR: Color = Color::new(0xeffffff5);
710            const SPLASH_RADIUS: f64 = 2.0;
711            const VISUAL_DENSITY: VisualDensity = VisualDensity::new(1.0, 1.0);
712            const INNER_RADIUS: f64 = 6.0;
713
714            let theme = theme_with(
715                tester,
716                RadioThemeData::new()
717                    .mouse_cursor(Rc::new(WidgetStatePropertyAll::new(Some(
718                        SystemMouseCursors::CLICK.into(),
719                    ))))
720                    .fill_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
721                        |states| {
722                            if states.contains(&WidgetState::Selected) {
723                                return Some(THEME_SELECTED_FILL_COLOR);
724                            }
725                            Some(THEME_DEFAULT_FILL_COLOR)
726                        },
727                    ))
728                    .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
729                        |states| {
730                            if states.contains(&WidgetState::Focused) {
731                                return Some(THEME_FOCUS_OVERLAY_COLOR);
732                            }
733                            if states.contains(&WidgetState::Hovered) {
734                                return Some(THEME_HOVER_OVERLAY_COLOR);
735                            }
736                            None
737                        },
738                    ))
739                    .splash_radius(THEME_SPLASH_RADIUS)
740                    .material_tap_target_size(MaterialTapTargetSize::Padded)
741                    .visual_density(VisualDensity::STANDARD)
742                    .background_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
743                        |states| {
744                            if states.contains(&WidgetState::Selected) {
745                                return Some(THEME_SELECTED_BACKGROUND_COLOR);
746                            }
747                            Some(THEME_DEFAULT_BACKGROUND_COLOR)
748                        },
749                    ))
750                    .inner_radius(Rc::new(WidgetStatePropertyAll::new(Some(
751                        THEME_INNER_RADIUS,
752                    )))),
753            );
754            let build_radio = |selected: bool, autofocus: bool| {
755                scaffold_app(
756                    theme.clone(),
757                    Radio::new(if selected { 0 } else { 1 })
758                        .on_changed(no_op())
759                        .group_value(0)
760                        .autofocus(autofocus)
761                        .mouse_cursor(SystemMouseCursors::TEXT.into())
762                        .fill_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
763                            |states| {
764                                if states.contains(&WidgetState::Selected) {
765                                    return Some(SELECTED_FILL_COLOR);
766                                }
767                                Some(DEFAULT_FILL_COLOR)
768                            },
769                        ))
770                        .focus_color(FOCUS_COLOR)
771                        .hover_color(HOVER_COLOR)
772                        .splash_radius(SPLASH_RADIUS)
773                        .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
774                        .visual_density(VISUAL_DENSITY)
775                        .background_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
776                            |states| {
777                                if states.contains(&WidgetState::Selected) {
778                                    return Some(SELECTED_BACKGROUND_COLOR);
779                                }
780                                Some(DEFAULT_BACKGROUND_COLOR)
781                            },
782                        ))
783                        .inner_radius(Rc::new(WidgetStatePropertyAll::new(Some(INNER_RADIUS)))),
784                )
785            };
786
787            // Radio.
788            tester.pump_widget(build_radio(false, false));
789            tester.pump_and_settle();
790            assert_paints(
791                tester,
792                radio_material::<i32>(tester),
793                &[circle(DEFAULT_BACKGROUND_COLOR), circle(DEFAULT_FILL_COLOR)],
794            );
795            // Size from MaterialTapTargetSize.shrinkWrap with added VisualDensity.
796            assert_eq!(
797                radio_size(tester),
798                Size::new(40.0, 40.0) + VISUAL_DENSITY.base_size_adjustment()
799            );
800
801            // Selected radio.
802            tester.pump_widget(build_radio(true, false));
803            tester.pump_and_settle();
804            assert_paints(
805                tester,
806                radio_material::<i32>(tester),
807                &[
808                    circle(SELECTED_BACKGROUND_COLOR),
809                    circle(SELECTED_FILL_COLOR),
810                    circle(SELECTED_FILL_COLOR).radius(INNER_RADIUS),
811                ],
812            );
813
814            // Radio with hover.
815            tester.pump_widget(build_radio(false, false));
816            point_gesture_to_radio(tester);
817            tester.pump_and_settle();
818            assert_paints(
819                tester,
820                radio_material::<i32>(tester),
821                &[circle(HOVER_COLOR)],
822            );
823            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
824
825            // Radio with focus.
826            tester.pump_widget(build_radio(false, true));
827            tester.pump_and_settle();
828            assert_paints(
829                tester,
830                radio_material::<i32>(tester),
831                &[circle(FOCUS_COLOR).radius(SPLASH_RADIUS)],
832            );
833        });
834    }
835
836    #[test]
837    fn the_radio_side_property_is_taken_over_the_theme_values() {
838        test_widgets(|tester| {
839            tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
840            let theme_default_side = side(Color::new(0xfffffff0), 2.0);
841            let theme_selected_side = side(Color::new(0xfffffff1), 3.0);
842            let default_side = side(Color::new(0xeffffff2), 4.0);
843            let selected_side = side(Color::new(0xeffffff3), 5.0);
844            let theme = theme_with(
845                tester,
846                RadioThemeData::new().side(WidgetStateBorderSide::resolve_with(move |states| {
847                    if states.contains(&WidgetState::Selected) {
848                        return Some(theme_selected_side);
849                    }
850                    Some(theme_default_side)
851                })),
852            );
853            let radio = |selected: bool| {
854                Radio::new(if selected { 0 } else { 1 })
855                    .group_value(0)
856                    .side(WidgetStateBorderSide::resolve_with(move |states| {
857                        if states.contains(&WidgetState::Selected) {
858                            return Some(selected_side);
859                        }
860                        Some(default_side)
861                    }))
862            };
863
864            // Radio.
865            side_radio(tester, &theme, radio(false));
866            tester.pump_and_settle();
867            assert_paints(
868                tester,
869                radio_material::<i32>(tester),
870                &[circle(default_side.color).stroke_width(default_side.width)],
871            );
872
873            // Selected radio.
874            side_radio(tester, &theme, radio(true));
875            tester.pump_and_settle();
876            assert_paints(
877                tester,
878                radio_material::<i32>(tester),
879                &[circle(selected_side.color).stroke_width(selected_side.width)],
880            );
881        });
882    }
883
884    #[test]
885    fn the_radio_active_color_is_taken_over_the_theme() {
886        test_widgets(|tester| {
887            const THEME_DEFAULT_FILL_COLOR: Color = Color::new(0xfffffff0);
888            const THEME_SELECTED_FILL_COLOR: Color = Color::new(0xfffffff1);
889            const SELECTED_FILL_COLOR: Color = Color::new(0xfffffff1);
890            let theme = theme_with(
891                tester,
892                RadioThemeData::new().fill_color(
893                    <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
894                        if states.contains(&WidgetState::Selected) {
895                            return Some(THEME_SELECTED_FILL_COLOR);
896                        }
897                        Some(THEME_DEFAULT_FILL_COLOR)
898                    }),
899                ),
900            );
901            let radio = |selected: bool| {
902                Radio::new(if selected { 0 } else { 1 })
903                    .group_value(0)
904                    .active_color(SELECTED_FILL_COLOR)
905            };
906
907            // Radio.
908            side_radio(tester, &theme, radio(false));
909            tester.pump_and_settle();
910            assert_paints(
911                tester,
912                radio_material::<i32>(tester),
913                &[circle(THEME_DEFAULT_FILL_COLOR)],
914            );
915
916            // Selected radio.
917            side_radio(tester, &theme, radio(true));
918            tester.pump_and_settle();
919            assert_paints(
920                tester,
921                radio_material::<i32>(tester),
922                &[circle(SELECTED_FILL_COLOR)],
923            );
924        });
925    }
926
927    #[test]
928    fn the_theme_overlay_color_resolves_in_active_and_pressed_states() {
929        test_widgets(|tester| {
930            const ACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000001);
931            const INACTIVE_PRESSED_OVERLAY_COLOR: Color = Color::new(0xFF000002);
932            const SPLASH_RADIUS: f64 = 24.0;
933            let theme = theme_with(
934                tester,
935                RadioThemeData::new()
936                    .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
937                        |states| {
938                            if states.contains(&WidgetState::Pressed) {
939                                if states.contains(&WidgetState::Selected) {
940                                    return Some(ACTIVE_PRESSED_OVERLAY_COLOR);
941                                }
942                                return Some(INACTIVE_PRESSED_OVERLAY_COLOR);
943                            }
944                            None
945                        },
946                    ))
947                    .splash_radius(SPLASH_RADIUS),
948            );
949            let radio = |active: bool| Radio::new(if active { 1 } else { 0 }).group_value(1);
950
951            side_radio(tester, &theme, radio(false));
952            let center = center_of_radio::<i32>(tester);
953            press_at(tester, center, 1);
954            tester.pump_and_settle();
955            // Inactive pressed Radio should have overlay color INACTIVE_PRESSED_OVERLAY_COLOR
956            assert_paints(
957                tester,
958                radio_material::<i32>(tester),
959                &[circle(INACTIVE_PRESSED_OVERLAY_COLOR).radius(SPLASH_RADIUS)],
960            );
961
962            side_radio(tester, &theme, radio(true));
963            let center = center_of_radio::<i32>(tester);
964            press_at(tester, center, 2);
965            tester.pump_and_settle();
966            // Active pressed Radio should have overlay color ACTIVE_PRESSED_OVERLAY_COLOR
967            assert_paints(
968                tester,
969                radio_material::<i32>(tester),
970                &[circle(ACTIVE_PRESSED_OVERLAY_COLOR).radius(SPLASH_RADIUS)],
971            );
972        });
973    }
974
975    #[test]
976    fn a_local_radio_theme_overrides_the_global_one() {
977        test_widgets(|tester| {
978            const GLOBAL_THEME_FILL_COLOR: Color = Color::new(0xfffffff1);
979            const LOCAL_THEME_FILL_COLOR: Color = Color::new(0xffff0000);
980            let theme = theme_with(
981                tester,
982                RadioThemeData::new().fill_color(Rc::new(WidgetStatePropertyAll::new(Some(
983                    GLOBAL_THEME_FILL_COLOR,
984                )))),
985            );
986
987            tester.pump_widget(scaffold_app(
988                theme,
989                RadioTheme::new(
990                    RadioThemeData::new().fill_color(Rc::new(WidgetStatePropertyAll::new(Some(
991                        LOCAL_THEME_FILL_COLOR,
992                    )))),
993                    Radio::new(1).group_value(1).on_changed(no_op()),
994                ),
995            ));
996            tester.pump_and_settle();
997            assert_paints(
998                tester,
999                radio_material::<i32>(tester),
1000                &[circle(LOCAL_THEME_FILL_COLOR)],
1001            );
1002        });
1003    }
1004    // Flutter's "Default RadioThemeData debugFillProperties".
1005    #[test]
1006    fn a_radio_theme_data_describes_nothing_by_default() {
1007        assert_eq!(
1008            waft_widgets::testing::describe_properties(|properties| {
1009                waft_foundation::Diagnosticable::debug_fill_properties(
1010                    &RadioThemeData::new(),
1011                    properties,
1012                )
1013            }),
1014            Vec::<String>::new()
1015        );
1016    }
1017
1018    // radio_theme_test.dart 'RadioThemeData implements debugFillProperties'.
1019    #[test]
1020    fn an_assigned_radio_theme_describes_every_property() {
1021        let theme = RadioThemeData::new()
1022            .mouse_cursor(Rc::new(WidgetStatePropertyAll::new(Some(
1023                SystemMouseCursors::CLICK.into(),
1024            ))))
1025            .fill_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1026                0xfffffff0,
1027            )))))
1028            .overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1029                0xfffffff1,
1030            )))))
1031            .splash_radius(1.0)
1032            .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
1033            .visual_density(VisualDensity::STANDARD)
1034            .background_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1035                0xfffffff2,
1036            )))))
1037            .side(BorderSide::new(
1038                Color::new(0xfffffff3),
1039                2.0,
1040                BorderStyle::Solid,
1041                1.0,
1042            ))
1043            .inner_radius(Rc::new(WidgetStatePropertyAll::new(Some(5.0))));
1044        let description = waft_widgets::testing::describe_properties(|properties| {
1045            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
1046        });
1047        let description: Vec<String> = description
1048            .iter()
1049            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
1050            .collect();
1051        assert_eq!(
1052            description,
1053            [
1054                "mouseCursor: WidgetStatePropertyAll(SystemMouseCursor(click))".to_string(),
1055                format!(
1056                    "fillColor: WidgetStatePropertyAll({})",
1057                    Color::new(0xfffffff0)
1058                ),
1059                format!(
1060                    "overlayColor: WidgetStatePropertyAll({})",
1061                    Color::new(0xfffffff1)
1062                ),
1063                "splashRadius: 1.0".to_string(),
1064                "materialTapTargetSize: MaterialTapTargetSize.shrinkWrap".to_string(),
1065                "visualDensity: VisualDensity#00000(h: 0.0, v: 0.0)".to_string(),
1066                format!(
1067                    "backgroundColor: WidgetStatePropertyAll({})",
1068                    Color::new(0xfffffff2)
1069                ),
1070                format!(
1071                    "side: {}",
1072                    BorderSide::new(Color::new(0xfffffff3), 2.0, BorderStyle::Solid, 1.0)
1073                ),
1074                "innerRadius: WidgetStatePropertyAll(5.0)".to_string(),
1075            ]
1076        );
1077    }
1078}