Skip to main content

waft_material/
snack_bar_theme.rs

1//! Flutter counterpart: material_ui's `snack_bar_theme.dart`.
2
3use waft_embedder::{Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{
6    AnyColor, ColorProperty, EdgeInsets, EdgeInsetsGeometry, ShapeBorderRef, TextStyle,
7};
8use waft_widgets::{
9    BuildContext, DismissDirection, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
10    WidgetStateColor,
11};
12
13use crate::theme::Theme;
14
15/// Defines where a `SnackBar` should appear within a `Scaffold` and how its
16/// location should be adjusted when the scaffold also includes a
17/// `FloatingActionButton` or a `BottomNavigationBar`.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub enum SnackBarBehavior {
20    /// Fixes the `SnackBar` at the bottom of the `Scaffold`.
21    ///
22    /// The exception is that the `SnackBar` will be shown above a
23    /// `BottomNavigationBar` or a `NavigationBar`. Additionally, the `SnackBar`
24    /// will cause other non-fixed widgets inside `Scaffold` to be pushed above
25    /// (for example, the `FloatingActionButton`).
26    Fixed,
27
28    /// This behavior will cause `SnackBar` to be shown above other widgets in the
29    /// `Scaffold`. This includes being displayed above a `BottomNavigationBar` or
30    /// a `NavigationBar`, and a `FloatingActionButton` when its location is on the
31    /// bottom. When the floating action button location is on the top, this behavior
32    /// will cause the `SnackBar` to be shown above other widgets in the `Scaffold`
33    /// except the floating action button.
34    ///
35    /// See <https://material.io/design/components/snackbars.html> for more details.
36    Floating,
37}
38
39/// Customizes default property values for `SnackBar` widgets.
40///
41/// Descendant widgets obtain the current [`SnackBarThemeData`] object using
42/// [`SnackBarTheme::of`]. Instances of [`SnackBarThemeData`] can be
43/// customized with [`SnackBarThemeData::copy_with`].
44///
45/// Typically a [`SnackBarThemeData`] is specified as part of the overall `Theme`
46/// with `ThemeData::snack_bar_theme`. The default for `ThemeData::snack_bar_theme`
47/// provides all `null` properties.
48///
49/// All [`SnackBarThemeData`] properties are `null` by default. When null, the
50/// `SnackBar` will provide its own defaults.
51///
52/// Dart's constructor asserts run in the setters that can break them
53/// ([`elevation`](Self::elevation), [`width`](Self::width), [`behavior`](Self::behavior),
54/// [`action_overflow_threshold`](Self::action_overflow_threshold),
55/// [`action_background_color`](Self::action_background_color) and
56/// [`disabled_action_background_color`](Self::disabled_action_background_color)), so that
57/// they hold in any order. A [`width`](Self::width) given with no
58/// [`behavior`](Self::behavior) at all is not caught: a setter cannot know that no
59/// [`behavior`](Self::behavior) is coming.
60///
61/// See also:
62///
63///  * `ThemeData`, which describes the overall theme information for the
64///    application.
65#[derive(Clone, Debug, Default, PartialEq)]
66pub struct SnackBarThemeData {
67    /// Overrides the default value for `SnackBar::background_color`.
68    ///
69    /// If null, `SnackBar` defaults to dark grey: `Color(0xFF323232)`.
70    pub background_color: Option<Color>,
71
72    /// Overrides the default value for `SnackBarAction::text_color`.
73    ///
74    /// If null, `SnackBarAction` defaults to `ColorScheme::secondary` of
75    /// `ThemeData::color_scheme`.
76    pub action_text_color: Option<AnyColor>,
77
78    /// Overrides the default value for `SnackBarAction::disabled_text_color`.
79    ///
80    /// If null, `SnackBarAction` defaults to `ColorScheme::on_surface` with its
81    /// opacity set to 0.30 if the `Theme`'s brightness is `Brightness::Dark`, 0.38
82    /// otherwise.
83    pub disabled_action_text_color: Option<Color>,
84
85    /// Used to configure the `DefaultTextStyle` for the `SnackBar::content` widget.
86    ///
87    /// If null, `SnackBar` defines its default.
88    pub content_text_style: Option<TextStyle>,
89
90    /// Overrides the default value for `SnackBar::elevation`.
91    ///
92    /// If null, `SnackBar` uses a default of 6.0.
93    pub elevation: Option<f64>,
94
95    /// Overrides the default value for `SnackBar::shape`.
96    ///
97    /// If null, `SnackBar` provides different defaults depending on the
98    /// [`SnackBarBehavior`]. For [`SnackBarBehavior::Fixed`], no overriding shape is
99    /// specified, so the `SnackBar` is rectangular. For
100    /// [`SnackBarBehavior::Floating`], it uses a `RoundedRectangleBorder` with a
101    /// circular corner radius of 4.0.
102    pub shape: Option<ShapeBorderRef>,
103
104    /// Overrides the default value for `SnackBar::behavior`.
105    ///
106    /// If null, `SnackBar` will default to [`SnackBarBehavior::Fixed`].
107    pub behavior: Option<SnackBarBehavior>,
108
109    /// Overrides the default value for `SnackBar::width`.
110    ///
111    /// If this property is null, then the snack bar will take up the full device
112    /// width less the margin. This value is only used when [`behavior`](Self::behavior) is
113    /// [`SnackBarBehavior::Floating`].
114    pub width: Option<f64>,
115
116    /// Overrides the default value for `SnackBar::margin`.
117    ///
118    /// This value is only used when [`behavior`](Self::behavior) is [`SnackBarBehavior::Floating`].
119    pub inset_padding: Option<EdgeInsets>,
120
121    /// Overrides the default value for `SnackBar::show_close_icon`.
122    ///
123    /// Whether to show an optional "Close" icon.
124    pub show_close_icon: Option<bool>,
125
126    /// Overrides the default value for `SnackBar::close_icon_color`.
127    ///
128    /// This value is only used if [`show_close_icon`](Self::show_close_icon) is true.
129    pub close_icon_color: Option<AnyColor>,
130
131    /// Overrides the default value for `SnackBar::action_overflow_threshold`.
132    ///
133    /// Must be a value between 0 and 1, if present.
134    pub action_overflow_threshold: Option<f64>,
135
136    /// Overrides default value for `SnackBarAction::background_color`.
137    ///
138    /// If null, `SnackBarAction` falls back to `Colors::TRANSPARENT`.
139    pub action_background_color: Option<AnyColor>,
140
141    /// Overrides default value for `SnackBarAction::disabled_background_color`.
142    ///
143    /// If null, `SnackBarAction` falls back to `Colors::TRANSPARENT`.
144    pub disabled_action_background_color: Option<Color>,
145
146    /// Overrides the default value for `SnackBar::dismiss_direction`.
147    ///
148    /// If null, `SnackBar` will default to [`DismissDirection::Down`].
149    pub dismiss_direction: Option<DismissDirection>,
150}
151
152crate::theme_data_getters::theme_data_getters! {
153    /// Dart's getters of `SnackBarThemeData`: the theme data answers with its fields, and a defaults
154    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
155    /// are read.
156    pub trait SnackBarThemeDataGetters for SnackBarThemeData, fields: snack_bar_theme_data {
157        background_color: Option<Color>,
158        action_text_color: Option<AnyColor>,
159        disabled_action_text_color: Option<Color>,
160        content_text_style: Option<TextStyle>,
161        elevation: Option<f64>,
162        shape: Option<ShapeBorderRef>,
163        behavior: Option<SnackBarBehavior>,
164        width: Option<f64>,
165        inset_padding: Option<EdgeInsets>,
166        show_close_icon: Option<bool>,
167        close_icon_color: Option<AnyColor>,
168        action_overflow_threshold: Option<f64>,
169        action_background_color: Option<AnyColor>,
170        disabled_action_background_color: Option<Color>,
171        dismiss_direction: Option<DismissDirection>,
172    }
173}
174
175impl SnackBarThemeData {
176    /// Creates a theme that can be used for `ThemeData::snack_bar_theme`; Dart's optional
177    /// named arguments are the fluent setters.
178    ///
179    /// The [`elevation`](Self::elevation) must be null or non-negative.
180    pub fn new() -> SnackBarThemeData {
181        SnackBarThemeData::default()
182    }
183
184    /// Dart `SnackBarThemeData(backgroundColor:)`.
185    pub fn background_color(mut self, background_color: Color) -> SnackBarThemeData {
186        self.background_color = Some(background_color);
187        self
188    }
189
190    /// Dart `SnackBarThemeData(actionTextColor:)`.
191    pub fn action_text_color(
192        mut self,
193        action_text_color: impl Into<AnyColor>,
194    ) -> SnackBarThemeData {
195        self.action_text_color = Some(action_text_color.into());
196        self
197    }
198
199    /// Dart `SnackBarThemeData(disabledActionTextColor:)`.
200    pub fn disabled_action_text_color(
201        mut self,
202        disabled_action_text_color: Color,
203    ) -> SnackBarThemeData {
204        self.disabled_action_text_color = Some(disabled_action_text_color);
205        self
206    }
207
208    /// Dart `SnackBarThemeData(contentTextStyle:)`.
209    pub fn content_text_style(mut self, content_text_style: TextStyle) -> SnackBarThemeData {
210        self.content_text_style = Some(content_text_style);
211        self
212    }
213
214    /// Dart `SnackBarThemeData(elevation:)`.
215    pub fn elevation(mut self, elevation: f64) -> SnackBarThemeData {
216        debug_assert!(elevation >= 0.0);
217        self.elevation = Some(elevation);
218        self
219    }
220
221    /// Dart `SnackBarThemeData(shape:)`.
222    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> SnackBarThemeData {
223        self.shape = Some(shape.into());
224        self
225    }
226
227    /// Dart `SnackBarThemeData(behavior:)`.
228    pub fn behavior(mut self, behavior: SnackBarBehavior) -> SnackBarThemeData {
229        debug_assert!(
230            self.width.is_none() || behavior == SnackBarBehavior::Floating,
231            "Width can only be set if behaviour is SnackBarBehavior.floating"
232        );
233        self.behavior = Some(behavior);
234        self
235    }
236
237    /// Dart `SnackBarThemeData(width:)`.
238    pub fn width(mut self, width: f64) -> SnackBarThemeData {
239        debug_assert!(
240            self.behavior
241                .is_none_or(|behavior| behavior == SnackBarBehavior::Floating),
242            "Width can only be set if behaviour is SnackBarBehavior.floating"
243        );
244        self.width = Some(width);
245        self
246    }
247
248    /// Dart `SnackBarThemeData(insetPadding:)`.
249    pub fn inset_padding(mut self, inset_padding: EdgeInsets) -> SnackBarThemeData {
250        self.inset_padding = Some(inset_padding);
251        self
252    }
253
254    /// Dart `SnackBarThemeData(showCloseIcon:)`.
255    pub fn show_close_icon(mut self, show_close_icon: bool) -> SnackBarThemeData {
256        self.show_close_icon = Some(show_close_icon);
257        self
258    }
259
260    /// Dart `SnackBarThemeData(closeIconColor:)`.
261    pub fn close_icon_color(mut self, close_icon_color: impl Into<AnyColor>) -> SnackBarThemeData {
262        self.close_icon_color = Some(close_icon_color.into());
263        self
264    }
265
266    /// Dart `SnackBarThemeData(actionOverflowThreshold:)`.
267    pub fn action_overflow_threshold(
268        mut self,
269        action_overflow_threshold: f64,
270    ) -> SnackBarThemeData {
271        debug_assert!(
272            (0.0..=1.0).contains(&action_overflow_threshold),
273            "Action overflow threshold must be between 0 and 1 inclusive"
274        );
275        self.action_overflow_threshold = Some(action_overflow_threshold);
276        self
277    }
278
279    /// Dart `SnackBarThemeData(actionBackgroundColor:)`.
280    pub fn action_background_color(
281        mut self,
282        action_background_color: impl Into<AnyColor>,
283    ) -> SnackBarThemeData {
284        let action_background_color = action_background_color.into();
285        debug_assert!(
286            !is_widget_state_color(&action_background_color)
287                || self.disabled_action_background_color.is_none(),
288            "disabledBackgroundColor must not be provided when background color is a WidgetStateColor"
289        );
290        self.action_background_color = Some(action_background_color);
291        self
292    }
293
294    /// Dart `SnackBarThemeData(disabledActionBackgroundColor:)`.
295    pub fn disabled_action_background_color(
296        mut self,
297        disabled_action_background_color: Color,
298    ) -> SnackBarThemeData {
299        debug_assert!(
300            !self
301                .action_background_color
302                .as_ref()
303                .is_some_and(is_widget_state_color),
304            "disabledBackgroundColor must not be provided when background color is a WidgetStateColor"
305        );
306        self.disabled_action_background_color = Some(disabled_action_background_color);
307        self
308    }
309
310    /// Dart `SnackBarThemeData(dismissDirection:)`.
311    pub fn dismiss_direction(mut self, dismiss_direction: DismissDirection) -> SnackBarThemeData {
312        self.dismiss_direction = Some(dismiss_direction);
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) -> SnackBarThemeData {
322        self.clone()
323    }
324
325    /// Linearly interpolate between two SnackBar themes.
326    ///
327    /// {@macro dart.ui.shadow.lerp}
328    pub fn lerp(
329        a: Option<&SnackBarThemeData>,
330        b: Option<&SnackBarThemeData>,
331        t: f64,
332    ) -> SnackBarThemeData {
333        if let (Some(a), Some(b)) = (a, b)
334            && std::ptr::eq(a, b)
335        {
336            return a.clone();
337        }
338        let lerped = SnackBarThemeData {
339            background_color: Color::lerp(
340                a.and_then(|a| a.background_color),
341                b.and_then(|b| b.background_color),
342                t,
343            ),
344            action_text_color: AnyColor::lerp(
345                a.and_then(|a| a.action_text_color.as_ref()),
346                b.and_then(|b| b.action_text_color.as_ref()),
347                t,
348            )
349            .map(AnyColor::from),
350            disabled_action_text_color: Color::lerp(
351                a.and_then(|a| a.disabled_action_text_color),
352                b.and_then(|b| b.disabled_action_text_color),
353                t,
354            ),
355            content_text_style: TextStyle::lerp(
356                a.and_then(|a| a.content_text_style.as_ref()),
357                b.and_then(|b| b.content_text_style.as_ref()),
358                t,
359            ),
360            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
361            shape: ShapeBorderRef::lerp(
362                a.and_then(|a| a.shape.as_ref()),
363                b.and_then(|b| b.shape.as_ref()),
364                t,
365            ),
366            behavior: if t < 0.5 {
367                a.and_then(|a| a.behavior)
368            } else {
369                b.and_then(|b| b.behavior)
370            },
371            width: lerp_double(a.and_then(|a| a.width), b.and_then(|b| b.width), t),
372            inset_padding: EdgeInsets::lerp(
373                a.and_then(|a| a.inset_padding),
374                b.and_then(|b| b.inset_padding),
375                t,
376            ),
377            show_close_icon: if t < 0.5 {
378                a.and_then(|a| a.show_close_icon)
379            } else {
380                b.and_then(|b| b.show_close_icon)
381            },
382            close_icon_color: AnyColor::lerp(
383                a.and_then(|a| a.close_icon_color.as_ref()),
384                b.and_then(|b| b.close_icon_color.as_ref()),
385                t,
386            )
387            .map(AnyColor::from),
388            action_overflow_threshold: lerp_double(
389                a.and_then(|a| a.action_overflow_threshold),
390                b.and_then(|b| b.action_overflow_threshold),
391                t,
392            ),
393            action_background_color: AnyColor::lerp(
394                a.and_then(|a| a.action_background_color.as_ref()),
395                b.and_then(|b| b.action_background_color.as_ref()),
396                t,
397            )
398            .map(AnyColor::from),
399            disabled_action_background_color: Color::lerp(
400                a.and_then(|a| a.disabled_action_background_color),
401                b.and_then(|b| b.disabled_action_background_color),
402                t,
403            ),
404            dismiss_direction: if t < 0.5 {
405                a.and_then(|a| a.dismiss_direction)
406            } else {
407                b.and_then(|b| b.dismiss_direction)
408            },
409        };
410        lerped.debug_assert_valid();
411        lerped
412    }
413}
414
415impl SnackBarThemeData {
416    /// Dart's constructor asserts, for a value assembled field by field ([`lerp`](Self::lerp)).
417    fn debug_assert_valid(&self) {
418        debug_assert!(self.elevation.is_none_or(|elevation| elevation >= 0.0));
419        debug_assert!(
420            self.width.is_none() || self.behavior == Some(SnackBarBehavior::Floating),
421            "Width can only be set if behaviour is SnackBarBehavior.floating"
422        );
423        debug_assert!(
424            self.action_overflow_threshold
425                .is_none_or(|threshold| (0.0..=1.0).contains(&threshold)),
426            "Action overflow threshold must be between 0 and 1 inclusive"
427        );
428        debug_assert!(
429            !self
430                .action_background_color
431                .as_ref()
432                .is_some_and(is_widget_state_color)
433                || self.disabled_action_background_color.is_none(),
434            "disabledBackgroundColor must not be provided when background color is a WidgetStateColor"
435        );
436    }
437}
438
439/// Dart's `color is WidgetStateColor`.
440fn is_widget_state_color(color: &AnyColor) -> bool {
441    color.extension::<WidgetStateColor>().is_some()
442}
443
444/// An inherited widget that defines the configuration for
445/// `SnackBar`s in this widget's subtree.
446///
447/// Values specified here are used for `SnackBar` properties that are not
448/// given an explicit non-null value.
449#[derive(Debug)]
450pub struct SnackBarTheme {
451    pub key: Option<KeyRef>,
452    /// The properties for descendant `SnackBar` widgets.
453    pub data: SnackBarThemeData,
454    pub child: WidgetRef,
455}
456
457impl SnackBarTheme {
458    /// Creates a snackbar theme that controls the configurations for
459    /// `SnackBar`s in its widget subtree.
460    #[cfg_attr(debug_assertions, track_caller)]
461    pub fn new<K>(data: SnackBarThemeData, child: impl IntoWidget<K>) -> SnackBarTheme {
462        SnackBarTheme {
463            key: None,
464            data,
465            child: child.into_widget(),
466        }
467    }
468
469    /// Dart `SnackBarTheme(key:)`.
470    pub fn key(mut self, key: KeyRef) -> SnackBarTheme {
471        self.key = Some(key);
472        self
473    }
474
475    /// The closest instance of this class's [`data`](Self::data) value that encloses the given
476    /// context.
477    ///
478    /// If there is no ancestor, it returns `ThemeData::snack_bar_theme`. Applications
479    /// can assume that the returned value will not be null.
480    ///
481    /// Typical usage is as follows:
482    ///
483    /// ```text
484    /// let theme = SnackBarTheme::of(app, context);
485    /// ```
486    pub fn of(app: &mut App, context: BuildContext) -> SnackBarThemeData {
487        match context.depend_on_inherited_widget_of_exact_type::<SnackBarTheme>(app) {
488            Some(snack_bar_theme) => snack_bar_theme.data.clone(),
489            None => Theme::of(app, context).snack_bar_theme.clone(),
490        }
491    }
492}
493
494impl InheritedTheme for SnackBarTheme {
495    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
496        SnackBarTheme::new(self.data.clone(), child).into_widget()
497    }
498}
499
500impl InheritedWidget for SnackBarTheme {
501    fn key(&self) -> Option<&KeyRef> {
502        self.key.as_ref()
503    }
504
505    fn child(&self) -> &WidgetRef {
506        &self.child
507    }
508
509    fn update_should_notify(&self, old_widget: &SnackBarTheme) -> bool {
510        self.data != old_widget.data
511    }
512
513    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
514        Some(self)
515    }
516}
517
518impl waft_foundation::Diagnosticable for SnackBarThemeData {
519    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
520        properties
521            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
522        properties.add(
523            DiagnosticsProperty::<AnyColor>::new("actionTextColor", self.action_text_color.clone())
524                .default_value(None),
525        );
526        properties.add(
527            ColorProperty::new("disabledActionTextColor", self.disabled_action_text_color)
528                .default_value(None),
529        );
530        properties.add(
531            DiagnosticsProperty::<TextStyle>::new(
532                "contentTextStyle",
533                self.content_text_style.clone(),
534            )
535            .default_value(None),
536        );
537        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
538        properties.add(
539            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
540                .default_value(None),
541        );
542        properties.add(
543            DiagnosticsProperty::<waft_foundation::DartEnum<SnackBarBehavior>>::new(
544                "behavior",
545                self.behavior.map(waft_foundation::DartEnum),
546            )
547            .default_value(None),
548        );
549        properties.add(DoubleProperty::new("width", self.width).default_value(None));
550        properties.add(
551            DiagnosticsProperty::<EdgeInsetsGeometry>::new(
552                "insetPadding",
553                self.inset_padding.map(EdgeInsetsGeometry::from),
554            )
555            .default_value(None),
556        );
557        properties.add(
558            DiagnosticsProperty::<bool>::new("showCloseIcon", self.show_close_icon)
559                .default_value(None),
560        );
561        properties.add(
562            DiagnosticsProperty::<AnyColor>::new("closeIconColor", self.close_icon_color.clone())
563                .default_value(None),
564        );
565        properties.add(
566            DoubleProperty::new("actionOverflowThreshold", self.action_overflow_threshold)
567                .default_value(None),
568        );
569        properties.add(
570            DiagnosticsProperty::<AnyColor>::new(
571                "actionBackgroundColor",
572                self.action_background_color.clone(),
573            )
574            .default_value(None),
575        );
576        properties.add(
577            ColorProperty::new(
578                "disabledActionBackgroundColor",
579                self.disabled_action_background_color,
580            )
581            .default_value(None),
582        );
583        properties.add(
584            DiagnosticsProperty::<waft_foundation::DartEnum<DismissDirection>>::new(
585                "dismissDirection",
586                self.dismiss_direction.map(waft_foundation::DartEnum),
587            )
588            .default_value(None),
589        );
590    }
591}
592
593impl std::fmt::Display for SnackBarThemeData {
594    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
595        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use waft_painting::ShapeBorder;
602    use waft_painting::{BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
603    use waft_widgets::{SizedBox, WidgetState};
604
605    use waft_widgets::testing::test_widgets;
606
607    use super::*;
608    use crate::colors::Colors;
609    use crate::drawer_theme::tests::probe;
610    use crate::drawer_theme::tests::theme_seen_through_capture;
611    use crate::theme_data::ThemeData;
612
613    fn rounded(radius: f64) -> RoundedRectangleBorder {
614        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(radius))
615    }
616
617    fn widget_state_color() -> AnyColor {
618        WidgetStateColor::resolve_with(|states| {
619            if states.contains(&WidgetState::Disabled) {
620                Colors::BLUE.primary()
621            } else {
622                Colors::PURPLE.primary()
623            }
624        })
625        .into_any()
626    }
627
628    #[test]
629    fn snack_bar_theme_data_copy_with_equality_basics() {
630        assert_eq!(
631            SnackBarThemeData::new(),
632            SnackBarThemeData::new().copy_with()
633        );
634
635        let theme = SnackBarThemeData::new()
636            .elevation(4.0)
637            .shape(rounded(8.0))
638            .behavior(SnackBarBehavior::Floating)
639            .width(300.0);
640        assert_eq!(theme.copy_with(), theme);
641        assert_eq!(
642            theme
643                .copy_with()
644                .dismiss_direction(DismissDirection::Up)
645                .elevation,
646            Some(4.0)
647        );
648        assert_eq!(
649            theme
650                .copy_with()
651                .dismiss_direction(DismissDirection::Up)
652                .dismiss_direction,
653            Some(DismissDirection::Up)
654        );
655        assert_ne!(theme.copy_with().elevation(5.0), theme);
656        assert_ne!(theme.copy_with().shape(rounded(9.0)), theme);
657    }
658
659    #[test]
660    fn snack_bar_theme_data_lerp_special_cases() {
661        assert_eq!(
662            SnackBarThemeData::lerp(None, None, 0.0),
663            SnackBarThemeData::new()
664        );
665        let data = SnackBarThemeData::new();
666        assert_eq!(SnackBarThemeData::lerp(Some(&data), Some(&data), 0.5), data);
667    }
668
669    #[test]
670    fn snack_bar_theme_data_lerp_keeps_show_close_icon() {
671        let a = SnackBarThemeData::new().show_close_icon(true);
672        let b = SnackBarThemeData::new().show_close_icon(false);
673
674        assert_eq!(
675            SnackBarThemeData::lerp(Some(&a), Some(&b), 0.25).show_close_icon,
676            Some(true)
677        );
678        assert_eq!(
679            SnackBarThemeData::lerp(Some(&a), Some(&b), 0.75).show_close_icon,
680            Some(false)
681        );
682        assert_eq!(
683            SnackBarThemeData::lerp(Some(&a), None, 0.25).show_close_icon,
684            Some(true)
685        );
686        assert_eq!(
687            SnackBarThemeData::lerp(None, Some(&a), 0.75).show_close_icon,
688            Some(true)
689        );
690    }
691
692    #[test]
693    fn snack_bar_theme_data_null_fields_by_default() {
694        let snack_bar_theme = SnackBarThemeData::new();
695        assert_eq!(snack_bar_theme.background_color, None);
696        assert_eq!(snack_bar_theme.action_text_color, None);
697        assert_eq!(snack_bar_theme.disabled_action_text_color, None);
698        assert_eq!(snack_bar_theme.content_text_style, None);
699        assert_eq!(snack_bar_theme.elevation, None);
700        assert!(snack_bar_theme.shape.is_none());
701        assert_eq!(snack_bar_theme.behavior, None);
702        assert_eq!(snack_bar_theme.width, None);
703        assert_eq!(snack_bar_theme.inset_padding, None);
704        assert_eq!(snack_bar_theme.show_close_icon, None);
705        assert_eq!(snack_bar_theme.close_icon_color, None);
706        assert_eq!(snack_bar_theme.action_overflow_threshold, None);
707        assert_eq!(snack_bar_theme.action_background_color, None);
708        assert_eq!(snack_bar_theme.disabled_action_background_color, None);
709        assert_eq!(snack_bar_theme.dismiss_direction, None);
710    }
711
712    #[test]
713    fn snack_bar_theme_data_lerps_each_field() {
714        let a = SnackBarThemeData::new()
715            .background_color(Colors::BLACK)
716            .action_text_color(Colors::BLACK)
717            .elevation(2.0)
718            .shape(rounded(4.0))
719            .behavior(SnackBarBehavior::Floating)
720            .width(100.0)
721            .inset_padding(EdgeInsets::all(10.0))
722            .action_overflow_threshold(0.2)
723            .dismiss_direction(DismissDirection::Down);
724        let b = SnackBarThemeData::new()
725            .background_color(Colors::WHITE)
726            .action_text_color(Colors::WHITE)
727            .close_icon_color(Colors::RED.primary())
728            .elevation(6.0)
729            .shape(rounded(8.0))
730            .behavior(SnackBarBehavior::Floating)
731            .width(300.0)
732            .inset_padding(EdgeInsets::all(30.0))
733            .action_overflow_threshold(0.6)
734            .dismiss_direction(DismissDirection::Up);
735
736        let halfway = SnackBarThemeData::lerp(Some(&a), Some(&b), 0.5);
737
738        assert_eq!(
739            halfway.background_color,
740            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
741        );
742        assert_eq!(
743            halfway.action_text_color.map(|color| color.color()),
744            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
745        );
746        assert_eq!(
747            halfway.close_icon_color.map(|color| color.color()),
748            Color::lerp(None, Some(Colors::RED.primary()), 0.5)
749        );
750        assert_eq!(halfway.elevation, Some(4.0));
751        assert_eq!(
752            halfway.shape.as_deref(),
753            Some(&rounded(6.0) as &dyn ShapeBorder)
754        );
755        assert_eq!(halfway.behavior, Some(SnackBarBehavior::Floating));
756        assert_eq!(halfway.width, Some(200.0));
757        assert_eq!(halfway.inset_padding, Some(EdgeInsets::all(20.0)));
758        assert_eq!(halfway.action_overflow_threshold, Some(0.4));
759        assert_eq!(halfway.dismiss_direction, Some(DismissDirection::Up));
760        assert_eq!(
761            SnackBarThemeData::lerp(Some(&a), Some(&b), 0.25).dismiss_direction,
762            Some(DismissDirection::Down)
763        );
764    }
765
766    #[test]
767    #[should_panic(expected = "Width can only be set if behaviour is SnackBarBehavior.floating")]
768    fn snack_bar_theme_data_asserts_if_width_is_provided_with_fixed_behavior() {
769        SnackBarThemeData::new()
770            .behavior(SnackBarBehavior::Fixed)
771            .width(300.0);
772    }
773
774    #[test]
775    #[should_panic(expected = "Width can only be set if behaviour is SnackBarBehavior.floating")]
776    fn snack_bar_theme_data_asserts_if_fixed_behavior_is_provided_with_width() {
777        SnackBarThemeData::new()
778            .width(300.0)
779            .behavior(SnackBarBehavior::Fixed);
780    }
781
782    #[test]
783    fn snack_bar_theme_data_accepts_width_with_floating_behavior_in_either_order() {
784        let width_first = SnackBarThemeData::new()
785            .width(300.0)
786            .behavior(SnackBarBehavior::Floating);
787        let behavior_first = SnackBarThemeData::new()
788            .behavior(SnackBarBehavior::Floating)
789            .width(300.0);
790
791        assert_eq!(width_first, behavior_first);
792    }
793
794    #[test]
795    fn snack_bar_theme_data_asserts_for_action_overflow_threshold_outside_of_0_to_1() {
796        for overflow_threshold in [-1.0, -0.0001, 1.000001, 5.0] {
797            let result = std::panic::catch_unwind(|| {
798                SnackBarThemeData::new().action_overflow_threshold(overflow_threshold)
799            });
800            assert!(result.is_err(), "{overflow_threshold} was accepted");
801        }
802        for overflow_threshold in [0.0, 0.5, 1.0] {
803            assert_eq!(
804                SnackBarThemeData::new()
805                    .action_overflow_threshold(overflow_threshold)
806                    .action_overflow_threshold,
807                Some(overflow_threshold)
808            );
809        }
810    }
811
812    #[test]
813    #[should_panic]
814    fn snack_bar_theme_data_asserts_for_a_negative_elevation() {
815        SnackBarThemeData::new().elevation(-1.0);
816    }
817
818    #[test]
819    #[should_panic(
820        expected = "disabledBackgroundColor must not be provided when background color is a WidgetStateColor"
821    )]
822    fn snack_bar_theme_data_asserts_when_action_background_color_is_a_widget_state_color_and_disabled_action_background_color_is_also_provided()
823     {
824        SnackBarThemeData::new()
825            .action_background_color(widget_state_color())
826            .disabled_action_background_color(Colors::AMBER.primary());
827    }
828
829    #[test]
830    #[should_panic(
831        expected = "disabledBackgroundColor must not be provided when background color is a WidgetStateColor"
832    )]
833    fn snack_bar_theme_data_asserts_when_disabled_action_background_color_is_provided_before_a_widget_state_color()
834     {
835        SnackBarThemeData::new()
836            .disabled_action_background_color(Colors::AMBER.primary())
837            .action_background_color(widget_state_color());
838    }
839
840    #[test]
841    fn snack_bar_theme_data_keeps_a_widget_state_color_as_the_action_background_color() {
842        let theme = SnackBarThemeData::new().action_background_color(widget_state_color());
843
844        let color = theme.action_background_color.expect("a color");
845
846        assert!(color.extension::<WidgetStateColor>().is_some());
847        assert_eq!(color.color(), Colors::PURPLE.primary());
848    }
849
850    #[test]
851    fn snack_bar_theme_data_accepts_a_plain_action_background_color_with_a_disabled_one() {
852        let theme = SnackBarThemeData::new()
853            .action_background_color(Colors::PURPLE.primary())
854            .disabled_action_background_color(Colors::AMBER.primary());
855
856        assert_eq!(
857            theme.disabled_action_background_color,
858            Some(Colors::AMBER.primary())
859        );
860    }
861
862    #[test]
863    fn of_returns_the_theme_data_snack_bar_theme_without_an_ancestor() {
864        test_widgets(|tester| {
865            let expected = SnackBarThemeData::new()
866                .elevation(3.0)
867                .background_color(Colors::RED.primary());
868            let theme_data_snack_bar = expected.clone();
869
870            let seen = probe(
871                tester,
872                move |app, child| {
873                    let data = ThemeData::builder()
874                        .snack_bar_theme(theme_data_snack_bar.clone())
875                        .build(app);
876                    Theme::new(data, child).into_widget()
877                },
878                SnackBarTheme::of,
879            );
880
881            assert_eq!(seen, expected);
882        });
883    }
884
885    #[test]
886    fn of_returns_the_closest_snack_bar_theme_over_theme_data() {
887        test_widgets(|tester| {
888            let widget_snack_bar = SnackBarThemeData::new().elevation(7.0);
889            let expected = widget_snack_bar.clone();
890
891            let seen = probe(
892                tester,
893                move |app, child| {
894                    let data = ThemeData::builder()
895                        .snack_bar_theme(SnackBarThemeData::new().elevation(3.0))
896                        .build(app);
897                    Theme::new(data, SnackBarTheme::new(widget_snack_bar.clone(), child))
898                        .into_widget()
899                },
900                SnackBarTheme::of,
901            );
902
903            assert_eq!(seen, expected);
904        });
905    }
906
907    #[test]
908    fn a_captured_snack_bar_theme_is_kept_under_another_snack_bar_theme() {
909        test_widgets(|tester| {
910            let captured = SnackBarThemeData::new().elevation(1.0);
911            let shadowing = SnackBarThemeData::new().elevation(2.0);
912
913            let seen = theme_seen_through_capture(
914                tester,
915                |probe| SnackBarTheme::new(captured.clone(), probe).into_widget(),
916                |wrapped| SnackBarTheme::new(shadowing.clone(), wrapped).into_widget(),
917                SnackBarTheme::of,
918            );
919
920            assert_eq!(seen.elevation, Some(1.0));
921        });
922    }
923
924    #[test]
925    fn update_should_notify_only_when_the_data_differs() {
926        let theme = |data: SnackBarThemeData| SnackBarTheme::new(data, SizedBox::shrink());
927        let old = theme(SnackBarThemeData::new().elevation(1.0));
928
929        assert!(!theme(SnackBarThemeData::new().elevation(1.0)).update_should_notify(&old));
930        assert!(theme(SnackBarThemeData::new().elevation(2.0)).update_should_notify(&old));
931    }
932
933    #[test]
934    fn theme_data_holds_the_snack_bar_theme() {
935        test_widgets(|tester| {
936            let app = tester.cell.borrow();
937            let theme = ThemeData::new(&app);
938            assert_eq!(theme.snack_bar_theme, SnackBarThemeData::new());
939
940            let raised = ThemeData::builder()
941                .snack_bar_theme(SnackBarThemeData::new().elevation(8.0))
942                .build(&app);
943            assert_eq!(raised.snack_bar_theme.elevation, Some(8.0));
944            assert_ne!(theme, raised);
945            assert_eq!(
946                theme
947                    .copy_with()
948                    .snack_bar_theme(raised.snack_bar_theme.clone())
949                    .build(),
950                raised
951            );
952
953            let flat = ThemeData::builder()
954                .snack_bar_theme(SnackBarThemeData::new().elevation(0.0))
955                .build(&app);
956            assert_eq!(
957                ThemeData::lerp(&flat, &raised, 0.5)
958                    .snack_bar_theme
959                    .elevation,
960                Some(4.0)
961            );
962        });
963    }
964    // Flutter's "Default SnackBarThemeData debugFillProperties".
965    #[test]
966    fn a_snack_bar_theme_data_describes_nothing_by_default() {
967        assert_eq!(
968            waft_widgets::testing::describe_properties(|properties| {
969                waft_foundation::Diagnosticable::debug_fill_properties(
970                    &SnackBarThemeData::new(),
971                    properties,
972                )
973            }),
974            Vec::<String>::new()
975        );
976    }
977
978    // snack_bar_theme_test.dart 'SnackBarThemeData implements debugFillProperties'.
979    #[test]
980    fn an_assigned_snack_bar_theme_describes_every_property() {
981        let theme = SnackBarThemeData::new()
982            .background_color(Color::new(0xffffffff))
983            .action_text_color(Color::new(0xff0000aa))
984            .disabled_action_text_color(Color::new(0xff00aa00))
985            .content_text_style(TextStyle::new().color(Color::new(0xff123456)))
986            .elevation(2.0)
987            .shape(RoundedRectangleBorder::new(
988                BorderSide::NONE,
989                BorderRadiusGeometry::circular(2.0),
990            ))
991            .behavior(SnackBarBehavior::Floating)
992            .width(400.0)
993            .inset_padding(EdgeInsets::all(10.0))
994            .show_close_icon(false)
995            .close_icon_color(Color::new(0xff0000aa))
996            .action_overflow_threshold(0.5)
997            .dismiss_direction(DismissDirection::Down);
998        let description = waft_widgets::testing::describe_properties(|properties| {
999            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
1000        });
1001        let description: Vec<String> = description
1002            .iter()
1003            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
1004            .collect();
1005        assert_eq!(
1006            description,
1007            [
1008                format!("backgroundColor: {}", Color::new(0xffffffff)),
1009                format!("actionTextColor: {}", Color::new(0xff0000aa)),
1010                format!("disabledActionTextColor: {}", Color::new(0xff00aa00)),
1011                format!(
1012                    "contentTextStyle: {}",
1013                    TextStyle::new().color(Color::new(0xff123456))
1014                ),
1015                "elevation: 2.0".to_string(),
1016                format!(
1017                    "shape: {}",
1018                    ShapeBorderRef::from(RoundedRectangleBorder::new(
1019                        BorderSide::NONE,
1020                        BorderRadiusGeometry::circular(2.0)
1021                    ))
1022                ),
1023                "behavior: SnackBarBehavior.floating".to_string(),
1024                "width: 400.0".to_string(),
1025                "insetPadding: EdgeInsets.all(10.0)".to_string(),
1026                "showCloseIcon: false".to_string(),
1027                format!("closeIconColor: {}", Color::new(0xff0000aa)),
1028                "actionOverflowThreshold: 0.5".to_string(),
1029                "dismissDirection: DismissDirection.down".to_string(),
1030            ]
1031        );
1032    }
1033}