Skip to main content

waft_material/
floating_action_button_theme.rs

1//! Flutter counterpart: material_ui's `floating_action_button_theme.dart`.
2
3use waft_embedder::{Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{ColorProperty, EdgeInsetsGeometry, ShapeBorderRef, TextStyle};
6use waft_rendering::BoxConstraints;
7use waft_services::MouseCursorRef;
8use waft_widgets::{
9    BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
10    WidgetStatePropertyRef,
11};
12
13use crate::theme::Theme;
14
15/// Defines default property values for descendant `FloatingActionButton`
16/// widgets.
17///
18/// Descendant widgets obtain the current [`FloatingActionButtonThemeData`] object
19/// using [`FloatingActionButtonTheme::of`]. Instances of
20/// [`FloatingActionButtonThemeData`] can be customized with
21/// [`FloatingActionButtonThemeData::copy_with`].
22///
23/// Typically a [`FloatingActionButtonThemeData`] is specified as part of the
24/// overall `Theme` with `ThemeData::floating_action_button_theme`.
25///
26/// All [`FloatingActionButtonThemeData`] properties are `null` by default.
27/// When null, the `FloatingActionButton` provides its own defaults.
28///
29/// See also:
30///
31///  * `ThemeData`, which describes the overall theme information for the
32///    application.
33#[derive(Clone, Debug, Default)]
34pub struct FloatingActionButtonThemeData {
35    /// Color to be used for the unselected, enabled `FloatingActionButton`'s
36    /// foreground.
37    pub foreground_color: Option<Color>,
38
39    /// Color to be used for the unselected, enabled `FloatingActionButton`'s
40    /// background.
41    pub background_color: Option<Color>,
42
43    /// The color to use for filling the button when the button has input focus.
44    pub focus_color: Option<Color>,
45
46    /// The color to use for filling the button when the button has a pointer
47    /// hovering over it.
48    pub hover_color: Option<Color>,
49
50    /// The splash color for this `FloatingActionButton`'s `InkWell`.
51    pub splash_color: Option<Color>,
52
53    /// The z-coordinate to be used for the unselected, enabled
54    /// `FloatingActionButton`'s elevation foreground.
55    pub elevation: Option<f64>,
56
57    /// The z-coordinate at which to place this button relative to its parent when
58    /// the button has the input focus.
59    ///
60    /// This controls the size of the shadow below the floating action button.
61    pub focus_elevation: Option<f64>,
62
63    /// The z-coordinate at which to place this button relative to its parent when
64    /// the button is enabled and has a pointer hovering over it.
65    ///
66    /// This controls the size of the shadow below the floating action button.
67    pub hover_elevation: Option<f64>,
68
69    /// The z-coordinate to be used for the disabled `FloatingActionButton`'s
70    /// elevation foreground.
71    pub disabled_elevation: Option<f64>,
72
73    /// The z-coordinate to be used for the selected, enabled
74    /// `FloatingActionButton`'s elevation foreground.
75    pub highlight_elevation: Option<f64>,
76
77    /// The shape to be used for the floating action button's `Material`.
78    pub shape: Option<ShapeBorderRef>,
79
80    /// If specified, defines the feedback property for `FloatingActionButton`.
81    ///
82    /// If `FloatingActionButton::enable_feedback` is provided, [`enable_feedback`](Self::enable_feedback) is
83    /// ignored.
84    pub enable_feedback: Option<bool>,
85
86    /// Overrides the default icon size for the `FloatingActionButton`;
87    pub icon_size: Option<f64>,
88
89    /// Overrides the default size constraints for the `FloatingActionButton`.
90    pub size_constraints: Option<BoxConstraints>,
91
92    /// Overrides the default size constraints for `FloatingActionButton::small`.
93    pub small_size_constraints: Option<BoxConstraints>,
94
95    /// Overrides the default size constraints for `FloatingActionButton::large`.
96    pub large_size_constraints: Option<BoxConstraints>,
97
98    /// Overrides the default size constraints for `FloatingActionButton::extended`.
99    pub extended_size_constraints: Option<BoxConstraints>,
100
101    /// The spacing between the icon and the label for an extended
102    /// `FloatingActionButton`.
103    pub extended_icon_label_spacing: Option<f64>,
104
105    /// The padding for an extended `FloatingActionButton`'s content.
106    pub extended_padding: Option<EdgeInsetsGeometry>,
107
108    /// The text style for an extended `FloatingActionButton`'s label.
109    pub extended_text_style: Option<TextStyle>,
110
111    /// The cursor for a mouse pointer when it enters or is hovering over the
112    /// button.
113    ///
114    /// If [`mouse_cursor`](Self::mouse_cursor) is a `WidgetStateMouseCursor`,
115    /// `WidgetStateProperty::resolve` is used for the following `WidgetState`s:
116    ///
117    ///  * `WidgetState::Pressed`.
118    ///  * `WidgetState::Hovered`.
119    ///  * `WidgetState::Focused`.
120    ///  * `WidgetState::Disabled`.
121    ///
122    /// If specified, overrides the default value of `FloatingActionButton::mouse_cursor`.
123    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
124}
125
126crate::theme_data_getters::theme_data_getters! {
127    /// Dart's getters of `FloatingActionButtonThemeData`: the theme data answers with its fields, and a defaults
128    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
129    /// are read.
130    pub trait FloatingActionButtonThemeDataGetters for FloatingActionButtonThemeData, fields: floating_action_button_theme_data {
131        foreground_color: Option<Color>,
132        background_color: Option<Color>,
133        focus_color: Option<Color>,
134        hover_color: Option<Color>,
135        splash_color: Option<Color>,
136        elevation: Option<f64>,
137        focus_elevation: Option<f64>,
138        hover_elevation: Option<f64>,
139        disabled_elevation: Option<f64>,
140        highlight_elevation: Option<f64>,
141        shape: Option<ShapeBorderRef>,
142        enable_feedback: Option<bool>,
143        icon_size: Option<f64>,
144        size_constraints: Option<BoxConstraints>,
145        small_size_constraints: Option<BoxConstraints>,
146        large_size_constraints: Option<BoxConstraints>,
147        extended_size_constraints: Option<BoxConstraints>,
148        extended_icon_label_spacing: Option<f64>,
149        extended_padding: Option<EdgeInsetsGeometry>,
150        extended_text_style: Option<TextStyle>,
151        mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
152    }
153}
154
155impl FloatingActionButtonThemeData {
156    /// Creates a theme that can be used for `ThemeData::floating_action_button_theme` and
157    /// [`FloatingActionButtonTheme`]; Dart's optional named arguments are the fluent setters.
158    pub fn new() -> FloatingActionButtonThemeData {
159        FloatingActionButtonThemeData::default()
160    }
161
162    /// Dart `FloatingActionButtonThemeData(foregroundColor:)`.
163    pub fn foreground_color(mut self, foreground_color: Color) -> FloatingActionButtonThemeData {
164        self.foreground_color = Some(foreground_color);
165        self
166    }
167
168    /// Dart `FloatingActionButtonThemeData(backgroundColor:)`.
169    pub fn background_color(mut self, background_color: Color) -> FloatingActionButtonThemeData {
170        self.background_color = Some(background_color);
171        self
172    }
173
174    /// Dart `FloatingActionButtonThemeData(focusColor:)`.
175    pub fn focus_color(mut self, focus_color: Color) -> FloatingActionButtonThemeData {
176        self.focus_color = Some(focus_color);
177        self
178    }
179
180    /// Dart `FloatingActionButtonThemeData(hoverColor:)`.
181    pub fn hover_color(mut self, hover_color: Color) -> FloatingActionButtonThemeData {
182        self.hover_color = Some(hover_color);
183        self
184    }
185
186    /// Dart `FloatingActionButtonThemeData(splashColor:)`.
187    pub fn splash_color(mut self, splash_color: Color) -> FloatingActionButtonThemeData {
188        self.splash_color = Some(splash_color);
189        self
190    }
191
192    /// Dart `FloatingActionButtonThemeData(elevation:)`.
193    pub fn elevation(mut self, elevation: f64) -> FloatingActionButtonThemeData {
194        self.elevation = Some(elevation);
195        self
196    }
197
198    /// Dart `FloatingActionButtonThemeData(focusElevation:)`.
199    pub fn focus_elevation(mut self, focus_elevation: f64) -> FloatingActionButtonThemeData {
200        self.focus_elevation = Some(focus_elevation);
201        self
202    }
203
204    /// Dart `FloatingActionButtonThemeData(hoverElevation:)`.
205    pub fn hover_elevation(mut self, hover_elevation: f64) -> FloatingActionButtonThemeData {
206        self.hover_elevation = Some(hover_elevation);
207        self
208    }
209
210    /// Dart `FloatingActionButtonThemeData(disabledElevation:)`.
211    pub fn disabled_elevation(mut self, disabled_elevation: f64) -> FloatingActionButtonThemeData {
212        self.disabled_elevation = Some(disabled_elevation);
213        self
214    }
215
216    /// Dart `FloatingActionButtonThemeData(highlightElevation:)`.
217    pub fn highlight_elevation(
218        mut self,
219        highlight_elevation: f64,
220    ) -> FloatingActionButtonThemeData {
221        self.highlight_elevation = Some(highlight_elevation);
222        self
223    }
224
225    /// Dart `FloatingActionButtonThemeData(shape:)`.
226    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> FloatingActionButtonThemeData {
227        self.shape = Some(shape.into());
228        self
229    }
230
231    /// Dart `FloatingActionButtonThemeData(enableFeedback:)`.
232    pub fn enable_feedback(mut self, enable_feedback: bool) -> FloatingActionButtonThemeData {
233        self.enable_feedback = Some(enable_feedback);
234        self
235    }
236
237    /// Dart `FloatingActionButtonThemeData(iconSize:)`.
238    pub fn icon_size(mut self, icon_size: f64) -> FloatingActionButtonThemeData {
239        self.icon_size = Some(icon_size);
240        self
241    }
242
243    /// Dart `FloatingActionButtonThemeData(sizeConstraints:)`.
244    pub fn size_constraints(
245        mut self,
246        size_constraints: BoxConstraints,
247    ) -> FloatingActionButtonThemeData {
248        self.size_constraints = Some(size_constraints);
249        self
250    }
251
252    /// Dart `FloatingActionButtonThemeData(smallSizeConstraints:)`.
253    pub fn small_size_constraints(
254        mut self,
255        small_size_constraints: BoxConstraints,
256    ) -> FloatingActionButtonThemeData {
257        self.small_size_constraints = Some(small_size_constraints);
258        self
259    }
260
261    /// Dart `FloatingActionButtonThemeData(largeSizeConstraints:)`.
262    pub fn large_size_constraints(
263        mut self,
264        large_size_constraints: BoxConstraints,
265    ) -> FloatingActionButtonThemeData {
266        self.large_size_constraints = Some(large_size_constraints);
267        self
268    }
269
270    /// Dart `FloatingActionButtonThemeData(extendedSizeConstraints:)`.
271    pub fn extended_size_constraints(
272        mut self,
273        extended_size_constraints: BoxConstraints,
274    ) -> FloatingActionButtonThemeData {
275        self.extended_size_constraints = Some(extended_size_constraints);
276        self
277    }
278
279    /// Dart `FloatingActionButtonThemeData(extendedIconLabelSpacing:)`.
280    pub fn extended_icon_label_spacing(
281        mut self,
282        extended_icon_label_spacing: f64,
283    ) -> FloatingActionButtonThemeData {
284        self.extended_icon_label_spacing = Some(extended_icon_label_spacing);
285        self
286    }
287
288    /// Dart `FloatingActionButtonThemeData(extendedPadding:)`.
289    pub fn extended_padding(
290        mut self,
291        extended_padding: impl Into<EdgeInsetsGeometry>,
292    ) -> FloatingActionButtonThemeData {
293        let extended_padding = extended_padding.into();
294        self.extended_padding = Some(extended_padding);
295        self
296    }
297
298    /// Dart `FloatingActionButtonThemeData(extendedTextStyle:)`.
299    pub fn extended_text_style(
300        mut self,
301        extended_text_style: TextStyle,
302    ) -> FloatingActionButtonThemeData {
303        self.extended_text_style = Some(extended_text_style);
304        self
305    }
306
307    /// Dart `FloatingActionButtonThemeData(mouseCursor:)`.
308    pub fn mouse_cursor(
309        mut self,
310        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
311    ) -> FloatingActionButtonThemeData {
312        self.mouse_cursor = Some(mouse_cursor);
313        self
314    }
315
316    /// Creates a copy of this object with the given fields replaced with the
317    /// new values.
318    ///
319    /// Dart's named arguments are the fluent setters on the copy
320    /// (`data.copy_with().elevation(2.0)`).
321    pub fn copy_with(&self) -> FloatingActionButtonThemeData {
322        self.clone()
323    }
324
325    /// Linearly interpolate between two floating action button themes.
326    ///
327    /// If both arguments are null, then null is returned.
328    ///
329    /// {@macro dart.ui.shadow.lerp}
330    pub fn lerp(
331        a: Option<&FloatingActionButtonThemeData>,
332        b: Option<&FloatingActionButtonThemeData>,
333        t: f64,
334    ) -> Option<FloatingActionButtonThemeData> {
335        match (a, b) {
336            (None, None) => return None,
337            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
338            _ => {}
339        }
340        Some(FloatingActionButtonThemeData {
341            foreground_color: Color::lerp(
342                a.and_then(|a| a.foreground_color),
343                b.and_then(|b| b.foreground_color),
344                t,
345            ),
346            background_color: Color::lerp(
347                a.and_then(|a| a.background_color),
348                b.and_then(|b| b.background_color),
349                t,
350            ),
351            focus_color: Color::lerp(
352                a.and_then(|a| a.focus_color),
353                b.and_then(|b| b.focus_color),
354                t,
355            ),
356            hover_color: Color::lerp(
357                a.and_then(|a| a.hover_color),
358                b.and_then(|b| b.hover_color),
359                t,
360            ),
361            splash_color: Color::lerp(
362                a.and_then(|a| a.splash_color),
363                b.and_then(|b| b.splash_color),
364                t,
365            ),
366            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
367            focus_elevation: lerp_double(
368                a.and_then(|a| a.focus_elevation),
369                b.and_then(|b| b.focus_elevation),
370                t,
371            ),
372            hover_elevation: lerp_double(
373                a.and_then(|a| a.hover_elevation),
374                b.and_then(|b| b.hover_elevation),
375                t,
376            ),
377            disabled_elevation: lerp_double(
378                a.and_then(|a| a.disabled_elevation),
379                b.and_then(|b| b.disabled_elevation),
380                t,
381            ),
382            highlight_elevation: lerp_double(
383                a.and_then(|a| a.highlight_elevation),
384                b.and_then(|b| b.highlight_elevation),
385                t,
386            ),
387            shape: ShapeBorderRef::lerp(
388                a.and_then(|a| a.shape.as_ref()),
389                b.and_then(|b| b.shape.as_ref()),
390                t,
391            ),
392            enable_feedback: if t < 0.5 {
393                a.and_then(|a| a.enable_feedback)
394            } else {
395                b.and_then(|b| b.enable_feedback)
396            },
397            icon_size: lerp_double(a.and_then(|a| a.icon_size), b.and_then(|b| b.icon_size), t),
398            size_constraints: BoxConstraints::lerp(
399                a.and_then(|a| a.size_constraints),
400                b.and_then(|b| b.size_constraints),
401                t,
402            ),
403            small_size_constraints: BoxConstraints::lerp(
404                a.and_then(|a| a.small_size_constraints),
405                b.and_then(|b| b.small_size_constraints),
406                t,
407            ),
408            large_size_constraints: BoxConstraints::lerp(
409                a.and_then(|a| a.large_size_constraints),
410                b.and_then(|b| b.large_size_constraints),
411                t,
412            ),
413            extended_size_constraints: BoxConstraints::lerp(
414                a.and_then(|a| a.extended_size_constraints),
415                b.and_then(|b| b.extended_size_constraints),
416                t,
417            ),
418            extended_icon_label_spacing: lerp_double(
419                a.and_then(|a| a.extended_icon_label_spacing),
420                b.and_then(|b| b.extended_icon_label_spacing),
421                t,
422            ),
423            extended_padding: EdgeInsetsGeometry::lerp(
424                a.and_then(|a| a.extended_padding),
425                b.and_then(|b| b.extended_padding),
426                t,
427            ),
428            extended_text_style: TextStyle::lerp(
429                a.and_then(|a| a.extended_text_style.as_ref()),
430                b.and_then(|b| b.extended_text_style.as_ref()),
431                t,
432            ),
433            mouse_cursor: if t < 0.5 {
434                a.and_then(|a| a.mouse_cursor.clone())
435            } else {
436                b.and_then(|b| b.mouse_cursor.clone())
437            },
438        })
439    }
440}
441
442impl PartialEq for FloatingActionButtonThemeData {
443    fn eq(&self, other: &FloatingActionButtonThemeData) -> bool {
444        if std::ptr::eq(self, other) {
445            return true;
446        }
447        other.foreground_color == self.foreground_color
448            && other.background_color == self.background_color
449            && other.focus_color == self.focus_color
450            && other.hover_color == self.hover_color
451            && other.splash_color == self.splash_color
452            && other.elevation == self.elevation
453            && other.focus_elevation == self.focus_elevation
454            && other.hover_elevation == self.hover_elevation
455            && other.disabled_elevation == self.disabled_elevation
456            && other.highlight_elevation == self.highlight_elevation
457            && other.shape == self.shape
458            && other.enable_feedback == self.enable_feedback
459            && other.icon_size == self.icon_size
460            && other.size_constraints == self.size_constraints
461            && other.small_size_constraints == self.small_size_constraints
462            && other.large_size_constraints == self.large_size_constraints
463            && other.extended_size_constraints == self.extended_size_constraints
464            && other.extended_icon_label_spacing == self.extended_icon_label_spacing
465            && other.extended_padding == self.extended_padding
466            && other.extended_text_style == self.extended_text_style
467            && other.mouse_cursor == self.mouse_cursor
468    }
469}
470
471/// An inherited widget that defines the configuration for
472/// `FloatingActionButton`s in this widget's subtree.
473///
474/// Values specified here are used for `FloatingActionButton` properties that are not
475/// given an explicit non-null value.
476#[derive(Debug)]
477pub struct FloatingActionButtonTheme {
478    pub key: Option<KeyRef>,
479    /// The properties for descendant `FloatingActionButton` widgets.
480    pub data: FloatingActionButtonThemeData,
481    pub child: WidgetRef,
482}
483
484impl FloatingActionButtonTheme {
485    /// Creates a floating action button theme that controls the configurations for
486    /// `FloatingActionButton`s in its widget subtree.
487    #[cfg_attr(debug_assertions, track_caller)]
488    pub fn new<K>(
489        data: FloatingActionButtonThemeData,
490        child: impl IntoWidget<K>,
491    ) -> FloatingActionButtonTheme {
492        FloatingActionButtonTheme {
493            key: None,
494            data,
495            child: child.into_widget(),
496        }
497    }
498
499    /// Dart `FloatingActionButtonTheme(key:)`.
500    pub fn key(mut self, key: KeyRef) -> FloatingActionButtonTheme {
501        self.key = Some(key);
502        self
503    }
504
505    /// The closest instance of this class's [`data`](Self::data) value that encloses the given
506    /// context.
507    ///
508    /// If there is no ancestor, it returns `ThemeData::floating_action_button_theme`. Applications
509    /// can assume that the returned value will not be null.
510    ///
511    /// Typical usage is as follows:
512    ///
513    /// ```text
514    /// let theme = FloatingActionButtonTheme::of(app, context);
515    /// ```
516    pub fn of(app: &mut App, context: BuildContext) -> FloatingActionButtonThemeData {
517        match context.depend_on_inherited_widget_of_exact_type::<FloatingActionButtonTheme>(app) {
518            Some(fab_theme) => fab_theme.data.clone(),
519            None => Theme::of(app, context).floating_action_button_theme.clone(),
520        }
521    }
522}
523
524impl InheritedTheme for FloatingActionButtonTheme {
525    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
526        FloatingActionButtonTheme::new(self.data.clone(), child).into_widget()
527    }
528}
529
530impl InheritedWidget for FloatingActionButtonTheme {
531    fn key(&self) -> Option<&KeyRef> {
532        self.key.as_ref()
533    }
534
535    fn child(&self) -> &WidgetRef {
536        &self.child
537    }
538
539    fn update_should_notify(&self, old_widget: &FloatingActionButtonTheme) -> bool {
540        self.data != old_widget.data
541    }
542
543    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
544        Some(self)
545    }
546}
547
548impl waft_foundation::Diagnosticable for FloatingActionButtonThemeData {
549    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
550        properties
551            .add(ColorProperty::new("foregroundColor", self.foreground_color).default_value(None));
552        properties
553            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
554        properties.add(ColorProperty::new("focusColor", self.focus_color).default_value(None));
555        properties.add(ColorProperty::new("hoverColor", self.hover_color).default_value(None));
556        properties.add(ColorProperty::new("splashColor", self.splash_color).default_value(None));
557        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
558        properties
559            .add(DoubleProperty::new("focusElevation", self.focus_elevation).default_value(None));
560        properties
561            .add(DoubleProperty::new("hoverElevation", self.hover_elevation).default_value(None));
562        properties.add(
563            DoubleProperty::new("disabledElevation", self.disabled_elevation).default_value(None),
564        );
565        properties.add(
566            DoubleProperty::new("highlightElevation", self.highlight_elevation).default_value(None),
567        );
568        properties.add(
569            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
570                .default_value(None),
571        );
572        properties.add(
573            DiagnosticsProperty::<bool>::new("enableFeedback", self.enable_feedback)
574                .default_value(None),
575        );
576        properties.add(DoubleProperty::new("iconSize", self.icon_size).default_value(None));
577        properties.add(
578            DiagnosticsProperty::<BoxConstraints>::new("sizeConstraints", self.size_constraints)
579                .default_value(None),
580        );
581        properties.add(
582            DiagnosticsProperty::<BoxConstraints>::new(
583                "smallSizeConstraints",
584                self.small_size_constraints,
585            )
586            .default_value(None),
587        );
588        properties.add(
589            DiagnosticsProperty::<BoxConstraints>::new(
590                "largeSizeConstraints",
591                self.large_size_constraints,
592            )
593            .default_value(None),
594        );
595        properties.add(
596            DiagnosticsProperty::<BoxConstraints>::new(
597                "extendedSizeConstraints",
598                self.extended_size_constraints,
599            )
600            .default_value(None),
601        );
602        properties.add(
603            DoubleProperty::new("extendedIconLabelSpacing", self.extended_icon_label_spacing)
604                .default_value(None),
605        );
606        properties.add(
607            DiagnosticsProperty::<EdgeInsetsGeometry>::new(
608                "extendedPadding",
609                self.extended_padding,
610            )
611            .default_value(None),
612        );
613        properties.add(
614            DiagnosticsProperty::<TextStyle>::new(
615                "extendedTextStyle",
616                self.extended_text_style.clone(),
617            )
618            .default_value(None),
619        );
620        properties.add(
621            DiagnosticsProperty::<String>::new(
622                "mouseCursor",
623                self.mouse_cursor
624                    .as_deref()
625                    .map(|property| property.to_string()),
626            )
627            .default_value(None),
628        );
629    }
630}
631
632impl std::fmt::Display for FloatingActionButtonThemeData {
633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
634        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
635    }
636}
637
638#[cfg(test)]
639mod tests {
640    use std::rc::Rc;
641    use waft_painting::ShapeBorder;
642
643    use waft_embedder::Size;
644    use waft_painting::{
645        BeveledRectangleBorder, BorderRadiusGeometry, BorderSide, EdgeInsetsDirectional,
646        RoundedRectangleBorder, ShapeBorderRef, TextStyle,
647    };
648    use waft_rendering::BoxConstraints;
649    use waft_services::SystemMouseCursors;
650    use waft_widgets::{SizedBox, WidgetStatePropertyAll};
651
652    use waft_widgets::testing::test_widgets;
653
654    use super::*;
655    use crate::colors::Colors;
656    use crate::drawer_theme::tests::probe;
657    use crate::drawer_theme::tests::theme_seen_through_capture;
658    use crate::theme_data::ThemeData;
659
660    fn rounded(radius: f64) -> RoundedRectangleBorder {
661        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(radius))
662    }
663
664    fn cursor(cursor: impl Into<MouseCursorRef>) -> WidgetStatePropertyRef<Option<MouseCursorRef>> {
665        Rc::new(WidgetStatePropertyAll::new(Some(cursor.into())))
666    }
667
668    #[test]
669    fn floating_action_button_theme_data_copy_with_equality_basics() {
670        assert_eq!(
671            FloatingActionButtonThemeData::new(),
672            FloatingActionButtonThemeData::new().copy_with()
673        );
674
675        let theme = FloatingActionButtonThemeData::new()
676            .elevation(4.0)
677            .shape(rounded(8.0))
678            .mouse_cursor(cursor(SystemMouseCursors::FORBIDDEN));
679        assert_eq!(theme.copy_with(), theme);
680        assert_eq!(theme.copy_with().icon_size(30.0).icon_size, Some(30.0));
681        assert_eq!(theme.copy_with().icon_size(30.0).elevation, Some(4.0));
682        assert_ne!(theme.copy_with().elevation(5.0), theme);
683        assert_ne!(theme.copy_with().shape(rounded(9.0)), theme);
684    }
685
686    #[test]
687    fn floating_action_button_theme_data_equality_compares_the_mouse_cursor_by_value() {
688        let forbidden = cursor(SystemMouseCursors::FORBIDDEN);
689        let with = |mouse_cursor| FloatingActionButtonThemeData::new().mouse_cursor(mouse_cursor);
690
691        assert_eq!(with(Rc::clone(&forbidden)), with(Rc::clone(&forbidden)));
692        assert_eq!(
693            with(Rc::clone(&forbidden)),
694            with(cursor(SystemMouseCursors::FORBIDDEN))
695        );
696        assert_ne!(
697            with(Rc::clone(&forbidden)),
698            with(cursor(SystemMouseCursors::CLICK))
699        );
700        assert_ne!(with(forbidden), FloatingActionButtonThemeData::new());
701    }
702
703    #[test]
704    fn floating_action_button_theme_data_lerp_special_cases() {
705        assert_eq!(FloatingActionButtonThemeData::lerp(None, None, 0.0), None);
706        let data = FloatingActionButtonThemeData::new();
707        assert_eq!(
708            FloatingActionButtonThemeData::lerp(Some(&data), Some(&data), 0.5),
709            Some(data)
710        );
711    }
712
713    #[test]
714    fn floating_action_button_theme_data_null_fields_by_default() {
715        let theme = FloatingActionButtonThemeData::new();
716        assert_eq!(theme.foreground_color, None);
717        assert_eq!(theme.background_color, None);
718        assert_eq!(theme.focus_color, None);
719        assert_eq!(theme.hover_color, None);
720        assert_eq!(theme.splash_color, None);
721        assert_eq!(theme.elevation, None);
722        assert_eq!(theme.focus_elevation, None);
723        assert_eq!(theme.hover_elevation, None);
724        assert_eq!(theme.disabled_elevation, None);
725        assert_eq!(theme.highlight_elevation, None);
726        assert!(theme.shape.is_none());
727        assert_eq!(theme.enable_feedback, None);
728        assert_eq!(theme.icon_size, None);
729        assert_eq!(theme.size_constraints, None);
730        assert_eq!(theme.small_size_constraints, None);
731        assert_eq!(theme.large_size_constraints, None);
732        assert_eq!(theme.extended_size_constraints, None);
733        assert_eq!(theme.extended_icon_label_spacing, None);
734        assert_eq!(theme.extended_padding, None);
735        assert_eq!(theme.extended_text_style, None);
736        assert!(theme.mouse_cursor.is_none());
737    }
738
739    #[test]
740    fn floating_action_button_theme_data_lerps_each_field() {
741        let forbidden = cursor(SystemMouseCursors::FORBIDDEN);
742        let click = cursor(SystemMouseCursors::CLICK);
743        let a = FloatingActionButtonThemeData::new()
744            .foreground_color(Colors::BLACK)
745            .elevation(2.0)
746            .highlight_elevation(10.0)
747            .shape(rounded(4.0))
748            .enable_feedback(true)
749            .icon_size(20.0)
750            .size_constraints(BoxConstraints::tight(Size::new(100.0, 100.0)))
751            .extended_icon_label_spacing(8.0)
752            .extended_padding(EdgeInsetsGeometry::all(10.0))
753            .extended_text_style(TextStyle::new().font_size(10.0))
754            .mouse_cursor(Rc::clone(&forbidden));
755        let b = FloatingActionButtonThemeData::new()
756            .foreground_color(Colors::WHITE)
757            .splash_color(Colors::RED.primary())
758            .elevation(6.0)
759            .highlight_elevation(20.0)
760            .shape(rounded(8.0))
761            .enable_feedback(false)
762            .icon_size(40.0)
763            .size_constraints(BoxConstraints::tight(Size::new(300.0, 300.0)))
764            .small_size_constraints(BoxConstraints::tight(Size::new(30.0, 30.0)))
765            .extended_icon_label_spacing(16.0)
766            .extended_padding(EdgeInsetsGeometry::all(30.0))
767            .extended_text_style(TextStyle::new().font_size(20.0))
768            .mouse_cursor(Rc::clone(&click));
769
770        let halfway =
771            FloatingActionButtonThemeData::lerp(Some(&a), Some(&b), 0.5).expect("both given");
772
773        assert_eq!(
774            halfway.foreground_color,
775            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
776        );
777        assert_eq!(
778            halfway.splash_color,
779            Color::lerp(None, Some(Colors::RED.primary()), 0.5)
780        );
781        assert_eq!(halfway.elevation, Some(4.0));
782        assert_eq!(halfway.highlight_elevation, Some(15.0));
783        assert_eq!(
784            halfway.shape.as_deref(),
785            Some(&rounded(6.0) as &dyn ShapeBorder)
786        );
787        assert_eq!(halfway.enable_feedback, Some(false));
788        assert_eq!(halfway.icon_size, Some(30.0));
789        assert_eq!(
790            halfway.size_constraints,
791            Some(BoxConstraints::tight(Size::new(200.0, 200.0)))
792        );
793        assert_eq!(
794            halfway.small_size_constraints,
795            BoxConstraints::lerp(
796                None,
797                Some(BoxConstraints::tight(Size::new(30.0, 30.0))),
798                0.5
799            )
800        );
801        assert_eq!(halfway.extended_icon_label_spacing, Some(12.0));
802        assert_eq!(
803            halfway.extended_padding,
804            Some(EdgeInsetsGeometry::all(20.0))
805        );
806        assert_eq!(
807            halfway
808                .extended_text_style
809                .and_then(|style| style.font_size),
810            Some(15.0)
811        );
812        assert!(Rc::ptr_eq(
813            halfway.mouse_cursor.as_ref().expect("a cursor"),
814            &click
815        ));
816
817        let early =
818            FloatingActionButtonThemeData::lerp(Some(&a), Some(&b), 0.25).expect("both given");
819        assert_eq!(early.enable_feedback, Some(true));
820        assert!(Rc::ptr_eq(
821            early.mouse_cursor.as_ref().expect("a cursor"),
822            &forbidden
823        ));
824    }
825
826    #[test]
827    fn of_returns_the_theme_data_floating_action_button_theme_without_an_ancestor() {
828        test_widgets(|tester| {
829            let expected = FloatingActionButtonThemeData::new()
830                .elevation(3.0)
831                .background_color(Colors::RED.primary());
832            let theme_data_fab = expected.clone();
833
834            let seen = probe(
835                tester,
836                move |app, child| {
837                    let data = ThemeData::builder()
838                        .floating_action_button_theme(theme_data_fab.clone())
839                        .build(app);
840                    Theme::new(data, child).into_widget()
841                },
842                FloatingActionButtonTheme::of,
843            );
844
845            assert_eq!(seen, expected);
846        });
847    }
848
849    #[test]
850    fn of_returns_the_closest_floating_action_button_theme_over_theme_data() {
851        test_widgets(|tester| {
852            let widget_fab = FloatingActionButtonThemeData::new().elevation(7.0);
853            let expected = widget_fab.clone();
854
855            let seen = probe(
856                tester,
857                move |app, child| {
858                    let data = ThemeData::builder()
859                        .floating_action_button_theme(
860                            FloatingActionButtonThemeData::new().elevation(3.0),
861                        )
862                        .build(app);
863                    Theme::new(
864                        data,
865                        FloatingActionButtonTheme::new(widget_fab.clone(), child),
866                    )
867                    .into_widget()
868                },
869                FloatingActionButtonTheme::of,
870            );
871
872            assert_eq!(seen, expected);
873        });
874    }
875
876    #[test]
877    fn a_captured_floating_action_button_theme_is_kept_under_another_one() {
878        test_widgets(|tester| {
879            let captured = FloatingActionButtonThemeData::new().elevation(1.0);
880            let shadowing = FloatingActionButtonThemeData::new().elevation(2.0);
881
882            let seen = theme_seen_through_capture(
883                tester,
884                |probe| FloatingActionButtonTheme::new(captured.clone(), probe).into_widget(),
885                |wrapped| FloatingActionButtonTheme::new(shadowing.clone(), wrapped).into_widget(),
886                FloatingActionButtonTheme::of,
887            );
888
889            assert_eq!(seen.elevation, Some(1.0));
890        });
891    }
892
893    #[test]
894    fn update_should_notify_only_when_the_data_differs() {
895        let theme = |data: FloatingActionButtonThemeData| {
896            FloatingActionButtonTheme::new(data, SizedBox::shrink())
897        };
898        let old = theme(FloatingActionButtonThemeData::new().elevation(1.0));
899
900        assert!(
901            !theme(FloatingActionButtonThemeData::new().elevation(1.0)).update_should_notify(&old)
902        );
903        assert!(
904            theme(FloatingActionButtonThemeData::new().elevation(2.0)).update_should_notify(&old)
905        );
906    }
907
908    #[test]
909    fn theme_data_holds_the_floating_action_button_theme() {
910        test_widgets(|tester| {
911            let app = tester.cell.borrow();
912            let theme = ThemeData::new(&app);
913            assert_eq!(
914                theme.floating_action_button_theme,
915                FloatingActionButtonThemeData::new()
916            );
917
918            let raised = ThemeData::builder()
919                .floating_action_button_theme(FloatingActionButtonThemeData::new().elevation(8.0))
920                .build(&app);
921            assert_eq!(raised.floating_action_button_theme.elevation, Some(8.0));
922            assert_ne!(theme, raised);
923            assert_eq!(
924                theme
925                    .copy_with()
926                    .floating_action_button_theme(raised.floating_action_button_theme.clone())
927                    .build(),
928                raised
929            );
930
931            let flat = ThemeData::builder()
932                .floating_action_button_theme(FloatingActionButtonThemeData::new().elevation(0.0))
933                .build(&app);
934            assert_eq!(
935                ThemeData::lerp(&flat, &raised, 0.5)
936                    .floating_action_button_theme
937                    .elevation,
938                Some(4.0)
939            );
940        });
941    }
942    // Flutter's "Default FloatingActionButtonThemeData debugFillProperties".
943    #[test]
944    fn a_floating_action_button_theme_data_describes_nothing_by_default() {
945        assert_eq!(
946            waft_widgets::testing::describe_properties(|properties| {
947                waft_foundation::Diagnosticable::debug_fill_properties(
948                    &FloatingActionButtonThemeData::new(),
949                    properties,
950                )
951            }),
952            Vec::<String>::new()
953        );
954    }
955
956    // floating_action_button_theme_test.dart 'FloatingActionButtonThemeData implements debugFillProperties'.
957    #[test]
958    fn an_assigned_floating_action_button_theme_describes_every_property() {
959        let mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>> = Rc::new(
960            WidgetStatePropertyAll::new(Some(SystemMouseCursors::CLICK.into())),
961        );
962        let theme = FloatingActionButtonThemeData::new()
963            .foreground_color(Color::new(0xfeedfeed))
964            .background_color(Color::new(0xcafecafe))
965            .focus_color(Color::new(0xfeedfee1))
966            .hover_color(Color::new(0xfeedfee2))
967            .splash_color(Color::new(0xfeedfee3))
968            .elevation(23.0)
969            .focus_elevation(9.0)
970            .hover_elevation(10.0)
971            .disabled_elevation(11.0)
972            .highlight_elevation(43.0)
973            .shape(BeveledRectangleBorder::default())
974            .enable_feedback(true)
975            .icon_size(42.0)
976            .size_constraints(BoxConstraints::tight(Size::new(100.0, 100.0)))
977            .small_size_constraints(BoxConstraints::tight(Size::new(101.0, 101.0)))
978            .large_size_constraints(BoxConstraints::tight(Size::new(102.0, 102.0)))
979            .extended_size_constraints(BoxConstraints::new().min_height(103.0).max_height(103.0))
980            .extended_icon_label_spacing(12.0)
981            .extended_padding(EdgeInsetsDirectional::from_steb(7.0, 0.0, 8.0, 0.0))
982            .extended_text_style(TextStyle::new().letter_spacing(2.0))
983            .mouse_cursor(mouse_cursor);
984        let description = waft_widgets::testing::describe_properties(|properties| {
985            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
986        });
987        assert_eq!(
988            description,
989            [
990                format!("foregroundColor: {}", Color::new(0xfeedfeed)),
991                format!("backgroundColor: {}", Color::new(0xcafecafe)),
992                format!("focusColor: {}", Color::new(0xfeedfee1)),
993                format!("hoverColor: {}", Color::new(0xfeedfee2)),
994                format!("splashColor: {}", Color::new(0xfeedfee3)),
995                "elevation: 23.0".to_string(),
996                "focusElevation: 9.0".to_string(),
997                "hoverElevation: 10.0".to_string(),
998                "disabledElevation: 11.0".to_string(),
999                "highlightElevation: 43.0".to_string(),
1000                format!(
1001                    "shape: {}",
1002                    ShapeBorderRef::from(BeveledRectangleBorder::default())
1003                ),
1004                "enableFeedback: true".to_string(),
1005                "iconSize: 42.0".to_string(),
1006                "sizeConstraints: BoxConstraints(w=100.0, h=100.0)".to_string(),
1007                "smallSizeConstraints: BoxConstraints(w=101.0, h=101.0)".to_string(),
1008                "largeSizeConstraints: BoxConstraints(w=102.0, h=102.0)".to_string(),
1009                "extendedSizeConstraints: BoxConstraints(0.0<=w<=Infinity, h=103.0)".to_string(),
1010                "extendedIconLabelSpacing: 12.0".to_string(),
1011                "extendedPadding: EdgeInsetsDirectional(7.0, 0.0, 8.0, 0.0)".to_string(),
1012                "extendedTextStyle: TextStyle(inherit: true, letterSpacing: 2.0)".to_string(),
1013                "mouseCursor: WidgetStatePropertyAll(SystemMouseCursor(click))".to_string(),
1014            ]
1015        );
1016    }
1017}