Skip to main content

waft_material/
menu_style.rs

1//! Flutter counterpart: material_ui's `menu_style.dart`.
2//!
3//! A state-dependent field holds a [`WidgetStatePropertyRef`] of `Option<T>`, as
4//! [`ButtonStyle`](crate::ButtonStyle)'s do.
5
6use std::fmt::{self, Debug};
7
8use waft_embedder::{Color, Size, lerp_double};
9use waft_foundation::{DiagnosticPropertiesBuilder, Diagnosticable, DiagnosticsProperty};
10use waft_painting::{AlignmentGeometry, BorderSide, EdgeInsetsGeometry, OutlinedBorderRef};
11use waft_services::MouseCursorRef;
12use waft_widgets::{WidgetStateBorderSide, WidgetStateProperty, WidgetStatePropertyRef};
13
14use crate::theme_data::VisualDensity;
15
16/// The visual properties that menus have in common.
17///
18/// Menus created by `MenuBar` and `MenuAnchor` and their themes have a
19/// [`MenuStyle`] property which defines the visual properties whose default
20/// values are to be overridden. The default values are defined by the
21/// individual menu widgets and are typically based on overall theme's
22/// `ThemeData::color_scheme` and `ThemeData::text_theme`.
23///
24/// All of the [`MenuStyle`] properties are null by default.
25///
26/// Many of the [`MenuStyle`] properties are [`WidgetStateProperty`] objects which
27/// resolve to different values depending on the menu's state. For example the
28/// [`Color`] properties are defined with `WidgetStateProperty<Option<Color>>` and can
29/// resolve to different colors depending on if the menu is pressed, hovered,
30/// focused, disabled, etc.
31///
32/// These properties can override the default value for just one state or all of
33/// them. For example to create a `SubmenuButton` whose background color is the
34/// color scheme’s primary color with 50% opacity, but only when the menu is
35/// pressed, one could write:
36///
37/// ```text
38/// SubmenuButton::new(menu_children, Text::new("Fly me to the moon")).menu_style(
39///     MenuStyle::new().background_color(
40///         <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
41///             if states.contains(&WidgetState::Focused) {
42///                 return Some(primary.with_values(Some(0.5), None, None, None, None));
43///             }
44///             None // Use the component's default.
45///         }),
46///     ),
47/// )
48/// ```
49///
50/// In this case the background color for all other menu states would fall back
51/// to the `SubmenuButton`'s default values. To unconditionally set the menu's
52/// [`background_color`](Self::background_color) for all states one could write:
53///
54/// ```text
55/// SubmenuButton::new(menu_children, Text::new("Let me play among the stars")).menu_style(
56///     MenuStyle::new().background_color(Rc::new(WidgetStatePropertyAll::new(Some(
57///         Colors::GREEN.primary(),
58///     )))),
59/// )
60/// ```
61///
62/// To configure all of the application's menus in the same way, specify the
63/// overall theme's `menu_theme`:
64///
65/// ```text
66/// MaterialApp::new().theme(ThemeData::new().menu_theme(MenuThemeData::new().style(
67///     MenuStyle::new().background_color(Rc::new(WidgetStatePropertyAll::new(Some(
68///         Colors::RED.primary(),
69///     )))),
70/// )))
71/// ```
72///
73/// See also:
74///
75/// * `MenuAnchor`, a widget which hosts cascading menus.
76/// * `MenuBar`, a widget which defines a menu bar of buttons hosting cascading
77///   menus.
78/// * `MenuButtonTheme`, the theme for `SubmenuButton`s and `MenuItemButton`s.
79/// * [`ButtonStyle`](crate::ButtonStyle), a similar configuration object for button styles.
80#[derive(Clone, Default)]
81pub struct MenuStyle {
82    /// The menu's background fill color.
83    pub background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
84
85    /// The shadow color of the menu's `Material`.
86    ///
87    /// The material's elevation shadow can be difficult to see for dark themes,
88    /// so by default the menu classes add a semi-transparent overlay to indicate
89    /// elevation. See `ThemeData::apply_elevation_overlay_color`.
90    pub shadow_color: Option<WidgetStatePropertyRef<Option<Color>>>,
91
92    /// The surface tint color of the menu's `Material`.
93    ///
94    /// See `Material::surface_tint_color` for more details.
95    pub surface_tint_color: Option<WidgetStatePropertyRef<Option<Color>>>,
96
97    /// The elevation of the menu's `Material`.
98    pub elevation: Option<WidgetStatePropertyRef<Option<f64>>>,
99
100    /// The padding between the menu's boundary and its child.
101    pub padding: Option<WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>>,
102
103    /// The minimum size of the menu itself.
104    ///
105    /// This value must be less than or equal to [`maximum_size`](Self::maximum_size).
106    pub minimum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
107
108    /// The menu's size.
109    ///
110    /// This size is still constrained by the style's [`minimum_size`](Self::minimum_size) and
111    /// [`maximum_size`](Self::maximum_size). Fixed size dimensions whose value is
112    /// [`f64::INFINITY`] are ignored.
113    ///
114    /// To specify menus with a fixed width and the default height use
115    /// `fixed_size(Size::from_width(320.0))`. Similarly, to specify a fixed height and the
116    /// default width use `fixed_size(Size::from_height(100.0))`.
117    pub fixed_size: Option<WidgetStatePropertyRef<Option<Size>>>,
118
119    /// The maximum size of the menu itself.
120    ///
121    /// A `Size::INFINITE` or null value for this property means that the menu's
122    /// maximum size is not constrained.
123    ///
124    /// This value must be greater than or equal to [`minimum_size`](Self::minimum_size).
125    pub maximum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
126
127    /// The color and weight of the menu's outline.
128    ///
129    /// This value is combined with [`shape`](Self::shape) to create a shape decorated with an
130    /// outline.
131    pub side: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
132
133    /// The shape of the menu's underlying `Material`.
134    ///
135    /// This shape is combined with [`side`](Self::side) to create a shape decorated with an
136    /// outline.
137    pub shape: Option<WidgetStatePropertyRef<Option<OutlinedBorderRef>>>,
138
139    /// The cursor for a mouse pointer when it enters or is hovering over this
140    /// menu's `InkWell`.
141    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
142
143    /// Defines how compact the menu's layout will be.
144    ///
145    /// See also:
146    ///
147    ///  * `ThemeData::visual_density`, which specifies the
148    ///    [`visual_density`](Self::visual_density) for all widgets within a `Theme`.
149    pub visual_density: Option<VisualDensity>,
150
151    /// Determines the desired alignment of the submenu when opened relative to
152    /// the button that opens it.
153    ///
154    /// If there isn't sufficient space to open the menu with the given alignment,
155    /// and there's space on the other side of the button, then the alignment is
156    /// swapped to it's opposite (1 becomes -1, etc.), and the menu will try to
157    /// appear on the other side of the button. If there isn't enough space there
158    /// either, then the menu will be pushed as far over as necessary to display
159    /// as much of itself as possible, possibly overlapping the parent button.
160    pub alignment: Option<AlignmentGeometry>,
161}
162
163crate::theme_data_getters::theme_data_getters! {
164    /// Dart's getters of `MenuStyle`: the theme data answers with its fields, and a defaults
165    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
166    /// are read.
167    pub trait MenuStyleGetters for MenuStyle, fields: menu_style {
168        background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
169        shadow_color: Option<WidgetStatePropertyRef<Option<Color>>>,
170        surface_tint_color: Option<WidgetStatePropertyRef<Option<Color>>>,
171        elevation: Option<WidgetStatePropertyRef<Option<f64>>>,
172        padding: Option<WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>>,
173        minimum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
174        fixed_size: Option<WidgetStatePropertyRef<Option<Size>>>,
175        maximum_size: Option<WidgetStatePropertyRef<Option<Size>>>,
176        side: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
177        shape: Option<WidgetStatePropertyRef<Option<OutlinedBorderRef>>>,
178        mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
179        visual_density: Option<VisualDensity>,
180        alignment: Option<AlignmentGeometry>,
181    }
182}
183
184/// The fluent setters of Dart's named `MenuStyle` arguments, which `copyWith` shares.
185macro_rules! menu_style_setters {
186    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
187        $(
188            #[doc = concat!("Dart `MenuStyle(", $dart, ":)`.")]
189            pub fn $field(mut self, $field: $ty) -> MenuStyle {
190                self.$field = Some($field);
191                self
192            }
193        )*
194    };
195}
196
197impl MenuStyle {
198    /// Create a [`MenuStyle`].
199    pub fn new() -> MenuStyle {
200        MenuStyle::default()
201    }
202
203    menu_style_setters!(
204        background_color: WidgetStatePropertyRef<Option<Color>> => "backgroundColor",
205        shadow_color: WidgetStatePropertyRef<Option<Color>> => "shadowColor",
206        surface_tint_color: WidgetStatePropertyRef<Option<Color>> => "surfaceTintColor",
207        elevation: WidgetStatePropertyRef<Option<f64>> => "elevation",
208        padding: WidgetStatePropertyRef<Option<EdgeInsetsGeometry>> => "padding",
209        minimum_size: WidgetStatePropertyRef<Option<Size>> => "minimumSize",
210        fixed_size: WidgetStatePropertyRef<Option<Size>> => "fixedSize",
211        maximum_size: WidgetStatePropertyRef<Option<Size>> => "maximumSize",
212        side: WidgetStatePropertyRef<Option<BorderSide>> => "side",
213        shape: WidgetStatePropertyRef<Option<OutlinedBorderRef>> => "shape",
214        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>> => "mouseCursor",
215        visual_density: VisualDensity => "visualDensity",
216        alignment: AlignmentGeometry => "alignment",
217    );
218
219    /// Returns a copy of this MenuStyle with the given fields replaced with
220    /// the new values.
221    ///
222    /// Chain setters: `style.copy_with().elevation(e)`.
223    pub fn copy_with(&self) -> MenuStyle {
224        self.clone()
225    }
226
227    /// Returns a copy of this MenuStyle where the non-null fields in `style`
228    /// have replaced the corresponding null fields in this MenuStyle.
229    ///
230    /// In other words, `style` is used to fill in unspecified (null) fields
231    /// this MenuStyle.
232    pub fn merge(&self, style: Option<&MenuStyle>) -> MenuStyle {
233        let Some(style) = style else {
234            return self.clone();
235        };
236        MenuStyle {
237            background_color: self
238                .background_color
239                .clone()
240                .or_else(|| style.background_color.clone()),
241            shadow_color: self
242                .shadow_color
243                .clone()
244                .or_else(|| style.shadow_color.clone()),
245            surface_tint_color: self
246                .surface_tint_color
247                .clone()
248                .or_else(|| style.surface_tint_color.clone()),
249            elevation: self.elevation.clone().or_else(|| style.elevation.clone()),
250            padding: self.padding.clone().or_else(|| style.padding.clone()),
251            minimum_size: self
252                .minimum_size
253                .clone()
254                .or_else(|| style.minimum_size.clone()),
255            fixed_size: self.fixed_size.clone().or_else(|| style.fixed_size.clone()),
256            maximum_size: self
257                .maximum_size
258                .clone()
259                .or_else(|| style.maximum_size.clone()),
260            side: self.side.clone().or_else(|| style.side.clone()),
261            shape: self.shape.clone().or_else(|| style.shape.clone()),
262            mouse_cursor: self
263                .mouse_cursor
264                .clone()
265                .or_else(|| style.mouse_cursor.clone()),
266            visual_density: self.visual_density.or(style.visual_density),
267            alignment: self.alignment.or(style.alignment),
268        }
269    }
270
271    /// Linearly interpolate between two [`MenuStyle`]s.
272    pub fn lerp(a: Option<&MenuStyle>, b: Option<&MenuStyle>, t: f64) -> Option<MenuStyle> {
273        match (a, b) {
274            (None, None) => return None,
275            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
276            _ => {}
277        }
278        Some(MenuStyle {
279            background_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
280                a.and_then(|a| a.background_color.clone()),
281                b.and_then(|b| b.background_color.clone()),
282                t,
283                Color::lerp,
284            ),
285            shadow_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
286                a.and_then(|a| a.shadow_color.clone()),
287                b.and_then(|b| b.shadow_color.clone()),
288                t,
289                Color::lerp,
290            ),
291            surface_tint_color: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
292                a.and_then(|a| a.surface_tint_color.clone()),
293                b.and_then(|b| b.surface_tint_color.clone()),
294                t,
295                Color::lerp,
296            ),
297            elevation: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
298                a.and_then(|a| a.elevation.clone()),
299                b.and_then(|b| b.elevation.clone()),
300                t,
301                lerp_double,
302            ),
303            padding: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
304                a.and_then(|a| a.padding.clone()),
305                b.and_then(|b| b.padding.clone()),
306                t,
307                EdgeInsetsGeometry::lerp,
308            ),
309            minimum_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
310                a.and_then(|a| a.minimum_size.clone()),
311                b.and_then(|b| b.minimum_size.clone()),
312                t,
313                Size::lerp,
314            ),
315            fixed_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
316                a.and_then(|a| a.fixed_size.clone()),
317                b.and_then(|b| b.fixed_size.clone()),
318                t,
319                Size::lerp,
320            ),
321            maximum_size: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
322                a.and_then(|a| a.maximum_size.clone()),
323                b.and_then(|b| b.maximum_size.clone()),
324                t,
325                Size::lerp,
326            ),
327            side: WidgetStateBorderSide::lerp(
328                a.and_then(|a| a.side.clone()),
329                b.and_then(|b| b.side.clone()),
330                t,
331            ),
332            shape: <dyn WidgetStateProperty<Option<_>>>::lerp_optional(
333                a.and_then(|a| a.shape.clone()),
334                b.and_then(|b| b.shape.clone()),
335                t,
336                |a, b, t| OutlinedBorderRef::lerp(a.as_ref(), b.as_ref(), t),
337            ),
338            mouse_cursor: if t < 0.5 {
339                a.and_then(|a| a.mouse_cursor.clone())
340            } else {
341                b.and_then(|b| b.mouse_cursor.clone())
342            },
343            visual_density: if t < 0.5 {
344                a.and_then(|a| a.visual_density)
345            } else {
346                b.and_then(|b| b.visual_density)
347            },
348            alignment: AlignmentGeometry::lerp(
349                a.and_then(|a| a.alignment),
350                b.and_then(|b| b.alignment),
351                t,
352            ),
353        })
354    }
355}
356
357impl PartialEq for MenuStyle {
358    fn eq(&self, other: &MenuStyle) -> bool {
359        if std::ptr::eq(self, other) {
360            return true;
361        }
362        other.background_color == self.background_color
363            && other.shadow_color == self.shadow_color
364            && other.surface_tint_color == self.surface_tint_color
365            && other.elevation == self.elevation
366            && other.padding == self.padding
367            && other.minimum_size == self.minimum_size
368            && other.fixed_size == self.fixed_size
369            && other.maximum_size == self.maximum_size
370            && other.side == self.side
371            && other.shape == self.shape
372            && other.mouse_cursor == self.mouse_cursor
373            && other.visual_density == self.visual_density
374            && other.alignment == self.alignment
375    }
376}
377
378impl Debug for MenuStyle {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        let mut properties = f.debug_struct("MenuStyle");
381        macro_rules! property {
382            ($($field:ident),* $(,)?) => {
383                $(
384                    if let Some(value) = &self.$field {
385                        properties.field(stringify!($field), value);
386                    }
387                )*
388            };
389        }
390        property!(
391            background_color,
392            shadow_color,
393            surface_tint_color,
394            elevation,
395            padding,
396            minimum_size,
397            fixed_size,
398            maximum_size,
399            side,
400            shape,
401            mouse_cursor,
402            visual_density,
403            alignment,
404        );
405        properties.finish()
406    }
407}
408
409impl Diagnosticable for MenuStyle {
410    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
411        macro_rules! property {
412            ($(($field:ident, $name:literal)),* $(,)?) => {
413                $(
414                    properties.add(
415                        DiagnosticsProperty::<String>::new(
416                            $name,
417                            self.$field.as_ref().map(|property| property.to_string()),
418                        )
419                        .default_value(None),
420                    );
421                )*
422            };
423        }
424        property!(
425            (background_color, "backgroundColor"),
426            (shadow_color, "shadowColor"),
427            (surface_tint_color, "surfaceTintColor"),
428            (elevation, "elevation"),
429            (padding, "padding"),
430            (minimum_size, "minimumSize"),
431            (fixed_size, "fixedSize"),
432            (maximum_size, "maximumSize"),
433            (side, "side"),
434        );
435        properties.add(
436            DiagnosticsProperty::<String>::new(
437                "shape",
438                self.shape.as_ref().map(|property| property.to_string()),
439            )
440            .default_value(None),
441        );
442        properties.add(
443            DiagnosticsProperty::<String>::new(
444                "mouseCursor",
445                self.mouse_cursor
446                    .as_ref()
447                    .map(|property| property.to_string()),
448            )
449            .default_value(None),
450        );
451        properties.add(
452            DiagnosticsProperty::<crate::theme_data::VisualDensity>::new(
453                "visualDensity",
454                self.visual_density,
455            )
456            .default_value(None),
457        );
458        properties.add(
459            DiagnosticsProperty::<AlignmentGeometry>::new("alignment", self.alignment)
460                .default_value(None),
461        );
462    }
463}
464
465/// Dart's `MenuStyle.toString`, through its diagnostics.
466impl fmt::Display for MenuStyle {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        f.write_str(&Diagnosticable::to_string(self))
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use std::rc::Rc;
475
476    use waft_embedder::Rect;
477    use waft_rendering::BoxConstraints;
478    use waft_widgets::{
479        Column, ConstrainedBox, Expanded, IntoWidget, Text, WidgetRef, WidgetStatePropertyAll,
480    };
481
482    use waft_widgets::testing::{Finder, WidgetTester, find, test_widgets};
483
484    use super::*;
485    use crate::material::Material;
486    use crate::menu_anchor::{MenuBar, MenuItemButton, MenuPanel, SubmenuButton};
487    use crate::menu_bar_theme::{MenuBarTheme, MenuBarThemeData};
488    use crate::menu_theme::{MenuTheme, MenuThemeData};
489    use crate::test_support::material_app;
490    use crate::theme_data::ThemeData;
491    use crate::tooltip::tests::{m2, m3};
492
493    fn all<T: Clone + Debug + PartialEq + 'static>(value: T) -> WidgetStatePropertyRef<Option<T>> {
494        Rc::new(WidgetStatePropertyAll::new(Some(value)))
495    }
496
497    /// Dart's `createTestMenus(onPressed: (TestMenu menu) {})` of `menu_style_test.dart`.
498    fn test_menus() -> Vec<WidgetRef> {
499        let item = |label: &str| {
500            MenuItemButton::new()
501                .on_pressed(waft_foundation::Listener::new(|_app| {}))
502                .child(Text::new(label))
503                .into_widget()
504        };
505        vec![
506            SubmenuButton::new(
507                vec![
508                    item("Sub Menu 00"),
509                    item("Sub Menu 01"),
510                    item("Sub Menu 02"),
511                ],
512                Some(Text::new("Menu 0")),
513            )
514            .into_widget(),
515            SubmenuButton::new(
516                vec![
517                    item("Sub Menu 10"),
518                    SubmenuButton::new(
519                        vec![
520                            item("Sub Sub Menu 110"),
521                            item("Sub Sub Menu 111"),
522                            item("Sub Sub Menu 112"),
523                            item("Sub Sub Menu 113"),
524                        ],
525                        Some(Text::new("Sub Menu 11")),
526                    )
527                    .into_widget(),
528                    item("Sub Menu 12"),
529                ],
530                Some(Text::new("Menu 1")),
531            )
532            .into_widget(),
533            SubmenuButton::new(
534                // Always disabled.
535                vec![
536                    MenuItemButton::new()
537                        .child(Text::new("Sub Menu 20"))
538                        .into_widget(),
539                ],
540                Some(Text::new("Menu 2")),
541            )
542            .into_widget(),
543        ]
544    }
545
546    /// `MaterialApp(theme:, home: Material(child: Column([MenuBarTheme(bar_style,
547    /// MenuTheme(menu_style, MenuBar(test_menus))), Expanded(Placeholder())])))`.
548    fn pump_themed_bar(
549        tester: &mut WidgetTester,
550        theme: impl FnOnce(&waft_foundation::App) -> ThemeData,
551        bar_style: MenuStyle,
552        menu_style: MenuStyle,
553    ) {
554        let root = {
555            let app = tester.cell.borrow();
556            material_app(
557                theme(&app),
558                Material::new()
559                    .child(Column::new().children(vec![
560                        MenuBarTheme::new(
561                            MenuBarThemeData::new().style(bar_style),
562                            MenuTheme::new(
563                                MenuThemeData::new().style(menu_style),
564                                MenuBar::new(test_menus()),
565                            ),
566                        )
567                        .into_widget(),
568                        Expanded::new(ConstrainedBox::new(BoxConstraints::expand(None, None)))
569                            .into_widget(),
570                    ]))
571                    .into_widget(),
572            )
573        };
574        tester.pump_widget(root);
575    }
576
577    /// Dart's `findMenuPanels()`.
578    fn menu_panels() -> Finder {
579        find::by_type::<MenuPanel>()
580    }
581
582    /// Opens the first menu: Dart's "Have to open a menu initially to start things going."
583    fn open_first_menu(tester: &mut WidgetTester) {
584        tester.tap(find::text("Menu 0"));
585        tester.pump();
586    }
587
588    // menu_style_test.dart 'MenuStyle lerp special cases'.
589    #[test]
590    fn lerp_of_nothing_is_nothing_and_of_one_style_with_itself_is_that_style() {
591        assert!(MenuStyle::lerp(None, None, 0.0).is_none());
592        let data = MenuStyle::new();
593        assert_eq!(MenuStyle::lerp(Some(&data), Some(&data), 0.5), Some(data));
594    }
595
596    // menu_style_test.dart 'fixedSize affects geometry'.
597    #[test]
598    fn a_fixed_size_sizes_the_menu_bar_and_its_menus() {
599        test_widgets(|tester| {
600            pump_themed_bar(
601                tester,
602                m3,
603                MenuStyle::new().fixed_size(all(waft_embedder::Size::new(600.0, 60.0))),
604                MenuStyle::new().fixed_size(all(waft_embedder::Size::new(100.0, 100.0))),
605            );
606            open_first_menu(tester);
607
608            // MenuBarTheme affects MenuBar.
609            let panels = menu_panels();
610            assert_eq!(
611                tester.get_rect(panels.clone().at(0)),
612                Rect::from_ltrb(100.0, 0.0, 700.0, 60.0)
613            );
614            assert_eq!(
615                tester.get_rect(panels.clone().at(0)).size(),
616                waft_embedder::Size::new(600.0, 60.0)
617            );
618
619            // MenuTheme affects menus.
620            assert_eq!(
621                tester.get_rect(panels.clone().at(1)),
622                Rect::from_ltrb(104.0, 54.0, 204.0, 154.0)
623            );
624            assert_eq!(
625                tester.get_rect(panels.clone().at(1)).size(),
626                waft_embedder::Size::new(100.0, 100.0)
627            );
628        });
629    }
630
631    // menu_style_test.dart 'maximumSize affects geometry'.
632    #[test]
633    fn a_maximum_size_limits_the_menu_bar_and_its_menus() {
634        test_widgets(|tester| {
635            pump_themed_bar(
636                tester,
637                m3,
638                MenuStyle::new().maximum_size(all(waft_embedder::Size::new(250.0, 40.0))),
639                MenuStyle::new().maximum_size(all(waft_embedder::Size::new(100.0, 100.0))),
640            );
641            open_first_menu(tester);
642
643            // MenuBarTheme affects MenuBar.
644            let panels = menu_panels();
645            assert_eq!(
646                tester.get_rect(panels.clone().at(0)),
647                Rect::from_ltrb(275.0, 0.0, 525.0, 40.0)
648            );
649            assert_eq!(
650                tester.get_rect(panels.clone().at(0)).size(),
651                waft_embedder::Size::new(250.0, 40.0)
652            );
653
654            // MenuTheme affects menus.
655            assert_eq!(
656                tester.get_rect(panels.clone().at(1)),
657                Rect::from_ltrb(279.0, 44.0, 379.0, 144.0)
658            );
659            assert_eq!(
660                tester.get_rect(panels.clone().at(1)).size(),
661                waft_embedder::Size::new(100.0, 100.0)
662            );
663        });
664    }
665
666    // menu_style_test.dart 'minimumSize affects geometry'.
667    #[test]
668    fn a_minimum_size_grows_the_menu_bar_and_its_menus() {
669        test_widgets(|tester| {
670            pump_themed_bar(
671                tester,
672                m3,
673                MenuStyle::new().minimum_size(all(waft_embedder::Size::new(400.0, 60.0))),
674                MenuStyle::new().minimum_size(all(waft_embedder::Size::new(300.0, 300.0))),
675            );
676            open_first_menu(tester);
677
678            // MenuBarTheme affects MenuBar.
679            let panels = menu_panels();
680            assert_eq!(
681                tester.get_rect(panels.clone().at(0)),
682                Rect::from_ltrb(200.0, 0.0, 600.0, 60.0)
683            );
684            assert_eq!(
685                tester.get_rect(panels.clone().at(0)).size(),
686                waft_embedder::Size::new(400.0, 60.0)
687            );
688
689            // MenuTheme affects menus.
690            assert_eq!(
691                tester.get_rect(panels.clone().at(1)),
692                Rect::from_ltrb(204.0, 54.0, 504.0, 354.0)
693            );
694            assert_eq!(
695                tester.get_rect(panels.clone().at(1)).size(),
696                waft_embedder::Size::new(300.0, 300.0)
697            );
698        });
699    }
700
701    // menu_style_test.dart 'visual density'.
702    #[test]
703    fn a_menu_styles_visual_density_spaces_the_bar_and_its_menus() {
704        test_widgets(|tester| {
705            pump_themed_bar(
706                tester,
707                m2,
708                MenuStyle::new().visual_density(VisualDensity::new(1.5, -1.5)),
709                MenuStyle::new().visual_density(VisualDensity::new(0.5, -0.5)),
710            );
711            tester.pump();
712
713            let bar = find::by_type::<MenuBar>();
714            assert_eq!(
715                tester.get_rect(&bar),
716                Rect::from_ltrb(228.0, 0.0, 572.0, 48.0)
717            );
718
719            // Open and make sure things are the right size.
720            tester.tap(find::text("Menu 1"));
721            tester.pump();
722
723            assert_eq!(
724                tester.get_rect(&bar),
725                Rect::from_ltrb(228.0, 0.0, 572.0, 48.0)
726            );
727            assert_eq!(
728                tester.get_rect(find::text("Sub Menu 10")),
729                Rect::from_ltrb(372.0, 70.0, 565.0, 84.0)
730            );
731            let materials = find::ancestor(find::text("Sub Menu 10"), find::by_type::<Material>());
732            assert_eq!(
733                tester.get_rect(materials.at(1)),
734                Rect::from_ltrb(352.0, 48.0, 585.0, 190.0)
735            );
736        });
737    }
738    /// `menu_anchor_test.dart`, "MenuBar's MenuStyle is used": a `MenuStyle` prints its
739    /// diagnostics with the hash ignored; the color is the `Color` the port stores, not
740    /// Dart's `MaterialColor` swatch wrapper.
741    #[test]
742    fn a_menu_style_describes_its_properties() {
743        use waft_embedder::Color;
744        use waft_rendering::testing::ignoring_hash_codes;
745
746        let red = Color::new(0xfff44336);
747        let style = MenuStyle::new()
748            .background_color(all(red))
749            .elevation(all(10.0));
750        assert_eq!(
751            ignoring_hash_codes(&format!("{style}")),
752            format!(
753                "MenuStyle#00000(backgroundColor: WidgetStatePropertyAll({red}), elevation: WidgetStatePropertyAll(10.0))"
754            )
755        );
756    }
757}