Skip to main content

waft_material/
card_theme.rs

1//! Flutter counterpart: material_ui's `card_theme.dart`.
2
3use waft_embedder::{Clip, Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty};
5use waft_painting::{ColorProperty, EdgeInsetsGeometry, ShapeBorderRef};
6use waft_widgets::{BuildContext, InheritedWidget, IntoWidget, KeyRef, SizedBox, WidgetRef};
7
8use crate::theme::Theme;
9
10/// Defines default property values for descendant [`Card`](crate::Card) widgets.
11///
12/// Descendant widgets obtain the current [`CardThemeData`] object using
13/// [`CardTheme::of`]. Instances of [`CardThemeData`] can be
14/// customized with [`CardThemeData::copy_with`].
15///
16/// Typically a [`CardThemeData`] is specified as part of the overall `Theme`
17/// with `ThemeData::card_theme`.
18///
19/// All [`CardThemeData`] properties are `null` by default. When null, the [`Card`](crate::Card)
20/// will use the values from `ThemeData` if they exist, otherwise it will
21/// provide its own defaults.
22///
23/// Dart's `CardTheme` constructor takes either the properties or a [`data`](Self::data);
24/// here the properties are the `with_*` setters and [`with_data`](Self::with_data) the other,
25/// and each setter that breaks Dart's constructor assert (a `data` together with any property)
26/// fails in a debug build. The getters are methods, as Dart's, hence the `with_` prefix.
27///
28/// See also:
29///
30///  * `ThemeData`, which describes the overall theme information for the
31///    application.
32#[derive(Clone, Debug)]
33pub struct CardTheme {
34    pub key: Option<KeyRef>,
35    data: Option<CardThemeData>,
36    clip_behavior: Option<Clip>,
37    color: Option<Color>,
38    surface_tint_color: Option<Color>,
39    shadow_color: Option<Color>,
40    elevation: Option<f64>,
41    margin: Option<EdgeInsetsGeometry>,
42    shape: Option<ShapeBorderRef>,
43    child: WidgetRef,
44}
45
46impl CardTheme {
47    /// Creates a theme that can be used for `ThemeData::card_theme`.
48    ///
49    /// The [`elevation`](Self::elevation) must be null or non-negative.
50    pub fn new() -> CardTheme {
51        CardTheme {
52            key: None,
53            data: None,
54            clip_behavior: None,
55            color: None,
56            surface_tint_color: None,
57            shadow_color: None,
58            elevation: None,
59            margin: None,
60            shape: None,
61            child: SizedBox::new().into_widget(),
62        }
63    }
64
65    /// Dart `CardTheme(key:)`.
66    pub fn key(mut self, key: KeyRef) -> CardTheme {
67        self.key = Some(key);
68        self
69    }
70
71    /// Dart `CardTheme(child:)`; the default is an empty `SizedBox`.
72    #[cfg_attr(debug_assertions, track_caller)]
73    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> CardTheme {
74        self.child = child.into_widget();
75        self
76    }
77
78    /// Dart `CardTheme(data:)`.
79    pub fn with_data(mut self, data: CardThemeData) -> CardTheme {
80        debug_assert!(self.has_no_property());
81        self.data = Some(data);
82        self
83    }
84
85    /// Dart `CardTheme(clipBehavior:)`.
86    pub fn with_clip_behavior(mut self, clip_behavior: Clip) -> CardTheme {
87        debug_assert!(self.data.is_none());
88        self.clip_behavior = Some(clip_behavior);
89        self
90    }
91
92    /// Dart `CardTheme(color:)`.
93    pub fn with_color(mut self, color: Color) -> CardTheme {
94        debug_assert!(self.data.is_none());
95        self.color = Some(color);
96        self
97    }
98
99    /// Dart `CardTheme(surfaceTintColor:)`.
100    pub fn with_surface_tint_color(mut self, surface_tint_color: Color) -> CardTheme {
101        debug_assert!(self.data.is_none());
102        self.surface_tint_color = Some(surface_tint_color);
103        self
104    }
105
106    /// Dart `CardTheme(shadowColor:)`.
107    pub fn with_shadow_color(mut self, shadow_color: Color) -> CardTheme {
108        debug_assert!(self.data.is_none());
109        self.shadow_color = Some(shadow_color);
110        self
111    }
112
113    /// Dart `CardTheme(elevation:)`.
114    pub fn with_elevation(mut self, elevation: f64) -> CardTheme {
115        debug_assert!(self.data.is_none());
116        debug_assert!(elevation >= 0.0);
117        self.elevation = Some(elevation);
118        self
119    }
120
121    /// Dart `CardTheme(margin:)`.
122    pub fn with_margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> CardTheme {
123        let margin = margin.into();
124        debug_assert!(self.data.is_none());
125        self.margin = Some(margin);
126        self
127    }
128
129    /// Dart `CardTheme(shape:)`.
130    pub fn with_shape(mut self, shape: impl Into<ShapeBorderRef>) -> CardTheme {
131        debug_assert!(self.data.is_none());
132        self.shape = Some(shape.into());
133        self
134    }
135
136    /// Overrides the default value for `Card::clip_behavior`.
137    ///
138    /// This property is obsolete and will be deprecated in a future release:
139    /// please use the [`CardThemeData::clip_behavior`] property in [`data`](Self::data) instead.
140    pub fn clip_behavior(&self) -> Option<Clip> {
141        match &self.data {
142            Some(data) => data.clip_behavior,
143            None => self.clip_behavior,
144        }
145    }
146
147    /// Overrides the default value for `Card::color`.
148    ///
149    /// This property is obsolete and will be deprecated in a future release:
150    /// please use the [`CardThemeData::color`] property in [`data`](Self::data) instead.
151    pub fn color(&self) -> Option<Color> {
152        match &self.data {
153            Some(data) => data.color,
154            None => self.color,
155        }
156    }
157
158    /// Overrides the default value for `Card::surface_tint_color`.
159    ///
160    /// This property is obsolete and will be deprecated in a future release:
161    /// please use the [`CardThemeData::surface_tint_color`] property in [`data`](Self::data)
162    /// instead.
163    pub fn surface_tint_color(&self) -> Option<Color> {
164        match &self.data {
165            Some(data) => data.surface_tint_color,
166            None => self.surface_tint_color,
167        }
168    }
169
170    /// Overrides the default value for `Card::shadow_color`.
171    ///
172    /// This property is obsolete and will be deprecated in a future release:
173    /// please use the [`CardThemeData::shadow_color`] property in [`data`](Self::data) instead.
174    pub fn shadow_color(&self) -> Option<Color> {
175        match &self.data {
176            Some(data) => data.shadow_color,
177            None => self.shadow_color,
178        }
179    }
180
181    /// Overrides the default value for `Card::elevation`.
182    ///
183    /// This property is obsolete and will be deprecated in a future release:
184    /// please use the [`CardThemeData::elevation`] property in [`data`](Self::data) instead.
185    pub fn elevation(&self) -> Option<f64> {
186        match &self.data {
187            Some(data) => data.elevation,
188            None => self.elevation,
189        }
190    }
191
192    /// Overrides the default value for `Card::margin`.
193    ///
194    /// This property is obsolete and will be deprecated in a future release:
195    /// please use the [`CardThemeData::margin`] property in [`data`](Self::data) instead.
196    pub fn margin(&self) -> Option<EdgeInsetsGeometry> {
197        match &self.data {
198            Some(data) => data.margin,
199            None => self.margin,
200        }
201    }
202
203    /// Overrides the default value for `Card::shape`.
204    ///
205    /// This property is obsolete and will be deprecated in a future release:
206    /// please use the [`CardThemeData::shape`] property in [`data`](Self::data) instead.
207    pub fn shape(&self) -> Option<&ShapeBorderRef> {
208        match &self.data {
209            Some(data) => data.shape.as_ref(),
210            None => self.shape.as_ref(),
211        }
212    }
213
214    /// The properties used for all descendant [`Card`](crate::Card) widgets.
215    pub fn data(&self) -> CardThemeData {
216        self.data.clone().unwrap_or_else(|| CardThemeData {
217            clip_behavior: self.clip_behavior,
218            color: self.color,
219            shadow_color: self.shadow_color,
220            surface_tint_color: self.surface_tint_color,
221            elevation: self.elevation,
222            margin: self.margin,
223            shape: self.shape.clone(),
224        })
225    }
226
227    /// Creates a copy of this object with the given fields replaced with the
228    /// new values.
229    ///
230    /// This method is obsolete and will be deprecated in a future release:
231    /// please use the [`CardThemeData::copy_with`] instead.
232    ///
233    /// Dart's named arguments are the fluent setters on the copy
234    /// (`theme.copy_with().with_elevation(2.0)`). As in Dart, the copy carries neither the key
235    /// nor the child, and holds the properties, never a [`data`](Self::data).
236    pub fn copy_with(&self) -> CardTheme {
237        CardTheme {
238            key: None,
239            data: None,
240            clip_behavior: self.clip_behavior(),
241            color: self.color(),
242            surface_tint_color: self.surface_tint_color(),
243            shadow_color: self.shadow_color(),
244            elevation: self.elevation(),
245            margin: self.margin(),
246            shape: self.shape().cloned(),
247            child: SizedBox::new().into_widget(),
248        }
249    }
250
251    /// Returns the configuration [`data`](Self::data) from the closest [`CardTheme`] ancestor.
252    ///
253    /// If there is no ancestor, it returns `ThemeData::card_theme`.
254    ///
255    /// Typical usage is as follows:
256    ///
257    /// ```text
258    /// let theme = CardTheme::of(app, context);
259    /// ```
260    pub fn of(app: &mut App, context: BuildContext) -> CardThemeData {
261        match context.depend_on_inherited_widget_of_exact_type::<CardTheme>(app) {
262            Some(card_theme) => card_theme.data(),
263            None => Theme::of(app, context).card_theme.clone(),
264        }
265    }
266
267    /// Linearly interpolate between two Card themes.
268    ///
269    /// {@macro dart.ui.shadow.lerp}
270    ///
271    /// This method is obsolete and will be deprecated in a future release:
272    /// please use the [`CardThemeData::lerp`] instead.
273    pub fn lerp(a: Option<&CardTheme>, b: Option<&CardTheme>, t: f64) -> CardTheme {
274        if let (Some(a), Some(b)) = (a, b)
275            && std::ptr::eq(a, b)
276        {
277            return a.clone();
278        }
279        CardTheme {
280            key: None,
281            data: None,
282            clip_behavior: if t < 0.5 {
283                a.and_then(|a| a.clip_behavior())
284            } else {
285                b.and_then(|b| b.clip_behavior())
286            },
287            color: Color::lerp(a.and_then(|a| a.color()), b.and_then(|b| b.color()), t),
288            shadow_color: Color::lerp(
289                a.and_then(|a| a.shadow_color()),
290                b.and_then(|b| b.shadow_color()),
291                t,
292            ),
293            surface_tint_color: Color::lerp(
294                a.and_then(|a| a.surface_tint_color()),
295                b.and_then(|b| b.surface_tint_color()),
296                t,
297            ),
298            elevation: lerp_double(
299                a.and_then(|a| a.elevation()),
300                b.and_then(|b| b.elevation()),
301                t,
302            ),
303            margin: EdgeInsetsGeometry::lerp(
304                a.and_then(|a| a.margin()),
305                b.and_then(|b| b.margin()),
306                t,
307            ),
308            shape: ShapeBorderRef::lerp(a.and_then(|a| a.shape()), b.and_then(|b| b.shape()), t),
309            child: SizedBox::new().into_widget(),
310        }
311    }
312
313    /// Dart's constructor assert: a `data` takes the place of every property.
314    fn has_no_property(&self) -> bool {
315        self.clip_behavior.is_none()
316            && self.color.is_none()
317            && self.surface_tint_color.is_none()
318            && self.shadow_color.is_none()
319            && self.elevation.is_none()
320            && self.margin.is_none()
321            && self.shape.is_none()
322    }
323}
324
325impl Default for CardTheme {
326    fn default() -> CardTheme {
327        CardTheme::new()
328    }
329}
330
331impl InheritedWidget for CardTheme {
332    fn key(&self) -> Option<&KeyRef> {
333        self.key.as_ref()
334    }
335
336    fn debug_fill_properties(
337        &self,
338        _app: &App,
339        properties: &mut waft_foundation::DiagnosticPropertiesBuilder,
340    ) {
341        // Dart repeats `CardThemeData.debugFillProperties` with `CardTheme`'s getters, which
342        // answer this theme's `data()`.
343        waft_foundation::Diagnosticable::debug_fill_properties(&self.data(), properties);
344    }
345
346    fn child(&self) -> &WidgetRef {
347        &self.child
348    }
349
350    fn update_should_notify(&self, old_widget: &CardTheme) -> bool {
351        self.data() != old_widget.data()
352    }
353}
354
355/// Defines default property values for descendant [`Card`](crate::Card) widgets.
356///
357/// Descendant widgets obtain the current [`CardThemeData`] object using
358/// `CardTheme::of(app, context)`. Instances of [`CardThemeData`] can be
359/// customized with [`CardThemeData::copy_with`].
360///
361/// Typically a [`CardThemeData`] is specified as part of the overall `Theme`
362/// with `ThemeData::card_theme`.
363///
364/// All [`CardThemeData`] properties are `null` by default. When null, the [`Card`](crate::Card)
365/// will use the values from `ThemeData` if they exist, otherwise it will
366/// provide its own defaults. See the individual [`Card`](crate::Card) properties for details.
367///
368/// See also:
369///
370///  * `ThemeData`, which describes the overall theme information for the
371///    application.
372#[derive(Clone, Debug, Default, PartialEq)]
373pub struct CardThemeData {
374    /// Overrides the default value for `Card::clip_behavior`.
375    pub clip_behavior: Option<Clip>,
376
377    /// Overrides the default value for `Card::color`.
378    pub color: Option<Color>,
379
380    /// Overrides the default value for `Card::shadow_color`.
381    pub shadow_color: Option<Color>,
382
383    /// Overrides the default value for `Card::surface_tint_color`.
384    pub surface_tint_color: Option<Color>,
385
386    /// Overrides the default value for `Card::elevation`.
387    pub elevation: Option<f64>,
388
389    /// Overrides the default value for `Card::margin`.
390    pub margin: Option<EdgeInsetsGeometry>,
391
392    /// Overrides the default value for `Card::shape`.
393    pub shape: Option<ShapeBorderRef>,
394}
395
396crate::theme_data_getters::theme_data_getters! {
397    /// Dart's getters of `CardThemeData`: the theme data answers with its fields, and a defaults
398    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
399    /// are read.
400    pub trait CardThemeDataGetters for CardThemeData, fields: card_theme_data {
401        clip_behavior: Option<Clip>,
402        color: Option<Color>,
403        shadow_color: Option<Color>,
404        surface_tint_color: Option<Color>,
405        elevation: Option<f64>,
406        margin: Option<EdgeInsetsGeometry>,
407        shape: Option<ShapeBorderRef>,
408    }
409}
410
411impl CardThemeData {
412    /// Creates a theme that can be used for `ThemeData::card_theme`; Dart's optional named
413    /// arguments are the fluent setters.
414    ///
415    /// The [`elevation`](Self::elevation) must be null or non-negative.
416    pub fn new() -> CardThemeData {
417        CardThemeData::default()
418    }
419
420    /// Dart `CardThemeData(clipBehavior:)`.
421    pub fn clip_behavior(mut self, clip_behavior: Clip) -> CardThemeData {
422        self.clip_behavior = Some(clip_behavior);
423        self
424    }
425
426    /// Dart `CardThemeData(color:)`.
427    pub fn color(mut self, color: Color) -> CardThemeData {
428        self.color = Some(color);
429        self
430    }
431
432    /// Dart `CardThemeData(shadowColor:)`.
433    pub fn shadow_color(mut self, shadow_color: Color) -> CardThemeData {
434        self.shadow_color = Some(shadow_color);
435        self
436    }
437
438    /// Dart `CardThemeData(surfaceTintColor:)`.
439    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> CardThemeData {
440        self.surface_tint_color = Some(surface_tint_color);
441        self
442    }
443
444    /// Dart `CardThemeData(elevation:)`.
445    pub fn elevation(mut self, elevation: f64) -> CardThemeData {
446        debug_assert!(elevation >= 0.0);
447        self.elevation = Some(elevation);
448        self
449    }
450
451    /// Dart `CardThemeData(margin:)`.
452    pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> CardThemeData {
453        let margin = margin.into();
454        self.margin = Some(margin);
455        self
456    }
457
458    /// Dart `CardThemeData(shape:)`.
459    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> CardThemeData {
460        self.shape = Some(shape.into());
461        self
462    }
463
464    /// Creates a copy of this object with the given fields replaced with the
465    /// new values.
466    ///
467    /// Dart's named arguments are the fluent setters on the copy
468    /// (`data.copy_with().elevation(2.0)`).
469    pub fn copy_with(&self) -> CardThemeData {
470        self.clone()
471    }
472
473    /// Linearly interpolate between two Card themes.
474    ///
475    /// {@macro dart.ui.shadow.lerp}
476    pub fn lerp(a: Option<&CardThemeData>, b: Option<&CardThemeData>, t: f64) -> CardThemeData {
477        if let (Some(a), Some(b)) = (a, b)
478            && std::ptr::eq(a, b)
479        {
480            return a.clone();
481        }
482        CardThemeData {
483            clip_behavior: if t < 0.5 {
484                a.and_then(|a| a.clip_behavior)
485            } else {
486                b.and_then(|b| b.clip_behavior)
487            },
488            color: Color::lerp(a.and_then(|a| a.color), b.and_then(|b| b.color), t),
489            shadow_color: Color::lerp(
490                a.and_then(|a| a.shadow_color),
491                b.and_then(|b| b.shadow_color),
492                t,
493            ),
494            surface_tint_color: Color::lerp(
495                a.and_then(|a| a.surface_tint_color),
496                b.and_then(|b| b.surface_tint_color),
497                t,
498            ),
499            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
500            margin: EdgeInsetsGeometry::lerp(a.and_then(|a| a.margin), b.and_then(|b| b.margin), t),
501            shape: ShapeBorderRef::lerp(
502                a.and_then(|a| a.shape.as_ref()),
503                b.and_then(|b| b.shape.as_ref()),
504                t,
505            ),
506        }
507    }
508}
509
510impl waft_foundation::Diagnosticable for CardThemeData {
511    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
512        properties.add(
513            DiagnosticsProperty::<waft_foundation::DartEnum<Clip>>::new(
514                "clipBehavior",
515                self.clip_behavior.map(waft_foundation::DartEnum),
516            )
517            .default_value(None),
518        );
519        properties.add(ColorProperty::new("color", self.color).default_value(None));
520        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
521        properties.add(
522            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
523        );
524        properties
525            .add(DiagnosticsProperty::<f64>::new("elevation", self.elevation).default_value(None));
526        properties.add(
527            DiagnosticsProperty::<EdgeInsetsGeometry>::new("margin", self.margin)
528                .default_value(None),
529        );
530        properties.add(
531            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
532                .default_value(None),
533        );
534    }
535}
536
537impl std::fmt::Display for CardThemeData {
538    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    //! Ported from `test/card_theme_test.dart`; the `debugFillProperties` cases wait for
546    //! diagnostics, `hashCode` for `Hash`, and the goldens are not ported.
547
548    use waft_painting::{BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
549
550    use waft_widgets::testing::test_widgets;
551
552    use super::*;
553    use crate::card::Card;
554    use crate::card::tests::{card_material, card_padding, rounded};
555    use crate::colors::Colors;
556    use crate::drawer_theme::tests::probe;
557    use crate::drawer_theme::tests::theme_seen_through_capture;
558    use crate::scaffold::Scaffold;
559    use crate::theme_data::ThemeData;
560    use crate::tooltip::tests::{m2, m3, pump_app};
561
562    /// Dart's `_cardTheme()`.
563    fn card_theme() -> CardThemeData {
564        CardThemeData::new()
565            .clip_behavior(Clip::AntiAlias)
566            .color(Colors::GREEN.primary())
567            .shadow_color(Colors::RED.primary())
568            .surface_tint_color(Colors::PURPLE.primary())
569            .elevation(6.0)
570            .margin(EdgeInsetsGeometry::all(7.0))
571            .shape(RoundedRectangleBorder::new(
572                BorderSide::NONE,
573                BorderRadiusGeometry::circular(5.0),
574            ))
575    }
576
577    fn scaffold_with_card() -> impl FnOnce(&mut App) -> WidgetRef {
578        |_app| Scaffold::new().body(Card::new()).into_widget()
579    }
580
581    #[test]
582    fn card_theme_data_copy_with_equality_basics() {
583        assert_eq!(CardThemeData::new(), CardThemeData::new().copy_with());
584
585        let theme = card_theme();
586        assert_eq!(theme.copy_with(), theme);
587        assert_eq!(theme.copy_with().elevation(9.0).elevation, Some(9.0));
588        assert_eq!(theme.copy_with().elevation(9.0).color, theme.color);
589        assert_ne!(theme.copy_with().elevation(5.0), theme);
590        assert_ne!(
591            theme.copy_with().shape(RoundedRectangleBorder::default()),
592            theme
593        );
594    }
595
596    #[test]
597    fn card_theme_data_lerp_special_cases() {
598        assert_eq!(CardThemeData::lerp(None, None, 0.0), CardThemeData::new());
599        let theme = CardThemeData::new();
600        assert_eq!(CardThemeData::lerp(Some(&theme), Some(&theme), 0.5), theme);
601    }
602
603    #[test]
604    fn card_theme_data_lerps_each_field() {
605        let a = CardThemeData::new()
606            .clip_behavior(Clip::None)
607            .color(Colors::BLACK)
608            .elevation(2.0)
609            .margin(EdgeInsetsGeometry::all(10.0));
610        let b = CardThemeData::new()
611            .clip_behavior(Clip::HardEdge)
612            .color(Colors::WHITE)
613            .shadow_color(Colors::RED.primary())
614            .elevation(6.0)
615            .margin(EdgeInsetsGeometry::all(30.0));
616
617        let before = CardThemeData::lerp(Some(&a), Some(&b), 0.25);
618        let after = CardThemeData::lerp(Some(&a), Some(&b), 0.75);
619
620        assert_eq!(before.clip_behavior, Some(Clip::None));
621        assert_eq!(after.clip_behavior, Some(Clip::HardEdge));
622        assert_eq!(
623            before.color,
624            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.25)
625        );
626        assert_eq!(
627            before.shadow_color,
628            Color::lerp(None, Some(Colors::RED.primary()), 0.25)
629        );
630        assert_eq!(before.elevation, Some(3.0));
631        assert_eq!(before.margin, Some(EdgeInsetsGeometry::all(15.0)));
632    }
633
634    #[test]
635    fn card_theme_data_defaults() {
636        let card_theme_data = CardThemeData::new();
637
638        assert_eq!(card_theme_data.clip_behavior, None);
639        assert_eq!(card_theme_data.color, None);
640        assert_eq!(card_theme_data.elevation, None);
641        assert_eq!(card_theme_data.margin, None);
642        assert_eq!(card_theme_data.shadow_color, None);
643        assert!(card_theme_data.shape.is_none());
644        assert_eq!(card_theme_data.surface_tint_color, None);
645
646        let card_theme = CardTheme::new().with_data(CardThemeData::new());
647        assert_eq!(card_theme.clip_behavior(), None);
648        assert_eq!(card_theme.color(), None);
649        assert_eq!(card_theme.elevation(), None);
650        assert_eq!(card_theme.margin(), None);
651        assert_eq!(card_theme.shadow_color(), None);
652        assert!(card_theme.shape().is_none());
653        assert_eq!(card_theme.surface_tint_color(), None);
654    }
655
656    #[test]
657    fn card_theme_reads_its_properties_or_its_data() {
658        let by_properties = CardTheme::new()
659            .with_clip_behavior(Clip::AntiAlias)
660            .with_color(Colors::GREEN.primary())
661            .with_shadow_color(Colors::RED.primary())
662            .with_surface_tint_color(Colors::PURPLE.primary())
663            .with_elevation(6.0)
664            .with_margin(EdgeInsetsGeometry::all(7.0))
665            .with_shape(RoundedRectangleBorder::new(
666                BorderSide::NONE,
667                BorderRadiusGeometry::circular(5.0),
668            ));
669        let by_data = CardTheme::new().with_data(card_theme());
670
671        assert_eq!(by_properties.data(), card_theme());
672        assert_eq!(by_data.data(), card_theme());
673        assert_eq!(by_properties.elevation(), by_data.elevation());
674        assert_eq!(by_properties.shape(), by_data.shape());
675        assert_eq!(by_data.copy_with().data(), card_theme());
676    }
677
678    #[test]
679    fn card_theme_lerps_through_its_getters() {
680        let a = CardTheme::new().with_elevation(2.0);
681        let b = CardTheme::new().with_data(CardThemeData::new().elevation(6.0));
682
683        assert_eq!(
684            CardTheme::lerp(Some(&a), Some(&b), 0.5).elevation(),
685            Some(4.0)
686        );
687        assert_eq!(
688            CardTheme::lerp(None, None, 0.5).data(),
689            CardThemeData::new()
690        );
691        assert_eq!(
692            CardTheme::lerp(Some(&a), Some(&a), 0.5).elevation(),
693            Some(2.0)
694        );
695    }
696
697    #[test]
698    fn material3_passing_no_card_theme_returns_defaults() {
699        test_widgets(|tester| {
700            pump_app(tester, m3, scaffold_with_card());
701            let colors = m3(&tester.cell.borrow()).color_scheme;
702
703            let padding = card_padding(tester);
704            let material = card_material(tester);
705
706            assert_eq!(material.clip_behavior, Clip::None);
707            assert_eq!(material.color, Some(colors.surface_container_low()));
708            assert_eq!(material.shadow_color, Some(colors.shadow()));
709            assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
710            assert_eq!(material.elevation, 1.0);
711            assert_eq!(padding, EdgeInsetsGeometry::all(4.0));
712            assert_eq!(material.shape, rounded(12.0));
713        });
714    }
715
716    #[test]
717    fn card_uses_values_from_card_theme() {
718        test_widgets(|tester| {
719            let card_theme = card_theme();
720            pump_app(
721                tester,
722                |app| {
723                    ThemeData::builder()
724                        .card_theme(card_theme.clone())
725                        .build(app)
726                },
727                scaffold_with_card(),
728            );
729
730            let padding = card_padding(tester);
731            let material = card_material(tester);
732
733            assert_eq!(Some(material.clip_behavior), card_theme.clip_behavior);
734            assert_eq!(material.color, card_theme.color);
735            assert_eq!(material.shadow_color, card_theme.shadow_color);
736            assert_eq!(material.surface_tint_color, card_theme.surface_tint_color);
737            assert_eq!(Some(material.elevation), card_theme.elevation);
738            assert_eq!(Some(padding), card_theme.margin);
739            assert_eq!(material.shape, card_theme.shape);
740        });
741    }
742
743    #[test]
744    fn card_widget_properties_take_priority_over_theme() {
745        test_widgets(|tester| {
746            pump_app(
747                tester,
748                |app| {
749                    ThemeData::builder()
750                        .card_color(Colors::PINK.primary())
751                        .card_theme(card_theme())
752                        .build(app)
753                },
754                |_app| {
755                    Scaffold::new()
756                        .body(
757                            Card::new()
758                                .clip_behavior(Clip::HardEdge)
759                                .color(Colors::ORANGE.primary())
760                                .shadow_color(Colors::PINK.primary())
761                                .elevation(7.0)
762                                .margin(EdgeInsetsGeometry::all(3.0))
763                                .shape(RoundedRectangleBorder::new(
764                                    BorderSide::NONE,
765                                    BorderRadiusGeometry::circular(9.0),
766                                )),
767                        )
768                        .into_widget()
769                },
770            );
771
772            let padding = card_padding(tester);
773            let material = card_material(tester);
774
775            assert_eq!(material.clip_behavior, Clip::HardEdge);
776            assert_eq!(material.color, Some(Colors::ORANGE.primary()));
777            assert_eq!(material.shadow_color, Some(Colors::PINK.primary()));
778            assert_eq!(material.elevation, 7.0);
779            assert_eq!(padding, EdgeInsetsGeometry::all(3.0));
780            assert_eq!(material.shape, rounded(9.0));
781        });
782    }
783
784    #[test]
785    fn card_theme_properties_take_priority_over_theme_data_properties() {
786        test_widgets(|tester| {
787            let card_theme = card_theme();
788            pump_app(
789                tester,
790                |app| {
791                    ThemeData::builder()
792                        .card_color(Colors::PINK.primary())
793                        .card_theme(card_theme.clone())
794                        .build(app)
795                },
796                scaffold_with_card(),
797            );
798
799            assert_eq!(card_material(tester).color, card_theme.color);
800        });
801    }
802
803    #[test]
804    fn material3_theme_data_properties_are_used_when_no_card_theme_is_set() {
805        test_widgets(|tester| {
806            pump_app(tester, m3, scaffold_with_card());
807            let colors = m3(&tester.cell.borrow()).color_scheme;
808
809            assert_eq!(
810                card_material(tester).color,
811                Some(colors.surface_container_low())
812            );
813        });
814    }
815
816    #[test]
817    fn card_properties_are_taken_over_the_theme_values() {
818        test_widgets(|tester| {
819            pump_app(
820                tester,
821                |app| {
822                    ThemeData::builder()
823                        .card_theme(
824                            CardThemeData::new()
825                                .clip_behavior(Clip::AntiAlias)
826                                .color(Colors::RED.primary())
827                                .shadow_color(Colors::ORANGE.primary())
828                                .elevation(10.0)
829                                .margin(EdgeInsetsGeometry::all(12.0))
830                                .shape(RoundedRectangleBorder::new(
831                                    BorderSide::NONE,
832                                    BorderRadiusGeometry::circular(15.0),
833                                )),
834                        )
835                        .build(app)
836                },
837                |_app| {
838                    Scaffold::new()
839                        .body(
840                            Card::new()
841                                .clip_behavior(Clip::HardEdge)
842                                .color(Colors::YELLOW.primary())
843                                .shadow_color(Colors::GREEN.primary())
844                                .elevation(20.0)
845                                .margin(EdgeInsetsGeometry::all(18.0))
846                                .shape(RoundedRectangleBorder::new(
847                                    BorderSide::NONE,
848                                    BorderRadiusGeometry::circular(25.0),
849                                ))
850                                .child(waft_widgets::SizedBox::new().width(200.0).height(200.0)),
851                        )
852                        .into_widget()
853                },
854            );
855
856            let card_margin = card_padding(tester);
857            let material = card_material(tester);
858
859            assert_eq!(material.clip_behavior, Clip::HardEdge);
860            assert_eq!(material.color, Some(Colors::YELLOW.primary()));
861            assert_eq!(material.shadow_color, Some(Colors::GREEN.primary()));
862            assert_eq!(material.elevation, 20.0);
863            assert_eq!(material.shape, rounded(25.0));
864            assert_eq!(card_margin, EdgeInsetsGeometry::all(18.0));
865        });
866    }
867
868    #[test]
869    fn local_card_theme_can_override_global_card_theme() {
870        test_widgets(|tester| {
871            pump_app(
872                tester,
873                |app| {
874                    ThemeData::builder()
875                        .card_theme(
876                            CardThemeData::new()
877                                .clip_behavior(Clip::AntiAlias)
878                                .color(Colors::RED.primary())
879                                .shadow_color(Colors::ORANGE.primary())
880                                .elevation(10.0)
881                                .margin(EdgeInsetsGeometry::all(12.0))
882                                .shape(RoundedRectangleBorder::new(
883                                    BorderSide::NONE,
884                                    BorderRadiusGeometry::circular(15.0),
885                                )),
886                        )
887                        .build(app)
888                },
889                |_app| {
890                    Scaffold::new()
891                        .body(
892                            CardTheme::new()
893                                .with_data(
894                                    CardThemeData::new()
895                                        .clip_behavior(Clip::HardEdge)
896                                        .color(Colors::YELLOW.primary())
897                                        .shadow_color(Colors::GREEN.primary())
898                                        .elevation(20.0)
899                                        .margin(EdgeInsetsGeometry::all(18.0))
900                                        .shape(RoundedRectangleBorder::new(
901                                            BorderSide::NONE,
902                                            BorderRadiusGeometry::circular(25.0),
903                                        )),
904                                )
905                                .child(Card::new().child(
906                                    waft_widgets::SizedBox::new().width(200.0).height(200.0),
907                                )),
908                        )
909                        .into_widget()
910                },
911            );
912
913            let card_margin = card_padding(tester);
914            let material = card_material(tester);
915
916            assert_eq!(material.clip_behavior, Clip::HardEdge);
917            assert_eq!(material.color, Some(Colors::YELLOW.primary()));
918            assert_eq!(material.shadow_color, Some(Colors::GREEN.primary()));
919            assert_eq!(material.elevation, 20.0);
920            assert_eq!(material.shape, rounded(25.0));
921            assert_eq!(card_margin, EdgeInsetsGeometry::all(18.0));
922        });
923    }
924
925    #[test]
926    fn material2_theme_data_properties_are_used_when_no_card_theme_is_set() {
927        test_widgets(|tester| {
928            pump_app(tester, m2, scaffold_with_card());
929            let card_color = m2(&tester.cell.borrow()).card_color;
930
931            assert_eq!(card_material(tester).color, Some(card_color));
932        });
933    }
934
935    #[test]
936    fn material2_passing_no_card_theme_returns_defaults() {
937        test_widgets(|tester| {
938            pump_app(tester, m2, scaffold_with_card());
939
940            let padding = card_padding(tester);
941            let material = card_material(tester);
942
943            assert_eq!(material.clip_behavior, Clip::None);
944            assert_eq!(material.color, Some(Colors::WHITE));
945            assert_eq!(material.shadow_color, Some(Colors::BLACK));
946            assert_eq!(material.surface_tint_color, None);
947            assert_eq!(material.elevation, 1.0);
948            assert_eq!(padding, EdgeInsetsGeometry::all(4.0));
949            assert_eq!(material.shape, rounded(4.0));
950        });
951    }
952
953    #[test]
954    fn of_returns_the_theme_data_card_theme_without_an_ancestor() {
955        test_widgets(|tester| {
956            let expected = card_theme();
957            let theme_data_card = expected.clone();
958
959            let seen = probe(
960                tester,
961                move |app, child| {
962                    let data = ThemeData::builder()
963                        .card_theme(theme_data_card.clone())
964                        .build(app);
965                    Theme::new(data, child).into_widget()
966                },
967                CardTheme::of,
968            );
969
970            assert_eq!(seen, expected);
971        });
972    }
973
974    #[test]
975    fn of_returns_the_closest_card_theme_over_theme_data() {
976        test_widgets(|tester| {
977            let widget_card = CardThemeData::new().elevation(7.0);
978            let expected = widget_card.clone();
979
980            let seen = probe(
981                tester,
982                move |app, child| {
983                    let data = ThemeData::builder()
984                        .card_theme(CardThemeData::new().elevation(3.0))
985                        .build(app);
986                    Theme::new(
987                        data,
988                        CardTheme::new().with_data(widget_card.clone()).child(child),
989                    )
990                    .into_widget()
991                },
992                CardTheme::of,
993            );
994
995            assert_eq!(seen, expected);
996        });
997    }
998
999    #[test]
1000    fn a_card_theme_without_properties_shadows_theme_data_with_an_empty_theme() {
1001        test_widgets(|tester| {
1002            let seen = probe(
1003                tester,
1004                move |app, child| {
1005                    let data = ThemeData::builder()
1006                        .card_theme(CardThemeData::new().elevation(3.0))
1007                        .build(app);
1008                    Theme::new(data, CardTheme::new().child(child)).into_widget()
1009                },
1010                CardTheme::of,
1011            );
1012
1013            assert_eq!(seen, CardThemeData::new());
1014        });
1015    }
1016
1017    #[test]
1018    fn update_should_notify_only_when_the_data_differs() {
1019        let theme = |elevation: f64| CardTheme::new().with_elevation(elevation);
1020        let old = theme(1.0);
1021
1022        assert!(!theme(1.0).update_should_notify(&old));
1023        assert!(theme(2.0).update_should_notify(&old));
1024        assert!(
1025            !CardTheme::new()
1026                .with_data(CardThemeData::new().elevation(1.0))
1027                .update_should_notify(&old)
1028        );
1029    }
1030
1031    #[test]
1032    fn theme_data_holds_the_card_theme() {
1033        test_widgets(|tester| {
1034            let app = tester.cell.borrow();
1035            let theme = ThemeData::new(&app);
1036            assert_eq!(theme.card_theme, CardThemeData::new());
1037
1038            let raised = ThemeData::builder()
1039                .card_theme(CardThemeData::new().elevation(8.0))
1040                .build(&app);
1041            assert_eq!(raised.card_theme.elevation, Some(8.0));
1042            assert_ne!(theme, raised);
1043            assert_eq!(
1044                theme
1045                    .copy_with()
1046                    .card_theme(raised.card_theme.clone())
1047                    .build(),
1048                raised
1049            );
1050
1051            let flat = ThemeData::builder()
1052                .card_theme(CardThemeData::new().elevation(0.0))
1053                .build(&app);
1054            assert_eq!(
1055                ThemeData::lerp(&flat, &raised, 0.5).card_theme.elevation,
1056                Some(4.0)
1057            );
1058        });
1059    }
1060
1061    #[test]
1062    fn a_captured_card_theme_is_not_a_theme_to_wrap() {
1063        // CardTheme extends InheritedWidget, not InheritedTheme: a `Theme` that captures its
1064        // ancestors does not carry it, so the probe reads what is nearest to it.
1065        test_widgets(|tester| {
1066            let seen = theme_seen_through_capture(
1067                tester,
1068                |probe| {
1069                    CardTheme::new()
1070                        .with_data(CardThemeData::new().elevation(1.0))
1071                        .child(probe)
1072                        .into_widget()
1073                },
1074                |wrapped| {
1075                    CardTheme::new()
1076                        .with_data(CardThemeData::new().elevation(2.0))
1077                        .child(wrapped)
1078                        .into_widget()
1079                },
1080                CardTheme::of,
1081            );
1082
1083            assert_eq!(seen.elevation, Some(2.0));
1084        });
1085    }
1086}