Skip to main content

waft_material/
bottom_sheet_theme.rs

1//! Flutter counterpart: material_ui's `bottom_sheet_theme.dart`.
2
3use waft_embedder::{Clip, Color, Size, lerp_double};
4use waft_foundation::{DiagnosticsProperty, DoubleProperty};
5use waft_painting::{AnyColor, ColorProperty, ShapeBorderRef};
6use waft_rendering::BoxConstraints;
7
8/// Defines default property values for `BottomSheet`'s `Material`.
9///
10/// Descendant widgets obtain the current [`BottomSheetThemeData`] object
11/// using `Theme::of(app, context).bottom_sheet_theme`. Instances of
12/// [`BottomSheetThemeData`] can be customized with
13/// [`BottomSheetThemeData::copy_with`].
14///
15/// Typically a [`BottomSheetThemeData`] is specified as part of the
16/// overall `Theme` with `ThemeData::bottom_sheet_theme`.
17///
18/// All [`BottomSheetThemeData`] properties are `null` by default.
19/// When null, the `BottomSheet` will provide its own defaults.
20///
21/// See also:
22///
23///  * `ThemeData`, which describes the overall theme information for the
24///    application.
25#[derive(Clone, Debug, Default, PartialEq)]
26pub struct BottomSheetThemeData {
27    /// Overrides the default value for `BottomSheet::background_color`.
28    ///
29    /// If null, `BottomSheet` defaults to `Material`'s default.
30    pub background_color: Option<Color>,
31
32    /// Overrides the default value for surfaceTintColor.
33    ///
34    /// If null, `BottomSheet` will not display an overlay color.
35    ///
36    /// See `Material::surface_tint_color` for more details.
37    pub surface_tint_color: Option<Color>,
38
39    /// Overrides the default value for `BottomSheet::elevation`.
40    ///
41    /// {@macro material_ui.material.elevation}
42    ///
43    /// If null, `BottomSheet` defaults to 0.0.
44    pub elevation: Option<f64>,
45
46    /// Value for `BottomSheet::background_color` when the Bottom sheet is presented
47    /// as a modal bottom sheet.
48    pub modal_background_color: Option<Color>,
49
50    /// Overrides the default value for barrier color when the Bottom sheet is presented as
51    /// a modal bottom sheet.
52    pub modal_barrier_color: Option<Color>,
53
54    /// Overrides the default value for `BottomSheet::shadow_color`.
55    pub shadow_color: Option<Color>,
56
57    /// Value for `BottomSheet::elevation` when the Bottom sheet is presented as a
58    /// modal bottom sheet.
59    pub modal_elevation: Option<f64>,
60
61    /// Overrides the default value for `BottomSheet::shape`.
62    ///
63    /// If null, no overriding shape is specified for `BottomSheet`, so the
64    /// `BottomSheet` is rectangular.
65    pub shape: Option<ShapeBorderRef>,
66
67    /// Overrides the default value for `BottomSheet::show_drag_handle`.
68    pub show_drag_handle: Option<bool>,
69
70    /// Overrides the default value for `BottomSheet::drag_handle_color`.
71    pub drag_handle_color: Option<AnyColor>,
72
73    /// Overrides the default value for `BottomSheet::drag_handle_size`.
74    pub drag_handle_size: Option<Size>,
75
76    /// Overrides the default value for `BottomSheet::clip_behavior`.
77    ///
78    /// If null, `BottomSheet` uses [`Clip::None`].
79    pub clip_behavior: Option<Clip>,
80
81    /// Constrains the size of the `BottomSheet`.
82    ///
83    /// If null, the bottom sheet's size will be unconstrained.
84    pub constraints: Option<BoxConstraints>,
85}
86
87crate::theme_data_getters::theme_data_getters! {
88    /// Dart's getters of `BottomSheetThemeData`: the theme data answers with its fields, and a defaults
89    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
90    /// are read.
91    pub trait BottomSheetThemeDataGetters for BottomSheetThemeData, fields: bottom_sheet_theme_data {
92        background_color: Option<Color>,
93        surface_tint_color: Option<Color>,
94        elevation: Option<f64>,
95        modal_background_color: Option<Color>,
96        modal_barrier_color: Option<Color>,
97        shadow_color: Option<Color>,
98        modal_elevation: Option<f64>,
99        shape: Option<ShapeBorderRef>,
100        show_drag_handle: Option<bool>,
101        drag_handle_color: Option<AnyColor>,
102        drag_handle_size: Option<Size>,
103        clip_behavior: Option<Clip>,
104        constraints: Option<BoxConstraints>,
105    }
106}
107
108impl BottomSheetThemeData {
109    /// Creates a theme that can be used for `ThemeData::bottom_sheet_theme`; Dart's optional
110    /// named arguments are the fluent setters.
111    pub fn new() -> BottomSheetThemeData {
112        BottomSheetThemeData::default()
113    }
114
115    /// Dart `BottomSheetThemeData(backgroundColor:)`.
116    pub fn background_color(mut self, background_color: Color) -> BottomSheetThemeData {
117        self.background_color = Some(background_color);
118        self
119    }
120
121    /// Dart `BottomSheetThemeData(surfaceTintColor:)`.
122    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> BottomSheetThemeData {
123        self.surface_tint_color = Some(surface_tint_color);
124        self
125    }
126
127    /// Dart `BottomSheetThemeData(elevation:)`.
128    pub fn elevation(mut self, elevation: f64) -> BottomSheetThemeData {
129        self.elevation = Some(elevation);
130        self
131    }
132
133    /// Dart `BottomSheetThemeData(modalBackgroundColor:)`.
134    pub fn modal_background_color(mut self, modal_background_color: Color) -> BottomSheetThemeData {
135        self.modal_background_color = Some(modal_background_color);
136        self
137    }
138
139    /// Dart `BottomSheetThemeData(modalBarrierColor:)`.
140    pub fn modal_barrier_color(mut self, modal_barrier_color: Color) -> BottomSheetThemeData {
141        self.modal_barrier_color = Some(modal_barrier_color);
142        self
143    }
144
145    /// Dart `BottomSheetThemeData(shadowColor:)`.
146    pub fn shadow_color(mut self, shadow_color: Color) -> BottomSheetThemeData {
147        self.shadow_color = Some(shadow_color);
148        self
149    }
150
151    /// Dart `BottomSheetThemeData(modalElevation:)`.
152    pub fn modal_elevation(mut self, modal_elevation: f64) -> BottomSheetThemeData {
153        self.modal_elevation = Some(modal_elevation);
154        self
155    }
156
157    /// Dart `BottomSheetThemeData(shape:)`.
158    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> BottomSheetThemeData {
159        self.shape = Some(shape.into());
160        self
161    }
162
163    /// Dart `BottomSheetThemeData(showDragHandle:)`.
164    pub fn show_drag_handle(mut self, show_drag_handle: bool) -> BottomSheetThemeData {
165        self.show_drag_handle = Some(show_drag_handle);
166        self
167    }
168
169    /// Dart `BottomSheetThemeData(dragHandleColor:)`.
170    pub fn drag_handle_color(
171        mut self,
172        drag_handle_color: impl Into<AnyColor>,
173    ) -> BottomSheetThemeData {
174        self.drag_handle_color = Some(drag_handle_color.into());
175        self
176    }
177
178    /// Dart `BottomSheetThemeData(dragHandleSize:)`.
179    pub fn drag_handle_size(mut self, drag_handle_size: Size) -> BottomSheetThemeData {
180        self.drag_handle_size = Some(drag_handle_size);
181        self
182    }
183
184    /// Dart `BottomSheetThemeData(clipBehavior:)`.
185    pub fn clip_behavior(mut self, clip_behavior: Clip) -> BottomSheetThemeData {
186        self.clip_behavior = Some(clip_behavior);
187        self
188    }
189
190    /// Dart `BottomSheetThemeData(constraints:)`.
191    pub fn constraints(mut self, constraints: BoxConstraints) -> BottomSheetThemeData {
192        self.constraints = Some(constraints);
193        self
194    }
195
196    /// Creates a copy of this object with the given fields replaced with the
197    /// new values.
198    ///
199    /// Dart's named arguments are the fluent setters on the copy
200    /// (`data.copy_with().elevation(4.0)`).
201    pub fn copy_with(&self) -> BottomSheetThemeData {
202        self.clone()
203    }
204
205    /// Linearly interpolate between two bottom sheet themes.
206    ///
207    /// If both arguments are null then null is returned.
208    ///
209    /// {@macro dart.ui.shadow.lerp}
210    pub fn lerp(
211        a: Option<&BottomSheetThemeData>,
212        b: Option<&BottomSheetThemeData>,
213        t: f64,
214    ) -> Option<BottomSheetThemeData> {
215        match (a, b) {
216            (None, None) => return None,
217            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
218            _ => {}
219        }
220        Some(BottomSheetThemeData {
221            background_color: Color::lerp(
222                a.and_then(|a| a.background_color),
223                b.and_then(|b| b.background_color),
224                t,
225            ),
226            surface_tint_color: Color::lerp(
227                a.and_then(|a| a.surface_tint_color),
228                b.and_then(|b| b.surface_tint_color),
229                t,
230            ),
231            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
232            modal_background_color: Color::lerp(
233                a.and_then(|a| a.modal_background_color),
234                b.and_then(|b| b.modal_background_color),
235                t,
236            ),
237            modal_barrier_color: Color::lerp(
238                a.and_then(|a| a.modal_barrier_color),
239                b.and_then(|b| b.modal_barrier_color),
240                t,
241            ),
242            shadow_color: Color::lerp(
243                a.and_then(|a| a.shadow_color),
244                b.and_then(|b| b.shadow_color),
245                t,
246            ),
247            modal_elevation: lerp_double(
248                a.and_then(|a| a.modal_elevation),
249                b.and_then(|b| b.modal_elevation),
250                t,
251            ),
252            shape: ShapeBorderRef::lerp(
253                a.and_then(|a| a.shape.as_ref()),
254                b.and_then(|b| b.shape.as_ref()),
255                t,
256            ),
257            show_drag_handle: pick(a, b, t, |theme| theme.show_drag_handle),
258            drag_handle_color: AnyColor::lerp(
259                a.and_then(|a| a.drag_handle_color.as_ref()),
260                b.and_then(|b| b.drag_handle_color.as_ref()),
261                t,
262            )
263            .map(AnyColor::from),
264            drag_handle_size: Size::lerp(
265                a.and_then(|a| a.drag_handle_size),
266                b.and_then(|b| b.drag_handle_size),
267                t,
268            ),
269            clip_behavior: pick(a, b, t, |theme| theme.clip_behavior),
270            constraints: BoxConstraints::lerp(
271                a.and_then(|a| a.constraints),
272                b.and_then(|b| b.constraints),
273                t,
274            ),
275        })
276    }
277}
278
279/// Dart's `t < 0.5 ? a?.field : b?.field`.
280fn pick<T>(
281    a: Option<&BottomSheetThemeData>,
282    b: Option<&BottomSheetThemeData>,
283    t: f64,
284    field: impl Fn(&BottomSheetThemeData) -> Option<T>,
285) -> Option<T> {
286    if t < 0.5 {
287        a.and_then(&field)
288    } else {
289        b.and_then(&field)
290    }
291}
292
293impl waft_foundation::Diagnosticable for BottomSheetThemeData {
294    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
295        properties
296            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
297        properties.add(
298            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
299        );
300        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
301        properties.add(
302            ColorProperty::new("modalBackgroundColor", self.modal_background_color)
303                .default_value(None),
304        );
305        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
306        properties.add(
307            ColorProperty::new("modalBarrierColor", self.modal_barrier_color).default_value(None),
308        );
309        properties
310            .add(DoubleProperty::new("modalElevation", self.modal_elevation).default_value(None));
311        properties.add(
312            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
313                .default_value(None),
314        );
315        properties.add(
316            DiagnosticsProperty::<bool>::new("showDragHandle", self.show_drag_handle)
317                .default_value(None),
318        );
319        properties.add(
320            DiagnosticsProperty::<AnyColor>::new("dragHandleColor", self.drag_handle_color.clone())
321                .default_value(None),
322        );
323        properties.add(
324            DiagnosticsProperty::<Size>::new("dragHandleSize", self.drag_handle_size)
325                .default_value(None),
326        );
327        properties.add(
328            DiagnosticsProperty::<waft_foundation::DartEnum<Clip>>::new(
329                "clipBehavior",
330                self.clip_behavior.map(waft_foundation::DartEnum),
331            )
332            .default_value(None),
333        );
334        properties.add(
335            DiagnosticsProperty::<BoxConstraints>::new("constraints", self.constraints)
336                .default_value(None),
337        );
338    }
339}
340
341impl std::fmt::Display for BottomSheetThemeData {
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use waft_painting::ShapeBorder;
350    use waft_painting::{BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
351
352    use waft_widgets::testing::test_widgets;
353
354    use super::*;
355    use crate::colors::Colors;
356    use crate::theme_data::ThemeData;
357
358    fn rounded(radius: f64) -> RoundedRectangleBorder {
359        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(radius))
360    }
361
362    #[test]
363    fn bottom_sheet_theme_data_copy_with_equality_basics() {
364        assert_eq!(
365            BottomSheetThemeData::new(),
366            BottomSheetThemeData::new().copy_with()
367        );
368
369        let theme = BottomSheetThemeData::new()
370            .elevation(4.0)
371            .shape(rounded(8.0))
372            .drag_handle_size(Size::new(32.0, 4.0));
373        assert_eq!(theme.copy_with(), theme);
374        assert_eq!(
375            theme.copy_with().modal_elevation(9.0).modal_elevation,
376            Some(9.0)
377        );
378        assert_eq!(theme.copy_with().modal_elevation(9.0).elevation, Some(4.0));
379        assert_ne!(theme.copy_with().elevation(5.0), theme);
380        assert_ne!(theme.copy_with().shape(rounded(9.0)), theme);
381    }
382
383    #[test]
384    fn bottom_sheet_theme_data_lerp_special_cases() {
385        assert_eq!(BottomSheetThemeData::lerp(None, None, 0.0), None);
386        let data = BottomSheetThemeData::new();
387        assert_eq!(
388            BottomSheetThemeData::lerp(Some(&data), Some(&data), 0.5),
389            Some(data)
390        );
391    }
392
393    #[test]
394    fn bottom_sheet_theme_data_null_fields_by_default() {
395        let theme = BottomSheetThemeData::new();
396        assert_eq!(theme.background_color, None);
397        assert_eq!(theme.surface_tint_color, None);
398        assert_eq!(theme.shadow_color, None);
399        assert_eq!(theme.elevation, None);
400        assert_eq!(theme.modal_background_color, None);
401        assert_eq!(theme.modal_barrier_color, None);
402        assert_eq!(theme.modal_elevation, None);
403        assert!(theme.shape.is_none());
404        assert_eq!(theme.show_drag_handle, None);
405        assert_eq!(theme.clip_behavior, None);
406        assert_eq!(theme.constraints, None);
407        assert_eq!(theme.drag_handle_color, None);
408        assert_eq!(theme.drag_handle_size, None);
409    }
410
411    #[test]
412    fn bottom_sheet_theme_data_lerps_each_field() {
413        let a = BottomSheetThemeData::new()
414            .background_color(Colors::BLACK)
415            .elevation(2.0)
416            .modal_elevation(4.0)
417            .shape(rounded(4.0))
418            .show_drag_handle(true)
419            .drag_handle_size(Size::new(20.0, 2.0))
420            .clip_behavior(Clip::HardEdge)
421            .constraints(BoxConstraints::tight(Size::new(100.0, 100.0)));
422        let b = BottomSheetThemeData::new()
423            .background_color(Colors::WHITE)
424            .surface_tint_color(Colors::RED.primary())
425            .elevation(6.0)
426            .modal_elevation(8.0)
427            .shape(rounded(8.0))
428            .show_drag_handle(false)
429            .drag_handle_size(Size::new(40.0, 6.0))
430            .clip_behavior(Clip::AntiAlias)
431            .constraints(BoxConstraints::tight(Size::new(300.0, 300.0)));
432
433        let halfway = BottomSheetThemeData::lerp(Some(&a), Some(&b), 0.5).expect("both given");
434
435        assert_eq!(
436            halfway.background_color,
437            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
438        );
439        assert_eq!(
440            halfway.surface_tint_color,
441            Color::lerp(None, Some(Colors::RED.primary()), 0.5)
442        );
443        assert_eq!(halfway.elevation, Some(4.0));
444        assert_eq!(halfway.modal_elevation, Some(6.0));
445        assert_eq!(
446            halfway.shape.as_deref(),
447            Some(&rounded(6.0) as &dyn ShapeBorder)
448        );
449        assert_eq!(halfway.show_drag_handle, Some(false));
450        assert_eq!(halfway.drag_handle_size, Some(Size::new(30.0, 4.0)));
451        assert_eq!(halfway.clip_behavior, Some(Clip::AntiAlias));
452        assert_eq!(
453            halfway.constraints,
454            Some(BoxConstraints::tight(Size::new(200.0, 200.0)))
455        );
456
457        let early = BottomSheetThemeData::lerp(Some(&a), Some(&b), 0.25).expect("both given");
458        assert_eq!(early.show_drag_handle, Some(true));
459        assert_eq!(early.clip_behavior, Some(Clip::HardEdge));
460    }
461
462    #[test]
463    fn theme_data_holds_the_bottom_sheet_theme() {
464        test_widgets(|tester| {
465            let app = tester.cell.borrow();
466            let theme = ThemeData::new(&app);
467            assert_eq!(theme.bottom_sheet_theme, BottomSheetThemeData::new());
468
469            let tall = ThemeData::builder()
470                .bottom_sheet_theme(BottomSheetThemeData::new().elevation(8.0))
471                .build(&app);
472            assert_eq!(tall.bottom_sheet_theme.elevation, Some(8.0));
473            assert_ne!(theme, tall);
474            assert_eq!(
475                theme
476                    .copy_with()
477                    .bottom_sheet_theme(tall.bottom_sheet_theme.clone())
478                    .build(),
479                tall
480            );
481
482            let flat = ThemeData::builder()
483                .bottom_sheet_theme(BottomSheetThemeData::new().elevation(0.0))
484                .build(&app);
485            assert_eq!(
486                ThemeData::lerp(&flat, &tall, 0.5)
487                    .bottom_sheet_theme
488                    .elevation,
489                Some(4.0)
490            );
491        });
492    }
493    // Flutter's "Default BottomSheetThemeData debugFillProperties".
494    #[test]
495    fn a_bottom_sheet_theme_data_describes_nothing_by_default() {
496        assert_eq!(
497            waft_widgets::testing::describe_properties(|properties| {
498                waft_foundation::Diagnosticable::debug_fill_properties(
499                    &BottomSheetThemeData::new(),
500                    properties,
501                )
502            }),
503            Vec::<String>::new()
504        );
505    }
506
507    // bottom_sheet_theme_test.dart 'BottomSheetThemeData implements debugFillProperties'.
508    #[test]
509    fn an_assigned_bottom_sheet_theme_describes_every_property() {
510        let theme = BottomSheetThemeData::new()
511            .background_color(Color::new(0xffffffff))
512            .elevation(2.0)
513            .shadow_color(Color::new(0xff00ffff))
514            .shape(RoundedRectangleBorder::new(
515                BorderSide::NONE,
516                BorderRadiusGeometry::circular(2.0),
517            ))
518            .clip_behavior(Clip::AntiAlias)
519            .constraints(BoxConstraints::new().min_width(200.0).max_width(640.0))
520            .drag_handle_color(Color::new(0xffffffff))
521            .drag_handle_size(Size::new(20.0, 20.0));
522        let description = waft_widgets::testing::describe_properties(|properties| {
523            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
524        });
525        assert_eq!(
526            description,
527            [
528                format!("backgroundColor: {}", Color::new(0xffffffff)),
529                "elevation: 2.0".to_string(),
530                format!("shadowColor: {}", Color::new(0xff00ffff)),
531                format!(
532                    "shape: {}",
533                    ShapeBorderRef::from(RoundedRectangleBorder::new(
534                        BorderSide::NONE,
535                        BorderRadiusGeometry::circular(2.0)
536                    ))
537                ),
538                format!("dragHandleColor: {}", Color::new(0xffffffff)),
539                "dragHandleSize: Size(20.0, 20.0)".to_string(),
540                "clipBehavior: Clip.antiAlias".to_string(),
541                "constraints: BoxConstraints(200.0<=w<=640.0, 0.0<=h<=Infinity)".to_string(),
542            ]
543        );
544    }
545}