Skip to main content

waft_material/
menu_bar_theme.rs

1//! Flutter counterpart: material_ui's `menu_bar_theme.dart`.
2
3use std::ops::Deref;
4
5use waft_foundation::App;
6use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
7
8use crate::menu_style::MenuStyle;
9use crate::menu_theme::MenuThemeData;
10use crate::theme::Theme;
11
12/// A data class that [`MenuBarTheme`] uses to define the visual properties of
13/// `MenuBar` widgets.
14///
15/// This class defines the visual properties of `MenuBar` widgets themselves,
16/// but not their submenus. Those properties are defined by [`MenuThemeData`] or
17/// `MenuButtonThemeData` instead.
18///
19/// Descendant widgets obtain the current [`MenuBarThemeData`] object using
20/// [`MenuBarTheme::of`].
21///
22/// Typically, a [`MenuBarThemeData`] is specified as part of the overall `Theme`
23/// with `ThemeData::menu_bar_theme`. Otherwise, `MenuTheme` can be used to
24/// configure its own widget subtree.
25///
26/// All [`MenuBarThemeData`] properties are `null` by default. If any of these
27/// properties are null, the menu bar will provide its own defaults.
28///
29/// Dart's `MenuBarThemeData extends MenuThemeData`: it holds the [`MenuThemeData`] it
30/// derefs to, whose `submenu_icon` its constructor never sets.
31///
32/// See also:
33///
34/// * [`MenuThemeData`], which describes the theme for the submenus of a
35///   `MenuBar`.
36/// * `MenuButtonThemeData`, which describes the theme for the `MenuItemButton`s
37///   in a menu.
38/// * `ThemeData`, which describes the overall theme for the application.
39#[derive(Clone, Debug, Default, PartialEq)]
40pub struct MenuBarThemeData {
41    menu_theme_data: MenuThemeData,
42}
43
44impl MenuBarThemeData {
45    /// Creates a const set of properties used to configure `MenuTheme`.
46    pub fn new() -> MenuBarThemeData {
47        MenuBarThemeData::default()
48    }
49
50    /// Dart `MenuBarThemeData(style:)`.
51    pub fn style(mut self, style: MenuStyle) -> MenuBarThemeData {
52        self.menu_theme_data.style = Some(style);
53        self
54    }
55
56    /// Linearly interpolate between two `MenuBar` themes.
57    pub fn lerp(
58        a: Option<&MenuBarThemeData>,
59        b: Option<&MenuBarThemeData>,
60        t: f64,
61    ) -> Option<MenuBarThemeData> {
62        match (a, b) {
63            (None, None) => return None,
64            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
65            _ => {}
66        }
67        let mut data = MenuBarThemeData::new();
68        if let Some(style) = MenuStyle::lerp(
69            a.and_then(|a| a.style.as_ref()),
70            b.and_then(|b| b.style.as_ref()),
71            t,
72        ) {
73            data = data.style(style);
74        }
75        Some(data)
76    }
77}
78
79impl Deref for MenuBarThemeData {
80    type Target = MenuThemeData;
81
82    fn deref(&self) -> &MenuThemeData {
83        &self.menu_theme_data
84    }
85}
86
87/// An inherited widget that defines the configuration for the `MenuBar` widgets
88/// in this widget's descendants.
89///
90/// This class defines the visual properties of `MenuBar` widgets themselves,
91/// but not their submenus. Those properties are defined by `MenuTheme` or
92/// `MenuButtonTheme` instead.
93///
94/// Values specified here are used for `MenuBar`'s properties that are not given
95/// an explicit non-null value.
96///
97/// See also:
98/// * [`MenuStyle`], a configuration object that holds attributes of a menu, and
99///   is used by this theme to define those attributes.
100/// * `MenuTheme`, which does the same thing for the menus created by a
101///   `SubmenuButton` or `MenuAnchor`.
102/// * `MenuButtonTheme`, which does the same thing for the `MenuItemButton`s
103///   inside of the menus.
104/// * `SubmenuButton`, a button that manages a submenu that uses these
105///   properties.
106/// * `MenuBar`, a widget that creates a menu bar that can use `SubmenuButton`s.
107#[derive(Debug)]
108pub struct MenuBarTheme {
109    pub key: Option<KeyRef>,
110    /// The properties to set for `MenuBar` in this widget's descendants.
111    pub data: MenuBarThemeData,
112    pub child: WidgetRef,
113}
114
115impl MenuBarTheme {
116    /// Creates a theme that controls the configurations for `MenuBar` and
117    /// `MenuItemButton` in its widget subtree.
118    #[cfg_attr(debug_assertions, track_caller)]
119    pub fn new<K>(data: MenuBarThemeData, child: impl IntoWidget<K>) -> MenuBarTheme {
120        MenuBarTheme {
121            key: None,
122            data,
123            child: child.into_widget(),
124        }
125    }
126
127    /// Dart `MenuBarTheme(key:)`.
128    pub fn key(mut self, key: KeyRef) -> MenuBarTheme {
129        self.key = Some(key);
130        self
131    }
132
133    /// Returns the closest instance of this class's [`data`](Self::data) value that encloses
134    /// the given context. If there is no ancestor, it returns
135    /// `ThemeData::menu_bar_theme`.
136    ///
137    /// Typical usage is as follows:
138    ///
139    /// ```text
140    /// let theme = MenuBarTheme::of(app, context);
141    /// ```
142    pub fn of(app: &mut App, context: BuildContext) -> MenuBarThemeData {
143        match context.depend_on_inherited_widget_of_exact_type::<MenuBarTheme>(app) {
144            Some(menu_bar_theme) => menu_bar_theme.data.clone(),
145            None => Theme::of(app, context).menu_bar_theme.clone(),
146        }
147    }
148}
149
150impl InheritedTheme for MenuBarTheme {
151    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
152        MenuBarTheme::new(self.data.clone(), child).into_widget()
153    }
154}
155
156impl InheritedWidget for MenuBarTheme {
157    fn key(&self) -> Option<&KeyRef> {
158        self.key.as_ref()
159    }
160
161    fn child(&self) -> &WidgetRef {
162        &self.child
163    }
164
165    fn update_should_notify(&self, old_widget: &MenuBarTheme) -> bool {
166        self.data != old_widget.data
167    }
168
169    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
170        Some(self)
171    }
172}
173
174impl waft_foundation::Diagnosticable for MenuBarThemeData {}
175
176impl std::fmt::Display for MenuBarThemeData {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
179    }
180}
181
182#[cfg(test)]
183mod tests {
184
185    use waft_embedder::Rect;
186    use waft_rendering::BoxConstraints;
187    use waft_widgets::{Axis, Builder, Column, ConstrainedBox, Expanded};
188
189    use waft_widgets::testing::{WidgetTester, find, test_widgets};
190
191    use super::*;
192    use crate::colors::Colors;
193    use crate::material::Material;
194    use crate::menu_anchor::MenuBar;
195    use crate::menu_theme::MenuTheme;
196    use crate::menu_theme::tests::{
197        ThemeTestMenus, assert_constructor_parameters_override_theme_parameters, green_menu_style,
198        menu_panels, overriding_bar, panel_material, red_stadium_menu_style, test_menu,
199        theme_test_menus,
200    };
201    use crate::test_support::material_app;
202    use crate::tooltip::tests::m2;
203
204    /// The bar of `menu_bar_theme_test.dart`'s two widget cases: `MenuTheme(menu_style)` over
205    /// `MenuBarTheme(bar_style)` over `Column([bar, Expanded(Placeholder())])`.
206    fn pump_themed_bar(
207        tester: &mut WidgetTester,
208        menu_theme: MenuThemeData,
209        bar_theme: MenuBarThemeData,
210        bar: impl Fn() -> WidgetRef + 'static,
211    ) {
212        let root = {
213            let app = tester.cell.borrow();
214            material_app(
215                m2(&app),
216                Material::new()
217                    .child(Builder::new(move |_app, _context| {
218                        MenuTheme::new(
219                            menu_theme.clone(),
220                            MenuBarTheme::new(
221                                bar_theme.clone(),
222                                Column::new().children(vec![
223                                    bar(),
224                                    Expanded::new(ConstrainedBox::new(BoxConstraints::expand(
225                                        None, None,
226                                    )))
227                                    .into_widget(),
228                                ]),
229                            ),
230                        )
231                        .into_widget()
232                    }))
233                    .into_widget(),
234            )
235        };
236        tester.pump_widget(root);
237    }
238
239    // menu_bar_theme_test.dart 'MenuBarThemeData lerp special cases'.
240    #[test]
241    fn lerp_of_nothing_is_nothing_and_of_one_theme_with_itself_is_that_theme() {
242        assert!(MenuBarThemeData::lerp(None, None, 0.0).is_none());
243        let data = MenuBarThemeData::new();
244        assert_eq!(
245            MenuBarThemeData::lerp(Some(&data), Some(&data), 0.5),
246            Some(data)
247        );
248    }
249
250    // menu_bar_theme_test.dart 'theme is honored'.
251    #[test]
252    fn a_menu_bar_theme_styles_the_bar_and_a_menu_theme_the_submenus() {
253        test_widgets(|tester| {
254            pump_themed_bar(
255                tester,
256                MenuThemeData::new().style(green_menu_style()),
257                MenuBarThemeData::new().style(red_stadium_menu_style()),
258                || MenuBar::new(theme_test_menus(ThemeTestMenus::default())).into_widget(),
259            );
260
261            // Open a test menu.
262            tester.tap(find::text(test_menu::MAIN_MENU_1));
263            tester.pump();
264            assert_eq!(
265                tester.get_rect(menu_panels(Axis::Horizontal).first()),
266                Rect::from_ltrb(228.0, 0.0, 572.0, 68.0)
267            );
268            panel_material(tester, Axis::Horizontal, |material| {
269                assert_eq!(material.elevation, 15.0);
270                assert_eq!(material.color, Some(Colors::RED.primary()));
271            });
272
273            assert_eq!(
274                tester.get_rect(menu_panels(Axis::Vertical)),
275                Rect::from_ltrb(346.0, 58.0, 560.0, 218.0)
276            );
277            panel_material(tester, Axis::Vertical, |material| {
278                assert_eq!(material.elevation, 20.0);
279                assert_eq!(material.color, Some(Colors::GREEN.primary()));
280            });
281        });
282    }
283
284    // menu_bar_theme_test.dart 'Constructor parameters override theme parameters'.
285    #[test]
286    fn a_menu_bars_and_its_buttons_own_styles_override_the_themes() {
287        test_widgets(|tester| {
288            pump_themed_bar(
289                tester,
290                MenuThemeData::new().style(green_menu_style()),
291                MenuBarThemeData::new().style(red_stadium_menu_style()),
292                overriding_bar,
293            );
294
295            // Open a test menu.
296            tester.tap(find::text(test_menu::MAIN_MENU_1));
297            tester.pump();
298
299            assert_constructor_parameters_override_theme_parameters(tester);
300        });
301    }
302}