Skip to main content

waft_material/
navigation_drawer_theme.rs

1//! Flutter counterpart: material_ui's `navigation_drawer_theme.dart`.
2
3use waft_embedder::{Color, Size, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{ColorProperty, ShapeBorderRef, TextStyle};
6use waft_widgets::{
7    BuildContext, IconThemeData, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
8    WidgetStateProperty, WidgetStatePropertyRef,
9};
10
11use crate::theme::Theme;
12
13/// Defines default property values for descendant `NavigationDrawer`
14/// widgets.
15///
16/// Descendant widgets obtain the current [`NavigationDrawerThemeData`] object
17/// using [`NavigationDrawerTheme::of`]. Instances of [`NavigationDrawerThemeData`]
18/// can be customized with [`NavigationDrawerThemeData::copy_with`].
19///
20/// Typically a [`NavigationDrawerThemeData`] is specified as part of the
21/// overall `Theme` with `ThemeData::navigation_drawer_theme`. Alternatively, a
22/// [`NavigationDrawerTheme`] inherited widget can be used to theme `NavigationDrawer`s
23/// in a subtree of widgets.
24///
25/// All [`NavigationDrawerThemeData`] properties are `null` by default.
26/// When null, the `NavigationDrawer` will provide its own defaults based on the
27/// overall `Theme`'s textTheme and colorScheme. See the individual
28/// `NavigationDrawer` properties for details.
29///
30/// See also:
31///
32///  * `ThemeData`, which describes the overall theme information for the
33///    application.
34#[derive(Clone, Debug, Default)]
35pub struct NavigationDrawerThemeData {
36    /// Overrides the default height of `NavigationDrawerDestination`.
37    pub tile_height: Option<f64>,
38
39    /// Overrides the default value of `NavigationDrawer::background_color`.
40    pub background_color: Option<Color>,
41
42    /// Overrides the default value of `NavigationDrawer::elevation`.
43    pub elevation: Option<f64>,
44
45    /// Overrides the default value of `NavigationDrawer::shadow_color`.
46    pub shadow_color: Option<Color>,
47
48    /// Overrides the default value of `NavigationDrawer::surface_tint_color`.
49    pub surface_tint_color: Option<Color>,
50
51    /// Overrides the default value of `NavigationDrawer`'s selection indicator.
52    pub indicator_color: Option<Color>,
53
54    /// Overrides the default shape of the `NavigationDrawer`'s selection indicator.
55    pub indicator_shape: Option<ShapeBorderRef>,
56
57    /// Overrides the default size of the `NavigationDrawer`'s selection indicator.
58    pub indicator_size: Option<Size>,
59
60    /// The style to merge with the default text style for
61    /// `NavigationDestination` labels.
62    ///
63    /// You can use this to specify a different style when the label is selected.
64    pub label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
65
66    /// The theme to merge with the default icon theme for
67    /// `NavigationDestination` icons.
68    ///
69    /// You can use this to specify a different icon theme when the icon is
70    /// selected.
71    pub icon_theme: Option<WidgetStatePropertyRef<Option<IconThemeData>>>,
72}
73
74crate::theme_data_getters::theme_data_getters! {
75    /// Dart's getters of `NavigationDrawerThemeData`: the theme data answers with its fields, and a defaults
76    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
77    /// are read.
78    pub trait NavigationDrawerThemeDataGetters for NavigationDrawerThemeData, fields: navigation_drawer_theme_data {
79        tile_height: Option<f64>,
80        background_color: Option<Color>,
81        elevation: Option<f64>,
82        shadow_color: Option<Color>,
83        surface_tint_color: Option<Color>,
84        indicator_color: Option<Color>,
85        indicator_shape: Option<ShapeBorderRef>,
86        indicator_size: Option<Size>,
87        label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
88        icon_theme: Option<WidgetStatePropertyRef<Option<IconThemeData>>>,
89    }
90}
91
92impl NavigationDrawerThemeData {
93    /// Creates a theme that can be used for `ThemeData::navigation_drawer_theme` and
94    /// [`NavigationDrawerTheme`]; Dart's optional named arguments are the fluent setters.
95    pub fn new() -> NavigationDrawerThemeData {
96        NavigationDrawerThemeData::default()
97    }
98
99    /// Dart `NavigationDrawerThemeData(tileHeight:)`.
100    pub fn tile_height(mut self, tile_height: f64) -> NavigationDrawerThemeData {
101        self.tile_height = Some(tile_height);
102        self
103    }
104
105    /// Dart `NavigationDrawerThemeData(backgroundColor:)`.
106    pub fn background_color(mut self, background_color: Color) -> NavigationDrawerThemeData {
107        self.background_color = Some(background_color);
108        self
109    }
110
111    /// Dart `NavigationDrawerThemeData(elevation:)`.
112    pub fn elevation(mut self, elevation: f64) -> NavigationDrawerThemeData {
113        self.elevation = Some(elevation);
114        self
115    }
116
117    /// Dart `NavigationDrawerThemeData(shadowColor:)`.
118    pub fn shadow_color(mut self, shadow_color: Color) -> NavigationDrawerThemeData {
119        self.shadow_color = Some(shadow_color);
120        self
121    }
122
123    /// Dart `NavigationDrawerThemeData(surfaceTintColor:)`.
124    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> NavigationDrawerThemeData {
125        self.surface_tint_color = Some(surface_tint_color);
126        self
127    }
128
129    /// Dart `NavigationDrawerThemeData(indicatorColor:)`.
130    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationDrawerThemeData {
131        self.indicator_color = Some(indicator_color);
132        self
133    }
134
135    /// Dart `NavigationDrawerThemeData(indicatorShape:)`.
136    pub fn indicator_shape(
137        mut self,
138        indicator_shape: impl Into<ShapeBorderRef>,
139    ) -> NavigationDrawerThemeData {
140        self.indicator_shape = Some(indicator_shape.into());
141        self
142    }
143
144    /// Dart `NavigationDrawerThemeData(indicatorSize:)`.
145    pub fn indicator_size(mut self, indicator_size: Size) -> NavigationDrawerThemeData {
146        self.indicator_size = Some(indicator_size);
147        self
148    }
149
150    /// Dart `NavigationDrawerThemeData(labelTextStyle:)`.
151    pub fn label_text_style(
152        mut self,
153        label_text_style: WidgetStatePropertyRef<Option<TextStyle>>,
154    ) -> NavigationDrawerThemeData {
155        self.label_text_style = Some(label_text_style);
156        self
157    }
158
159    /// Dart `NavigationDrawerThemeData(iconTheme:)`.
160    pub fn icon_theme(
161        mut self,
162        icon_theme: WidgetStatePropertyRef<Option<IconThemeData>>,
163    ) -> NavigationDrawerThemeData {
164        self.icon_theme = Some(icon_theme);
165        self
166    }
167
168    /// Creates a copy of this object with the given fields replaced with the
169    /// new values.
170    ///
171    /// Dart's named arguments are the fluent setters on the copy
172    /// (`data.copy_with().tile_height(48.0)`).
173    pub fn copy_with(&self) -> NavigationDrawerThemeData {
174        self.clone()
175    }
176
177    /// Linearly interpolate between two navigation rail themes.
178    ///
179    /// If both arguments are null then null is returned.
180    ///
181    /// {@macro dart.ui.shadow.lerp}
182    pub fn lerp(
183        a: Option<&NavigationDrawerThemeData>,
184        b: Option<&NavigationDrawerThemeData>,
185        t: f64,
186    ) -> Option<NavigationDrawerThemeData> {
187        match (a, b) {
188            (None, None) => return None,
189            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
190            _ => {}
191        }
192        Some(NavigationDrawerThemeData {
193            tile_height: lerp_double(
194                a.and_then(|a| a.tile_height),
195                b.and_then(|b| b.tile_height),
196                t,
197            ),
198            background_color: Color::lerp(
199                a.and_then(|a| a.background_color),
200                b.and_then(|b| b.background_color),
201                t,
202            ),
203            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
204            shadow_color: Color::lerp(
205                a.and_then(|a| a.shadow_color),
206                b.and_then(|b| b.shadow_color),
207                t,
208            ),
209            surface_tint_color: Color::lerp(
210                a.and_then(|a| a.surface_tint_color),
211                b.and_then(|b| b.surface_tint_color),
212                t,
213            ),
214            indicator_color: Color::lerp(
215                a.and_then(|a| a.indicator_color),
216                b.and_then(|b| b.indicator_color),
217                t,
218            ),
219            indicator_shape: ShapeBorderRef::lerp(
220                a.and_then(|a| a.indicator_shape.as_ref()),
221                b.and_then(|b| b.indicator_shape.as_ref()),
222                t,
223            ),
224            // Dart lerps `a`'s size with itself.
225            indicator_size: Size::lerp(
226                a.and_then(|a| a.indicator_size),
227                a.and_then(|a| a.indicator_size),
228                t,
229            ),
230            label_text_style: <dyn WidgetStateProperty<Option<TextStyle>>>::lerp_optional(
231                a.and_then(|a| a.label_text_style.clone()),
232                b.and_then(|b| b.label_text_style.clone()),
233                t,
234                |a: Option<TextStyle>, b: Option<TextStyle>, t| {
235                    TextStyle::lerp(a.as_ref(), b.as_ref(), t)
236                },
237            ),
238            icon_theme: <dyn WidgetStateProperty<Option<IconThemeData>>>::lerp_optional(
239                a.and_then(|a| a.icon_theme.clone()),
240                b.and_then(|b| b.icon_theme.clone()),
241                t,
242                |a: Option<IconThemeData>, b: Option<IconThemeData>, t| {
243                    Some(IconThemeData::lerp(a.as_ref(), b.as_ref(), t))
244                },
245            ),
246        })
247    }
248}
249
250impl PartialEq for NavigationDrawerThemeData {
251    fn eq(&self, other: &NavigationDrawerThemeData) -> bool {
252        if std::ptr::eq(self, other) {
253            return true;
254        }
255        other.tile_height == self.tile_height
256            && other.background_color == self.background_color
257            && other.elevation == self.elevation
258            && other.shadow_color == self.shadow_color
259            && other.surface_tint_color == self.surface_tint_color
260            && other.indicator_color == self.indicator_color
261            && other.indicator_shape == self.indicator_shape
262            && other.indicator_size == self.indicator_size
263            && other.label_text_style == self.label_text_style
264            && other.icon_theme == self.icon_theme
265    }
266}
267
268/// An inherited widget that defines visual properties for `NavigationDrawer`s and
269/// `NavigationDestination`s in this widget's subtree.
270///
271/// Values specified here are used for `NavigationDrawer` properties that are not
272/// given an explicit non-null value.
273///
274/// See also:
275///
276///  * `ThemeData::navigation_drawer_theme`, which describes the
277///    [`NavigationDrawerThemeData`] in the overall theme for the application.
278#[derive(Debug)]
279pub struct NavigationDrawerTheme {
280    pub key: Option<KeyRef>,
281    /// Specifies the background color, label text style, icon theme, and label
282    /// type values for descendant `NavigationDrawer` widgets.
283    pub data: NavigationDrawerThemeData,
284    pub child: WidgetRef,
285}
286
287impl NavigationDrawerTheme {
288    /// Creates a navigation rail theme that controls the
289    /// [`NavigationDrawerThemeData`] properties for a `NavigationDrawer`.
290    #[cfg_attr(debug_assertions, track_caller)]
291    pub fn new<K>(
292        data: NavigationDrawerThemeData,
293        child: impl IntoWidget<K>,
294    ) -> NavigationDrawerTheme {
295        NavigationDrawerTheme {
296            key: None,
297            data,
298            child: child.into_widget(),
299        }
300    }
301
302    /// Dart `NavigationDrawerTheme(key:)`.
303    pub fn key(mut self, key: KeyRef) -> NavigationDrawerTheme {
304        self.key = Some(key);
305        self
306    }
307
308    /// Retrieves the [`NavigationDrawerThemeData`] from the closest
309    /// ancestor [`NavigationDrawerTheme`].
310    ///
311    /// If there is no enclosing [`NavigationDrawerTheme`] widget, then
312    /// `ThemeData::navigation_drawer_theme` is used.
313    ///
314    /// Typical usage is as follows:
315    ///
316    /// ```text
317    /// let theme = NavigationDrawerTheme::of(app, context);
318    /// ```
319    pub fn of(app: &mut App, context: BuildContext) -> NavigationDrawerThemeData {
320        match context.depend_on_inherited_widget_of_exact_type::<NavigationDrawerTheme>(app) {
321            Some(navigation_drawer_theme) => navigation_drawer_theme.data.clone(),
322            None => Theme::of(app, context).navigation_drawer_theme.clone(),
323        }
324    }
325}
326
327impl InheritedTheme for NavigationDrawerTheme {
328    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
329        NavigationDrawerTheme::new(self.data.clone(), child).into_widget()
330    }
331}
332
333impl InheritedWidget for NavigationDrawerTheme {
334    fn key(&self) -> Option<&KeyRef> {
335        self.key.as_ref()
336    }
337
338    fn child(&self) -> &WidgetRef {
339        &self.child
340    }
341
342    fn update_should_notify(&self, old_widget: &NavigationDrawerTheme) -> bool {
343        self.data != old_widget.data
344    }
345
346    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
347        Some(self)
348    }
349}
350
351impl waft_foundation::Diagnosticable for NavigationDrawerThemeData {
352    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
353        properties.add(DoubleProperty::new("tileHeight", self.tile_height).default_value(None));
354        properties
355            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
356        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
357        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
358        properties.add(
359            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
360        );
361        properties
362            .add(ColorProperty::new("indicatorColor", self.indicator_color).default_value(None));
363        properties.add(
364            DiagnosticsProperty::<ShapeBorderRef>::new(
365                "indicatorShape",
366                self.indicator_shape.clone(),
367            )
368            .default_value(None),
369        );
370        properties.add(
371            DiagnosticsProperty::<Size>::new("indicatorSize", self.indicator_size)
372                .default_value(None),
373        );
374        properties.add(
375            DiagnosticsProperty::<String>::new(
376                "labelTextStyle",
377                self.label_text_style
378                    .as_deref()
379                    .map(|property| property.to_string()),
380            )
381            .default_value(None),
382        );
383        properties.add(
384            DiagnosticsProperty::<String>::new(
385                "iconTheme",
386                self.icon_theme
387                    .as_deref()
388                    .map(|property| property.to_string()),
389            )
390            .default_value(None),
391        );
392    }
393}
394
395impl std::fmt::Display for NavigationDrawerThemeData {
396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use std::rc::Rc;
404
405    use waft_embedder::Size;
406    use waft_painting::{
407        BorderRadiusGeometry, BorderSide, RoundedRectangleBorder, ShapeBorderRef, TextStyle,
408    };
409    use waft_widgets::{IconThemeData, WidgetStatePropertyAll};
410
411    use super::*;
412
413    // navigation_drawer_theme_test.dart 'NavigationDrawerThemeData implements debugFillProperties'.
414    #[test]
415    fn an_assigned_navigation_drawer_theme_describes_every_property() {
416        let theme = NavigationDrawerThemeData::new()
417            .tile_height(50.0)
418            .background_color(Color::new(0x00000099))
419            .elevation(5.0)
420            .shadow_color(Color::new(0x00000098))
421            .surface_tint_color(Color::new(0x00000097))
422            .indicator_color(Color::new(0x00000096))
423            .indicator_shape(RoundedRectangleBorder::new(
424                BorderSide::NONE,
425                BorderRadiusGeometry::circular(2.0),
426            ))
427            .indicator_size(Size::new(10.0, 10.0))
428            .label_text_style(Rc::new(WidgetStatePropertyAll::new(Some(
429                TextStyle::new().font_size(7.0),
430            ))))
431            .icon_theme(Rc::new(WidgetStatePropertyAll::new(Some(
432                IconThemeData::new().color(Color::new(0x00000095)),
433            ))));
434        let description = waft_widgets::testing::describe_properties(|properties| {
435            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
436        });
437        let description: Vec<String> = description
438            .iter()
439            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
440            .collect();
441        assert_eq!(
442            description,
443            [
444                "tileHeight: 50.0".to_string(),
445                format!("backgroundColor: {}", Color::new(0x00000099)),
446                "elevation: 5.0".to_string(),
447                format!("shadowColor: {}", Color::new(0x00000098)),
448                format!("surfaceTintColor: {}", Color::new(0x00000097)),
449                format!("indicatorColor: {}", Color::new(0x00000096)),
450                format!(
451                    "indicatorShape: {}",
452                    ShapeBorderRef::from(RoundedRectangleBorder::new(
453                        BorderSide::NONE,
454                        BorderRadiusGeometry::circular(2.0)
455                    ))
456                ),
457                "indicatorSize: Size(10.0, 10.0)".to_string(),
458                "labelTextStyle: WidgetStatePropertyAll(TextStyle(inherit: true, size: 7.0))"
459                    .to_string(),
460                format!(
461                    "iconTheme: WidgetStatePropertyAll(IconThemeData#00000(color: {}))",
462                    Color::new(0x00000095)
463                ),
464            ]
465        );
466    }
467}