Skip to main content

waft_material/
drawer_theme.rs

1//! Flutter counterpart: material_ui's `drawer_theme.dart`.
2
3use waft_embedder::{Clip, Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{ColorProperty, ShapeBorderRef};
6use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
7
8use crate::theme::Theme;
9
10/// Defines default property values for descendant `Drawer` widgets.
11///
12/// Descendant widgets obtain the current [`DrawerThemeData`] object
13/// using [`DrawerTheme::of`]. Instances of [`DrawerThemeData`] can be
14/// customized with [`DrawerThemeData::copy_with`].
15///
16/// Typically a [`DrawerThemeData`] is specified as part of the
17/// overall `Theme` with `ThemeData::drawer_theme`.
18///
19/// All [`DrawerThemeData`] properties are `null` by default.
20///
21/// See also:
22///
23///  * [`DrawerTheme`], an `InheritedWidget` that propagates the theme down its
24///    subtree.
25///  * `ThemeData`, which describes the overall theme information for the
26///    application and can customize a drawer using `ThemeData::drawer_theme`.
27#[derive(Clone, Debug, Default, PartialEq)]
28pub struct DrawerThemeData {
29    /// Overrides the default value of `Drawer::background_color`.
30    pub background_color: Option<Color>,
31
32    /// Overrides the default value of `DrawerController::scrim_color`.
33    pub scrim_color: Option<Color>,
34
35    /// Overrides the default value of `Drawer::elevation`.
36    pub elevation: Option<f64>,
37
38    /// Overrides the default value for `Drawer::shadow_color`.
39    pub shadow_color: Option<Color>,
40
41    /// Overrides the default value for `Drawer::surface_tint_color`.
42    pub surface_tint_color: Option<Color>,
43
44    /// Overrides the default value of `Drawer::shape`.
45    pub shape: Option<ShapeBorderRef>,
46
47    /// Overrides the default value of `Drawer::shape` for an end drawer.
48    pub end_shape: Option<ShapeBorderRef>,
49
50    /// Overrides the default value of `Drawer::width`.
51    pub width: Option<f64>,
52
53    /// Overrides the default value of `Drawer::clip_behavior`.
54    pub clip_behavior: Option<Clip>,
55}
56
57crate::theme_data_getters::theme_data_getters! {
58    /// Dart's getters of `DrawerThemeData`: the theme data answers with its fields, and a defaults
59    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
60    /// are read.
61    pub trait DrawerThemeDataGetters for DrawerThemeData, fields: drawer_theme_data {
62        background_color: Option<Color>,
63        scrim_color: Option<Color>,
64        elevation: Option<f64>,
65        shadow_color: Option<Color>,
66        surface_tint_color: Option<Color>,
67        shape: Option<ShapeBorderRef>,
68        end_shape: Option<ShapeBorderRef>,
69        width: Option<f64>,
70        clip_behavior: Option<Clip>,
71    }
72}
73
74impl DrawerThemeData {
75    /// Creates a theme that can be used for `ThemeData::drawer_theme` and
76    /// [`DrawerTheme`]; Dart's optional named arguments are the fluent setters.
77    pub fn new() -> DrawerThemeData {
78        DrawerThemeData::default()
79    }
80
81    /// Dart `DrawerThemeData(backgroundColor:)`.
82    pub fn background_color(mut self, background_color: Color) -> DrawerThemeData {
83        self.background_color = Some(background_color);
84        self
85    }
86
87    /// Dart `DrawerThemeData(scrimColor:)`.
88    pub fn scrim_color(mut self, scrim_color: Color) -> DrawerThemeData {
89        self.scrim_color = Some(scrim_color);
90        self
91    }
92
93    /// Dart `DrawerThemeData(elevation:)`.
94    pub fn elevation(mut self, elevation: f64) -> DrawerThemeData {
95        self.elevation = Some(elevation);
96        self
97    }
98
99    /// Dart `DrawerThemeData(shadowColor:)`.
100    pub fn shadow_color(mut self, shadow_color: Color) -> DrawerThemeData {
101        self.shadow_color = Some(shadow_color);
102        self
103    }
104
105    /// Dart `DrawerThemeData(surfaceTintColor:)`.
106    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> DrawerThemeData {
107        self.surface_tint_color = Some(surface_tint_color);
108        self
109    }
110
111    /// Dart `DrawerThemeData(shape:)`.
112    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> DrawerThemeData {
113        self.shape = Some(shape.into());
114        self
115    }
116
117    /// Dart `DrawerThemeData(endShape:)`.
118    pub fn end_shape(mut self, end_shape: impl Into<ShapeBorderRef>) -> DrawerThemeData {
119        self.end_shape = Some(end_shape.into());
120        self
121    }
122
123    /// Dart `DrawerThemeData(width:)`.
124    pub fn width(mut self, width: f64) -> DrawerThemeData {
125        self.width = Some(width);
126        self
127    }
128
129    /// Dart `DrawerThemeData(clipBehavior:)`.
130    pub fn clip_behavior(mut self, clip_behavior: Clip) -> DrawerThemeData {
131        self.clip_behavior = Some(clip_behavior);
132        self
133    }
134
135    /// Creates a copy of this object with the given fields replaced with the
136    /// new values.
137    ///
138    /// Dart's named arguments are the fluent setters on the copy
139    /// (`data.copy_with().width(300.0)`).
140    pub fn copy_with(&self) -> DrawerThemeData {
141        self.clone()
142    }
143
144    /// Linearly interpolate between two drawer themes.
145    ///
146    /// If both arguments are null, then null is returned.
147    ///
148    /// {@macro dart.ui.shadow.lerp}
149    pub fn lerp(
150        a: Option<&DrawerThemeData>,
151        b: Option<&DrawerThemeData>,
152        t: f64,
153    ) -> Option<DrawerThemeData> {
154        match (a, b) {
155            (None, None) => return None,
156            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
157            _ => {}
158        }
159        Some(DrawerThemeData {
160            background_color: Color::lerp(
161                a.and_then(|a| a.background_color),
162                b.and_then(|b| b.background_color),
163                t,
164            ),
165            scrim_color: Color::lerp(
166                a.and_then(|a| a.scrim_color),
167                b.and_then(|b| b.scrim_color),
168                t,
169            ),
170            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
171            shadow_color: Color::lerp(
172                a.and_then(|a| a.shadow_color),
173                b.and_then(|b| b.shadow_color),
174                t,
175            ),
176            surface_tint_color: Color::lerp(
177                a.and_then(|a| a.surface_tint_color),
178                b.and_then(|b| b.surface_tint_color),
179                t,
180            ),
181            shape: ShapeBorderRef::lerp(
182                a.and_then(|a| a.shape.as_ref()),
183                b.and_then(|b| b.shape.as_ref()),
184                t,
185            ),
186            end_shape: ShapeBorderRef::lerp(
187                a.and_then(|a| a.end_shape.as_ref()),
188                b.and_then(|b| b.end_shape.as_ref()),
189                t,
190            ),
191            width: lerp_double(a.and_then(|a| a.width), b.and_then(|b| b.width), t),
192            clip_behavior: if t < 0.5 {
193                a.and_then(|a| a.clip_behavior)
194            } else {
195                b.and_then(|b| b.clip_behavior)
196            },
197        })
198    }
199}
200
201/// An inherited widget that defines visual properties for `Drawer`s in this
202/// widget's subtree.
203///
204/// Values specified here are used for `Drawer` properties that are not
205/// given an explicit non-null value.
206///
207/// Using this would allow you to override the `ThemeData::drawer_theme`.
208#[derive(Debug)]
209pub struct DrawerTheme {
210    pub key: Option<KeyRef>,
211    /// Specifies the background color, scrim color, elevation, and shape for
212    /// descendant `Drawer` widgets.
213    pub data: DrawerThemeData,
214    pub child: WidgetRef,
215}
216
217impl DrawerTheme {
218    /// Creates a theme that defines the [`DrawerThemeData`] properties for a
219    /// `Drawer`.
220    #[cfg_attr(debug_assertions, track_caller)]
221    pub fn new<K>(data: DrawerThemeData, child: impl IntoWidget<K>) -> DrawerTheme {
222        DrawerTheme {
223            key: None,
224            data,
225            child: child.into_widget(),
226        }
227    }
228
229    /// Dart `DrawerTheme(key:)`.
230    pub fn key(mut self, key: KeyRef) -> DrawerTheme {
231        self.key = Some(key);
232        self
233    }
234
235    /// Retrieves the [`DrawerThemeData`] from the closest ancestor [`DrawerTheme`].
236    ///
237    /// If there is no enclosing [`DrawerTheme`] widget, then
238    /// `ThemeData::drawer_theme` is used.
239    ///
240    /// Typical usage is as follows:
241    ///
242    /// ```text
243    /// let theme = DrawerTheme::of(app, context);
244    /// ```
245    pub fn of(app: &mut App, context: BuildContext) -> DrawerThemeData {
246        match context.depend_on_inherited_widget_of_exact_type::<DrawerTheme>(app) {
247            Some(drawer_theme) => drawer_theme.data.clone(),
248            None => Theme::of(app, context).drawer_theme.clone(),
249        }
250    }
251}
252
253impl InheritedTheme for DrawerTheme {
254    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
255        DrawerTheme::new(self.data.clone(), child).into_widget()
256    }
257}
258
259impl InheritedWidget for DrawerTheme {
260    fn key(&self) -> Option<&KeyRef> {
261        self.key.as_ref()
262    }
263
264    fn child(&self) -> &WidgetRef {
265        &self.child
266    }
267
268    fn update_should_notify(&self, old_widget: &DrawerTheme) -> bool {
269        self.data != old_widget.data
270    }
271
272    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
273        Some(self)
274    }
275}
276
277impl waft_foundation::Diagnosticable for DrawerThemeData {
278    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
279        properties
280            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
281        properties.add(ColorProperty::new("scrimColor", self.scrim_color).default_value(None));
282        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
283        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
284        properties.add(
285            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
286        );
287        properties.add(
288            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
289                .default_value(None),
290        );
291        properties.add(
292            DiagnosticsProperty::<ShapeBorderRef>::new("endShape", self.end_shape.clone())
293                .default_value(None),
294        );
295        properties.add(DoubleProperty::new("width", self.width).default_value(None));
296        properties.add(
297            DiagnosticsProperty::<waft_foundation::DartEnum<Clip>>::new(
298                "clipBehavior",
299                self.clip_behavior.map(waft_foundation::DartEnum),
300            )
301            .default_value(None),
302        );
303    }
304}
305
306impl std::fmt::Display for DrawerThemeData {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
309    }
310}
311
312#[cfg(test)]
313pub(crate) mod tests {
314    use std::cell::RefCell;
315    use std::rc::Rc;
316    use waft_painting::ShapeBorder;
317
318    use waft_painting::{BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
319    use waft_widgets::{Builder, SizedBox};
320
321    use waft_widgets::testing::{WidgetTester, test_widgets};
322
323    use super::*;
324    use crate::colors::Colors;
325    use crate::theme_data::ThemeData;
326
327    /// Builds `wrap(probe)` and returns what `read` saw at the probe's context.
328    pub(crate) fn probe<T: 'static>(
329        tester: &mut WidgetTester,
330        wrap: impl FnOnce(&App, WidgetRef) -> WidgetRef,
331        read: impl Fn(&mut App, BuildContext) -> T + 'static,
332    ) -> T {
333        let seen = Rc::new(RefCell::new(None));
334        let probe = Builder::new({
335            let seen = Rc::clone(&seen);
336            move |app, context| {
337                *seen.borrow_mut() = Some(read(app, context));
338                SizedBox::shrink().into_widget()
339            }
340        })
341        .into_widget();
342        let root = wrap(&tester.cell.borrow(), probe);
343        tester.pump_widget(root);
344        let value = seen.borrow_mut().take();
345        value.expect("the probe built")
346    }
347
348    /// What `read` sees at a probe that is wrapped, by `<dyn InheritedTheme>::capture`, in the
349    /// inherited themes above a first probe, and then built under `shadowed_by`.
350    ///
351    /// Dart's `InheritedTheme.captureAll` / `CapturedThemes.wrap` on a theme `captured_under`
352    /// puts above the first probe: the wrapped probe sees that theme, not the one
353    /// `shadowed_by` puts above it.
354    pub(crate) fn theme_seen_through_capture<T: 'static>(
355        tester: &mut WidgetTester,
356        captured_under: impl FnOnce(WidgetRef) -> WidgetRef,
357        shadowed_by: impl FnOnce(WidgetRef) -> WidgetRef,
358        read: impl Fn(&mut App, BuildContext) -> T + 'static,
359    ) -> T {
360        let captured = Rc::new(RefCell::new(None));
361        let capturing_probe = Builder::new({
362            let captured = Rc::clone(&captured);
363            move |app, context| {
364                *captured.borrow_mut() = Some(<dyn waft_widgets::InheritedTheme>::capture(
365                    app, context, None,
366                ));
367                SizedBox::shrink().into_widget()
368            }
369        })
370        .into_widget();
371        tester.pump_widget(captured_under(capturing_probe));
372        let captured = captured.borrow_mut().take().expect("the probe built");
373        probe(
374            tester,
375            |_, reading_probe| shadowed_by(captured.wrap(reading_probe)),
376            read,
377        )
378    }
379
380    fn rounded(radius: f64) -> RoundedRectangleBorder {
381        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(radius))
382    }
383
384    #[test]
385    fn copy_with_equality_basics() {
386        assert_eq!(DrawerThemeData::new(), DrawerThemeData::new().copy_with());
387
388        let theme = DrawerThemeData::new().elevation(4.0).shape(rounded(8.0));
389        assert_eq!(theme.copy_with(), theme);
390        assert_eq!(theme.copy_with().width(300.0).width, Some(300.0));
391        assert_eq!(theme.copy_with().width(300.0).elevation, Some(4.0));
392        assert_ne!(theme.copy_with().elevation(5.0), theme);
393        assert_ne!(theme.copy_with().shape(rounded(9.0)), theme);
394    }
395
396    #[test]
397    fn drawer_theme_data_lerp_special_cases() {
398        assert_eq!(DrawerThemeData::lerp(None, None, 0.0), None);
399        let data = DrawerThemeData::new();
400        assert_eq!(
401            DrawerThemeData::lerp(Some(&data), Some(&data), 0.5),
402            Some(data)
403        );
404    }
405
406    #[test]
407    fn drawer_theme_data_null_fields_by_default() {
408        let theme = DrawerThemeData::new();
409        assert_eq!(theme.background_color, None);
410        assert_eq!(theme.scrim_color, None);
411        assert_eq!(theme.elevation, None);
412        assert_eq!(theme.shadow_color, None);
413        assert_eq!(theme.surface_tint_color, None);
414        assert!(theme.shape.is_none());
415        assert!(theme.end_shape.is_none());
416        assert_eq!(theme.width, None);
417        assert_eq!(theme.clip_behavior, None);
418    }
419
420    #[test]
421    fn drawer_theme_data_lerps_each_field() {
422        let a = DrawerThemeData::new()
423            .background_color(Colors::BLACK)
424            .elevation(2.0)
425            .shape(rounded(4.0))
426            .width(100.0)
427            .clip_behavior(Clip::HardEdge);
428        let b = DrawerThemeData::new()
429            .background_color(Colors::WHITE)
430            .scrim_color(Colors::RED.primary())
431            .elevation(6.0)
432            .shape(rounded(8.0))
433            .end_shape(rounded(8.0))
434            .width(300.0)
435            .clip_behavior(Clip::AntiAlias);
436
437        let halfway = DrawerThemeData::lerp(Some(&a), Some(&b), 0.5).expect("both given");
438
439        assert_eq!(
440            halfway.background_color,
441            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
442        );
443        assert_eq!(
444            halfway.scrim_color,
445            Color::lerp(None, Some(Colors::RED.primary()), 0.5)
446        );
447        assert_eq!(halfway.elevation, Some(4.0));
448        assert_eq!(
449            halfway.shape.as_deref(),
450            Some(&rounded(6.0) as &dyn ShapeBorder)
451        );
452        assert_eq!(
453            halfway.end_shape.as_deref(),
454            ShapeBorderRef::lerp(None, Some(&ShapeBorderRef::new(rounded(8.0))), 0.5).as_deref()
455        );
456        assert_eq!(halfway.width, Some(200.0));
457        assert_eq!(halfway.clip_behavior, Some(Clip::AntiAlias));
458        assert_eq!(
459            DrawerThemeData::lerp(Some(&a), Some(&b), 0.25)
460                .expect("both given")
461                .clip_behavior,
462            Some(Clip::HardEdge)
463        );
464    }
465
466    #[test]
467    fn of_returns_the_theme_data_drawer_theme_without_an_ancestor() {
468        test_widgets(|tester| {
469            let expected = DrawerThemeData::new().width(280.0).elevation(3.0);
470            let theme_data_drawer = expected.clone();
471
472            let seen = probe(
473                tester,
474                move |app, child| {
475                    let data = ThemeData::builder()
476                        .drawer_theme(theme_data_drawer.clone())
477                        .build(app);
478                    crate::theme::Theme::new(data, child).into_widget()
479                },
480                DrawerTheme::of,
481            );
482
483            assert_eq!(seen, expected);
484        });
485    }
486
487    #[test]
488    fn of_returns_the_closest_drawer_theme_over_theme_data() {
489        test_widgets(|tester| {
490            let widget_drawer = DrawerThemeData::new().width(100.0);
491            let expected = widget_drawer.clone();
492
493            let seen = probe(
494                tester,
495                move |app, child| {
496                    let data = ThemeData::builder()
497                        .drawer_theme(DrawerThemeData::new().width(280.0))
498                        .build(app);
499                    crate::theme::Theme::new(data, DrawerTheme::new(widget_drawer.clone(), child))
500                        .into_widget()
501                },
502                DrawerTheme::of,
503            );
504
505            assert_eq!(seen, expected);
506        });
507    }
508
509    #[test]
510    fn a_captured_drawer_theme_is_kept_under_another_drawer_theme() {
511        test_widgets(|tester| {
512            let captured = DrawerThemeData::new().width(111.0);
513            let shadowing = DrawerThemeData::new().width(222.0);
514
515            let seen = theme_seen_through_capture(
516                tester,
517                |probe| DrawerTheme::new(captured.clone(), probe).into_widget(),
518                |wrapped| DrawerTheme::new(shadowing.clone(), wrapped).into_widget(),
519                DrawerTheme::of,
520            );
521
522            assert_eq!(seen.width, Some(111.0));
523        });
524    }
525
526    #[test]
527    fn update_should_notify_only_when_the_data_differs() {
528        let theme = |data: DrawerThemeData| DrawerTheme::new(data, SizedBox::shrink());
529        let old = theme(DrawerThemeData::new().width(1.0));
530
531        assert!(!theme(DrawerThemeData::new().width(1.0)).update_should_notify(&old));
532        assert!(theme(DrawerThemeData::new().width(2.0)).update_should_notify(&old));
533    }
534
535    #[test]
536    fn theme_data_holds_the_drawer_theme() {
537        test_widgets(|tester| {
538            let app = tester.cell.borrow();
539            let theme = ThemeData::new(&app);
540            assert_eq!(theme.drawer_theme, DrawerThemeData::new());
541
542            let wide = ThemeData::builder()
543                .drawer_theme(DrawerThemeData::new().width(300.0))
544                .build(&app);
545            assert_eq!(wide.drawer_theme.width, Some(300.0));
546            assert_ne!(theme, wide);
547            assert_eq!(
548                theme
549                    .copy_with()
550                    .drawer_theme(wide.drawer_theme.clone())
551                    .build(),
552                wide
553            );
554
555            let narrow = ThemeData::builder()
556                .drawer_theme(DrawerThemeData::new().width(100.0))
557                .build(&app);
558            assert_eq!(
559                ThemeData::lerp(&narrow, &wide, 0.5).drawer_theme.width,
560                Some(200.0)
561            );
562        });
563    }
564    // Flutter's "Default DrawerThemeData debugFillProperties".
565    #[test]
566    fn a_drawer_theme_data_describes_nothing_by_default() {
567        assert_eq!(
568            waft_widgets::testing::describe_properties(|properties| {
569                waft_foundation::Diagnosticable::debug_fill_properties(
570                    &DrawerThemeData::new(),
571                    properties,
572                )
573            }),
574            Vec::<String>::new()
575        );
576    }
577
578    // drawer_theme_test.dart 'Custom debugFillProperties'.
579    #[test]
580    fn an_assigned_drawer_theme_describes_every_property() {
581        let theme = DrawerThemeData::new()
582            .background_color(Color::new(0x00000099))
583            .scrim_color(Color::new(0x00000098))
584            .elevation(5.0)
585            .shadow_color(Color::new(0x00000097))
586            .surface_tint_color(Color::new(0x00000096))
587            .shape(RoundedRectangleBorder::new(
588                BorderSide::NONE,
589                BorderRadiusGeometry::circular(2.0),
590            ))
591            .width(200.0)
592            .clip_behavior(Clip::HardEdge);
593        let description = waft_widgets::testing::describe_properties(|properties| {
594            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
595        });
596        let description: Vec<String> = description
597            .iter()
598            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
599            .collect();
600        assert_eq!(
601            description,
602            [
603                format!("backgroundColor: {}", Color::new(0x00000099)),
604                format!("scrimColor: {}", Color::new(0x00000098)),
605                "elevation: 5.0".to_string(),
606                format!("shadowColor: {}", Color::new(0x00000097)),
607                format!("surfaceTintColor: {}", Color::new(0x00000096)),
608                format!(
609                    "shape: {}",
610                    waft_painting::ShapeBorderRef::from(RoundedRectangleBorder::new(
611                        BorderSide::NONE,
612                        BorderRadiusGeometry::circular(2.0)
613                    ))
614                ),
615                "width: 200.0".to_string(),
616                "clipBehavior: Clip.hardEdge".to_string(),
617            ]
618        );
619    }
620}