Skip to main content

waft_material/
bottom_navigation_bar_theme.rs

1//! Flutter counterpart: material_ui's `bottom_navigation_bar_theme.dart`.
2
3use waft_embedder::{Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{ColorProperty, TextStyle};
6use waft_services::MouseCursorRef;
7use waft_widgets::{
8    BuildContext, IconThemeData, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
9    WidgetStatePropertyRef,
10};
11
12use crate::bottom_navigation_bar::{BottomNavigationBarLandscapeLayout, BottomNavigationBarType};
13use crate::theme::Theme;
14
15/// Defines default property values for descendant `BottomNavigationBar`
16/// widgets.
17///
18/// Descendant widgets obtain the current [`BottomNavigationBarThemeData`] object
19/// using [`BottomNavigationBarTheme::of`]. Instances of
20/// [`BottomNavigationBarThemeData`] can be customized with
21/// [`BottomNavigationBarThemeData::copy_with`].
22///
23/// Typically a [`BottomNavigationBarThemeData`] is specified as part of the
24/// overall `Theme` with `ThemeData::bottom_navigation_bar_theme`.
25///
26/// All [`BottomNavigationBarThemeData`] properties are `None` by default. When
27/// null, the `BottomNavigationBar`'s build method provides defaults.
28///
29/// See also:
30///
31///  * `ThemeData`, which describes the overall theme information for the
32///    application.
33#[derive(Clone, Debug, Default)]
34pub struct BottomNavigationBarThemeData {
35    /// The color of the `BottomNavigationBar` itself.
36    ///
37    /// See `BottomNavigationBar::background_color`.
38    pub background_color: Option<Color>,
39
40    /// The z-coordinate of the `BottomNavigationBar`.
41    ///
42    /// See `BottomNavigationBar::elevation`.
43    pub elevation: Option<f64>,
44
45    /// The size, opacity, and color of the icon in the currently selected
46    /// `BottomNavigationBarItem::icon`.
47    ///
48    /// If `BottomNavigationBar::selected_icon_theme` is non-null on the widget,
49    /// the whole [`IconThemeData`] from the widget will be used over this
50    /// [`selected_icon_theme`](Self::selected_icon_theme).
51    ///
52    /// See `BottomNavigationBar::selected_icon_theme`.
53    pub selected_icon_theme: Option<IconThemeData>,
54
55    /// The size, opacity, and color of the icon in the currently unselected
56    /// `BottomNavigationBarItem::icon`s.
57    ///
58    /// If `BottomNavigationBar::unselected_icon_theme` is non-null on the widget,
59    /// the whole [`IconThemeData`] from the widget will be used over this
60    /// [`unselected_icon_theme`](Self::unselected_icon_theme).
61    ///
62    /// See `BottomNavigationBar::unselected_icon_theme`.
63    pub unselected_icon_theme: Option<IconThemeData>,
64
65    /// The color of the selected `BottomNavigationBarItem::icon` and
66    /// `BottomNavigationBarItem::label`.
67    ///
68    /// See `BottomNavigationBar::selected_item_color`.
69    pub selected_item_color: Option<Color>,
70
71    /// The color of the unselected `BottomNavigationBarItem::icon` and
72    /// `BottomNavigationBarItem::label`s.
73    ///
74    /// See `BottomNavigationBar::unselected_item_color`.
75    pub unselected_item_color: Option<Color>,
76
77    /// The [`TextStyle`] of the `BottomNavigationBarItem` labels when they are
78    /// selected.
79    ///
80    /// See `BottomNavigationBar::selected_label_style`.
81    pub selected_label_style: Option<TextStyle>,
82
83    /// The [`TextStyle`] of the `BottomNavigationBarItem` labels when they are not
84    /// selected.
85    ///
86    /// See `BottomNavigationBar::unselected_label_style`.
87    pub unselected_label_style: Option<TextStyle>,
88
89    /// Whether the labels are shown for the selected `BottomNavigationBarItem`.
90    ///
91    /// See `BottomNavigationBar::show_selected_labels`.
92    pub show_selected_labels: Option<bool>,
93
94    /// Whether the labels are shown for the unselected `BottomNavigationBarItem`s.
95    ///
96    /// See `BottomNavigationBar::show_unselected_labels`.
97    pub show_unselected_labels: Option<bool>,
98
99    /// Defines the layout and behavior of a `BottomNavigationBar`.
100    ///
101    /// See `BottomNavigationBar::type`.
102    pub r#type: Option<BottomNavigationBarType>,
103
104    /// If specified, defines the feedback property for `BottomNavigationBar`.
105    ///
106    /// If `BottomNavigationBar::enable_feedback` is provided,
107    /// [`enable_feedback`](Self::enable_feedback) is ignored.
108    pub enable_feedback: Option<bool>,
109
110    /// If non-null, overrides the `BottomNavigationBar::landscape_layout` property.
111    pub landscape_layout: Option<BottomNavigationBarLandscapeLayout>,
112
113    /// If specified, overrides the default value of `BottomNavigationBar::mouse_cursor`.
114    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
115}
116
117impl BottomNavigationBarThemeData {
118    /// Creates a theme that can be used for `ThemeData::bottom_navigation_bar_theme`;
119    /// Dart's optional named arguments are the fluent setters.
120    pub fn new() -> BottomNavigationBarThemeData {
121        BottomNavigationBarThemeData::default()
122    }
123
124    /// Dart `BottomNavigationBarThemeData(backgroundColor:)`.
125    pub fn background_color(mut self, background_color: Color) -> BottomNavigationBarThemeData {
126        self.background_color = Some(background_color);
127        self
128    }
129
130    /// Dart `BottomNavigationBarThemeData(elevation:)`.
131    pub fn elevation(mut self, elevation: f64) -> BottomNavigationBarThemeData {
132        self.elevation = Some(elevation);
133        self
134    }
135
136    /// Dart `BottomNavigationBarThemeData(selectedIconTheme:)`.
137    pub fn selected_icon_theme(
138        mut self,
139        selected_icon_theme: IconThemeData,
140    ) -> BottomNavigationBarThemeData {
141        self.selected_icon_theme = Some(selected_icon_theme);
142        self
143    }
144
145    /// Dart `BottomNavigationBarThemeData(unselectedIconTheme:)`.
146    pub fn unselected_icon_theme(
147        mut self,
148        unselected_icon_theme: IconThemeData,
149    ) -> BottomNavigationBarThemeData {
150        self.unselected_icon_theme = Some(unselected_icon_theme);
151        self
152    }
153
154    /// Dart `BottomNavigationBarThemeData(selectedItemColor:)`.
155    pub fn selected_item_color(
156        mut self,
157        selected_item_color: Color,
158    ) -> BottomNavigationBarThemeData {
159        self.selected_item_color = Some(selected_item_color);
160        self
161    }
162
163    /// Dart `BottomNavigationBarThemeData(unselectedItemColor:)`.
164    pub fn unselected_item_color(
165        mut self,
166        unselected_item_color: Color,
167    ) -> BottomNavigationBarThemeData {
168        self.unselected_item_color = Some(unselected_item_color);
169        self
170    }
171
172    /// Dart `BottomNavigationBarThemeData(selectedLabelStyle:)`.
173    pub fn selected_label_style(
174        mut self,
175        selected_label_style: TextStyle,
176    ) -> BottomNavigationBarThemeData {
177        self.selected_label_style = Some(selected_label_style);
178        self
179    }
180
181    /// Dart `BottomNavigationBarThemeData(unselectedLabelStyle:)`.
182    pub fn unselected_label_style(
183        mut self,
184        unselected_label_style: TextStyle,
185    ) -> BottomNavigationBarThemeData {
186        self.unselected_label_style = Some(unselected_label_style);
187        self
188    }
189
190    /// Dart `BottomNavigationBarThemeData(showSelectedLabels:)`.
191    pub fn show_selected_labels(
192        mut self,
193        show_selected_labels: bool,
194    ) -> BottomNavigationBarThemeData {
195        self.show_selected_labels = Some(show_selected_labels);
196        self
197    }
198
199    /// Dart `BottomNavigationBarThemeData(showUnselectedLabels:)`.
200    pub fn show_unselected_labels(
201        mut self,
202        show_unselected_labels: bool,
203    ) -> BottomNavigationBarThemeData {
204        self.show_unselected_labels = Some(show_unselected_labels);
205        self
206    }
207
208    /// Dart `BottomNavigationBarThemeData(type:)`.
209    pub fn r#type(mut self, r#type: BottomNavigationBarType) -> BottomNavigationBarThemeData {
210        self.r#type = Some(r#type);
211        self
212    }
213
214    /// Dart `BottomNavigationBarThemeData(enableFeedback:)`.
215    pub fn enable_feedback(mut self, enable_feedback: bool) -> BottomNavigationBarThemeData {
216        self.enable_feedback = Some(enable_feedback);
217        self
218    }
219
220    /// Dart `BottomNavigationBarThemeData(landscapeLayout:)`.
221    pub fn landscape_layout(
222        mut self,
223        landscape_layout: BottomNavigationBarLandscapeLayout,
224    ) -> BottomNavigationBarThemeData {
225        self.landscape_layout = Some(landscape_layout);
226        self
227    }
228
229    /// Dart `BottomNavigationBarThemeData(mouseCursor:)`.
230    pub fn mouse_cursor(
231        mut self,
232        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
233    ) -> BottomNavigationBarThemeData {
234        self.mouse_cursor = Some(mouse_cursor);
235        self
236    }
237
238    /// Creates a copy of this object but with the given fields replaced with the
239    /// new values.
240    ///
241    /// Dart's named arguments are the fluent setters on the copy
242    /// (`data.copy_with().elevation(4.0)`).
243    pub fn copy_with(&self) -> BottomNavigationBarThemeData {
244        self.clone()
245    }
246
247    /// Linearly interpolate between two [`BottomNavigationBarThemeData`].
248    ///
249    /// {@macro dart.ui.shadow.lerp}
250    pub fn lerp(
251        a: Option<&BottomNavigationBarThemeData>,
252        b: Option<&BottomNavigationBarThemeData>,
253        t: f64,
254    ) -> BottomNavigationBarThemeData {
255        if let (Some(a), Some(b)) = (a, b)
256            && std::ptr::eq(a, b)
257        {
258            return a.clone();
259        }
260        BottomNavigationBarThemeData {
261            background_color: Color::lerp(
262                a.and_then(|a| a.background_color),
263                b.and_then(|b| b.background_color),
264                t,
265            ),
266            elevation: lerp_double(a.and_then(|a| a.elevation), b.and_then(|b| b.elevation), t),
267            selected_icon_theme: Some(IconThemeData::lerp(
268                a.and_then(|a| a.selected_icon_theme.as_ref()),
269                b.and_then(|b| b.selected_icon_theme.as_ref()),
270                t,
271            )),
272            unselected_icon_theme: Some(IconThemeData::lerp(
273                a.and_then(|a| a.unselected_icon_theme.as_ref()),
274                b.and_then(|b| b.unselected_icon_theme.as_ref()),
275                t,
276            )),
277            selected_item_color: Color::lerp(
278                a.and_then(|a| a.selected_item_color),
279                b.and_then(|b| b.selected_item_color),
280                t,
281            ),
282            unselected_item_color: Color::lerp(
283                a.and_then(|a| a.unselected_item_color),
284                b.and_then(|b| b.unselected_item_color),
285                t,
286            ),
287            selected_label_style: TextStyle::lerp(
288                a.and_then(|a| a.selected_label_style.as_ref()),
289                b.and_then(|b| b.selected_label_style.as_ref()),
290                t,
291            ),
292            unselected_label_style: TextStyle::lerp(
293                a.and_then(|a| a.unselected_label_style.as_ref()),
294                b.and_then(|b| b.unselected_label_style.as_ref()),
295                t,
296            ),
297            show_selected_labels: pick(a, b, t, |theme| theme.show_selected_labels),
298            show_unselected_labels: pick(a, b, t, |theme| theme.show_unselected_labels),
299            r#type: pick(a, b, t, |theme| theme.r#type),
300            enable_feedback: pick(a, b, t, |theme| theme.enable_feedback),
301            landscape_layout: pick(a, b, t, |theme| theme.landscape_layout),
302            mouse_cursor: pick(a, b, t, |theme| theme.mouse_cursor.clone()),
303        }
304    }
305}
306
307/// Dart's `t < 0.5 ? a?.field : b?.field`.
308fn pick<T>(
309    a: Option<&BottomNavigationBarThemeData>,
310    b: Option<&BottomNavigationBarThemeData>,
311    t: f64,
312    field: impl Fn(&BottomNavigationBarThemeData) -> Option<T>,
313) -> Option<T> {
314    if t < 0.5 {
315        a.and_then(&field)
316    } else {
317        b.and_then(&field)
318    }
319}
320
321impl PartialEq for BottomNavigationBarThemeData {
322    fn eq(&self, other: &BottomNavigationBarThemeData) -> bool {
323        if std::ptr::eq(self, other) {
324            return true;
325        }
326        other.background_color == self.background_color
327            && other.elevation == self.elevation
328            && other.selected_icon_theme == self.selected_icon_theme
329            && other.unselected_icon_theme == self.unselected_icon_theme
330            && other.selected_item_color == self.selected_item_color
331            && other.unselected_item_color == self.unselected_item_color
332            && other.selected_label_style == self.selected_label_style
333            && other.unselected_label_style == self.unselected_label_style
334            && other.show_selected_labels == self.show_selected_labels
335            && other.show_unselected_labels == self.show_unselected_labels
336            && other.r#type == self.r#type
337            && other.enable_feedback == self.enable_feedback
338            && other.landscape_layout == self.landscape_layout
339            && other.mouse_cursor == self.mouse_cursor
340    }
341}
342
343/// Applies a bottom navigation bar theme to descendant `BottomNavigationBar`
344/// widgets.
345///
346/// Descendant widgets obtain the current theme's [`BottomNavigationBarTheme`]
347/// object using [`BottomNavigationBarTheme::of`]. When a widget uses
348/// [`BottomNavigationBarTheme::of`], it is automatically rebuilt if the theme
349/// later changes.
350///
351/// A bottom navigation theme can be specified as part of the overall Material
352/// theme using `ThemeData::bottom_navigation_bar_theme`.
353///
354/// See also:
355///
356///  * [`BottomNavigationBarThemeData`], which describes the actual configuration
357///    of a bottom navigation bar theme.
358#[derive(Debug)]
359pub struct BottomNavigationBarTheme {
360    pub key: Option<KeyRef>,
361    /// The properties used for all descendant `BottomNavigationBar` widgets.
362    pub data: BottomNavigationBarThemeData,
363    pub child: WidgetRef,
364}
365
366impl BottomNavigationBarTheme {
367    /// Constructs a bottom navigation bar theme that configures all descendant
368    /// `BottomNavigationBar` widgets.
369    #[cfg_attr(debug_assertions, track_caller)]
370    pub fn new<K>(
371        data: BottomNavigationBarThemeData,
372        child: impl IntoWidget<K>,
373    ) -> BottomNavigationBarTheme {
374        BottomNavigationBarTheme {
375            key: None,
376            data,
377            child: child.into_widget(),
378        }
379    }
380
381    /// Dart `BottomNavigationBarTheme(key:)`.
382    pub fn key(mut self, key: KeyRef) -> BottomNavigationBarTheme {
383        self.key = Some(key);
384        self
385    }
386
387    /// Returns the configuration [`data`](Self::data) from the closest
388    /// [`BottomNavigationBarTheme`] ancestor. If there is no ancestor, it returns
389    /// `ThemeData::bottom_navigation_bar_theme`. Applications can assume that the
390    /// returned value will not be null.
391    ///
392    /// Typical usage is as follows:
393    ///
394    /// ```text
395    /// let theme = BottomNavigationBarTheme::of(app, context);
396    /// ```
397    pub fn of(app: &mut App, context: BuildContext) -> BottomNavigationBarThemeData {
398        match context.depend_on_inherited_widget_of_exact_type::<BottomNavigationBarTheme>(app) {
399            Some(bottom_nav_theme) => bottom_nav_theme.data.clone(),
400            None => Theme::of(app, context).bottom_navigation_bar_theme.clone(),
401        }
402    }
403}
404
405impl InheritedWidget for BottomNavigationBarTheme {
406    fn key(&self) -> Option<&KeyRef> {
407        self.key.as_ref()
408    }
409
410    fn child(&self) -> &WidgetRef {
411        &self.child
412    }
413
414    fn update_should_notify(&self, old_widget: &BottomNavigationBarTheme) -> bool {
415        self.data != old_widget.data
416    }
417}
418
419impl waft_foundation::Diagnosticable for BottomNavigationBarThemeData {
420    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
421        properties
422            .add(ColorProperty::new("backgroundColor", self.background_color).default_value(None));
423        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(None));
424        properties.add(
425            DiagnosticsProperty::<waft_widgets::IconThemeData>::new(
426                "selectedIconTheme",
427                self.selected_icon_theme.clone(),
428            )
429            .default_value(None),
430        );
431        properties.add(
432            DiagnosticsProperty::<waft_widgets::IconThemeData>::new(
433                "unselectedIconTheme",
434                self.unselected_icon_theme.clone(),
435            )
436            .default_value(None),
437        );
438        properties.add(
439            ColorProperty::new("selectedItemColor", self.selected_item_color).default_value(None),
440        );
441        properties.add(
442            ColorProperty::new("unselectedItemColor", self.unselected_item_color)
443                .default_value(None),
444        );
445        properties.add(
446            DiagnosticsProperty::<TextStyle>::new(
447                "selectedLabelStyle",
448                self.selected_label_style.clone(),
449            )
450            .default_value(None),
451        );
452        properties.add(
453            DiagnosticsProperty::<TextStyle>::new(
454                "unselectedLabelStyle",
455                self.unselected_label_style.clone(),
456            )
457            .default_value(None),
458        );
459        properties.add(
460            DiagnosticsProperty::<bool>::new("showSelectedLabels", self.show_selected_labels)
461                .default_value(None),
462        );
463        properties.add(
464            DiagnosticsProperty::<bool>::new("showUnselectedLabels", self.show_unselected_labels)
465                .default_value(None),
466        );
467        properties.add(
468            DiagnosticsProperty::<waft_foundation::DartEnum<BottomNavigationBarType>>::new(
469                "type",
470                self.r#type.map(waft_foundation::DartEnum),
471            )
472            .default_value(None),
473        );
474        properties.add(
475            DiagnosticsProperty::<bool>::new("enableFeedback", self.enable_feedback)
476                .default_value(None),
477        );
478        properties.add(
479            DiagnosticsProperty::<waft_foundation::DartEnum<BottomNavigationBarLandscapeLayout>>::new(
480                "landscapeLayout",
481                self.landscape_layout.map(waft_foundation::DartEnum),
482            )
483            .default_value(None),
484        );
485        properties.add(
486            DiagnosticsProperty::<String>::new(
487                "mouseCursor",
488                self.mouse_cursor
489                    .as_deref()
490                    .map(|property| property.to_string()),
491            )
492            .default_value(None),
493        );
494    }
495}
496
497impl std::fmt::Display for BottomNavigationBarThemeData {
498    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
499        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    //! The cases of `test/bottom_navigation_bar_theme_test.dart`.
506
507    use std::rc::Rc;
508
509    use waft_embedder::{Color, Offset};
510    use waft_services::SystemMouseCursors;
511    use waft_widgets::{
512        FadeTransition, Opacity, SizedBox, Visibility, WidgetState, WidgetStateMouseCursor,
513        WidgetStateProperty,
514    };
515    use waft_widgets::{IconThemeData, WidgetStatePropertyAll};
516
517    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
518
519    use super::*;
520    use crate::bottom_navigation_bar::BottomNavigationBar;
521    use crate::bottom_navigation_bar::tests::{
522        ac_alarm, color_of, descendants_of_bar, diagonal3, first_text, icon_style, label_transform,
523        material_of, paragraph_style, pump_bar,
524    };
525    use crate::icons::Icons;
526    use crate::theme_data::ThemeData;
527
528    #[test]
529    fn bottom_navigation_bar_theme_data_copy_with_equality_basics() {
530        assert_eq!(
531            BottomNavigationBarThemeData::new(),
532            BottomNavigationBarThemeData::new().copy_with()
533        );
534    }
535
536    #[test]
537    fn bottom_navigation_bar_theme_data_lerp_special_cases() {
538        let data = BottomNavigationBarThemeData::new();
539        assert_eq!(
540            BottomNavigationBarThemeData::lerp(Some(&data), Some(&data), 0.5),
541            data
542        );
543    }
544
545    fn assert_all_none(theme_data: &BottomNavigationBarThemeData) {
546        assert_eq!(theme_data.background_color, None);
547        assert_eq!(theme_data.elevation, None);
548        assert_eq!(theme_data.selected_icon_theme, None);
549        assert_eq!(theme_data.unselected_icon_theme, None);
550        assert_eq!(theme_data.selected_item_color, None);
551        assert_eq!(theme_data.unselected_item_color, None);
552        assert_eq!(theme_data.selected_label_style, None);
553        assert_eq!(theme_data.unselected_label_style, None);
554        assert_eq!(theme_data.show_selected_labels, None);
555        assert_eq!(theme_data.show_unselected_labels, None);
556        assert_eq!(theme_data.r#type, None);
557        assert_eq!(theme_data.landscape_layout, None);
558        assert!(theme_data.mouse_cursor.is_none());
559    }
560
561    #[test]
562    fn bottom_navigation_bar_theme_data_defaults() {
563        let theme_data = BottomNavigationBarThemeData::new();
564        assert_all_none(&theme_data);
565
566        let theme =
567            BottomNavigationBarTheme::new(BottomNavigationBarThemeData::new(), SizedBox::new());
568        assert_all_none(&theme.data);
569    }
570
571    /// Dart's `WidgetStateMouseCursor` given to a theme's `mouseCursor`.
572    fn as_theme_cursor(
573        cursor: WidgetStateMouseCursor,
574    ) -> waft_widgets::WidgetStatePropertyRef<Option<MouseCursorRef>> {
575        <dyn WidgetStateProperty<Option<MouseCursorRef>>>::resolve_with(move |states| {
576            Some(cursor.resolve(states))
577        })
578    }
579
580    fn transform_center(tester: &WidgetTester, text: &str) -> Offset {
581        let transform =
582            tester.ancestor_of_type::<waft_widgets::Transform>(first_text(tester, text));
583        tester.get_rect(transform).center()
584    }
585
586    #[test]
587    fn bottom_navigation_bar_is_themeable() {
588        test_widgets(|tester| {
589            let background_color = Color::new(0xFF000001);
590            let selected_item_color = Color::new(0xFF000002);
591            let unselected_item_color = Color::new(0xFF000003);
592            let selected_icon_theme = IconThemeData::new().size(10.0);
593            let unselected_icon_theme = IconThemeData::new().size(11.0);
594            let selected_text_style = TextStyle::new().font_size(22.0);
595            let unselected_text_style = TextStyle::new().font_size(21.0);
596            let elevation = 9.0;
597
598            let theme = BottomNavigationBarThemeData::new()
599                .background_color(background_color)
600                .selected_item_color(selected_item_color)
601                .unselected_item_color(unselected_item_color)
602                .selected_icon_theme(selected_icon_theme.clone())
603                .unselected_icon_theme(unselected_icon_theme.clone())
604                .elevation(elevation)
605                .show_unselected_labels(true)
606                .show_selected_labels(true)
607                .r#type(BottomNavigationBarType::Fixed)
608                .selected_label_style(selected_text_style.clone())
609                .unselected_label_style(unselected_text_style.clone())
610                .mouse_cursor(
611                    <dyn WidgetStateProperty<Option<MouseCursorRef>>>::resolve_with(|states| {
612                        if states.contains(&WidgetState::Selected) {
613                            return Some(SystemMouseCursors::GRAB.into());
614                        }
615                        Some(SystemMouseCursors::MOVE.into())
616                    }),
617                );
618            pump_bar(
619                tester,
620                move |app| {
621                    ThemeData::builder()
622                        .bottom_navigation_bar_theme(theme)
623                        .build(app)
624                },
625                || BottomNavigationBar::new(ac_alarm()),
626            );
627
628            let selected_font_style = paragraph_style(tester, "AC");
629            let selected_icon = icon_style(tester, Icons::ac_unit());
630            let unselected_icon = icon_style(tester, Icons::access_alarm());
631            assert_eq!(selected_font_style.font_size, selected_font_style.font_size);
632            // Unselected label has a font size of 22 but is scaled down to be font size 21.
633            assert_eq!(
634                label_transform(tester, "Alarm"),
635                diagonal3(
636                    unselected_text_style.font_size.unwrap()
637                        / selected_text_style.font_size.unwrap()
638                )
639            );
640            assert_eq!(color_of(&selected_icon), Some(selected_item_color));
641            assert_eq!(selected_icon.font_size, selected_icon_theme.size);
642            assert_eq!(color_of(&unselected_icon), Some(unselected_item_color));
643            assert_eq!(unselected_icon.font_size, unselected_icon_theme.size);
644            // There should not be any [Opacity] or [FadeTransition] widgets
645            // since showUnselectedLabels and showSelectedLabels are true.
646            assert_eq!(descendants_of_bar::<Opacity>(tester), 0);
647            assert_eq!(descendants_of_bar::<FadeTransition>(tester), 0);
648            assert_eq!(
649                material_of(tester, |material| material.elevation),
650                elevation
651            );
652            assert_eq!(
653                material_of(tester, |material| material.color),
654                Some(background_color)
655            );
656
657            let selected_bar_item = transform_center(tester, "AC");
658            let unselected_bar_item = transform_center(tester, "Alarm");
659            let mut gesture = TestPointer::mouse(1, 0);
660            tester.add_pointer(&mut gesture, Offset::ZERO);
661            tester.move_to(&mut gesture, selected_bar_item, false);
662            tester.pump_and_settle();
663            let grab: MouseCursorRef = SystemMouseCursors::GRAB.into();
664            assert!(*tester.active_cursor(1) == *grab);
665            tester.move_to(&mut gesture, unselected_bar_item, false);
666            tester.pump_and_settle();
667            let move_cursor: MouseCursorRef = SystemMouseCursors::MOVE.into();
668            assert!(*tester.active_cursor(1) == *move_cursor);
669        });
670    }
671
672    #[test]
673    fn bottom_navigation_bar_properties_are_taken_over_the_theme_values() {
674        test_widgets(|tester| {
675            let theme = BottomNavigationBarThemeData::new()
676                .background_color(Color::new(0xFF000001))
677                .selected_item_color(Color::new(0xFF000002))
678                .unselected_item_color(Color::new(0xFF000003))
679                .selected_icon_theme(IconThemeData::new().size(10.0))
680                .unselected_icon_theme(IconThemeData::new().size(11.0))
681                .elevation(9.0)
682                .show_unselected_labels(false)
683                .show_selected_labels(false)
684                .r#type(BottomNavigationBarType::Shifting)
685                .selected_label_style(TextStyle::new().font_size(22.0))
686                .unselected_label_style(TextStyle::new().font_size(21.0))
687                .landscape_layout(BottomNavigationBarLandscapeLayout::Centered)
688                .mouse_cursor(as_theme_cursor(WidgetStateMouseCursor::clickable()));
689
690            let background_color = Color::new(0xFF000004);
691            let selected_item_color = Color::new(0xFF000005);
692            let unselected_item_color = Color::new(0xFF000006);
693            let selected_icon_theme = IconThemeData::new().size(15.0);
694            let unselected_icon_theme = IconThemeData::new().size(16.0);
695            let selected_text_style = TextStyle::new().font_size(25.0);
696            let unselected_text_style = TextStyle::new().font_size(26.0);
697            let elevation = 7.0;
698            let landscape_layout = BottomNavigationBarLandscapeLayout::Spread;
699            let cursor = WidgetStateMouseCursor::textable();
700
701            let (selected_icon_given, unselected_icon_given) =
702                (selected_icon_theme.clone(), unselected_icon_theme.clone());
703            let (selected_text_given, unselected_text_given) =
704                (selected_text_style.clone(), unselected_text_style.clone());
705            pump_bar(
706                tester,
707                move |app| {
708                    ThemeData::builder()
709                        .bottom_navigation_bar_theme(theme)
710                        .build(app)
711                },
712                move || {
713                    BottomNavigationBar::new(ac_alarm())
714                        .background_color(background_color)
715                        .selected_item_color(selected_item_color)
716                        .unselected_item_color(unselected_item_color)
717                        .selected_icon_theme(selected_icon_given)
718                        .unselected_icon_theme(unselected_icon_given)
719                        .elevation(elevation)
720                        .show_unselected_labels(true)
721                        .show_selected_labels(true)
722                        .r#type(BottomNavigationBarType::Fixed)
723                        .selected_label_style(selected_text_given)
724                        .unselected_label_style(unselected_text_given)
725                        .landscape_layout(landscape_layout)
726                        .mouse_cursor(cursor)
727                },
728            );
729
730            let selected_font_style = paragraph_style(tester, "AC");
731            let selected_icon = icon_style(tester, Icons::ac_unit());
732            let unselected_icon = icon_style(tester, Icons::access_alarm());
733            assert_eq!(selected_font_style.font_size, selected_font_style.font_size);
734            // Unselected label has a font size of 22 but is scaled down to be font size 21.
735            assert_eq!(
736                label_transform(tester, "Alarm"),
737                diagonal3(
738                    unselected_text_style.font_size.unwrap()
739                        / selected_text_style.font_size.unwrap()
740                )
741            );
742            assert_eq!(color_of(&selected_icon), Some(selected_item_color));
743            assert_eq!(selected_icon.font_size, selected_icon_theme.size);
744            assert_eq!(color_of(&unselected_icon), Some(unselected_item_color));
745            assert_eq!(unselected_icon.font_size, unselected_icon_theme.size);
746            // There should not be any [Opacity] or [FadeTransition] widgets
747            // since showUnselectedLabels and showSelectedLabels are true.
748            assert_eq!(descendants_of_bar::<Opacity>(tester), 0);
749            assert_eq!(descendants_of_bar::<FadeTransition>(tester), 0);
750            assert_eq!(
751                material_of(tester, |material| material.elevation),
752                elevation
753            );
754            assert_eq!(
755                material_of(tester, |material| material.color),
756                Some(background_color)
757            );
758
759            let bar_item = transform_center(tester, "AC");
760            let mut gesture = TestPointer::mouse(1, 0);
761            tester.add_pointer(&mut gesture, Offset::ZERO);
762            tester.move_to(&mut gesture, bar_item, false);
763            tester.pump_and_settle();
764            let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
765            assert!(*tester.active_cursor(1) == *text);
766        });
767    }
768
769    fn pump_with_labels(tester: &mut WidgetTester, show_selected: bool, show_unselected: bool) {
770        pump_bar(
771            tester,
772            move |app| {
773                ThemeData::builder()
774                    .bottom_navigation_bar_theme(
775                        BottomNavigationBarThemeData::new()
776                            .show_selected_labels(show_selected)
777                            .show_unselected_labels(show_unselected),
778                    )
779                    .build(app)
780            },
781            || BottomNavigationBar::new(ac_alarm()),
782        );
783    }
784
785    fn bar_descendants<W: 'static>(tester: &WidgetTester) -> Vec<waft_widgets::AnyElement> {
786        let bar = find::by_type::<BottomNavigationBar>().evaluate(tester)[0];
787        tester.descendants_of_type::<W>(bar)
788    }
789
790    fn fade_opacity(tester: &WidgetTester, element: waft_widgets::AnyElement) -> f64 {
791        let opacity = tester.widget(element, |fade: &FadeTransition| fade.opacity.clone());
792        opacity.value(&tester.cell.borrow())
793    }
794
795    #[test]
796    fn bottom_navigation_bar_theme_can_be_used_to_hide_all_labels() {
797        test_widgets(|tester| {
798            // Regression test for https://github.com/flutter/flutter/issues/66738.
799            pump_with_labels(tester, false, false);
800
801            let find_visibility = bar_descendants::<Visibility>(tester);
802            assert_eq!(find_visibility.len(), 2);
803            for element in find_visibility {
804                assert!(!tester.widget(element, |visibility: &Visibility| visibility.visible));
805            }
806        });
807    }
808
809    #[test]
810    fn bottom_navigation_bar_theme_can_be_used_to_hide_selected_labels() {
811        test_widgets(|tester| {
812            // Regression test for https://github.com/flutter/flutter/issues/66738.
813            pump_with_labels(tester, false, true);
814
815            let find_fade_transition = bar_descendants::<FadeTransition>(tester);
816            assert_eq!(find_fade_transition.len(), 2);
817            assert_eq!(fade_opacity(tester, find_fade_transition[0]), 0.0);
818            assert_eq!(fade_opacity(tester, find_fade_transition[1]), 1.0);
819        });
820    }
821
822    #[test]
823    fn bottom_navigation_bar_theme_can_be_used_to_hide_unselected_labels() {
824        test_widgets(|tester| {
825            pump_with_labels(tester, true, false);
826
827            let find_fade_transition = bar_descendants::<FadeTransition>(tester);
828            assert_eq!(find_fade_transition.len(), 2);
829            assert_eq!(fade_opacity(tester, find_fade_transition[0]), 1.0);
830            assert_eq!(fade_opacity(tester, find_fade_transition[1]), 0.0);
831        });
832    }
833
834    #[test]
835    fn theme_data_holds_the_bottom_navigation_bar_theme() {
836        test_widgets(|tester| {
837            let app = tester.cell.borrow();
838            let theme = ThemeData::new(&app);
839            assert_eq!(
840                theme.bottom_navigation_bar_theme,
841                BottomNavigationBarThemeData::new()
842            );
843
844            let raised = ThemeData::builder()
845                .bottom_navigation_bar_theme(BottomNavigationBarThemeData::new().elevation(10.0))
846                .build(&app);
847            assert_eq!(raised.bottom_navigation_bar_theme.elevation, Some(10.0));
848            assert_ne!(theme, raised);
849            assert_eq!(
850                theme
851                    .copy_with()
852                    .bottom_navigation_bar_theme(raised.bottom_navigation_bar_theme.clone())
853                    .build(),
854                raised
855            );
856
857            let flat = ThemeData::builder()
858                .bottom_navigation_bar_theme(BottomNavigationBarThemeData::new().elevation(0.0))
859                .build(&app);
860            assert_eq!(
861                ThemeData::lerp(&flat, &raised, 0.5)
862                    .bottom_navigation_bar_theme
863                    .elevation,
864                Some(5.0)
865            );
866        });
867    }
868
869    #[test]
870    fn bottom_navigation_bar_theme_data_lerps_each_field() {
871        let a = BottomNavigationBarThemeData::new()
872            .background_color(Color::new(0xFF000000))
873            .elevation(2.0)
874            .show_selected_labels(true)
875            .r#type(BottomNavigationBarType::Fixed);
876        let b = BottomNavigationBarThemeData::new()
877            .background_color(Color::new(0xFFFFFFFF))
878            .elevation(6.0)
879            .show_selected_labels(false)
880            .r#type(BottomNavigationBarType::Shifting)
881            .selected_label_style(TextStyle::new().font_size(20.0));
882
883        let quarter = BottomNavigationBarThemeData::lerp(Some(&a), Some(&b), 0.25);
884        assert_eq!(quarter.elevation, Some(3.0));
885        assert_eq!(quarter.show_selected_labels, Some(true));
886        assert_eq!(quarter.r#type, Some(BottomNavigationBarType::Fixed));
887        let halfway = BottomNavigationBarThemeData::lerp(Some(&a), Some(&b), 0.5);
888        assert_eq!(
889            halfway.background_color,
890            Color::lerp(
891                Some(Color::new(0xFF000000)),
892                Some(Color::new(0xFFFFFFFF)),
893                0.5
894            )
895        );
896        assert_eq!(halfway.show_selected_labels, Some(false));
897        assert_eq!(halfway.r#type, Some(BottomNavigationBarType::Shifting));
898        assert_eq!(
899            halfway.selected_label_style,
900            TextStyle::lerp(None, Some(&TextStyle::new().font_size(20.0)), 0.5)
901        );
902        assert_eq!(
903            halfway.selected_icon_theme,
904            Some(IconThemeData::lerp(None, None, 0.5))
905        );
906    }
907    // Flutter's "Default BottomNavigationBarThemeData debugFillProperties".
908    #[test]
909    fn a_bottom_navigation_bar_theme_data_describes_nothing_by_default() {
910        assert_eq!(
911            waft_widgets::testing::describe_properties(|properties| {
912                waft_foundation::Diagnosticable::debug_fill_properties(
913                    &BottomNavigationBarThemeData::new(),
914                    properties,
915                )
916            }),
917            Vec::<String>::new()
918        );
919    }
920
921    // bottom_navigation_bar_theme_test.dart 'BottomNavigationBarThemeData implements debugFillProperties'.
922    #[test]
923    fn an_assigned_bottom_navigation_bar_theme_describes_every_property() {
924        let mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>> = Rc::new(
925            WidgetStatePropertyAll::new(Some(SystemMouseCursors::CLICK.into())),
926        );
927        let theme = BottomNavigationBarThemeData::new()
928            .background_color(Color::new(0xfffffff0))
929            .elevation(10.0)
930            .selected_icon_theme(IconThemeData::new().size(1.0))
931            .unselected_icon_theme(IconThemeData::new().size(2.0))
932            .selected_item_color(Color::new(0xfffffff1))
933            .unselected_item_color(Color::new(0xfffffff2))
934            .selected_label_style(TextStyle::new().font_size(3.0))
935            .unselected_label_style(TextStyle::new().font_size(4.0))
936            .show_selected_labels(true)
937            .show_unselected_labels(true)
938            .r#type(BottomNavigationBarType::Fixed)
939            .mouse_cursor(mouse_cursor);
940        let description = waft_widgets::testing::describe_properties(|properties| {
941            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
942        });
943        let description: Vec<String> = description
944            .iter()
945            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
946            .collect();
947        assert_eq!(
948            description,
949            [
950                format!("backgroundColor: {}", Color::new(0xfffffff0)),
951                "elevation: 10.0".to_string(),
952                "selectedIconTheme: IconThemeData#00000(size: 1.0)".to_string(),
953                "unselectedIconTheme: IconThemeData#00000(size: 2.0)".to_string(),
954                format!("selectedItemColor: {}", Color::new(0xfffffff1)),
955                format!("unselectedItemColor: {}", Color::new(0xfffffff2)),
956                "selectedLabelStyle: TextStyle(inherit: true, size: 3.0)".to_string(),
957                "unselectedLabelStyle: TextStyle(inherit: true, size: 4.0)".to_string(),
958                "showSelectedLabels: true".to_string(),
959                "showUnselectedLabels: true".to_string(),
960                "type: BottomNavigationBarType.fixed".to_string(),
961                "mouseCursor: WidgetStatePropertyAll(SystemMouseCursor(click))".to_string(),
962            ]
963        );
964    }
965}