Skip to main content

waft_material/
carousel_theme.rs

1//! Flutter counterpart: material_ui's `carousel_theme.dart`.
2
3use waft_embedder::{Clip, Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, EnumProperty};
5use waft_painting::{ColorProperty, EdgeInsets, EdgeInsetsGeometry, OutlinedBorderRef};
6use waft_widgets::{
7    BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
8    WidgetStateProperty, WidgetStatePropertyRef,
9};
10
11use crate::theme::Theme;
12
13/// Defines default property values for descendant [`CarouselView`](crate::CarouselView)
14/// widgets.
15///
16/// Descendant widgets obtain the current [`CarouselViewThemeData`] object using
17/// [`CarouselViewTheme::of`]. Instances of [`CarouselViewThemeData`] can be customized with
18/// [`CarouselViewThemeData::copy_with`].
19///
20/// Typically a [`CarouselViewThemeData`] is specified as part of the overall `Theme` with
21/// `ThemeData::carousel_view_theme`.
22///
23/// All [`CarouselViewThemeData`] properties are `None` by default. When null, the
24/// [`CarouselView`](crate::CarouselView) will use the values from the default values
25/// provided by the carousel.
26///
27/// See also:
28///
29///  * [`CarouselViewTheme`], an [`InheritedWidget`] that propagates the theme down its
30///    subtree.
31///  * `ThemeData::carousel_view_theme`, which describes the overall theme information for
32///    the application.
33#[derive(Clone, Debug, Default)]
34pub struct CarouselViewThemeData {
35    /// The amount of space surrounding each carousel item.
36    ///
37    /// If null, [`CarouselView`](crate::CarouselView) defaults to `EdgeInsets::all(4.0)`.
38    pub padding: Option<EdgeInsets>,
39
40    /// The background color of each carousel item.
41    ///
42    /// If null, [`CarouselView`](crate::CarouselView) defaults to
43    /// `ColorScheme::surface`.
44    pub background_color: Option<Color>,
45
46    /// The z-coordinate of each carousel item's `Material`.
47    ///
48    /// If null, [`CarouselView`](crate::CarouselView) defaults to 0.0.
49    pub elevation: Option<f64>,
50
51    /// The shape of each carousel item's `Material`.
52    ///
53    /// Defines each item's `Material::shape`.
54    ///
55    /// If null, [`CarouselView`](crate::CarouselView) defaults to a
56    /// `RoundedRectangleBorder` with a circular border radius of 28.0.
57    pub shape: Option<OutlinedBorderRef>,
58
59    /// The clip behavior of each carousel item.
60    ///
61    /// If null, [`CarouselView`](crate::CarouselView) defaults to [`Clip::AntiAlias`].
62    pub item_clip_behavior: Option<Clip>,
63
64    /// The highlight color of each carousel item in the different `WidgetState`s.
65    ///
66    /// If null, [`CarouselView`](crate::CarouselView) defaults to
67    /// `ColorScheme::onSurface` with the Material 3 opacities for hover, focus and press.
68    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
69}
70
71impl CarouselViewThemeData {
72    /// Creates a theme that can be used for `ThemeData::carousel_view_theme`. Dart's
73    /// optional named arguments are the fluent setters.
74    pub fn new() -> CarouselViewThemeData {
75        CarouselViewThemeData::default()
76    }
77
78    /// Dart `CarouselViewThemeData(padding:)`.
79    pub fn padding(mut self, padding: EdgeInsets) -> CarouselViewThemeData {
80        self.padding = Some(padding);
81        self
82    }
83
84    /// Dart `CarouselViewThemeData(backgroundColor:)`.
85    pub fn background_color(mut self, background_color: Color) -> CarouselViewThemeData {
86        self.background_color = Some(background_color);
87        self
88    }
89
90    /// Dart `CarouselViewThemeData(elevation:)`.
91    pub fn elevation(mut self, elevation: f64) -> CarouselViewThemeData {
92        self.elevation = Some(elevation);
93        self
94    }
95
96    /// Dart `CarouselViewThemeData(shape:)`.
97    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> CarouselViewThemeData {
98        self.shape = Some(shape.into());
99        self
100    }
101
102    /// Dart `CarouselViewThemeData(itemClipBehavior:)`.
103    pub fn item_clip_behavior(mut self, item_clip_behavior: Clip) -> CarouselViewThemeData {
104        self.item_clip_behavior = Some(item_clip_behavior);
105        self
106    }
107
108    /// Dart `CarouselViewThemeData(overlayColor:)`.
109    pub fn overlay_color(
110        mut self,
111        overlay_color: WidgetStatePropertyRef<Option<Color>>,
112    ) -> CarouselViewThemeData {
113        self.overlay_color = Some(overlay_color);
114        self
115    }
116
117    /// Creates a copy of this object but with the given fields replaced with the new values:
118    /// Dart's `copyWith`, whose named arguments are the fluent setters on the copy.
119    pub fn copy_with(&self) -> CarouselViewThemeData {
120        self.clone()
121    }
122
123    /// Linearly interpolate between two carousel themes.
124    ///
125    /// {@macro dart.ui.shadow.lerp}
126    pub fn lerp(
127        a: Option<&CarouselViewThemeData>,
128        b: Option<&CarouselViewThemeData>,
129        t: f64,
130    ) -> CarouselViewThemeData {
131        if let (Some(a), Some(b)) = (a, b)
132            && std::ptr::eq(a, b)
133        {
134            return a.clone();
135        }
136        CarouselViewThemeData {
137            background_color: Color::lerp(
138                a.and_then(|a| a.background_color),
139                b.and_then(|b| b.background_color),
140                t,
141            ),
142            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
143            shape: OutlinedBorderRef::lerp(
144                a.and_then(|a| a.shape.as_ref()),
145                b.and_then(|b| b.shape.as_ref()),
146                t,
147            ),
148            overlay_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
149                a.and_then(|a| a.overlay_color.clone()),
150                b.and_then(|b| b.overlay_color.clone()),
151                t,
152                Color::lerp,
153            ),
154            padding: EdgeInsets::lerp(a.and_then(|a| a.padding), b.and_then(|b| b.padding), t),
155            item_clip_behavior: if t < 0.5 {
156                a.and_then(|a| a.item_clip_behavior)
157            } else {
158                b.and_then(|b| b.item_clip_behavior)
159            },
160        }
161    }
162}
163
164impl PartialEq for CarouselViewThemeData {
165    fn eq(&self, other: &CarouselViewThemeData) -> bool {
166        if std::ptr::eq(self, other) {
167            return true;
168        }
169        other.background_color == self.background_color
170            && other.elevation == self.elevation
171            && other.shape == self.shape
172            && other.overlay_color == self.overlay_color
173            && other.padding == self.padding
174            && other.item_clip_behavior == self.item_clip_behavior
175    }
176}
177
178/// An inherited widget that defines the configuration for [`CarouselView`](crate::CarouselView)s
179/// in this widget's subtree.
180///
181/// Values specified here are used for [`CarouselView`](crate::CarouselView) properties that
182/// are not given an explicit non-null value.
183#[derive(Debug)]
184pub struct CarouselViewTheme {
185    pub key: Option<KeyRef>,
186    /// The properties used for all descendant [`CarouselView`](crate::CarouselView) widgets.
187    pub data: CarouselViewThemeData,
188    pub child: WidgetRef,
189}
190
191impl CarouselViewTheme {
192    /// Creates a theme that controls the configurations for [`CarouselView`](crate::CarouselView)
193    /// in its widget subtree.
194    #[cfg_attr(debug_assertions, track_caller)]
195    pub fn new<K>(data: CarouselViewThemeData, child: impl IntoWidget<K>) -> CarouselViewTheme {
196        CarouselViewTheme {
197            key: None,
198            data,
199            child: child.into_widget(),
200        }
201    }
202
203    /// Dart `CarouselViewTheme(key:)`.
204    pub fn key(mut self, key: KeyRef) -> CarouselViewTheme {
205        self.key = Some(key);
206        self
207    }
208
209    /// Returns the configuration [`data`](Self::data) from the closest
210    /// [`CarouselViewTheme`] ancestor. If there is no ancestor, it returns
211    /// `ThemeData::carousel_view_theme`.
212    ///
213    /// Typical usage is as follows:
214    ///
215    /// ```text
216    /// let theme = CarouselViewTheme::of(app, context);
217    /// ```
218    pub fn of(app: &mut App, context: BuildContext) -> CarouselViewThemeData {
219        match context.depend_on_inherited_widget_of_exact_type::<CarouselViewTheme>(app) {
220            Some(inherited_theme) => inherited_theme.data.clone(),
221            None => Theme::of(app, context).carousel_view_theme.clone(),
222        }
223    }
224}
225
226impl InheritedTheme for CarouselViewTheme {
227    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
228        CarouselViewTheme::new(self.data.clone(), child).into_widget()
229    }
230}
231
232impl InheritedWidget for CarouselViewTheme {
233    fn key(&self) -> Option<&KeyRef> {
234        self.key.as_ref()
235    }
236
237    fn child(&self) -> &WidgetRef {
238        &self.child
239    }
240
241    fn update_should_notify(&self, old_widget: &CarouselViewTheme) -> bool {
242        self.data != old_widget.data
243    }
244
245    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
246        Some(self)
247    }
248}
249
250impl waft_foundation::Diagnosticable for CarouselViewThemeData {
251    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
252        properties
253            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
254        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
255        properties.add(
256            DiagnosticsProperty::<OutlinedBorderRef>::new("shape", self.shape.clone())
257                .default_value(None),
258        );
259        properties.add(
260            DiagnosticsProperty::<String>::new(
261                "overlayColor",
262                self.overlay_color
263                    .as_deref()
264                    .map(|property| property.to_string()),
265            )
266            .default_value(None),
267        );
268        properties.add(
269            DiagnosticsProperty::<EdgeInsetsGeometry>::new(
270                "padding",
271                self.padding.map(EdgeInsetsGeometry::from),
272            )
273            .default_value(None),
274        );
275        properties.add(
276            EnumProperty::<Clip>::new("itemClipBehavior", self.item_clip_behavior)
277                .default_value(None),
278        );
279    }
280}
281
282impl std::fmt::Display for CarouselViewThemeData {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use std::rc::Rc;
291
292    use waft_painting::{
293        BorderRadiusGeometry, EdgeInsets, EdgeInsetsGeometry, RoundedRectangleBorder,
294        ShapeBorderRef,
295    };
296    use waft_widgets::WidgetStatePropertyAll;
297    use waft_widgets::testing::{WidgetTester, expect, find, finds_one_widget, test_widgets};
298    use waft_widgets::{Center, Padding, SizedBox, WidgetStates};
299
300    use super::*;
301    use crate::carousel::CarouselView;
302    use crate::colors::Colors;
303    use crate::ink_well::InkWell;
304    use crate::material::Material;
305    use crate::scaffold::Scaffold;
306    use crate::test_support::material_app;
307    use crate::theme_data::ThemeData;
308
309    fn carousel_view_theme_data() -> CarouselViewThemeData {
310        CarouselViewThemeData::new()
311            .background_color(Color::new(0xFF0000FF))
312            .elevation(5.0)
313            .padding(EdgeInsets::all(10.0))
314            .shape(RoundedRectangleBorder::default())
315            .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
316                Colors::RED.primary(),
317            )))
318            .item_clip_behavior(Clip::HardEdge)
319    }
320
321    /// Dart's `find.descendant(of: find.byType(CarouselView), matching:
322    /// find.byWidgetPredicate((widget) => widget is Padding && widget.child is Material))`.
323    fn item_padding() -> waft_widgets::testing::Finder {
324        find::descendant(
325            find::by_type::<CarouselView>(),
326            find::by_widget_predicate("Padding with a Material child", |_app, widget| {
327                waft_widgets::downcast_widget::<Padding>(widget).is_some_and(|padding| {
328                    padding.child.as_ref().is_some_and(|child| {
329                        waft_widgets::downcast_widget::<Material>(&**child).is_some()
330                    })
331                })
332            }),
333        )
334    }
335
336    fn pump_carousel(
337        tester: &mut WidgetTester,
338        theme: ThemeData,
339        carousel: impl FnOnce() -> WidgetRef,
340        local_theme: Option<CarouselViewThemeData>,
341    ) {
342        let mut child = carousel();
343        if let Some(data) = local_theme {
344            child = CarouselViewTheme::new(data, child).into_widget();
345        }
346        tester.pump_widget(material_app(
347            theme,
348            Scaffold::new()
349                .body(Center::new().child(child))
350                .into_widget(),
351        ));
352    }
353
354    fn read_item(
355        tester: &WidgetTester,
356    ) -> (
357        EdgeInsetsGeometry,
358        Option<Color>,
359        f64,
360        Option<waft_painting::ShapeBorderRef>,
361        Clip,
362    ) {
363        tester.widget(item_padding(), |padding: &Padding| {
364            let child = padding.child.as_ref().expect("a child");
365            let material =
366                waft_widgets::downcast_widget::<Material>(&**child).expect("a Material child");
367            (
368                padding.padding,
369                material.color,
370                material.elevation,
371                material.shape.clone(),
372                material.clip_behavior,
373            )
374        })
375    }
376
377    #[test]
378    fn carousel_view_theme_data_copy_with_equals_and_hash_code_basics() {
379        assert_eq!(
380            CarouselViewThemeData::new(),
381            CarouselViewThemeData::new().copy_with()
382        );
383    }
384
385    #[test]
386    fn carousel_view_theme_data_null_fields_by_default() {
387        let carousel_view_theme = CarouselViewThemeData::new();
388        assert_eq!(carousel_view_theme.background_color, None);
389        assert_eq!(carousel_view_theme.elevation, None);
390        assert!(carousel_view_theme.overlay_color.is_none());
391        assert_eq!(carousel_view_theme.padding, None);
392        assert!(carousel_view_theme.shape.is_none());
393        assert_eq!(carousel_view_theme.item_clip_behavior, None);
394    }
395
396    #[test]
397    fn uses_value_from_carousel_view_theme_data() {
398        test_widgets(|tester| {
399            let carousel_view_theme = carousel_view_theme_data();
400            let theme = ThemeData::builder()
401                .carousel_view_theme(carousel_view_theme.clone())
402                .build(&tester.cell.borrow());
403            pump_carousel(
404                tester,
405                theme,
406                || {
407                    CarouselView::new(
408                        100.0,
409                        vec![SizedBox::new().width(100.0).height(100.0).into_widget()],
410                    )
411                    .into_widget()
412                },
413                None,
414            );
415            expect(tester, &find::by_type::<CarouselView>(), finds_one_widget());
416            expect(tester, &item_padding(), finds_one_widget());
417
418            let (padding, color, elevation, shape, clip_behavior) = read_item(tester);
419            let ink_well_overlay_color = tester.widget(
420                find::descendant(find::by_type::<CarouselView>(), find::by_type::<InkWell>()),
421                |ink_well: &InkWell| ink_well.ink_response.overlay_color.clone(),
422            );
423
424            assert_eq!(Some(padding), carousel_view_theme.padding.map(Into::into));
425            assert_eq!(color, carousel_view_theme.background_color);
426            assert_eq!(Some(elevation), carousel_view_theme.elevation);
427            assert_eq!(shape, carousel_view_theme.shape.clone().map(Into::into));
428            assert_eq!(ink_well_overlay_color, carousel_view_theme.overlay_color);
429            assert_eq!(Some(clip_behavior), carousel_view_theme.item_clip_behavior);
430        });
431    }
432
433    #[test]
434    fn widgets_properties_override_theme() {
435        test_widgets(|tester| {
436            let carousel_view_theme = carousel_view_theme_data();
437            let background_color = Color::new(0xFFFF0000);
438            let elevation = 10.0;
439            let padding = EdgeInsets::all(15.0);
440            let shape = RoundedRectangleBorder::new(
441                waft_painting::BorderSide::NONE,
442                BorderRadiusGeometry::circular(10.0),
443            );
444            let overlay_color =
445                <dyn WidgetStateProperty<Option<Color>>>::all(Some(Colors::GREEN.primary()));
446            let theme = ThemeData::builder()
447                .carousel_view_theme(carousel_view_theme)
448                .build(&tester.cell.borrow());
449            pump_carousel(
450                tester,
451                theme,
452                || {
453                    CarouselView::new(
454                        100.0,
455                        vec![SizedBox::new().width(100.0).height(100.0).into_widget()],
456                    )
457                    .background_color(background_color)
458                    .elevation(elevation)
459                    .padding(padding)
460                    .shape(shape)
461                    .overlay_color(overlay_color.clone())
462                    .item_clip_behavior(Clip::HardEdge)
463                    .into_widget()
464                },
465                None,
466            );
467            expect(tester, &find::by_type::<CarouselView>(), finds_one_widget());
468            expect(tester, &item_padding(), finds_one_widget());
469
470            let (item_padding, color, item_elevation, item_shape, clip_behavior) =
471                read_item(tester);
472            let ink_well_overlay_color = tester.widget(
473                find::descendant(find::by_type::<CarouselView>(), find::by_type::<InkWell>()),
474                |ink_well: &InkWell| ink_well.ink_response.overlay_color.clone(),
475            );
476
477            assert_eq!(item_padding, padding.into());
478            assert_eq!(color, Some(background_color));
479            assert_eq!(item_elevation, elevation);
480            assert_eq!(item_shape, Some(shape.into()));
481            assert_eq!(ink_well_overlay_color, Some(overlay_color));
482            assert_eq!(clip_behavior, Clip::HardEdge);
483        });
484    }
485
486    #[test]
487    fn carousel_view_theme_can_override_theme_carousel_view_theme() {
488        test_widgets(|tester| {
489            let local_padding = EdgeInsets::all(15.0);
490            let local_shape = RoundedRectangleBorder::new(
491                waft_painting::BorderSide::NONE,
492                BorderRadiusGeometry::circular(10.0),
493            );
494            let theme = ThemeData::builder()
495                .carousel_view_theme(
496                    CarouselViewThemeData::new()
497                        .background_color(Color::new(0xfffffff1))
498                        .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
499                            Color::new(0xff000000),
500                        )))
501                        .elevation(5.0)
502                        .padding(EdgeInsets::all(10.0))
503                        .shape(RoundedRectangleBorder::default())
504                        .item_clip_behavior(Clip::HardEdge),
505                )
506                .build(&tester.cell.borrow());
507            pump_carousel(
508                tester,
509                theme,
510                || {
511                    CarouselView::new(
512                        100.0,
513                        vec![SizedBox::new().width(100.0).height(100.0).into_widget()],
514                    )
515                    .into_widget()
516                },
517                Some(
518                    CarouselViewThemeData::new()
519                        .background_color(Color::new(0xffff0000))
520                        .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
521                            Color::new(0xffffffff),
522                        )))
523                        .elevation(10.0)
524                        .padding(local_padding)
525                        .shape(local_shape)
526                        .item_clip_behavior(Clip::AntiAlias),
527                ),
528            );
529            expect(tester, &item_padding(), finds_one_widget());
530
531            let (padding, color, elevation, shape, clip_behavior) = read_item(tester);
532            let overlay_color = tester
533                .widget(
534                    find::descendant(find::by_type::<CarouselView>(), find::by_type::<InkWell>()),
535                    |ink_well: &InkWell| ink_well.ink_response.overlay_color.clone(),
536                )
537                .and_then(|overlay_color| overlay_color.resolve(&WidgetStates::new()));
538
539            assert_eq!(padding, local_padding.into());
540            assert_eq!(color, Some(Color::new(0xffff0000)));
541            assert_eq!(elevation, 10.0);
542            assert_eq!(shape, Some(local_shape.into()));
543            assert_eq!(overlay_color, Some(Color::new(0xffffffff)));
544            assert_eq!(clip_behavior, Clip::AntiAlias);
545        });
546    }
547    // Flutter's "Default CarouselViewThemeData debugFillProperties".
548    #[test]
549    fn a_carousel_view_theme_data_describes_nothing_by_default() {
550        assert_eq!(
551            waft_widgets::testing::describe_properties(|properties| {
552                waft_foundation::Diagnosticable::debug_fill_properties(
553                    &CarouselViewThemeData::new(),
554                    properties,
555                )
556            }),
557            Vec::<String>::new()
558        );
559    }
560
561    // carousel_theme_test.dart 'CarouselViewThemeData implements debugFillProperties'.
562    #[test]
563    fn an_assigned_carousel_theme_describes_every_property() {
564        let theme = CarouselViewThemeData::new()
565            .background_color(Color::new(0xffffffff))
566            .elevation(5.0)
567            .padding(EdgeInsets::default())
568            .shape(RoundedRectangleBorder::default())
569            .overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(Color::new(
570                0xffff0000,
571            )))))
572            .item_clip_behavior(Clip::HardEdge);
573        let description = waft_widgets::testing::describe_properties(|properties| {
574            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
575        });
576        assert_eq!(
577            description,
578            [
579                format!("backgroundColor: {}", Color::new(0xffffffff)),
580                "elevation: 5.0".to_string(),
581                format!(
582                    "shape: {}",
583                    ShapeBorderRef::from(RoundedRectangleBorder::default())
584                ),
585                format!(
586                    "overlayColor: WidgetStatePropertyAll({})",
587                    Color::new(0xffff0000)
588                ),
589                "padding: EdgeInsets.zero".to_string(),
590                "itemClipBehavior: hardEdge".to_string(),
591            ]
592        );
593    }
594}