Skip to main content

waft_material/
switch_theme.rs

1//! Flutter counterpart: material_ui's `switch_theme.dart`.
2
3use std::rc::Rc;
4
5use waft_embedder::{Color, lerp_double};
6use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
7use waft_painting::EdgeInsetsGeometry;
8use waft_services::MouseCursorRef;
9use waft_widgets::{
10    BuildContext, Icon, InheritedWidget, IntoWidget, KeyRef, WidgetRef, WidgetStateProperty,
11    WidgetStatePropertyRef,
12};
13
14use crate::theme::Theme;
15use crate::theme_data::MaterialTapTargetSize;
16
17/// Defines default property values for descendant `Switch` widgets.
18///
19/// Descendant widgets obtain the current [`SwitchThemeData`] object using
20/// [`SwitchTheme::of`]. Instances of [`SwitchThemeData`] can be customized
21/// with [`SwitchThemeData::copy_with`].
22///
23/// Typically a [`SwitchThemeData`] is specified as part of the overall `Theme`
24/// with `ThemeData::switch_theme`.
25///
26/// All [`SwitchThemeData`] properties are `None` by default. When `None`, the
27/// `Switch` will use the values from `ThemeData` if they exist, otherwise it
28/// will provide its own defaults based on the overall `Theme`'s color_scheme.
29/// See the individual `Switch` properties for details.
30///
31/// See also:
32///
33///  * `ThemeData`, which describes the overall theme information for the
34///    application.
35#[derive(Clone, Debug, Default)]
36pub struct SwitchThemeData {
37    /// The color of a `Switch`'s thumb, resolved in the selected, hovered, focused and
38    /// disabled states.
39    ///
40    /// If specified, overrides the default value of `Switch::thumb_color`.
41    pub thumb_color: Option<WidgetStatePropertyRef<Option<Color>>>,
42
43    /// The color of a `Switch`'s track, resolved in the selected, hovered, focused and
44    /// disabled states.
45    ///
46    /// If specified, overrides the default value of `Switch::track_color`.
47    pub track_color: Option<WidgetStatePropertyRef<Option<Color>>>,
48
49    /// The outline color of a `Switch`'s track, resolved in the selected, hovered, focused
50    /// and disabled states.
51    ///
52    /// If specified, overrides the default value of `Switch::track_outline_color`.
53    pub track_outline_color: Option<WidgetStatePropertyRef<Option<Color>>>,
54
55    /// The outline width of a `Switch`'s track, resolved in the selected, hovered, focused
56    /// and disabled states.
57    ///
58    /// If specified, overrides the default value of `Switch::track_outline_width`.
59    pub track_outline_width: Option<WidgetStatePropertyRef<Option<f64>>>,
60
61    /// Configures the minimum size of the tap target.
62    ///
63    /// If specified, overrides the default value of
64    /// `Switch::material_tap_target_size`.
65    pub material_tap_target_size: Option<MaterialTapTargetSize>,
66
67    /// The cursor for a mouse pointer when it enters or is hovering over the widget,
68    /// resolved in the selected, hovered, focused and disabled states.
69    ///
70    /// If specified, overrides the default value of `Switch::mouse_cursor`.
71    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
72
73    /// The color for the switch's `Material`, resolved in the pressed, selected, hovered
74    /// and focused states.
75    ///
76    /// If specified, overrides the default value of `Switch::overlay_color`.
77    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
78
79    /// The splash radius of the circular `Material` ink response.
80    ///
81    /// If specified, overrides the default value of `Switch::splash_radius`.
82    pub splash_radius: Option<f64>,
83
84    /// The icon to use on the thumb of a switch, resolved in the selected, hovered, focused
85    /// and disabled states.
86    ///
87    /// It is overridden by `Switch::thumb_icon`.
88    pub thumb_icon: Option<WidgetStatePropertyRef<Option<Rc<Icon>>>>,
89
90    /// If specified, overrides the default value of `Switch::padding`.
91    pub padding: Option<EdgeInsetsGeometry>,
92}
93
94crate::theme_data_getters::theme_data_getters! {
95    /// Dart's getters of `SwitchThemeData`: the theme data answers with its fields, and a defaults
96    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
97    /// are read.
98    pub trait SwitchThemeDataGetters for SwitchThemeData, fields: switch_theme_data {
99        thumb_color: Option<WidgetStatePropertyRef<Option<Color>>>,
100        track_color: Option<WidgetStatePropertyRef<Option<Color>>>,
101        track_outline_color: Option<WidgetStatePropertyRef<Option<Color>>>,
102        track_outline_width: Option<WidgetStatePropertyRef<Option<f64>>>,
103        material_tap_target_size: Option<MaterialTapTargetSize>,
104        mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
105        overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
106        splash_radius: Option<f64>,
107        thumb_icon: Option<WidgetStatePropertyRef<Option<Rc<Icon>>>>,
108        padding: Option<EdgeInsetsGeometry>,
109    }
110}
111
112impl SwitchThemeData {
113    /// Creates a theme that can be used for `ThemeData::switch_theme`; Dart's optional named
114    /// arguments are the fluent setters.
115    pub fn new() -> SwitchThemeData {
116        SwitchThemeData::default()
117    }
118
119    /// Dart `SwitchThemeData(thumbColor:)`.
120    pub fn thumb_color(
121        mut self,
122        thumb_color: WidgetStatePropertyRef<Option<Color>>,
123    ) -> SwitchThemeData {
124        self.thumb_color = Some(thumb_color);
125        self
126    }
127
128    /// Dart `SwitchThemeData(trackColor:)`.
129    pub fn track_color(
130        mut self,
131        track_color: WidgetStatePropertyRef<Option<Color>>,
132    ) -> SwitchThemeData {
133        self.track_color = Some(track_color);
134        self
135    }
136
137    /// Dart `SwitchThemeData(trackOutlineColor:)`.
138    pub fn track_outline_color(
139        mut self,
140        track_outline_color: WidgetStatePropertyRef<Option<Color>>,
141    ) -> SwitchThemeData {
142        self.track_outline_color = Some(track_outline_color);
143        self
144    }
145
146    /// Dart `SwitchThemeData(trackOutlineWidth:)`.
147    pub fn track_outline_width(
148        mut self,
149        track_outline_width: WidgetStatePropertyRef<Option<f64>>,
150    ) -> SwitchThemeData {
151        self.track_outline_width = Some(track_outline_width);
152        self
153    }
154
155    /// Dart `SwitchThemeData(materialTapTargetSize:)`.
156    pub fn material_tap_target_size(
157        mut self,
158        material_tap_target_size: MaterialTapTargetSize,
159    ) -> SwitchThemeData {
160        self.material_tap_target_size = Some(material_tap_target_size);
161        self
162    }
163
164    /// Dart `SwitchThemeData(mouseCursor:)`.
165    pub fn mouse_cursor(
166        mut self,
167        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
168    ) -> SwitchThemeData {
169        self.mouse_cursor = Some(mouse_cursor);
170        self
171    }
172
173    /// Dart `SwitchThemeData(overlayColor:)`.
174    pub fn overlay_color(
175        mut self,
176        overlay_color: WidgetStatePropertyRef<Option<Color>>,
177    ) -> SwitchThemeData {
178        self.overlay_color = Some(overlay_color);
179        self
180    }
181
182    /// Dart `SwitchThemeData(splashRadius:)`.
183    pub fn splash_radius(mut self, splash_radius: f64) -> SwitchThemeData {
184        self.splash_radius = Some(splash_radius);
185        self
186    }
187
188    /// Dart `SwitchThemeData(thumbIcon:)`.
189    pub fn thumb_icon(
190        mut self,
191        thumb_icon: WidgetStatePropertyRef<Option<Rc<Icon>>>,
192    ) -> SwitchThemeData {
193        self.thumb_icon = Some(thumb_icon);
194        self
195    }
196
197    /// Dart `SwitchThemeData(padding:)`.
198    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> SwitchThemeData {
199        self.padding = Some(padding.into());
200        self
201    }
202
203    /// Creates a copy of this object but with the given fields replaced with the
204    /// new values.
205    ///
206    /// Dart's named arguments are the fluent setters on the copy
207    /// (`data.copy_with().splash_radius(1.0)`).
208    pub fn copy_with(&self) -> SwitchThemeData {
209        self.clone()
210    }
211
212    /// Linearly interpolate between two [`SwitchThemeData`]s.
213    ///
214    /// {@macro dart.ui.shadow.lerp}
215    pub fn lerp(
216        a: Option<&SwitchThemeData>,
217        b: Option<&SwitchThemeData>,
218        t: f64,
219    ) -> SwitchThemeData {
220        if let (Some(a), Some(b)) = (a, b)
221            && std::ptr::eq(a, b)
222        {
223            return a.clone();
224        }
225        SwitchThemeData {
226            thumb_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
227                a.and_then(|a| a.thumb_color.clone()),
228                b.and_then(|b| b.thumb_color.clone()),
229                t,
230                Color::lerp,
231            ),
232            track_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
233                a.and_then(|a| a.track_color.clone()),
234                b.and_then(|b| b.track_color.clone()),
235                t,
236                Color::lerp,
237            ),
238            track_outline_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
239                a.and_then(|a| a.track_outline_color.clone()),
240                b.and_then(|b| b.track_outline_color.clone()),
241                t,
242                Color::lerp,
243            ),
244            track_outline_width: <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(
245                a.and_then(|a| a.track_outline_width.clone()),
246                b.and_then(|b| b.track_outline_width.clone()),
247                t,
248                lerp_double,
249            ),
250            material_tap_target_size: if t < 0.5 {
251                a.and_then(|a| a.material_tap_target_size)
252            } else {
253                b.and_then(|b| b.material_tap_target_size)
254            },
255            mouse_cursor: if t < 0.5 {
256                a.and_then(|a| a.mouse_cursor.clone())
257            } else {
258                b.and_then(|b| b.mouse_cursor.clone())
259            },
260            overlay_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
261                a.and_then(|a| a.overlay_color.clone()),
262                b.and_then(|b| b.overlay_color.clone()),
263                t,
264                Color::lerp,
265            ),
266            splash_radius: lerp_double(
267                a.and_then(|a| a.splash_radius),
268                b.and_then(|b| b.splash_radius),
269                t,
270            ),
271            thumb_icon: if t < 0.5 {
272                a.and_then(|a| a.thumb_icon.clone())
273            } else {
274                b.and_then(|b| b.thumb_icon.clone())
275            },
276            padding: EdgeInsetsGeometry::lerp(
277                a.and_then(|a| a.padding),
278                b.and_then(|b| b.padding),
279                t,
280            ),
281        }
282    }
283}
284
285impl PartialEq for SwitchThemeData {
286    fn eq(&self, other: &SwitchThemeData) -> bool {
287        if std::ptr::eq(self, other) {
288            return true;
289        }
290        other.thumb_color == self.thumb_color
291            && other.track_color == self.track_color
292            && other.track_outline_color == self.track_outline_color
293            && other.track_outline_width == self.track_outline_width
294            && other.material_tap_target_size == self.material_tap_target_size
295            && other.mouse_cursor == self.mouse_cursor
296            && other.overlay_color == self.overlay_color
297            && other.splash_radius == self.splash_radius
298            && other.thumb_icon == self.thumb_icon
299            && other.padding == self.padding
300    }
301}
302
303/// Applies a switch theme to descendant `Switch` widgets.
304///
305/// Descendant widgets obtain the current theme's [`SwitchTheme`] object using
306/// [`SwitchTheme::of`]. When a widget uses [`SwitchTheme::of`], it is automatically
307/// rebuilt if the theme later changes.
308///
309/// A switch theme can be specified as part of the overall Material theme using
310/// `ThemeData::switch_theme`.
311///
312/// See also:
313///
314///  * [`SwitchThemeData`], which describes the actual configuration of a switch
315///    theme.
316#[derive(Debug)]
317pub struct SwitchTheme {
318    pub key: Option<KeyRef>,
319    /// The properties used for all descendant `Switch` widgets.
320    pub data: SwitchThemeData,
321    pub child: WidgetRef,
322}
323
324impl SwitchTheme {
325    /// Constructs a switch theme that configures all descendant `Switch` widgets.
326    #[cfg_attr(debug_assertions, track_caller)]
327    pub fn new<K>(data: SwitchThemeData, child: impl IntoWidget<K>) -> SwitchTheme {
328        SwitchTheme {
329            key: None,
330            data,
331            child: child.into_widget(),
332        }
333    }
334
335    /// Dart `SwitchTheme(key:)`.
336    pub fn key(mut self, key: KeyRef) -> SwitchTheme {
337        self.key = Some(key);
338        self
339    }
340
341    /// Returns the configuration [`data`](Self::data) from the closest [`SwitchTheme`]
342    /// ancestor. If there is no ancestor, it returns `ThemeData::switch_theme`.
343    ///
344    /// Typical usage is as follows:
345    ///
346    /// ```text
347    /// let theme = SwitchTheme::of(app, context);
348    /// ```
349    pub fn of(app: &mut App, context: BuildContext) -> SwitchThemeData {
350        match context.depend_on_inherited_widget_of_exact_type::<SwitchTheme>(app) {
351            Some(switch_theme) => switch_theme.data.clone(),
352            None => Theme::of(app, context).switch_theme.clone(),
353        }
354    }
355}
356
357impl InheritedWidget for SwitchTheme {
358    fn key(&self) -> Option<&KeyRef> {
359        self.key.as_ref()
360    }
361
362    fn child(&self) -> &WidgetRef {
363        &self.child
364    }
365
366    fn update_should_notify(&self, old_widget: &SwitchTheme) -> bool {
367        self.data != old_widget.data
368    }
369}
370
371impl waft_foundation::Diagnosticable for SwitchThemeData {
372    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
373        properties.add(
374            DiagnosticsProperty::<String>::new(
375                "thumbColor",
376                self.thumb_color
377                    .as_deref()
378                    .map(|property| property.to_string()),
379            )
380            .default_value(None),
381        );
382        properties.add(
383            DiagnosticsProperty::<String>::new(
384                "trackColor",
385                self.track_color
386                    .as_deref()
387                    .map(|property| property.to_string()),
388            )
389            .default_value(None),
390        );
391        properties.add(
392            DiagnosticsProperty::<String>::new(
393                "trackOutlineColor",
394                self.track_outline_color
395                    .as_deref()
396                    .map(|property| property.to_string()),
397            )
398            .default_value(None),
399        );
400        properties.add(
401            DiagnosticsProperty::<String>::new(
402                "trackOutlineWidth",
403                self.track_outline_width
404                    .as_deref()
405                    .map(|property| property.to_string()),
406            )
407            .default_value(None),
408        );
409        properties.add(
410            DiagnosticsProperty::<waft_foundation::DartEnum<MaterialTapTargetSize>>::new(
411                "materialTapTargetSize",
412                self.material_tap_target_size.map(waft_foundation::DartEnum),
413            )
414            .default_value(None),
415        );
416        properties.add(
417            DiagnosticsProperty::<String>::new(
418                "mouseCursor",
419                self.mouse_cursor
420                    .as_deref()
421                    .map(|property| property.to_string()),
422            )
423            .default_value(None),
424        );
425        properties.add(
426            DiagnosticsProperty::<String>::new(
427                "overlayColor",
428                self.overlay_color
429                    .as_deref()
430                    .map(|property| property.to_string()),
431            )
432            .default_value(None),
433        );
434        properties.add(DoubleProperty::new("splashRadius", self.splash_radius).default_value(None));
435        properties.add(
436            DiagnosticsProperty::<String>::new(
437                "thumbIcon",
438                self.thumb_icon
439                    .as_deref()
440                    .map(|property| property.to_string()),
441            )
442            .default_value(None),
443        );
444        properties.add(
445            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
446                .default_value(None),
447        );
448    }
449}
450
451impl std::fmt::Display for SwitchThemeData {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    //! Ported from `test/switch_theme_test.dart`.
460
461    use waft_embedder::Size;
462    use waft_services::SystemMouseCursors;
463    use waft_widgets::{
464        Center, FocusHighlightStrategy, Icon, IconData, WidgetState, WidgetStatePropertyAll,
465        WidgetStates,
466    };
467
468    use waft_widgets::testing::{WidgetTester, test_widgets};
469
470    use super::*;
471    use crate::icons::{Icons, install_material_icon_font};
472    use crate::scaffold::Scaffold;
473    use crate::switch::Switch;
474    use crate::switch::tests::{
475        M2_SHADOWS, c, circles, color_of, colors, drawn, glyph_origins, hover, ignore, press,
476        stroke_of, switch_rect,
477    };
478    use crate::theme_data::ThemeData;
479    use crate::tooltip::tests::pump_app;
480
481    #[test]
482    fn copy_with_and_equality_keep_an_empty_theme_data() {
483        assert_eq!(SwitchThemeData::new(), SwitchThemeData::new().copy_with());
484    }
485
486    #[test]
487    fn lerp_of_a_theme_data_with_itself_is_that_theme_data() {
488        // A theme with a `thumb_color`: lerping it makes a new property, which compares by
489        // identity, so only Dart's `identical` shortcut hands back an equal theme.
490        let data = SwitchThemeData::new()
491            .thumb_color(by_selected(Color::new(0xff000001), Color::new(0xff000002)));
492        assert_eq!(SwitchThemeData::lerp(Some(&data), Some(&data), 0.5), data);
493    }
494
495    #[test]
496    fn every_switch_theme_data_property_defaults_to_none() {
497        let assert_defaults = |theme_data: &SwitchThemeData| {
498            assert!(theme_data.thumb_color.is_none());
499            assert!(theme_data.track_color.is_none());
500            assert!(theme_data.track_outline_color.is_none());
501            assert!(theme_data.track_outline_width.is_none());
502            assert!(theme_data.mouse_cursor.is_none());
503            assert!(theme_data.material_tap_target_size.is_none());
504            assert!(theme_data.overlay_color.is_none());
505            assert!(theme_data.splash_radius.is_none());
506            assert!(theme_data.thumb_icon.is_none());
507            assert!(theme_data.padding.is_none());
508        };
509        assert_defaults(&SwitchThemeData::new());
510        let theme = SwitchTheme::new(SwitchThemeData::new(), waft_widgets::SizedBox::new());
511        assert_defaults(&theme.data);
512    }
513
514    fn by_selected<T: Clone + 'static>(
515        selected: T,
516        default: T,
517    ) -> WidgetStatePropertyRef<Option<T>> {
518        <dyn WidgetStateProperty<Option<T>>>::resolve_with(move |states: &WidgetStates| {
519            if states.contains(&WidgetState::Selected) {
520                return Some(selected.clone());
521            }
522            Some(default.clone())
523        })
524    }
525
526    fn all<T: Clone + std::fmt::Debug + PartialEq + 'static>(
527        value: T,
528    ) -> WidgetStatePropertyRef<Option<T>> {
529        <dyn WidgetStateProperty<Option<T>>>::all(Some(value))
530    }
531
532    /// The overlay both themeable cases give: the focus colour when focused, else the hover
533    /// colour when hovered.
534    fn focus_then_hover(focus: Color, hover: Color) -> WidgetStatePropertyRef<Option<Color>> {
535        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
536            if states.contains(&WidgetState::Focused) {
537                return Some(focus);
538            }
539            if states.contains(&WidgetState::Hovered) {
540                return Some(hover);
541            }
542            None
543        })
544    }
545
546    /// `MaterialApp(theme: theme, home: Scaffold(body: switch))`.
547    fn pump_scaffold(
548        tester: &mut WidgetTester,
549        theme: impl FnOnce(&App) -> ThemeData,
550        switch: impl IntoWidget<waft_widgets::StatelessKind> + 'static,
551    ) {
552        let home = Scaffold::new().body(switch).into_widget();
553        pump_app(tester, theme, move |_app| home);
554    }
555
556    const DEFAULT_THUMB_COLOR: Color = Color::new(0xfffffff0);
557    const SELECTED_THUMB_COLOR: Color = Color::new(0xfffffff1);
558    const DEFAULT_TRACK_COLOR: Color = Color::new(0xfffffff2);
559    const SELECTED_TRACK_COLOR: Color = Color::new(0xfffffff3);
560    const DEFAULT_TRACK_OUTLINE_COLOR: Color = Color::new(0xfffffff4);
561    const SELECTED_TRACK_OUTLINE_COLOR: Color = Color::new(0xfffffff5);
562    const DEFAULT_TRACK_OUTLINE_WIDTH: f64 = 3.0;
563    const SELECTED_TRACK_OUTLINE_WIDTH: f64 = 6.0;
564    const FOCUS_OVERLAY_COLOR: Color = Color::new(0xfffffff4);
565    const HOVER_OVERLAY_COLOR: Color = Color::new(0xfffffff5);
566    const SPLASH_RADIUS: f64 = 1.0;
567
568    /// Dart's 'Material2 - Switch is themeable' and 'Material3 - Switch is themeable'.
569    #[test]
570    fn a_switch_is_themeable() {
571        for use_material3 in [false, true] {
572            test_widgets(|tester| {
573                install_material_icon_font(&mut tester.cell.borrow_mut());
574                tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
575                let icon1 = Rc::new(Icon::new(Some(Icons::check())));
576                let icon2 = Rc::new(Icon::new(Some(Icons::close())));
577                let switch_theme = SwitchThemeData::new()
578                    .thumb_color(by_selected(SELECTED_THUMB_COLOR, DEFAULT_THUMB_COLOR))
579                    .track_color(by_selected(SELECTED_TRACK_COLOR, DEFAULT_TRACK_COLOR))
580                    .track_outline_color(by_selected(
581                        SELECTED_TRACK_OUTLINE_COLOR,
582                        DEFAULT_TRACK_OUTLINE_COLOR,
583                    ))
584                    .track_outline_width(by_selected(
585                        SELECTED_TRACK_OUTLINE_WIDTH,
586                        DEFAULT_TRACK_OUTLINE_WIDTH,
587                    ))
588                    .mouse_cursor(all(MouseCursorRef::from(SystemMouseCursors::TEXT)))
589                    .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
590                    .overlay_color(focus_then_hover(FOCUS_OVERLAY_COLOR, HOVER_OVERLAY_COLOR))
591                    .splash_radius(SPLASH_RADIUS)
592                    .thumb_icon(by_selected(icon1, icon2));
593                let theme = Rc::new(move |app: &App| {
594                    ThemeData::builder()
595                        .use_material3(use_material3)
596                        .switch_theme(switch_theme.clone())
597                        .build(app)
598                });
599                let pump = |tester: &mut WidgetTester, selected: bool, autofocus: bool| {
600                    let theme = Rc::clone(&theme);
601                    pump_scaffold(
602                        tester,
603                        move |app| theme(app),
604                        Switch::new(selected, ignore())
605                            .drag_start_behavior(waft_gestures::DragStartBehavior::Down)
606                            .autofocus(autofocus),
607                    );
608                    tester.pump_and_settle();
609                };
610                let thumb_and_glyph = |painted: &[waft_embedder::valo::Op]| {
611                    let glyphs = glyph_origins(painted).len();
612                    (painted.iter().rev().find_map(color_of), glyphs)
613                };
614
615                // Switch.
616                pump(tester, false, false);
617                let painted = drawn(tester);
618                assert_eq!(color_of(&painted[0]), Some(c(DEFAULT_TRACK_COLOR)));
619                assert!(matches!(stroke_of(&painted[1]), Some((color, width, _))
620                    if color == c(DEFAULT_TRACK_OUTLINE_COLOR)
621                        && f64::from(width) == DEFAULT_TRACK_OUTLINE_WIDTH));
622                if use_material3 {
623                    assert_eq!(painted.len(), 4, "{painted:?}");
624                    assert_eq!(thumb_and_glyph(&painted), (Some(c(DEFAULT_THUMB_COLOR)), 1));
625                } else {
626                    assert_eq!(
627                        colors(&painted),
628                        [
629                            &[c(DEFAULT_TRACK_COLOR), c(DEFAULT_TRACK_OUTLINE_COLOR)][..],
630                            &M2_SHADOWS[..],
631                            &[c(DEFAULT_THUMB_COLOR)][..]
632                        ]
633                        .concat()
634                    );
635                }
636                // Size from MaterialTapTargetSize.shrinkWrap.
637                let width = if use_material3 { 60.0 } else { 59.0 };
638                assert_eq!(switch_rect(tester).size(), Size::new(width, 40.0));
639
640                // Selected switch.
641                pump(tester, true, false);
642                let painted = drawn(tester);
643                assert_eq!(color_of(&painted[0]), Some(c(SELECTED_TRACK_COLOR)));
644                assert!(matches!(stroke_of(&painted[1]), Some((color, width, _))
645                    if color == c(SELECTED_TRACK_OUTLINE_COLOR)
646                        && f64::from(width) == SELECTED_TRACK_OUTLINE_WIDTH));
647                if use_material3 {
648                    assert_eq!(
649                        thumb_and_glyph(&painted),
650                        (Some(c(SELECTED_THUMB_COLOR)), 1)
651                    );
652                } else {
653                    assert_eq!(colors(&painted).last(), Some(&c(SELECTED_THUMB_COLOR)));
654                }
655
656                // Switch with hover.
657                pump(tester, false, false);
658                hover(tester);
659                tester.pump_and_settle();
660                assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
661                assert_eq!(
662                    circles(&drawn(tester), SPLASH_RADIUS),
663                    [c(HOVER_OVERLAY_COLOR)]
664                );
665
666                // Switch with focus.
667                pump(tester, false, true);
668                assert_eq!(
669                    circles(&drawn(tester), SPLASH_RADIUS),
670                    [c(FOCUS_OVERLAY_COLOR)]
671                );
672            });
673        }
674    }
675
676    /// Dart's 'Material2 - Switch properties are taken over the theme values' and its
677    /// Material 3 twin.
678    #[test]
679    fn the_switch_properties_win_over_the_theme_values() {
680        for use_material3 in [false, true] {
681            test_widgets(|tester| {
682                const THEME_DEFAULT_THUMB_COLOR: Color = Color::new(0xfffffff0);
683                const THEME_SELECTED_THUMB_COLOR: Color = Color::new(0xfffffff1);
684                const THEME_DEFAULT_TRACK_COLOR: Color = Color::new(0xfffffff2);
685                const THEME_SELECTED_TRACK_COLOR: Color = Color::new(0xfffffff3);
686                const THEME_DEFAULT_OUTLINE_COLOR: Color = Color::new(0xfffffff6);
687                const THEME_SELECTED_OUTLINE_COLOR: Color = Color::new(0xfffffff7);
688                const THEME_FOCUS_OVERLAY_COLOR: Color = Color::new(0xfffffff4);
689                const THEME_HOVER_OVERLAY_COLOR: Color = Color::new(0xfffffff5);
690
691                const DEFAULT_THUMB: Color = Color::new(0xffffff0f);
692                const SELECTED_THUMB: Color = Color::new(0xffffff1f);
693                const DEFAULT_TRACK: Color = Color::new(0xffffff2f);
694                const SELECTED_TRACK: Color = Color::new(0xffffff3f);
695                const DEFAULT_OUTLINE: Color = Color::new(0xffffff6f);
696                const SELECTED_OUTLINE: Color = Color::new(0xffffff7f);
697                const DEFAULT_OUTLINE_WIDTH: f64 = 6.0;
698                const SELECTED_OUTLINE_WIDTH: f64 = 8.0;
699                const FOCUS_COLOR: Color = Color::new(0xffffff4f);
700                const HOVER_COLOR: Color = Color::new(0xffffff5f);
701                const SPLASH: f64 = 2.0;
702
703                install_material_icon_font(&mut tester.cell.borrow_mut());
704                tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
705                let switch_theme = SwitchThemeData::new()
706                    .thumb_color(by_selected(
707                        THEME_SELECTED_THUMB_COLOR,
708                        THEME_DEFAULT_THUMB_COLOR,
709                    ))
710                    .track_color(by_selected(
711                        THEME_SELECTED_TRACK_COLOR,
712                        THEME_DEFAULT_TRACK_COLOR,
713                    ))
714                    .track_outline_color(by_selected(
715                        THEME_SELECTED_OUTLINE_COLOR,
716                        THEME_DEFAULT_OUTLINE_COLOR,
717                    ))
718                    .track_outline_width(by_selected(7.0, 5.0))
719                    .mouse_cursor(all(MouseCursorRef::from(SystemMouseCursors::CLICK)))
720                    .material_tap_target_size(MaterialTapTargetSize::Padded)
721                    .overlay_color(focus_then_hover(
722                        THEME_FOCUS_OVERLAY_COLOR,
723                        THEME_HOVER_OVERLAY_COLOR,
724                    ))
725                    .splash_radius(1.0)
726                    .thumb_icon(<dyn WidgetStateProperty<Option<Rc<Icon>>>>::all(None));
727                let theme = Rc::new(move |app: &App| {
728                    ThemeData::builder()
729                        .use_material3(use_material3)
730                        .switch_theme(switch_theme.clone())
731                        .build(app)
732                });
733                let add = Rc::new(Icon::new(Some(Icons::add())));
734                let alarm = Rc::new(Icon::new(Some(Icons::access_alarm())));
735                let pump = |tester: &mut WidgetTester, selected: bool, autofocus: bool| {
736                    let theme = Rc::clone(&theme);
737                    pump_scaffold(
738                        tester,
739                        move |app| theme(app),
740                        Switch::new(selected, ignore())
741                            .autofocus(autofocus)
742                            .thumb_color(by_selected(SELECTED_THUMB, DEFAULT_THUMB))
743                            .track_color(by_selected(SELECTED_TRACK, DEFAULT_TRACK))
744                            .track_outline_color(by_selected(SELECTED_OUTLINE, DEFAULT_OUTLINE))
745                            .track_outline_width(by_selected(
746                                SELECTED_OUTLINE_WIDTH,
747                                DEFAULT_OUTLINE_WIDTH,
748                            ))
749                            .mouse_cursor(SystemMouseCursors::TEXT)
750                            .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
751                            .focus_color(FOCUS_COLOR)
752                            .hover_color(HOVER_COLOR)
753                            .splash_radius(SPLASH)
754                            .thumb_icon(by_selected(Rc::clone(&add), Rc::clone(&alarm))),
755                    );
756                    tester.pump_and_settle();
757                };
758                // Material 2 paints the thumb's three shadows between the outline and the thumb.
759                let thumb_index = if use_material3 { 2 } else { 5 };
760
761                // Switch.
762                pump(tester, false, false);
763                let painted = drawn(tester);
764                assert_eq!(color_of(&painted[0]), Some(c(DEFAULT_TRACK)));
765                assert!(matches!(stroke_of(&painted[1]), Some((color, width, _))
766                    if color == c(DEFAULT_OUTLINE) && f64::from(width) == DEFAULT_OUTLINE_WIDTH));
767                assert_eq!(color_of(&painted[thumb_index]), Some(c(DEFAULT_THUMB)));
768                if use_material3 {
769                    // Dart's `paragraph(offset: Offset(12, 12))`: the glyph's ink is in the
770                    // 16x16 icon square there.
771                    assert!(
772                        matches!(glyph_origins(&painted).as_slice(), [(x, y)] if (12.0..28.0).contains(x) && (12.0..28.0).contains(y)),
773                        "{:?}",
774                        painted[3]
775                    );
776                }
777                // Size from MaterialTapTargetSize.shrinkWrap.
778                let width = if use_material3 { 60.0 } else { 59.0 };
779                assert_eq!(switch_rect(tester).size(), Size::new(width, 40.0));
780
781                // Selected switch.
782                pump(tester, true, false);
783                let painted = drawn(tester);
784                assert_eq!(color_of(&painted[0]), Some(c(SELECTED_TRACK)));
785                assert!(matches!(stroke_of(&painted[1]), Some((color, width, _))
786                    if color == c(SELECTED_OUTLINE) && f64::from(width) == SELECTED_OUTLINE_WIDTH));
787                assert_eq!(color_of(&painted[thumb_index]), Some(c(SELECTED_THUMB)));
788
789                // Switch with hover.
790                pump(tester, false, false);
791                hover(tester);
792                tester.pump_and_settle();
793                assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
794                assert_eq!(circles(&drawn(tester), SPLASH), [c(HOVER_COLOR)]);
795
796                // Switch with focus.
797                pump(tester, false, true);
798                assert_eq!(circles(&drawn(tester), SPLASH), [c(FOCUS_COLOR)]);
799            });
800        }
801    }
802
803    /// Dart's 'Material2 - Switch active and inactive properties are taken over the theme
804    /// values' and its Material 3 twin.
805    #[test]
806    #[allow(deprecated)]
807    fn the_switch_active_and_inactive_colors_win_over_the_theme_values() {
808        for use_material3 in [false, true] {
809            test_widgets(|tester| {
810                const DEFAULT_THUMB: Color = Color::new(0xffffff0f);
811                const SELECTED_THUMB: Color = Color::new(0xffffff1f);
812                const DEFAULT_TRACK: Color = Color::new(0xffffff2f);
813                const SELECTED_TRACK: Color = Color::new(0xffffff3f);
814                let outline = ThemeData::new(&tester.cell.borrow()).color_scheme.outline();
815                let switch_theme = SwitchThemeData::new()
816                    .thumb_color(by_selected(Color::new(0xfffffff1), Color::new(0xfffffff0)))
817                    .track_color(by_selected(Color::new(0xfffffff3), Color::new(0xfffffff2)));
818                for selected in [false, true] {
819                    let switch_theme = switch_theme.clone();
820                    pump_scaffold(
821                        tester,
822                        move |app| {
823                            ThemeData::builder()
824                                .use_material3(use_material3)
825                                .switch_theme(switch_theme)
826                                .build(app)
827                        },
828                        Switch::new(selected, ignore())
829                            .active_color(SELECTED_THUMB)
830                            .inactive_thumb_color(DEFAULT_THUMB)
831                            .active_track_color(SELECTED_TRACK)
832                            .inactive_track_color(DEFAULT_TRACK),
833                    );
834                    tester.pump_and_settle();
835                    let (track, thumb) = if selected {
836                        (SELECTED_TRACK, SELECTED_THUMB)
837                    } else {
838                        (DEFAULT_TRACK, DEFAULT_THUMB)
839                    };
840                    // The Material 2 outline, and the selected Material 3 one, are transparent
841                    // and not recorded.
842                    let expected = match (use_material3, selected) {
843                        (false, _) => [&[c(track)][..], &M2_SHADOWS[..], &[c(thumb)][..]].concat(),
844                        (true, true) => vec![c(track), c(thumb)],
845                        (true, false) => vec![c(track), c(outline), c(thumb)],
846                    };
847                    assert_eq!(
848                        colors(&drawn(tester)),
849                        expected,
850                        "M3 {use_material3}, selected {selected}"
851                    );
852                }
853            });
854        }
855    }
856
857    /// Dart's 'Material2 - Switch theme overlay color resolves in active/pressed states' and its
858    /// Material 3 twin.
859    #[test]
860    fn the_theme_overlay_color_resolves_in_the_active_and_pressed_states() {
861        for use_material3 in [false, true] {
862            test_widgets(|tester| {
863                const ACTIVE_PRESSED_OVERLAY: Color = Color::new(0xFF000001);
864                const INACTIVE_PRESSED_OVERLAY: Color = Color::new(0xFF000002);
865                const SPLASH: f64 = 24.0;
866                let switch_theme = SwitchThemeData::new()
867                    .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
868                        |states: &WidgetStates| {
869                            if states.contains(&WidgetState::Pressed) {
870                                if states.contains(&WidgetState::Selected) {
871                                    return Some(ACTIVE_PRESSED_OVERLAY);
872                                }
873                                return Some(INACTIVE_PRESSED_OVERLAY);
874                            }
875                            None
876                        },
877                    ))
878                    .splash_radius(SPLASH);
879
880                for (active, expected) in [
881                    (false, INACTIVE_PRESSED_OVERLAY),
882                    (true, ACTIVE_PRESSED_OVERLAY),
883                ] {
884                    let switch_theme = switch_theme.clone();
885                    pump_scaffold(
886                        tester,
887                        move |app| {
888                            ThemeData::builder()
889                                .use_material3(use_material3)
890                                .switch_theme(switch_theme)
891                                .build(app)
892                        },
893                        Switch::new(active, ignore()),
894                    );
895                    let touch = press(tester);
896                    tester.pump_and_settle();
897                    assert_eq!(
898                        circles(&drawn(tester), SPLASH),
899                        [c(expected)],
900                        "M3 {use_material3}, active {active}"
901                    );
902                    tester.up(&touch);
903                    tester.pump_and_settle();
904                }
905            });
906        }
907    }
908
909    /// Dart's 'Material2 - Local SwitchTheme can override global SwitchTheme' and its
910    /// Material 3 twin.
911    #[test]
912    fn a_local_switch_theme_overrides_the_global_one() {
913        for use_material3 in [false, true] {
914            test_widgets(|tester| {
915                const LOCAL: Color = Color::new(0xffff0000);
916                const LOCAL_OUTLINE_WIDTH: f64 = 4.0;
917                let global = SwitchThemeData::new()
918                    .thumb_color(all(Color::new(0xfffffff1)))
919                    .track_color(all(Color::new(0xfffffff2)))
920                    .track_outline_color(all(Color::new(0xfffffff3)))
921                    .track_outline_width(all(6.0));
922                let local = SwitchThemeData::new()
923                    .thumb_color(all(LOCAL))
924                    .track_color(all(LOCAL))
925                    .track_outline_color(all(LOCAL))
926                    .track_outline_width(all(LOCAL_OUTLINE_WIDTH));
927                let home = Scaffold::new()
928                    .body(SwitchTheme::new(local, Switch::new(true, ignore())))
929                    .into_widget();
930                pump_app(
931                    tester,
932                    move |app| {
933                        ThemeData::builder()
934                            .use_material3(use_material3)
935                            .switch_theme(global)
936                            .build(app)
937                    },
938                    move |_app| home,
939                );
940                tester.pump_and_settle();
941                let painted = drawn(tester);
942                assert_eq!(color_of(&painted[0]), Some(c(LOCAL)));
943                assert!(matches!(stroke_of(&painted[1]), Some((color, width, _))
944                    if color == c(LOCAL) && f64::from(width) == LOCAL_OUTLINE_WIDTH));
945                let thumb_shadows = if use_material3 {
946                    &[][..]
947                } else {
948                    &M2_SHADOWS[..]
949                };
950                assert_eq!(
951                    colors(&painted),
952                    [&[c(LOCAL), c(LOCAL)][..], thumb_shadows, &[c(LOCAL)][..]].concat(),
953                    "M3 {use_material3}"
954                );
955            });
956        }
957    }
958
959    #[test]
960    fn the_switch_theme_padding_is_respected() {
961        test_widgets(|tester| {
962            for (padding, expected) in [
963                (None, Size::new(60.0, 48.0)),
964                (Some(EdgeInsetsGeometry::ZERO), Size::new(52.0, 48.0)),
965                (Some(EdgeInsetsGeometry::all(4.0)), Size::new(60.0, 56.0)),
966            ] {
967                let mut switch_theme = SwitchThemeData::new();
968                switch_theme.padding = padding;
969                let home = Scaffold::new()
970                    .body(Center::new().child(Switch::new(true, ignore())))
971                    .into_widget();
972                pump_app(
973                    tester,
974                    move |app| ThemeData::builder().switch_theme(switch_theme).build(app),
975                    move |_app| home,
976                );
977                tester.pump_and_settle();
978                assert_eq!(switch_rect(tester).size(), expected, "{padding:?}");
979            }
980        });
981    }
982    // Flutter's "Default SwitchThemeData debugFillProperties".
983    #[test]
984    fn a_switch_theme_data_describes_nothing_by_default() {
985        assert_eq!(
986            waft_widgets::testing::describe_properties(|properties| {
987                waft_foundation::Diagnosticable::debug_fill_properties(
988                    &SwitchThemeData::new(),
989                    properties,
990                )
991            }),
992            Vec::<String>::new()
993        );
994    }
995
996    // switch_theme_test.dart 'SwitchThemeData implements debugFillProperties'.
997    #[test]
998    fn an_assigned_switch_theme_describes_every_property() {
999        let mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>> = Rc::new(
1000            WidgetStatePropertyAll::new(Some(SystemMouseCursors::CLICK.into())),
1001        );
1002        let theme = SwitchThemeData::new()
1003            .thumb_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1004                0xfffffff0,
1005            )))))
1006            .track_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1007                0xfffffff1,
1008            )))))
1009            .track_outline_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1010                0xfffffff3,
1011            )))))
1012            .track_outline_width(Rc::new(WidgetStatePropertyAll::new(Some(6.0))))
1013            .mouse_cursor(mouse_cursor)
1014            .material_tap_target_size(MaterialTapTargetSize::ShrinkWrap)
1015            .overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
1016                0xfffffff2,
1017            )))))
1018            .splash_radius(1.0)
1019            .thumb_icon(Rc::new(WidgetStatePropertyAll::new(Some(Rc::new(
1020                Icon::new(Some(IconData::new(123))),
1021            )))))
1022            .padding(EdgeInsetsGeometry::all(4.0));
1023        let description = waft_widgets::testing::describe_properties(|properties| {
1024            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
1025        });
1026        assert_eq!(
1027            description,
1028            [
1029                format!(
1030                    "thumbColor: WidgetStatePropertyAll({})",
1031                    Color::new(0xfffffff0)
1032                ),
1033                format!(
1034                    "trackColor: WidgetStatePropertyAll({})",
1035                    Color::new(0xfffffff1)
1036                ),
1037                format!(
1038                    "trackOutlineColor: WidgetStatePropertyAll({})",
1039                    Color::new(0xfffffff3)
1040                ),
1041                "trackOutlineWidth: WidgetStatePropertyAll(6.0)".to_string(),
1042                "materialTapTargetSize: MaterialTapTargetSize.shrinkWrap".to_string(),
1043                "mouseCursor: WidgetStatePropertyAll(SystemMouseCursor(click))".to_string(),
1044                format!(
1045                    "overlayColor: WidgetStatePropertyAll({})",
1046                    Color::new(0xfffffff2)
1047                ),
1048                "splashRadius: 1.0".to_string(),
1049                "thumbIcon: WidgetStatePropertyAll(Icon(IconData(U+0007B)))".to_string(),
1050                "padding: EdgeInsets.all(4.0)".to_string(),
1051            ]
1052        );
1053    }
1054}