Skip to main content

waft_material/
menu_anchor.rs

1//! Flutter counterpart: material_ui's `menu_anchor.dart`.
2//!
3//! A [`MenuAnchor`] shows a Material menu over a [`RawMenuAnchor`]; a [`MenuBar`] is a
4//! [`RawMenuAnchorGroup`] of top-level [`SubmenuButton`]s. Every menu in the tree finds the
5//! menu that holds it through the nearest `_MenuAnchorScope`, which an anchor builds above its
6//! button and its overlay: a scope's state is the anchor of the widgets below it, so a widget
7//! that reads it from its own context gets the menu it sits in, never one it owns.
8
9#![allow(deprecated)]
10
11use std::any::{Any, TypeId};
12use std::collections::HashMap;
13use std::fmt::{self, Debug};
14use std::rc::Rc;
15use std::time::Duration;
16
17use unicode_segmentation::UnicodeSegmentation;
18use waft_animation::{
19    Animation, AnimationController, AnimationRef, AnimationStatus, AnimationStatusListener, Cubic,
20    Curve, CurvedAnimation, FlippedCurve, Interval,
21};
22use waft_embedder::{
23    Clip, Color, Offset, Rect, Size, TargetPlatform, TextDecoration, TextDirection, lerp_double,
24};
25use waft_foundation::{
26    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, EnumProperty, FlagProperty, Handle,
27    HandleId, Listener, OptionRetained, Ref, StringProperty, Timer, ValueChanged, VoidCallback,
28};
29use waft_gestures::{PointerDownEvent, PointerExitEvent, PointerHoverEvent};
30use waft_painting::{
31    Alignment, AlignmentGeometry, Axis, EdgeInsets, EdgeInsetsGeometry, InlineSpanRef,
32    OutlinedBorderRef, ShapeBorderRef, TextSpan,
33};
34use waft_rendering::{
35    BoxConstraints, CrossAxisAlignment, HitTestBehavior, LayerLink, MainAxisAlignment,
36    MainAxisSize, SingleChildLayoutDelegate,
37};
38use waft_scheduler::{
39    FrameCallback, SchedulerBinding, Ticker, TickerCallback, TickerProviderObject,
40};
41use waft_services::{
42    HardwareKeyboard, KeyEvent, KeyEventCallback, LogicalKeyboardKey, MouseCursor, MouseCursorRef,
43};
44use waft_widgets::{
45    Action, ActionData, ActionRef, Actions, ActivateIntent, AnimatedBuilder, AnyFocusNode,
46    AnyMenuController, AnyScrollController, BuildContext, Builder, CharacterActivator,
47    ClampingScrollPhysics, ClipRect, CompositedTransformFollower, CompositedTransformTarget,
48    ConstrainedBox, CustomSingleChildLayout, DefaultTextStyle, DirectionalFocusIntent,
49    Directionality, DismissIntent, DismissMenuAction, ExcludeFocus, ExcludeSemantics, Expanded,
50    FadeTransition, Flex, FocusManager, FocusNode, FocusNodeLeaf, FocusNodeRef, FocusScope,
51    FocusScopeNode, FocusTraversalGroup, FocusTraversalPolicy, GlobalKey, IgnorePointer,
52    InheritedWidget, IntoWidget, IntrinsicHeight, IntrinsicWidth, KeyRef, MediaQuery,
53    MediaQueryData, MenuController, MenuControllerRef, MenuSerializableShortcutRef, MergeSemantics,
54    MouseRegion, NextFocusIntent, Padding, PreviousFocusIntent, PrimaryScrollController,
55    RawMenuAnchor, RawMenuAnchorGroup, RawMenuOverlayInfo, ReadingOrderTraversalPolicy, RichText,
56    Row, ScrollConfiguration, ScrollController, ScrollControllerLeaf, ScrollPhysicsRef, Semantics,
57    ShortcutActivatorRef, ShortcutMap, ShortcutRegistry, ShortcutRegistryEntry, Shortcuts,
58    SingleActivator, SingleChildScrollView, SingleTickerProviderStateMixin,
59    SingleTickerProviderStateMixinData, State, StateData, StatefulWidget, StatelessWidget,
60    TapRegion, Text, TraversalDirection, UnconstrainedBox, View, VoidCallbackIntent, WidgetRef,
61    WidgetState, WidgetStateMouseCursor, WidgetStatePropertyRef, WidgetStates,
62    WidgetStatesController, debug_check_has_overlay, downcast_widget,
63};
64
65use crate::button_style::{ButtonStyle, ButtonStyleGetters};
66use crate::checkbox::Checkbox;
67use crate::generated::menu_defaults_m3::{MenuBarDefaultsM3, MenuButtonDefaultsM3, MenuDefaultsM3};
68use crate::icons::Icons;
69use crate::ink_well::InteractiveInkFeatureFactoryRef;
70use crate::material::{Material, MaterialType};
71use crate::material_localizations::MaterialLocalizations;
72use crate::menu_bar_theme::MenuBarTheme;
73use crate::menu_button_theme::MenuButtonTheme;
74use crate::menu_style::{MenuStyle, MenuStyleGetters};
75use crate::menu_theme::MenuTheme;
76use crate::motion::Easing;
77use crate::radio::Radio;
78use crate::scrollbar::Scrollbar;
79use crate::text_button::TextButton;
80use crate::theme::Theme;
81use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
82
83// The default size of the arrow in _MenuItemLabel that indicates that a menu
84// has a submenu.
85const K_DEFAULT_SUBMENU_ICON_SIZE: f64 = 24.0;
86
87// The default spacing between the leading icon, label, trailing icon, and
88// shortcut label in a _MenuItemLabel.
89pub(crate) const K_LABEL_ITEM_DEFAULT_SPACING: f64 = 12.0;
90
91// The minimum spacing between the leading icon, label, trailing icon, and
92// shortcut label in a _MenuItemLabel.
93const K_LABEL_ITEM_MIN_SPACING: f64 = 4.0;
94
95// Navigation shortcuts that we need to make sure are active when menus are
96// open.
97fn menu_traversal_shortcuts() -> ShortcutMap {
98    fn shortcut(
99        activator: SingleActivator,
100        intent: impl waft_widgets::Intent,
101    ) -> (ShortcutActivatorRef, waft_widgets::IntentRef) {
102        (Rc::new(activator), Rc::new(intent))
103    }
104    vec![
105        shortcut(
106            SingleActivator::new(LogicalKeyboardKey::GAME_BUTTON_A),
107            ActivateIntent::new(),
108        ),
109        shortcut(
110            SingleActivator::new(LogicalKeyboardKey::ESCAPE),
111            DismissIntent::new(),
112        ),
113        shortcut(
114            SingleActivator::new(LogicalKeyboardKey::TAB),
115            NextFocusIntent::new(),
116        ),
117        shortcut(
118            SingleActivator::new(LogicalKeyboardKey::TAB).shift(true),
119            PreviousFocusIntent::new(),
120        ),
121        shortcut(
122            SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN),
123            DirectionalFocusIntent::new(TraversalDirection::Down),
124        ),
125        shortcut(
126            SingleActivator::new(LogicalKeyboardKey::ARROW_UP),
127            DirectionalFocusIntent::new(TraversalDirection::Up),
128        ),
129        shortcut(
130            SingleActivator::new(LogicalKeyboardKey::ARROW_LEFT),
131            DirectionalFocusIntent::new(TraversalDirection::Left),
132        ),
133        shortcut(
134            SingleActivator::new(LogicalKeyboardKey::ARROW_RIGHT),
135            DirectionalFocusIntent::new(TraversalDirection::Right),
136        ),
137    ]
138}
139
140// The minimum vertical spacing on the outside of menus.
141pub(crate) const K_MENU_VERTICAL_MIN_PADDING: f64 = 8.0;
142
143// How close to the edge of the safe area the menu will be placed.
144pub(crate) const K_MENU_VIEW_PADDING: f64 = 8.0;
145
146// The minimum horizontal spacing on the outside of the top level menu.
147pub(crate) const K_TOP_LEVEL_MENU_HORIZONTAL_MIN_PADDING: f64 = 4.0;
148
149// The default opening animation duration for menus.
150const K_MENU_OPENING_DURATION: Duration = Duration::from_millis(500);
151
152// The default closing animation duration for menus.
153const K_MENU_CLOSING_DURATION: Duration = Duration::from_millis(150);
154
155/// The default curve used to animate the height of the menu panel while the
156/// menu is opening.
157///
158/// **NOTE**: This animation curve follows the material web implementation of
159/// [Easing.emphasized](https://github.com/material-components/material-web/blob/516cbc02bf770b7c3c5c6b546f1e5d81939b9f23/internal/motion/animation.ts#L18)
160/// instead of the curve recommended by the Material 3 specification,
161/// [Curves.easeInOutCubicEmphasized](https://m3.material.io/styles/motion/easing-and-duration/tokens-specs).
162/// This change was made because the web curve [was more consistent with the
163/// timing of the menu item fade-in
164/// animations](https://github.com/flutter/flutter/pull/176494#discussion_r2545178254).
165fn menu_panel_height_forward_curve() -> Rc<dyn Curve> {
166    Rc::new(Cubic::new(0.3, 0.0, 0.0, 1.0))
167}
168
169// The default curve used to animate the height of the menu panel while the menu
170// is closing.
171fn menu_panel_height_reverse_curve() -> Rc<dyn Curve> {
172    Rc::new(TweenCurve::new(
173        0.35,
174        1.0,
175        Rc::new(FlippedCurve::new(Easing::emphasized_accelerate())),
176    ))
177}
178
179// The default curve used to animate the opacity of the menu panel when opening.
180fn menu_panel_opacity_forward_curve() -> Rc<dyn Curve> {
181    Rc::new(Interval::new(
182        0.0,
183        50.0 / 500.0,
184        waft_animation::Curves::linear(),
185    ))
186}
187
188// The default curve used to animate the opacity of the menu panel when closing.
189#[allow(clippy::eq_op, reason = "Dart's `Interval(100 / 150, 150 / 150)`")]
190fn menu_panel_opacity_reverse_curve() -> Rc<dyn Curve> {
191    Rc::new(FlippedCurve::new(Rc::new(Interval::new(
192        100.0 / 150.0,
193        150.0 / 150.0,
194        waft_animation::Curves::linear(),
195    ))))
196}
197
198// The default fade-in duration of each menu item as a fraction of the opening
199// duration.
200const K_MENU_ITEM_RELATIVE_FADE_IN_DURATION: f64 = 1.0 / 2.0;
201
202// The default fade-out duration of each menu item as a fraction of the closing
203// duration.
204const K_MENU_ITEM_RELATIVE_FADE_OUT_DURATION: f64 = 1.0 / 3.0;
205
206// The default delay between the start of each menu item's fade-out as a
207// fraction of the closing duration.
208const K_MENU_ITEM_RELATIVE_FADE_OUT_DELAY: f64 = 1.0 / 3.0;
209
210/// The type of builder function used by [`MenuAnchor::builder`] to build the
211/// widget that the [`MenuAnchor`] surrounds.
212///
213/// The `context` is the context that the widget is being built in.
214///
215/// The `controller` is the [`MenuController`] that can be used to open and close
216/// the menu with.
217///
218/// The `child` is an optional child supplied as the [`MenuAnchor::child`]
219/// attribute. The child is intended to be incorporated in the result of the
220/// function.
221pub type MenuAnchorChildBuilder =
222    Rc<dyn Fn(&mut App, BuildContext, AnyMenuController, Option<&WidgetRef>) -> WidgetRef>;
223
224/// Dart's `_MenuAnchorScope`.
225#[derive(Debug)]
226struct MenuAnchorScope {
227    state: AnyMenuAnchorState,
228    animation_status: AnimationStatus,
229    child: WidgetRef,
230}
231
232impl InheritedWidget for MenuAnchorScope {
233    fn child(&self) -> &WidgetRef {
234        &self.child
235    }
236
237    fn update_should_notify(&self, old_widget: &MenuAnchorScope) -> bool {
238        debug_assert!(
239            old_widget.state == self.state,
240            "The state of a MenuAnchor should not change."
241        );
242        old_widget.animation_status != self.animation_status
243    }
244}
245
246// A curve that linearly interpolates between two values over a given curve.
247//
248// For example, `_TweenCurve(0.2, 0.8, curve: Curves.easeIn)` will produce a
249// curve that starts at 0.2, ends at 0.8, and follows the easeIn curve between
250// those two values. The curve is applied first, and then the result is linearly
251// interpolated between begin and end.
252//
253// This differs from an `Interval` in that an Interval changes the duration over
254// which the curve is applied, whereas `_TweenCurve` changes the output range of
255// the curve.
256struct TweenCurve {
257    begin: f64,
258    end: f64,
259    curve: Rc<dyn Curve>,
260}
261
262impl TweenCurve {
263    fn new(begin: f64, end: f64, curve: Rc<dyn Curve>) -> TweenCurve {
264        debug_assert!(begin >= 0.0);
265        debug_assert!(begin <= 1.0);
266        debug_assert!(end >= 0.0);
267        debug_assert!(end <= 1.0);
268        debug_assert!(end >= begin);
269        TweenCurve { begin, end, curve }
270    }
271}
272
273impl Curve for TweenCurve {
274    fn transform_internal(&self, t: f64) -> f64 {
275        let t = self.curve.transform(t);
276        lerp_double(Some(self.begin), Some(self.end), t).expect("both ends")
277    }
278}
279
280impl Debug for TweenCurve {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        write!(
283            f,
284            "_TweenCurve({}, {}, {:?})",
285            self.begin, self.end, self.curve
286        )
287    }
288}
289
290/// Dart's `'$Type(${widget.child})'`, the debug label of a button's own focus node.
291fn describe_child(type_name: &str, child: &Option<WidgetRef>) -> String {
292    match child {
293        Some(child) => format!("{type_name}({child:?})"),
294        None => format!("{type_name}(null)"),
295    }
296}
297
298/// Dart's `widget.menuChildren != oldWidget.menuChildren`, an identity test on the list: here
299/// the same widgets in the same order.
300fn same_widgets(a: &[WidgetRef], b: &[WidgetRef]) -> bool {
301    a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Rc::ptr_eq(a, b))
302}
303
304// ---------------------------------------------------------------------------------------------
305// MenuAnchor
306
307/// A widget used to mark the "anchor" for a set of submenus, defining the
308/// rectangle used to position the menu, which can be done either with an
309/// explicit location, or with an alignment.
310///
311/// When creating a menu with [`MenuBar`] or a [`SubmenuButton`], a [`MenuAnchor`] is
312/// not needed, since they provide their own internally.
313///
314/// The [`MenuAnchor`] is meant to be a slightly lower level interface than
315/// [`MenuBar`], used in situations where a [`MenuBar`] isn't appropriate, or to
316/// construct widgets or screen regions that have submenus.
317///
318/// To programmatically control a [`MenuAnchor`], like opening or closing it, or checking its
319/// state, you can get its associated [`MenuController`]. Use `MenuController::maybe_of(app,
320/// context)` to retrieve the controller for the closest [`MenuAnchor`] ancestor of a given
321/// [`BuildContext`]. More detailed usage of [`MenuController`] is available in its type
322/// documentation.
323///
324/// The [`MenuStyle::visual_density`] setting only affects horizontal padding,
325/// and it will never make it negative. Vertical padding is not affected at all.
326pub struct MenuAnchor {
327    /// See `Widget::key`.
328    pub key: Option<KeyRef>,
329
330    /// An optional controller that allows opening and closing of the menu from
331    /// other widgets.
332    pub controller: Option<MenuControllerRef>,
333
334    /// The [`child_focus_node`](Self::child_focus_node) attribute is the optional `FocusNode`
335    /// also associated to the [`child`](Self::child) or [`builder`](Self::builder) widget that
336    /// opens the menu.
337    ///
338    /// The focus node should be attached to the widget that should receive focus
339    /// if keyboard focus traversal moves the focus off of the submenu with the
340    /// arrow keys.
341    ///
342    /// If not supplied, then keyboard traversal from the menu back to the
343    /// controlling button when the menu is open is disabled.
344    pub child_focus_node: Option<FocusNodeRef>,
345
346    /// The [`MenuStyle`] that defines the visual attributes of the menu bar.
347    ///
348    /// Colors and sizing of the menus is controllable via the [`MenuStyle`].
349    ///
350    /// Defaults to the ambient `MenuThemeData::style`.
351    pub style: Option<MenuStyle>,
352
353    /// The offset of the menu relative to the alignment origin determined by
354    /// [`MenuStyle::alignment`] on the [`style`](Self::style) attribute and the ambient
355    /// `Directionality`.
356    ///
357    /// Use this for adjustments of the menu placement.
358    ///
359    /// Increasing `Offset::dy` values of [`alignment_offset`](Self::alignment_offset) move
360    /// the menu position down.
361    ///
362    /// If the [`MenuStyle::alignment`] from [`style`](Self::style) is not an
363    /// `AlignmentDirectional` (e.g. `Alignment`), then increasing `Offset::dx` values of
364    /// [`alignment_offset`](Self::alignment_offset) move the menu position to the right.
365    ///
366    /// If the [`MenuStyle::alignment`] from [`style`](Self::style) is an
367    /// `AlignmentDirectional`, then in a `TextDirection::Ltr` `Directionality`, increasing
368    /// `Offset::dx` values of [`alignment_offset`](Self::alignment_offset) move the menu
369    /// position to the right. In a `TextDirection::Rtl` directionality, increasing
370    /// `Offset::dx` values of [`alignment_offset`](Self::alignment_offset) move the menu
371    /// position to the left.
372    ///
373    /// Defaults to `Offset::ZERO`.
374    pub alignment_offset: Option<Offset>,
375
376    /// An optional [`LayerLink`] to attach the menu to the widget that this
377    /// [`MenuAnchor`] surrounds.
378    ///
379    /// When provided, the menu will follow the widget that this [`MenuAnchor`]
380    /// surrounds if it moves because of view insets changes.
381    pub layer_link: Option<Ref<LayerLink>>,
382
383    /// The content will be clipped (or not) according to this option.
384    ///
385    /// Defaults to `Clip::HardEdge`.
386    pub clip_behavior: Clip,
387
388    /// Whether the menus will be closed if the anchor area is tapped.
389    ///
390    /// For menus opened by buttons that toggle the menu, if the button is tapped
391    /// when the menu is open, the button should close the menu. But if
392    /// [`anchor_tap_closes_menu`](Self::anchor_tap_closes_menu) is true, then the menu will
393    /// close, and (surprisingly) immediately re-open. This is because tapping on the button
394    /// closes the menu before the `on_pressed` or `on_tap` handler is called
395    /// because of it being considered to be "outside" the menu system, and then
396    /// the button (seeing that the menu is closed) immediately reopens the menu.
397    /// The result is that the user thinks that tapping on the button does
398    /// nothing. So, for button-initiated menus, this value is typically false so
399    /// that the menu anchor area is considered "inside" of the menu system and
400    /// doesn't cause it to close unless [`MenuControllerLeaf::close`] is called.
401    ///
402    /// For menus that are positioned using [`MenuControllerLeaf::open`]'s `position`
403    /// parameter, it is often desirable that clicking on the anchor always closes
404    /// the menu since the anchor area isn't usually considered part of the menu
405    /// system by the user. In this case
406    /// [`anchor_tap_closes_menu`](Self::anchor_tap_closes_menu) should be true.
407    ///
408    /// Defaults to false.
409    #[deprecated(
410        note = "Use consumeOutsideTap instead. This feature was deprecated after \
411                v3.16.0-8.0.pre."
412    )]
413    pub anchor_tap_closes_menu: bool,
414
415    /// Whether or not a tap event that closes the menu will be permitted to
416    /// continue on to the gesture arena.
417    ///
418    /// If false, then tapping outside of a menu when the menu is open will both
419    /// close the menu, and allow the tap to participate in the gesture arena. If
420    /// true, then it will only close the menu, and the tap event will be
421    /// consumed.
422    ///
423    /// Defaults to false.
424    pub consume_outside_tap: bool,
425
426    /// A callback that is invoked when the menu begins opening.
427    ///
428    /// Defaults to null.
429    pub on_open: Option<VoidCallback>,
430
431    /// A callback that is invoked when the menu finishes closing.
432    ///
433    /// Defaults to null.
434    pub on_close: Option<VoidCallback>,
435
436    /// Determine if the menu panel can be wrapped by a `UnconstrainedBox` which allows
437    /// the panel to render at its "natural" size.
438    ///
439    /// Defaults to true as it allows developers to render the menu panel at the
440    /// size it should be. When it is set to false, it can be useful when the menu should
441    /// be constrained in both main axis and cross axis, such as a `DropdownMenu`.
442    pub cross_axis_unconstrained: bool,
443
444    /// Whether the menu panel should be rendered in the root `Overlay`.
445    ///
446    /// See [`RawMenuAnchor::use_root_overlay`].
447    ///
448    /// Defaults to false.
449    pub use_root_overlay: bool,
450
451    /// Whether this widget should open or close a submenu with an animation.
452    ///
453    /// Defaults to false.
454    pub animated: bool,
455
456    /// An optional callback that is invoked when the [`AnimationStatus`] of the
457    /// menu changes during open and close animations.
458    ///
459    /// If [`animated`](Self::animated) is false, this callback will only be invoked with
460    /// [`AnimationStatus::Completed`] when the menu is opened, and
461    /// [`AnimationStatus::Dismissed`] when the menu is closed.
462    ///
463    /// This callback provides a way to determine when the menu is opening or
464    /// closing. This is necessary because the [`MenuControllerLeaf::is_open`] property
465    /// remains true throughout the opening, opened, and closing phases, and
466    /// therefore cannot be used on its own to determine the current animation
467    /// direction.
468    ///
469    /// Defaults to null.
470    pub on_animation_status_changed: Option<ValueChanged<AnimationStatus>>,
471
472    /// A list of children containing the menu items that are the contents of the
473    /// menu surrounded by this [`MenuAnchor`].
474    ///
475    /// Menus using [`MenuItemButton`] can have a `SingleActivator` or `CharacterActivator`
476    /// assigned to them as their [`MenuItemButton::shortcut`], which will display an
477    /// appropriate shortcut hint. Even though the shortcut labels are displayed in the menu,
478    /// shortcuts are not automatically handled. They must be available in whatever context
479    /// they are appropriate, and handled via another mechanism.
480    pub menu_children: Vec<WidgetRef>,
481
482    /// The widget that this [`MenuAnchor`] surrounds.
483    ///
484    /// Typically this is a button used to open the menu by calling
485    /// [`MenuControllerLeaf::open`] on the `controller` passed to the builder.
486    ///
487    /// If not supplied, then the [`MenuAnchor`] will be the size that its parent
488    /// allocates for it.
489    ///
490    /// If provided, the builder will be called each time the menu is opened or
491    /// closed.
492    pub builder: Option<MenuAnchorChildBuilder>,
493
494    /// The semantic label of the menu.
495    ///
496    /// Defaults to null.
497    pub semantic_label: Option<String>,
498
499    /// The optional child to be passed to the [`builder`](Self::builder).
500    ///
501    /// Supply this child if there is a portion of the widget tree built in
502    /// [`builder`](Self::builder) that doesn't depend on the `controller` or `context`
503    /// supplied to the [`builder`](Self::builder). It will be more efficient, since Flutter
504    /// doesn't then need to rebuild this child when those change.
505    pub child: Option<WidgetRef>,
506
507    /// The padding between the edge of the safe area and the menu panel.
508    ///
509    /// Defaults to `EdgeInsets::all(8)`.
510    pub reserved_padding: Option<EdgeInsetsGeometry>,
511}
512
513impl MenuAnchor {
514    /// Creates a const [`MenuAnchor`].
515    ///
516    /// The [`menu_children`](Self::menu_children) argument is required.
517    pub fn new(menu_children: Vec<WidgetRef>) -> MenuAnchor {
518        MenuAnchor {
519            key: None,
520            controller: None,
521            child_focus_node: None,
522            style: None,
523            alignment_offset: Some(Offset::ZERO),
524            reserved_padding: None,
525            layer_link: None,
526            clip_behavior: Clip::HardEdge,
527            anchor_tap_closes_menu: false,
528            consume_outside_tap: false,
529            on_open: None,
530            on_close: None,
531            cross_axis_unconstrained: true,
532            use_root_overlay: false,
533            animated: false,
534            on_animation_status_changed: None,
535            menu_children,
536            builder: None,
537            semantic_label: None,
538            child: None,
539        }
540    }
541
542    /// Dart `MenuAnchor(key:)`.
543    pub fn key(mut self, key: KeyRef) -> MenuAnchor {
544        self.key = Some(key);
545        self
546    }
547
548    /// Dart `MenuAnchor(controller:)`.
549    pub fn controller(mut self, controller: MenuControllerRef) -> MenuAnchor {
550        self.controller = Some(controller);
551        self
552    }
553
554    /// Dart `MenuAnchor(childFocusNode:)`.
555    pub fn child_focus_node(mut self, child_focus_node: FocusNodeRef) -> MenuAnchor {
556        self.child_focus_node = Some(child_focus_node);
557        self
558    }
559
560    /// Dart `MenuAnchor(style:)`.
561    pub fn style(mut self, style: MenuStyle) -> MenuAnchor {
562        self.style = Some(style);
563        self
564    }
565
566    /// Dart `MenuAnchor(alignmentOffset:)`.
567    pub fn alignment_offset(mut self, alignment_offset: Offset) -> MenuAnchor {
568        self.alignment_offset = Some(alignment_offset);
569        self
570    }
571
572    /// Dart `MenuAnchor(reservedPadding:)`.
573    pub fn reserved_padding(
574        mut self,
575        reserved_padding: impl Into<EdgeInsetsGeometry>,
576    ) -> MenuAnchor {
577        let reserved_padding = reserved_padding.into();
578        self.reserved_padding = Some(reserved_padding);
579        self
580    }
581
582    /// Dart `MenuAnchor(layerLink:)`.
583    pub fn layer_link(mut self, layer_link: Ref<LayerLink>) -> MenuAnchor {
584        self.layer_link = Some(layer_link);
585        self
586    }
587
588    /// Dart `MenuAnchor(clipBehavior:)`.
589    pub fn clip_behavior(mut self, clip_behavior: Clip) -> MenuAnchor {
590        self.clip_behavior = clip_behavior;
591        self
592    }
593
594    /// Dart `MenuAnchor(anchorTapClosesMenu:)`.
595    #[deprecated(
596        note = "Use consumeOutsideTap instead. This feature was deprecated after \
597                v3.16.0-8.0.pre."
598    )]
599    pub fn anchor_tap_closes_menu(mut self, anchor_tap_closes_menu: bool) -> MenuAnchor {
600        self.anchor_tap_closes_menu = anchor_tap_closes_menu;
601        self
602    }
603
604    /// Dart `MenuAnchor(consumeOutsideTap:)`.
605    pub fn consume_outside_tap(mut self, consume_outside_tap: bool) -> MenuAnchor {
606        self.consume_outside_tap = consume_outside_tap;
607        self
608    }
609
610    /// Dart `MenuAnchor(onOpen:)`.
611    pub fn on_open(mut self, on_open: VoidCallback) -> MenuAnchor {
612        self.on_open = Some(on_open);
613        self
614    }
615
616    /// Dart `MenuAnchor(onClose:)`.
617    pub fn on_close(mut self, on_close: VoidCallback) -> MenuAnchor {
618        self.on_close = Some(on_close);
619        self
620    }
621
622    /// Dart `MenuAnchor(crossAxisUnconstrained:)`.
623    pub fn cross_axis_unconstrained(mut self, cross_axis_unconstrained: bool) -> MenuAnchor {
624        self.cross_axis_unconstrained = cross_axis_unconstrained;
625        self
626    }
627
628    /// Dart `MenuAnchor(useRootOverlay:)`.
629    pub fn use_root_overlay(mut self, use_root_overlay: bool) -> MenuAnchor {
630        self.use_root_overlay = use_root_overlay;
631        self
632    }
633
634    /// Dart `MenuAnchor(animated:)`.
635    pub fn animated(mut self, animated: bool) -> MenuAnchor {
636        self.animated = animated;
637        self
638    }
639
640    /// Dart `MenuAnchor(onAnimationStatusChanged:)`.
641    pub fn on_animation_status_changed(
642        mut self,
643        on_animation_status_changed: ValueChanged<AnimationStatus>,
644    ) -> MenuAnchor {
645        self.on_animation_status_changed = Some(on_animation_status_changed);
646        self
647    }
648
649    /// Dart `MenuAnchor(builder:)`.
650    pub fn builder(
651        mut self,
652        builder: impl Fn(&mut App, BuildContext, AnyMenuController, Option<&WidgetRef>) -> WidgetRef
653        + 'static,
654    ) -> MenuAnchor {
655        self.builder = Some(Rc::new(builder));
656        self
657    }
658
659    /// Dart `MenuAnchor(semanticLabel:)`.
660    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> MenuAnchor {
661        self.semantic_label = Some(semantic_label.into());
662        self
663    }
664
665    /// Dart `MenuAnchor(child:)`.
666    #[cfg_attr(debug_assertions, track_caller)]
667    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MenuAnchor {
668        self.child = Some(child.into_widget());
669        self
670    }
671}
672
673impl Debug for MenuAnchor {
674    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675        let mut properties = f.debug_struct("MenuAnchor");
676        if self.anchor_tap_closes_menu {
677            properties.field("anchorTapClosesMenu", &"AUTO-CLOSE");
678        }
679        properties
680            .field("focusNode", &self.child_focus_node)
681            .field("style", &self.style)
682            .field("clipBehavior", &self.clip_behavior)
683            .field("alignmentOffset", &self.alignment_offset)
684            .field("menuChildren", &self.menu_children)
685            .finish_non_exhaustive()
686    }
687}
688
689impl StatefulWidget for MenuAnchor {
690    type State = MenuAnchorState;
691
692    fn key(&self) -> Option<&KeyRef> {
693        self.key.as_ref()
694    }
695
696    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
697        // Dart's `debugDescribeChildren` has no widget-level hook in this port; the element
698        // tree dump shows the built children instead of `menuChildren`.
699        properties.add(
700            FlagProperty::new("anchorTapClosesMenu", Some(self.anchor_tap_closes_menu))
701                .if_true("AUTO-CLOSE"),
702        );
703        properties.add(DiagnosticsProperty::<String>::new(
704            "focusNode",
705            self.child_focus_node
706                .as_ref()
707                .map(|node| node.to_string(app)),
708        ));
709        properties.add(DiagnosticsProperty::<MenuStyle>::new(
710            "style",
711            self.style.clone(),
712        ));
713        properties.add(EnumProperty::<Clip>::new(
714            "clipBehavior",
715            Some(self.clip_behavior),
716        ));
717        properties.add(DiagnosticsProperty::<Offset>::new(
718            "alignmentOffset",
719            self.alignment_offset,
720        ));
721    }
722
723    fn create_state(&self) -> MenuAnchorState {
724        MenuAnchorState {
725            state: StateData::new(),
726            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
727            menu_anchor_state: MenuAnchorStateData::new(),
728        }
729    }
730}
731
732// ---------------------------------------------------------------------------------------------
733// _MenuAnchorState
734
735/// The fields of Dart's `_MenuAnchorState`, which its subclass `_MenuBarAnchorState` shares;
736/// each state carries them under the field `menu_anchor_state`.
737struct MenuAnchorStateData {
738    internal_menu_controller: Option<Ref<MenuController>>,
739    // Dart's field initializers; an arena object needs the `App`, so `init_state` makes them.
740    menu_scope_node: Option<Ref<FocusScopeNode>>,
741    animation_controller: Option<Ref<AnimationController>>,
742    height_animation: Option<Ref<CurvedAnimation>>,
743    opacity_animation: Option<Ref<CurvedAnimation>>,
744    menu_children: Vec<WidgetRef>,
745    cached_animations: Vec<Ref<CurvedAnimation>>,
746}
747
748impl MenuAnchorStateData {
749    fn new() -> MenuAnchorStateData {
750        MenuAnchorStateData {
751            internal_menu_controller: None,
752            menu_scope_node: None,
753            animation_controller: None,
754            height_animation: None,
755            opacity_animation: None,
756            menu_children: Vec::new(),
757            cached_animations: Vec::new(),
758        }
759    }
760}
761
762/// Dart's `_MenuAnchorState`: the state of a [`MenuAnchor`].
763pub struct MenuAnchorState {
764    state: StateData<MenuAnchor>,
765    single_ticker_provider: SingleTickerProviderStateMixinData,
766    menu_anchor_state: MenuAnchorStateData,
767}
768
769/// The base class Dart's `_MenuAnchorState` is to `_MenuBarAnchorState`: its fields, its
770/// overridable members and its bodies. A leaf's `State` hooks call this trait's
771/// `init_state`, `did_update_widget`, `dispose` and `build` by name, where Dart runs the base
772/// class's body through `super`.
773trait MenuAnchorStateLeaf: SingleTickerProviderStateMixin + TickerProviderObject {
774    fn menu_anchor_state_data(self: Handle<Self>, app: &App) -> &MenuAnchorStateData;
775
776    fn menu_anchor_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut MenuAnchorStateData;
777
778    /// The state's widget as the [`MenuAnchor`] Dart's `widget` is.
779    fn menu_anchor(self: Handle<Self>, app: &App) -> &MenuAnchor;
780
781    /// Dart's `_orientation`.
782    fn orientation() -> Axis {
783        Axis::Vertical
784    }
785
786    /// This state as the erased [`AnyMenuAnchorState`] a `_MenuAnchorScope` holds.
787    fn as_menu_anchor_state(self: Handle<Self>) -> AnyMenuAnchorState {
788        AnyMenuAnchorState {
789            id: self.id(),
790            vtable: const { &MenuAnchorStateVTable::of::<Self>() },
791        }
792    }
793
794    fn animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
795        self.menu_anchor_state_data(app)
796            .animation_controller
797            .handle()
798            .expect("created in init_state")
799    }
800
801    /// Dart's `initState` body.
802    fn init_state(self: Handle<Self>, app: &mut App) {
803        let menu_scope_node = FocusScopeNode::new(app);
804        let animation_controller = AnimationController::new(
805            app,
806            None,
807            None,
808            None,
809            0.0,
810            1.0,
811            waft_animation::AnimationBehavior::Normal,
812            self,
813        );
814        let height_animation = CurvedAnimation::new(
815            app,
816            animation_controller.erase(),
817            menu_panel_height_forward_curve(),
818            Some(menu_panel_height_reverse_curve()),
819        );
820        let opacity_animation = CurvedAnimation::new(
821            app,
822            animation_controller.erase(),
823            menu_panel_opacity_forward_curve(),
824            Some(menu_panel_opacity_reverse_curve()),
825        );
826        let data = self.menu_anchor_state_data_mut(app);
827        data.menu_scope_node = Some(menu_scope_node);
828        data.animation_controller = Some(animation_controller.clone());
829        data.height_animation = Some(height_animation);
830        data.opacity_animation = Some(opacity_animation);
831
832        self.resolve_animation_controller(app);
833        self.resolve_menu_items(app);
834        animation_controller.add_status_listener(
835            app,
836            AnimationStatusListener::handle_method(self, Self::handle_animation_status_changed),
837        );
838
839        if self.menu_anchor(app).controller.is_none() {
840            let controller = MenuController::new(app);
841            self.menu_anchor_state_data_mut(app)
842                .internal_menu_controller = Some(controller);
843        }
844    }
845
846    /// Dart's `didUpdateWidget` body.
847    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MenuAnchor) {
848        let widget = self.menu_anchor(app);
849        let controller = widget.controller.clone();
850        if old_widget.controller != controller {
851            let internal_menu_controller = if controller.is_none() {
852                Some(MenuController::new(app))
853            } else {
854                None
855            };
856            self.menu_anchor_state_data_mut(app)
857                .internal_menu_controller = internal_menu_controller;
858        }
859
860        let widget = self.menu_anchor(app);
861        if old_widget.animated != widget.animated
862            || !same_widgets(&widget.menu_children, &old_widget.menu_children)
863        {
864            self.resolve_menu_items(app);
865        }
866
867        if old_widget.animated != self.menu_anchor(app).animated {
868            self.resolve_animation_controller(app);
869        }
870    }
871
872    /// Dart's `dispose` body, up to `super.dispose()`.
873    fn dispose(self: Handle<Self>, app: &mut App) {
874        let data = self.menu_anchor_state_data_mut(app);
875        data.menu_children.clear();
876        let cached_animations = std::mem::take(&mut data.cached_animations);
877        let menu_scope_node = data
878            .menu_scope_node
879            .handle()
880            .expect("created in init_state");
881        let height_animation = data
882            .height_animation
883            .handle()
884            .expect("created in init_state");
885        let opacity_animation = data
886            .opacity_animation
887            .handle()
888            .expect("created in init_state");
889        let animation_controller = data
890            .animation_controller
891            .handle()
892            .expect("created in init_state");
893        for animation in cached_animations {
894            animation.dispose(app);
895        }
896        menu_scope_node.as_node().dispose(app);
897        height_animation.dispose(app);
898        opacity_animation.dispose(app);
899        animation_controller.stop(app, true);
900        animation_controller.dispose(app);
901        SingleTickerProviderStateMixin::dispose(self, app);
902    }
903
904    /// Dart's `_resolveAnimationController`.
905    fn resolve_animation_controller(self: Handle<Self>, app: &mut App) {
906        let animated = self.menu_anchor(app).animated;
907        let controller = app.get_mut(self.animation_controller(app));
908        if animated {
909            controller.duration = Some(K_MENU_OPENING_DURATION);
910            controller.reverse_duration = Some(K_MENU_CLOSING_DURATION);
911        } else {
912            controller.duration = Some(Duration::ZERO);
913            controller.reverse_duration = Some(Duration::ZERO);
914        }
915    }
916
917    /// Dart's `_resolveMenuItems`.
918    fn resolve_menu_items(self: Handle<Self>, app: &mut App) {
919        let data = self.menu_anchor_state_data_mut(app);
920        data.menu_children = Vec::new();
921        let cached_animations = std::mem::take(&mut data.cached_animations);
922        for animation in cached_animations {
923            animation.dispose(app);
924        }
925
926        let widget = self.menu_anchor(app);
927        let item_count = widget.menu_children.len();
928        if item_count == 0 {
929            return;
930        }
931
932        if !widget.animated {
933            let menu_children = widget.menu_children.clone();
934            self.menu_anchor_state_data_mut(app).menu_children = menu_children;
935            return;
936        }
937
938        const FORWARD_FINAL_ITEM_OFFSET: f64 = 1.0 - K_MENU_ITEM_RELATIVE_FADE_IN_DURATION;
939        const REVERSE_FINAL_ITEM_OFFSET: f64 =
940            1.0 - K_MENU_ITEM_RELATIVE_FADE_OUT_DURATION - K_MENU_ITEM_RELATIVE_FADE_OUT_DELAY;
941
942        let mut forward_progress = 0.0;
943        let mut reverse_progress = 0.0;
944        let mut item_fade_in_gap = 0.0;
945        let mut item_fade_out_gap = 0.0;
946        if item_count > 1 {
947            // Spread every item evenly across the remaining time after accounting for
948            // the fade in/out durations.
949            item_fade_in_gap = FORWARD_FINAL_ITEM_OFFSET / (item_count - 1) as f64;
950            item_fade_out_gap = REVERSE_FINAL_ITEM_OFFSET / (item_count - 1) as f64;
951        }
952
953        let parent: AnimationRef<f64> = self
954            .menu_anchor_state_data(app)
955            .animation_controller
956            .as_ref()
957            .expect("created in init_state")
958            .erase();
959        for child in widget.menu_children.clone() {
960            let forward_curve = Interval::new(
961                forward_progress,
962                forward_progress + K_MENU_ITEM_RELATIVE_FADE_IN_DURATION,
963                waft_animation::Curves::linear(),
964            );
965
966            let reverse_curve = Interval::new(
967                reverse_progress,
968                reverse_progress + K_MENU_ITEM_RELATIVE_FADE_OUT_DURATION,
969                waft_animation::Curves::linear(),
970            );
971
972            let animation = CurvedAnimation::new(
973                app,
974                parent.clone(),
975                Rc::new(forward_curve),
976                Some(Rc::new(reverse_curve)),
977            );
978
979            let data = self.menu_anchor_state_data_mut(app);
980            data.cached_animations.push(animation.clone());
981            data.menu_children.push(
982                FadeTransition::new(animation.erase())
983                    .child(child)
984                    .into_widget(),
985            );
986            forward_progress += item_fade_in_gap;
987            reverse_progress += item_fade_out_gap;
988        }
989    }
990
991    /// Dart's `_handleAnimationStatusChanged`.
992    fn handle_animation_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
993        self.set_state(app, |_| {
994            // Rebuild to update isClosedOrClosing and notify dependents of AnimationStatus changes.
995        });
996        if let Some(on_animation_status_changed) =
997            self.menu_anchor(app).on_animation_status_changed.clone()
998        {
999            on_animation_status_changed(app, status);
1000        }
1001    }
1002
1003    /// Dart's `_handleMenuOpenRequest`.
1004    fn handle_menu_open_request(
1005        self: Handle<Self>,
1006        app: &mut App,
1007        _position: Option<Offset>,
1008        show_overlay: VoidCallback,
1009    ) {
1010        let this = self.as_menu_anchor_state();
1011        // If this menu's parent is closing, submenus should not open. This prevents
1012        // a submenu calling MenuController.open() after a parent menu has started
1013        // closing.
1014        if this
1015            .parent(app)
1016            .is_some_and(|parent| parent.is_closing(app))
1017        {
1018            return;
1019        }
1020
1021        show_overlay(app);
1022
1023        let animation_controller = self.animation_controller(app);
1024        if animation_controller.status(app).is_forward_or_completed() {
1025            return;
1026        }
1027
1028        animation_controller.forward(app, None);
1029
1030        if this.is_submenu(app) || self.menu_anchor(app).child_focus_node.is_some() {
1031            return;
1032        }
1033
1034        let context = self.context(app);
1035        let scope = FocusScope::of(app, context, true);
1036        let focused_context = scope
1037            .focused_child(app)
1038            .and_then(|focused_child| focused_child.context(app));
1039        let is_anchor_focused = focused_context.is_some_and(|focused_context| {
1040            AnyMenuAnchorState::maybe_of(app, focused_context)
1041                .is_some_and(|anchor| anchor.root(app) == this)
1042        });
1043        if is_anchor_focused {
1044            return;
1045        }
1046
1047        let initial_focus = FocusManager::instance(app).primary_focus(app);
1048        let view = View::maybe_id_of(app, context);
1049        SchedulerBinding::add_post_frame_callback(
1050            app,
1051            FrameCallback::new(move |app, _timestamp| {
1052                if self.mounted(app)
1053                    && !this.is_closing_or_closed(app)
1054                    && FocusManager::instance(app).primary_focus(app) == initial_focus
1055                {
1056                    let menu_scope_node = this.menu_scope_node(app);
1057                    scope.set_first_focus(app, menu_scope_node);
1058                }
1059            }),
1060            view,
1061        );
1062    }
1063
1064    /// Dart's `_handleMenuCloseRequest`.
1065    fn handle_menu_close_request(self: Handle<Self>, app: &mut App, hide_overlay: VoidCallback) {
1066        let animation_controller = self.animation_controller(app);
1067        if !animation_controller.status(app).is_forward_or_completed() {
1068            return;
1069        }
1070
1071        animation_controller
1072            .reverse(app, None)
1073            .when_complete(app, Listener::new(move |app| hide_overlay(app)));
1074    }
1075
1076    /// Dart's `build`, which `_MenuBarAnchorState` overrides.
1077    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1078        let this = self.as_menu_anchor_state();
1079        let widget = self.menu_anchor(app);
1080        let mut anchor =
1081            RawMenuAnchor::new(this.menu_controller(app), move |app, context, info| {
1082                self.build_overlay(app, context, info)
1083            })
1084            .on_open_requested(Rc::new(move |app, position, show_overlay| {
1085                self.handle_menu_open_request(app, position, show_overlay);
1086            }))
1087            .on_close_requested(Rc::new(move |app, hide_overlay| {
1088                self.handle_menu_close_request(app, hide_overlay);
1089            }))
1090            .use_root_overlay(widget.use_root_overlay)
1091            .consume_outside_taps(widget.consume_outside_tap);
1092        anchor.on_open = widget.on_open.clone();
1093        anchor.on_close = widget.on_close.clone();
1094        anchor.child_focus_node = widget.child_focus_node.clone();
1095        anchor.builder = widget.builder.clone();
1096        anchor.child = widget.child.clone();
1097        let layer_link = widget.layer_link.clone();
1098        let child = MenuAnchorScope {
1099            state: this,
1100            animation_status: self.animation_controller(app).status(app),
1101            child: anchor.into_widget(),
1102        }
1103        .into_widget();
1104
1105        match layer_link {
1106            None => child,
1107            Some(layer_link) => CompositedTransformTarget::new(layer_link)
1108                .child(child)
1109                .into_widget(),
1110        }
1111    }
1112
1113    /// Dart's `_buildOverlay`.
1114    fn build_overlay(
1115        self: Handle<Self>,
1116        app: &mut App,
1117        _context: BuildContext,
1118        position: RawMenuOverlayInfo,
1119    ) -> WidgetRef {
1120        let this = self.as_menu_anchor_state();
1121        let data = self.menu_anchor_state_data(app);
1122        let fade_animation: AnimationRef<f64> = data
1123            .opacity_animation
1124            .as_ref()
1125            .expect("created in init_state")
1126            .erase();
1127        let height_animation: AnimationRef<f64> = data
1128            .height_animation
1129            .as_ref()
1130            .expect("created in init_state")
1131            .erase();
1132        let menu_scope_node = data.menu_scope_node.clone().expect("created in init_state");
1133        let menu_children = data.menu_children.clone();
1134        let widget = self.menu_anchor(app);
1135        let mut submenu = Submenu {
1136            fade_animation,
1137            height_animation,
1138            layer_link: widget.layer_link.clone(),
1139            consume_outside_taps: widget.consume_outside_tap,
1140            menu_scope_node,
1141            menu_style: widget.style.clone(),
1142            clip_behavior: widget.clip_behavior,
1143            menu_children,
1144            cross_axis_unconstrained: widget.cross_axis_unconstrained,
1145            menu_position: position,
1146            anchor: this,
1147            alignment_offset: widget.alignment_offset.unwrap_or(Offset::ZERO),
1148            reserved_padding: widget
1149                .reserved_padding
1150                .unwrap_or(EdgeInsetsGeometry::all(K_MENU_VIEW_PADDING)),
1151        }
1152        .into_widget();
1153
1154        // Only inject the semantics node if a label is provided
1155        if let Some(semantic_label) = widget.semantic_label.clone() {
1156            submenu = Semantics::new()
1157                .container(true)
1158                .explicit_child_nodes(true)
1159                .label(semantic_label)
1160                .child(submenu)
1161                .into_widget();
1162        }
1163
1164        // ExcludeSemantics, ExcludeFocus, and IgnorePointer are used to effectively
1165        // disable all interactions with the menu while it is closing.
1166        //
1167        // An animated menu should behave the same as a menu without animations.
1168        // Focus should be able to move to a menu as soon as it starts to open, and
1169        // a menu should not be interactive as soon as it starts to close.
1170        let is_closing_or_closed = this.is_closing_or_closed(app);
1171        ExcludeSemantics::new()
1172            .excluding(is_closing_or_closed)
1173            .child(
1174                IgnorePointer::new()
1175                    .ignoring(is_closing_or_closed)
1176                    .child(ExcludeFocus::new(submenu).excluding(is_closing_or_closed)),
1177            )
1178            .into_widget()
1179    }
1180}
1181
1182impl MenuAnchorStateLeaf for MenuAnchorState {
1183    fn menu_anchor_state_data(self: Handle<Self>, app: &App) -> &MenuAnchorStateData {
1184        &app.get(self).menu_anchor_state
1185    }
1186
1187    fn menu_anchor_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut MenuAnchorStateData {
1188        &mut app.get_mut(self).menu_anchor_state
1189    }
1190
1191    fn menu_anchor(self: Handle<Self>, app: &App) -> &MenuAnchor {
1192        self.widget(app)
1193    }
1194}
1195
1196impl SingleTickerProviderStateMixin for MenuAnchorState {
1197    fn single_ticker_provider_data(
1198        self: Handle<Self>,
1199        app: &App,
1200    ) -> &SingleTickerProviderStateMixinData {
1201        &app.get(self).single_ticker_provider
1202    }
1203
1204    fn single_ticker_provider_data_mut(
1205        self: Handle<Self>,
1206        app: &mut App,
1207    ) -> &mut SingleTickerProviderStateMixinData {
1208        &mut app.get_mut(self).single_ticker_provider
1209    }
1210}
1211
1212/// Dart's `vsync: this`.
1213impl TickerProviderObject for MenuAnchorState {
1214    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1215        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1216    }
1217}
1218
1219impl State for MenuAnchorState {
1220    type Widget = MenuAnchor;
1221    waft_widgets::state_accessors!();
1222
1223    fn init_state(self: Handle<Self>, app: &mut App) {
1224        MenuAnchorStateLeaf::init_state(self, app);
1225    }
1226
1227    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MenuAnchor) {
1228        MenuAnchorStateLeaf::did_update_widget(self, app, old_widget);
1229    }
1230
1231    fn activate(self: Handle<Self>, app: &mut App) {
1232        SingleTickerProviderStateMixin::activate(self, app);
1233    }
1234
1235    fn dispose(self: Handle<Self>, app: &mut App) {
1236        MenuAnchorStateLeaf::dispose(self, app);
1237    }
1238
1239    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1240        MenuAnchorStateLeaf::build(self, app, context)
1241    }
1242}
1243
1244impl Debug for MenuAnchorState {
1245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1246        f.write_str("_MenuAnchorState")
1247    }
1248}
1249
1250/// The vtable of an erased [`AnyMenuAnchorState`]: one `&'static` table per leaf type.
1251struct MenuAnchorStateVTable {
1252    type_name: fn() -> &'static str,
1253    data: fn(&App, HandleId) -> &MenuAnchorStateData,
1254    widget: fn(&App, HandleId) -> &MenuAnchor,
1255    orientation: fn() -> Axis,
1256    context: fn(&App, HandleId) -> BuildContext,
1257}
1258
1259/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
1260fn typed_handle<L: 'static>(id: HandleId) -> Handle<L> {
1261    Handle::from_id(id)
1262}
1263
1264impl MenuAnchorStateVTable {
1265    const fn of<L: MenuAnchorStateLeaf>() -> MenuAnchorStateVTable {
1266        MenuAnchorStateVTable {
1267            type_name: std::any::type_name::<L>,
1268            data: |app, id| L::menu_anchor_state_data(typed_handle(id), app),
1269            widget: |app, id| L::menu_anchor(typed_handle(id), app),
1270            orientation: L::orientation,
1271            context: |app, id| L::context(typed_handle(id), app),
1272        }
1273    }
1274}
1275
1276/// Erased `_MenuAnchorState`: what a field or parameter Dart types as `_MenuAnchorState`
1277/// becomes, a [`MenuAnchorState`] or a menu bar's state.
1278///
1279/// Its methods are Dart's members that no subclass overrides.
1280#[derive(Clone, Copy)]
1281struct AnyMenuAnchorState {
1282    id: HandleId,
1283    vtable: &'static MenuAnchorStateVTable,
1284}
1285
1286impl PartialEq for AnyMenuAnchorState {
1287    fn eq(&self, other: &AnyMenuAnchorState) -> bool {
1288        self.id == other.id
1289    }
1290}
1291
1292impl Eq for AnyMenuAnchorState {}
1293
1294impl Debug for AnyMenuAnchorState {
1295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1296        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1297    }
1298}
1299
1300impl AnyMenuAnchorState {
1301    fn data(self, app: &App) -> &MenuAnchorStateData {
1302        (self.vtable.data)(app, self.id)
1303    }
1304
1305    /// Dart's `widget`.
1306    fn widget(self, app: &App) -> &MenuAnchor {
1307        (self.vtable.widget)(app, self.id)
1308    }
1309
1310    /// Dart's `context`.
1311    fn context(self, app: &App) -> BuildContext {
1312        (self.vtable.context)(app, self.id)
1313    }
1314
1315    /// Dart's `_orientation`.
1316    fn orientation(self) -> Axis {
1317        (self.vtable.orientation)()
1318    }
1319
1320    /// Dart's `_menuController`.
1321    fn menu_controller(self, app: &App) -> MenuControllerRef {
1322        self.widget(app).controller.clone().unwrap_or_else(|| {
1323            self.data(app)
1324                .internal_menu_controller
1325                .as_ref()
1326                .expect("made when the widget has no controller")
1327                .erase()
1328        })
1329    }
1330
1331    /// Dart's `_menuScopeNode`.
1332    fn menu_scope_node(self, app: &App) -> Handle<FocusScopeNode> {
1333        self.data(app)
1334            .menu_scope_node
1335            .handle()
1336            .expect("created in init_state")
1337    }
1338
1339    fn animation_controller(self, app: &App) -> Handle<AnimationController> {
1340        self.data(app)
1341            .animation_controller
1342            .handle()
1343            .expect("created in init_state")
1344    }
1345
1346    /// Dart's `_parent`.
1347    fn parent(self, app: &App) -> Option<AnyMenuAnchorState> {
1348        AnyMenuAnchorState::maybe_of(app, self.context(app))
1349    }
1350
1351    /// Dart's `isSubmenu`.
1352    fn is_submenu(self, app: &App) -> bool {
1353        MenuController::maybe_of(app, self.context(app)).is_some()
1354    }
1355
1356    /// Dart's `isClosingOrClosed`.
1357    fn is_closing_or_closed(self, app: &App) -> bool {
1358        match self.animation_controller(app).status(app) {
1359            AnimationStatus::Dismissed | AnimationStatus::Reverse => true,
1360            AnimationStatus::Forward | AnimationStatus::Completed => false,
1361        }
1362    }
1363
1364    /// Dart's `isClosing`.
1365    fn is_closing(self, app: &App) -> bool {
1366        match self.animation_controller(app).status(app) {
1367            AnimationStatus::Reverse => true,
1368            AnimationStatus::Dismissed | AnimationStatus::Forward | AnimationStatus::Completed => {
1369                false
1370            }
1371        }
1372    }
1373
1374    /// Dart's `_root`.
1375    fn root(self, app: &App) -> AnyMenuAnchorState {
1376        let mut anchor = self;
1377        while let Some(parent) = anchor.parent(app) {
1378            anchor = parent;
1379        }
1380        anchor
1381    }
1382
1383    /// Dart's `_focusButton`.
1384    fn focus_button(self, app: &mut App) {
1385        let Some(child_focus_node) = self.widget(app).child_focus_node.clone() else {
1386            return;
1387        };
1388        child_focus_node.request_focus(app, None);
1389    }
1390
1391    /// Dart's `_focusFirstMenuItem`.
1392    fn focus_first_menu_item(self, app: &mut App) {
1393        let menu_scope_node = self.menu_scope_node(app);
1394        let Some(context) = menu_scope_node
1395            .as_node()
1396            .context(app)
1397            .filter(|context| context.mounted(app))
1398        else {
1399            return;
1400        };
1401        let (policy, _made) = traversal_policy_of(app, context);
1402        let first_focus = policy.find_first_focus(app, menu_scope_node.as_node(), true);
1403        if let Some(first_focus) = first_focus {
1404            first_focus.request_focus(app, None);
1405        }
1406    }
1407
1408    /// Dart's `_focusLastMenuItem`.
1409    fn focus_last_menu_item(self, app: &mut App) {
1410        let menu_scope_node = self.menu_scope_node(app);
1411        let Some(context) = menu_scope_node
1412            .as_node()
1413            .context(app)
1414            .filter(|context| context.mounted(app))
1415        else {
1416            return;
1417        };
1418        let (policy, _made) = traversal_policy_of(app, context);
1419        let last_focus = policy.find_last_focus(app, menu_scope_node.as_node(), true);
1420        last_focus.request_focus(app, None);
1421    }
1422
1423    /// Dart's `_maybeOf`.
1424    fn maybe_of(app: &App, context: BuildContext) -> Option<AnyMenuAnchorState> {
1425        context
1426            .get_inherited_widget_of_exact_type::<MenuAnchorScope>(app)
1427            .map(|scope| scope.state)
1428    }
1429
1430    /// Dart's `_maybeAnimationStatusOf`.
1431    fn maybe_animation_status_of(app: &mut App, context: BuildContext) -> Option<AnimationStatus> {
1432        context
1433            .depend_on_inherited_widget_of_exact_type::<MenuAnchorScope>(app)
1434            .map(|scope| scope.animation_status)
1435    }
1436}
1437
1438/// Dart's `FocusTraversalGroup.maybeOf(context) ?? ReadingOrderTraversalPolicy()`, with the
1439/// policy it made, if any, for the caller to keep while it uses the first.
1440fn traversal_policy_of(
1441    app: &mut App,
1442    context: BuildContext,
1443) -> (
1444    waft_widgets::AnyFocusTraversalPolicy,
1445    Option<Ref<ReadingOrderTraversalPolicy>>,
1446) {
1447    if let Some(policy) = FocusTraversalGroup::maybe_of(app, context) {
1448        return (policy, None);
1449    }
1450    let policy = ReadingOrderTraversalPolicy::new(app);
1451    (policy.as_policy(), Some(policy))
1452}
1453
1454// ---------------------------------------------------------------------------------------------
1455// MenuBar
1456
1457/// A menu bar that manages cascading child menus.
1458///
1459/// This is a Material Design menu bar that typically resides above the main
1460/// body of an application (but can go anywhere) that defines a menu system for
1461/// invoking callbacks in response to user selection of a menu item.
1462///
1463/// The menus can be opened with a click or tap. Once a menu is opened, it can
1464/// be navigated by using the arrow and tab keys or via mouse hover. Selecting a
1465/// menu item can be done by pressing enter, or by clicking or tapping on the
1466/// menu item. Clicking or tapping on any part of the user interface that isn't
1467/// part of the menu system controlled by the same controller will cause all of
1468/// the menus controlled by that controller to close, as will pressing the
1469/// escape key.
1470///
1471/// When a menu item with a submenu is clicked on, it toggles the visibility of
1472/// the submenu. When the menu item is hovered over, the submenu will open, and
1473/// hovering over other items will close the previous menu and open the newly
1474/// hovered one. When those open/close transitions occur,
1475/// [`SubmenuButton::on_open`], and [`SubmenuButton::on_close`] are called on the
1476/// corresponding [`SubmenuButton`] child of the menu bar.
1477///
1478/// Menus using [`MenuItemButton`] can have a `SingleActivator` or
1479/// `CharacterActivator` assigned to them as their [`MenuItemButton::shortcut`],
1480/// which will display an appropriate shortcut hint. Even though the shortcut
1481/// labels are displayed in the menu, shortcuts are not automatically handled.
1482/// They must be available in whatever context they are appropriate, and handled
1483/// via another mechanism.
1484///
1485/// If shortcuts should be generally enabled, but are not easily defined in a
1486/// context surrounding the menu bar, consider registering them with a
1487/// `ShortcutRegistry` (one is already included in the `WidgetsApp`, and thus
1488/// also `MaterialApp` and `CupertinoApp`). To be sure that selecting a menu item
1489/// and triggering the shortcut do the same thing, it is recommended that they
1490/// call the same callback.
1491///
1492/// See also:
1493///
1494/// * [`MenuAnchor`], a widget that creates a region with a submenu and shows it
1495///   when requested.
1496/// * [`SubmenuButton`], a menu item which manages a submenu.
1497/// * [`MenuItemButton`], a leaf menu item which displays the label, an optional
1498///   shortcut label, and optional leading and trailing icons.
1499/// * `PlatformMenuBar`, which creates a menu bar that is rendered by the host
1500///   platform instead of by Flutter (on macOS, for example).
1501/// * `ShortcutRegistry`, a registry of shortcuts that apply for the entire
1502///   application.
1503/// * `VoidCallbackIntent`, to define intents that will call a `VoidCallback` and
1504///   work with the `Actions` and `Shortcuts` system.
1505/// * `CallbackShortcuts`, to define shortcuts that call a callback without
1506///   involving `Actions`.
1507pub struct MenuBar {
1508    /// See `Widget::key`.
1509    pub key: Option<KeyRef>,
1510
1511    /// The [`MenuStyle`] that defines the visual attributes of the menu bar.
1512    ///
1513    /// Colors and sizing of the menus is controllable via the [`MenuStyle`].
1514    ///
1515    /// Defaults to the ambient `MenuThemeData::style`.
1516    pub style: Option<MenuStyle>,
1517
1518    /// The content will be clipped (or not) according to this option.
1519    ///
1520    /// Defaults to `Clip::None`.
1521    pub clip_behavior: Clip,
1522
1523    /// The [`MenuController`] to use for this menu bar.
1524    pub controller: Option<MenuControllerRef>,
1525
1526    /// The list of menu items that are the top level children of the [`MenuBar`].
1527    ///
1528    /// A Widget in Flutter is immutable, so directly modifying the [`children`](Self::children)
1529    /// with `Vec` APIs will result in incorrect behaviors. Whenever the menus list is modified,
1530    /// a new list object must be provided.
1531    pub children: Vec<WidgetRef>,
1532}
1533
1534impl MenuBar {
1535    /// Creates a const [`MenuBar`].
1536    ///
1537    /// The [`children`](Self::children) argument is required.
1538    pub fn new(children: Vec<WidgetRef>) -> MenuBar {
1539        MenuBar {
1540            key: None,
1541            style: None,
1542            clip_behavior: Clip::None,
1543            controller: None,
1544            children,
1545        }
1546    }
1547
1548    /// Dart `MenuBar(key:)`.
1549    pub fn key(mut self, key: KeyRef) -> MenuBar {
1550        self.key = Some(key);
1551        self
1552    }
1553
1554    /// Dart `MenuBar(style:)`.
1555    pub fn style(mut self, style: MenuStyle) -> MenuBar {
1556        self.style = Some(style);
1557        self
1558    }
1559
1560    /// Dart `MenuBar(clipBehavior:)`.
1561    pub fn clip_behavior(mut self, clip_behavior: Clip) -> MenuBar {
1562        self.clip_behavior = clip_behavior;
1563        self
1564    }
1565
1566    /// Dart `MenuBar(controller:)`.
1567    pub fn controller(mut self, controller: MenuControllerRef) -> MenuBar {
1568        self.controller = Some(controller);
1569        self
1570    }
1571}
1572
1573impl Debug for MenuBar {
1574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1575        f.debug_struct("MenuBar")
1576            .field("style", &self.style)
1577            .field("clipBehavior", &self.clip_behavior)
1578            .field("children", &self.children)
1579            .finish_non_exhaustive()
1580    }
1581}
1582
1583impl StatelessWidget for MenuBar {
1584    fn key(&self) -> Option<&KeyRef> {
1585        self.key.as_ref()
1586    }
1587
1588    fn debug_fill_properties(&self, __app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1589        // Dart's `debugDescribeChildren` has no widget-level hook in this port.
1590        properties.add(
1591            DiagnosticsProperty::<MenuStyle>::new("style", self.style.clone()).default_value(None),
1592        );
1593        properties.add(
1594            DiagnosticsProperty::<Clip>::new("clipBehavior", Some(self.clip_behavior))
1595                .default_value(None),
1596        );
1597    }
1598
1599    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1600        debug_assert!(debug_check_has_overlay(app, context));
1601        let mut menu_anchor =
1602            MenuAnchor::new(self.children.clone()).clip_behavior(self.clip_behavior);
1603        menu_anchor.controller = self.controller.clone();
1604        menu_anchor.style = self.style.clone();
1605        MenuBarAnchor { menu_anchor }.into_widget()
1606    }
1607}
1608
1609// ---------------------------------------------------------------------------------------------
1610// MenuItemButton
1611
1612/// A button for use in a [`MenuBar`], in a menu created with [`MenuAnchor`], or on
1613/// its own, that can be activated by click or keyboard navigation.
1614///
1615/// This widget represents a leaf entry in a menu hierarchy that is typically
1616/// part of a [`MenuBar`], but may be used independently, or as part of a menu
1617/// created with a [`MenuAnchor`].
1618///
1619/// Menus using [`MenuItemButton`] can have a `SingleActivator` or `CharacterActivator`
1620/// assigned to them as their [`shortcut`](Self::shortcut), which will display an
1621/// appropriate shortcut hint. Even though the shortcut labels are displayed in the menu,
1622/// shortcuts are not automatically handled. They must be available in whatever context they
1623/// are appropriate, and handled via another mechanism.
1624///
1625/// See also:
1626///
1627/// * [`MenuBar`], a class that creates a top level menu bar in a Material Design
1628///   style.
1629/// * [`MenuAnchor`], a widget that creates a region with a submenu and shows it
1630///   when requested.
1631/// * [`SubmenuButton`], a menu item similar to this one which manages a submenu.
1632/// * `PlatformMenuBar`, which creates a menu bar that is rendered by the host
1633///   platform instead of by Flutter (on macOS, for example).
1634/// * `ShortcutRegistry`, a registry of shortcuts that apply for the entire
1635///   application.
1636/// * `VoidCallbackIntent`, to define intents that will call a `VoidCallback` and
1637///   work with the `Actions` and `Shortcuts` system.
1638/// * `CallbackShortcuts` to define shortcuts that call a callback without
1639///   involving `Actions`.
1640pub struct MenuItemButton {
1641    /// See `Widget::key`.
1642    pub key: Option<KeyRef>,
1643
1644    /// Called when the button is tapped or otherwise activated.
1645    ///
1646    /// If this callback is null, then the button will be disabled.
1647    ///
1648    /// See also:
1649    ///
1650    ///  * [`enabled`](Self::enabled), which is true if the button is enabled.
1651    pub on_pressed: Option<Listener>,
1652
1653    /// Called when a pointer enters or exits the button response area.
1654    ///
1655    /// The value passed to the callback is true if a pointer has entered button
1656    /// area and false if a pointer has exited.
1657    pub on_hover: Option<ValueChanged<bool>>,
1658
1659    /// Determine if hovering can request focus.
1660    ///
1661    /// Defaults to true.
1662    pub request_focus_on_hover: bool,
1663
1664    /// Handler called when the focus changes.
1665    ///
1666    /// Called with true if this widget's node gains focus, and false if it loses
1667    /// focus.
1668    pub on_focus_change: Option<ValueChanged<bool>>,
1669
1670    /// An optional focus node to use as the focus node for this widget.
1671    pub focus_node: Option<FocusNodeRef>,
1672
1673    /// True if this widget will be selected as the initial focus when no other
1674    /// node in its scope is currently focused.
1675    pub autofocus: bool,
1676
1677    /// The optional shortcut that selects this [`MenuItemButton`].
1678    ///
1679    /// Even though the shortcut label is displayed in the menu, the shortcut is not
1680    /// automatically handled; see [`MenuBar`].
1681    pub shortcut: Option<MenuSerializableShortcutRef>,
1682
1683    /// An optional Semantics label, applied to the entire [`MenuItemButton`].
1684    ///
1685    /// A screen reader will default to reading the derived text on the
1686    /// [`MenuItemButton`] itself, which is not guaranteed to be readable.
1687    /// (For some shortcuts, such as comma, semicolon, and other
1688    /// punctuation, screen readers read silence).
1689    ///
1690    /// Setting this label overwrites the semantics properties of the entire
1691    /// Widget, including its children. Consider wrapping this widget in
1692    /// `Semantics` if you want to customize other properties besides just
1693    /// the label.
1694    ///
1695    /// Null by default.
1696    pub semantics_label: Option<String>,
1697
1698    /// Customizes this button's appearance.
1699    ///
1700    /// Non-null properties of this style override the corresponding properties in
1701    /// [`theme_style_of`](Self::theme_style_of) and [`default_style_of`](Self::default_style_of).
1702    /// `WidgetStateProperty`s that resolve to non-null values will similarly override the
1703    /// corresponding `WidgetStateProperty`s in [`theme_style_of`](Self::theme_style_of) and
1704    /// [`default_style_of`](Self::default_style_of).
1705    ///
1706    /// Null by default.
1707    pub style: Option<ButtonStyle>,
1708
1709    /// Represents the interactive "state" of this widget in terms of a set of
1710    /// `WidgetState`s, including `WidgetState::Pressed`, `WidgetState::Hovered`,
1711    /// `WidgetState::Focused`.
1712    pub states_controller: Option<Ref<WidgetStatesController>>,
1713
1714    /// The content will be clipped (or not) according to this option.
1715    ///
1716    /// Defaults to `Clip::None`.
1717    pub clip_behavior: Clip,
1718
1719    /// An optional icon to display before the [`child`](Self::child) label.
1720    pub leading_icon: Option<WidgetRef>,
1721
1722    /// An optional icon to display after the [`child`](Self::child) label.
1723    pub trailing_icon: Option<WidgetRef>,
1724
1725    /// Determines if the menu will be closed when a [`MenuItemButton`]
1726    /// is pressed.
1727    ///
1728    /// Defaults to true.
1729    pub close_on_activate: bool,
1730
1731    /// The direction in which the menu item expands.
1732    ///
1733    /// If the menu item button is a descendant of [`MenuAnchor`] or [`MenuBar`], then
1734    /// this property is ignored.
1735    ///
1736    /// If [`overflow_axis`](Self::overflow_axis) is `Axis::Vertical`, the menu will be
1737    /// expanded vertically. If [`overflow_axis`](Self::overflow_axis) is `Axis::Horizontal`,
1738    /// then the menu will be expanded horizontally.
1739    ///
1740    /// Defaults to `Axis::Horizontal`.
1741    pub overflow_axis: Axis,
1742
1743    /// The widget displayed in the center of this button.
1744    ///
1745    /// Typically this is the button's label, using a `Text` widget.
1746    pub child: Option<WidgetRef>,
1747}
1748
1749impl Default for MenuItemButton {
1750    fn default() -> MenuItemButton {
1751        MenuItemButton {
1752            key: None,
1753            on_pressed: None,
1754            on_hover: None,
1755            request_focus_on_hover: true,
1756            on_focus_change: None,
1757            focus_node: None,
1758            autofocus: false,
1759            shortcut: None,
1760            semantics_label: None,
1761            style: None,
1762            states_controller: None,
1763            clip_behavior: Clip::None,
1764            leading_icon: None,
1765            trailing_icon: None,
1766            close_on_activate: true,
1767            overflow_axis: Axis::Horizontal,
1768            child: None,
1769        }
1770    }
1771}
1772
1773impl MenuItemButton {
1774    /// Creates a const [`MenuItemButton`].
1775    pub fn new() -> MenuItemButton {
1776        MenuItemButton::default()
1777    }
1778
1779    /// Dart `MenuItemButton(key:)`.
1780    pub fn key(mut self, key: KeyRef) -> MenuItemButton {
1781        self.key = Some(key);
1782        self
1783    }
1784
1785    /// Dart `MenuItemButton(onPressed:)`.
1786    pub fn on_pressed(mut self, on_pressed: Listener) -> MenuItemButton {
1787        self.on_pressed = Some(on_pressed);
1788        self
1789    }
1790
1791    /// Dart `MenuItemButton(onHover:)`.
1792    pub fn on_hover(mut self, on_hover: ValueChanged<bool>) -> MenuItemButton {
1793        self.on_hover = Some(on_hover);
1794        self
1795    }
1796
1797    /// Dart `MenuItemButton(requestFocusOnHover:)`.
1798    pub fn request_focus_on_hover(mut self, request_focus_on_hover: bool) -> MenuItemButton {
1799        self.request_focus_on_hover = request_focus_on_hover;
1800        self
1801    }
1802
1803    /// Dart `MenuItemButton(onFocusChange:)`.
1804    pub fn on_focus_change(mut self, on_focus_change: ValueChanged<bool>) -> MenuItemButton {
1805        self.on_focus_change = Some(on_focus_change);
1806        self
1807    }
1808
1809    /// Dart `MenuItemButton(focusNode:)`.
1810    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> MenuItemButton {
1811        self.focus_node = Some(focus_node);
1812        self
1813    }
1814
1815    /// Dart `MenuItemButton(autofocus:)`.
1816    pub fn autofocus(mut self, autofocus: bool) -> MenuItemButton {
1817        self.autofocus = autofocus;
1818        self
1819    }
1820
1821    /// Dart `MenuItemButton(shortcut:)`.
1822    pub fn shortcut(mut self, shortcut: MenuSerializableShortcutRef) -> MenuItemButton {
1823        self.shortcut = Some(shortcut);
1824        self
1825    }
1826
1827    /// Dart `MenuItemButton(semanticsLabel:)`.
1828    pub fn semantics_label(mut self, semantics_label: impl Into<String>) -> MenuItemButton {
1829        self.semantics_label = Some(semantics_label.into());
1830        self
1831    }
1832
1833    /// Dart `MenuItemButton(style:)`.
1834    pub fn style(mut self, style: ButtonStyle) -> MenuItemButton {
1835        self.style = Some(style);
1836        self
1837    }
1838
1839    /// Dart `MenuItemButton(statesController:)`.
1840    pub fn states_controller(
1841        mut self,
1842        states_controller: Ref<WidgetStatesController>,
1843    ) -> MenuItemButton {
1844        self.states_controller = Some(states_controller);
1845        self
1846    }
1847
1848    /// Dart `MenuItemButton(clipBehavior:)`.
1849    pub fn clip_behavior(mut self, clip_behavior: Clip) -> MenuItemButton {
1850        self.clip_behavior = clip_behavior;
1851        self
1852    }
1853
1854    /// Dart `MenuItemButton(leadingIcon:)`.
1855    #[cfg_attr(debug_assertions, track_caller)]
1856    pub fn leading_icon<K>(mut self, leading_icon: impl IntoWidget<K>) -> MenuItemButton {
1857        self.leading_icon = Some(leading_icon.into_widget());
1858        self
1859    }
1860
1861    /// Dart `MenuItemButton(trailingIcon:)`.
1862    #[cfg_attr(debug_assertions, track_caller)]
1863    pub fn trailing_icon<K>(mut self, trailing_icon: impl IntoWidget<K>) -> MenuItemButton {
1864        self.trailing_icon = Some(trailing_icon.into_widget());
1865        self
1866    }
1867
1868    /// Dart `MenuItemButton(closeOnActivate:)`.
1869    pub fn close_on_activate(mut self, close_on_activate: bool) -> MenuItemButton {
1870        self.close_on_activate = close_on_activate;
1871        self
1872    }
1873
1874    /// Dart `MenuItemButton(overflowAxis:)`.
1875    pub fn overflow_axis(mut self, overflow_axis: Axis) -> MenuItemButton {
1876        self.overflow_axis = overflow_axis;
1877        self
1878    }
1879
1880    /// Dart `MenuItemButton(child:)`.
1881    #[cfg_attr(debug_assertions, track_caller)]
1882    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MenuItemButton {
1883        self.child = Some(child.into_widget());
1884        self
1885    }
1886
1887    /// Whether the button is enabled or disabled.
1888    ///
1889    /// To enable a button, set its [`on_pressed`](Self::on_pressed) property to a non-null
1890    /// value.
1891    pub fn enabled(&self) -> bool {
1892        self.on_pressed.is_some()
1893    }
1894
1895    /// Defines the button's default appearance.
1896    ///
1897    /// The button `child`'s `Text` and `Icon` widgets are rendered with the [`ButtonStyle`]'s
1898    /// foreground color. The button's `InkWell` adds the style's overlay color when the button
1899    /// is focused, hovered or pressed. The button's background color becomes its `Material`
1900    /// color and is transparent by default.
1901    pub fn default_style_of(
1902        &self,
1903        app: &mut App,
1904        context: BuildContext,
1905    ) -> Box<dyn ButtonStyleGetters> {
1906        let _ = app;
1907        Box::new(MenuButtonDefaultsM3::new(context))
1908    }
1909
1910    /// Returns the [`MenuButtonThemeData::style`](crate::MenuButtonThemeData::style) of the
1911    /// closest [`MenuButtonTheme`] ancestor.
1912    pub fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle> {
1913        MenuButtonTheme::of(app, context).style
1914    }
1915
1916    /// A static convenience method that constructs a [`MenuItemButton`]'s
1917    /// [`ButtonStyle`] given simple values.
1918    ///
1919    /// The `foreground_color` color is used to create a `WidgetStateProperty`
1920    /// [`ButtonStyle::foreground_color`] value. Specify a value for `foreground_color`
1921    /// to specify the color of the button's icons. Use `background_color` for the
1922    /// button's background fill color. Use `disabled_foreground_color` and
1923    /// `disabled_background_color` to specify the button's disabled icon and fill
1924    /// color.
1925    ///
1926    /// Similarly, the `enabled_mouse_cursor` and `disabled_mouse_cursor`
1927    /// parameters are used to construct [`ButtonStyle::mouse_cursor`].
1928    ///
1929    /// The `icon_color`, `disabled_icon_color` are used to construct
1930    /// [`ButtonStyle::icon_color`] and `icon_size` is used to construct
1931    /// [`ButtonStyle::icon_size`].
1932    ///
1933    /// All of the other parameters are either used directly or used to create a
1934    /// `WidgetStateProperty` with a single value for all states.
1935    ///
1936    /// All parameters default to null, by default this method returns a
1937    /// [`ButtonStyle`] that doesn't override anything.
1938    ///
1939    /// For example, to override the default foreground color for a
1940    /// [`MenuItemButton`], as well as its overlay color, with all of the standard
1941    /// opacity adjustments for the pressed, focused, and hovered states, one
1942    /// could write:
1943    ///
1944    /// ```text
1945    /// MenuItemButton::new()
1946    ///     .leading_icon(Icon::new(Some(Icons::pets())))
1947    ///     .style(MenuItemButton::style_from().foreground_color(Colors::GREEN.primary()).build())
1948    ///     .on_pressed(Listener::new(|_app| {
1949    ///         // ...
1950    ///     }))
1951    ///     .child(Text::new("Button Label"))
1952    /// ```
1953    pub fn style_from() -> MenuButtonStyleFromBuilder {
1954        MenuButtonStyleFromBuilder::default()
1955    }
1956}
1957
1958impl Debug for MenuItemButton {
1959    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1960        let mut properties = f.debug_struct("MenuItemButton");
1961        if self.on_pressed.is_none() {
1962            properties.field("enabled", &"DISABLED");
1963        }
1964        properties
1965            .field("style", &self.style)
1966            .field("shortcut", &self.shortcut)
1967            .field("focusNode", &self.focus_node)
1968            .field("clipBehavior", &self.clip_behavior)
1969            .field("statesController", &self.states_controller)
1970            .finish_non_exhaustive()
1971    }
1972}
1973
1974impl StatefulWidget for MenuItemButton {
1975    type State = MenuItemButtonState;
1976
1977    fn key(&self) -> Option<&KeyRef> {
1978        self.key.as_ref()
1979    }
1980
1981    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1982        properties.add(
1983            FlagProperty::new("enabled", Some(self.on_pressed.is_some())).if_false("DISABLED"),
1984        );
1985        properties.add(
1986            DiagnosticsProperty::<String>::new(
1987                "shortcut",
1988                self.shortcut
1989                    .as_ref()
1990                    .map(|shortcut| format!("{shortcut:?}")),
1991            )
1992            .default_value(None),
1993        );
1994        properties.add(
1995            DiagnosticsProperty::<String>::new(
1996                "focusNode",
1997                self.focus_node.as_ref().map(|node| node.to_string(app)),
1998            )
1999            .default_value(None),
2000        );
2001        properties.add(
2002            EnumProperty::<Clip>::new("clipBehavior", Some(self.clip_behavior))
2003                .default_value(Some(Clip::None)),
2004        );
2005        properties.add(
2006            DiagnosticsProperty::<String>::new(
2007                "statesController",
2008                self.states_controller
2009                    .as_ref()
2010                    .map(|controller| controller.handle().to_string(app)),
2011            )
2012            .default_value(None),
2013        );
2014    }
2015
2016    fn create_state(&self) -> MenuItemButtonState {
2017        MenuItemButtonState {
2018            state: StateData::new(),
2019            internal_focus_node: None,
2020            is_hovered: false,
2021        }
2022    }
2023}
2024
2025/// Dart's `MenuItemButton.styleFrom(..)` and `SubmenuButton.styleFrom(..)` arguments, which
2026/// both hand to `TextButton.styleFrom`; [`build`](Self::build) makes the [`ButtonStyle`].
2027#[derive(Clone, Default)]
2028pub struct MenuButtonStyleFromBuilder {
2029    foreground_color: Option<Color>,
2030    background_color: Option<Color>,
2031    disabled_foreground_color: Option<Color>,
2032    disabled_background_color: Option<Color>,
2033    shadow_color: Option<Color>,
2034    surface_tint_color: Option<Color>,
2035    icon_color: Option<Color>,
2036    icon_size: Option<f64>,
2037    disabled_icon_color: Option<Color>,
2038    text_style: Option<waft_painting::TextStyle>,
2039    overlay_color: Option<Color>,
2040    elevation: Option<f64>,
2041    padding: Option<EdgeInsetsGeometry>,
2042    minimum_size: Option<Size>,
2043    fixed_size: Option<Size>,
2044    maximum_size: Option<Size>,
2045    enabled_mouse_cursor: Option<MouseCursorRef>,
2046    disabled_mouse_cursor: Option<MouseCursorRef>,
2047    side: Option<waft_painting::BorderSide>,
2048    shape: Option<OutlinedBorderRef>,
2049    visual_density: Option<VisualDensity>,
2050    tap_target_size: Option<MaterialTapTargetSize>,
2051    animation_duration: Option<Duration>,
2052    enable_feedback: Option<bool>,
2053    alignment: Option<AlignmentGeometry>,
2054    splash_factory: Option<InteractiveInkFeatureFactoryRef>,
2055}
2056
2057/// The fluent setters of Dart's named `styleFrom` arguments.
2058macro_rules! menu_button_style_from_setters {
2059    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
2060        $(
2061            #[doc = concat!("Dart `MenuItemButton.styleFrom(", $dart, ":)`.")]
2062            pub fn $field(mut self, $field: $ty) -> MenuButtonStyleFromBuilder {
2063                self.$field = Some($field);
2064                self
2065            }
2066        )*
2067    };
2068}
2069
2070impl MenuButtonStyleFromBuilder {
2071    menu_button_style_from_setters!(
2072        foreground_color: Color => "foregroundColor",
2073        background_color: Color => "backgroundColor",
2074        disabled_foreground_color: Color => "disabledForegroundColor",
2075        disabled_background_color: Color => "disabledBackgroundColor",
2076        shadow_color: Color => "shadowColor",
2077        surface_tint_color: Color => "surfaceTintColor",
2078        icon_color: Color => "iconColor",
2079        icon_size: f64 => "iconSize",
2080        disabled_icon_color: Color => "disabledIconColor",
2081        text_style: waft_painting::TextStyle => "textStyle",
2082        overlay_color: Color => "overlayColor",
2083        elevation: f64 => "elevation",
2084        padding: EdgeInsetsGeometry => "padding",
2085        minimum_size: Size => "minimumSize",
2086        fixed_size: Size => "fixedSize",
2087        maximum_size: Size => "maximumSize",
2088        enabled_mouse_cursor: MouseCursorRef => "enabledMouseCursor",
2089        disabled_mouse_cursor: MouseCursorRef => "disabledMouseCursor",
2090        side: waft_painting::BorderSide => "side",
2091        visual_density: VisualDensity => "visualDensity",
2092        tap_target_size: MaterialTapTargetSize => "tapTargetSize",
2093        animation_duration: Duration => "animationDuration",
2094        enable_feedback: bool => "enableFeedback",
2095        alignment: AlignmentGeometry => "alignment",
2096        splash_factory: InteractiveInkFeatureFactoryRef => "splashFactory",
2097    );
2098
2099    /// Dart `MenuItemButton.styleFrom(shape:)`.
2100    pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> MenuButtonStyleFromBuilder {
2101        self.shape = Some(shape.into());
2102        self
2103    }
2104
2105    /// The [`ButtonStyle`] `TextButton.styleFrom` makes from these values.
2106    pub fn build(self) -> ButtonStyle {
2107        let mut style_from = TextButton::style_from();
2108        macro_rules! forward {
2109            ($($field:ident),* $(,)?) => {
2110                $(
2111                    if let Some(value) = self.$field {
2112                        style_from = style_from.$field(value);
2113                    }
2114                )*
2115            };
2116        }
2117        forward!(
2118            foreground_color,
2119            background_color,
2120            disabled_background_color,
2121            disabled_foreground_color,
2122            shadow_color,
2123            surface_tint_color,
2124            icon_color,
2125            icon_size,
2126            disabled_icon_color,
2127            text_style,
2128            overlay_color,
2129            elevation,
2130            padding,
2131            minimum_size,
2132            fixed_size,
2133            maximum_size,
2134            enabled_mouse_cursor,
2135            disabled_mouse_cursor,
2136            side,
2137            shape,
2138            visual_density,
2139            tap_target_size,
2140            animation_duration,
2141            enable_feedback,
2142            alignment,
2143            splash_factory,
2144        );
2145        style_from.build()
2146    }
2147}
2148
2149/// Dart's `_MenuItemButtonState`.
2150pub struct MenuItemButtonState {
2151    state: StateData<MenuItemButton>,
2152    // If a focus node isn't given to the widget, then we have to manage our own.
2153    internal_focus_node: Option<Ref<FocusNode>>,
2154    is_hovered: bool,
2155}
2156
2157impl MenuItemButtonState {
2158    /// Dart's `_focusNode`.
2159    fn focus_node(self: Handle<Self>, app: &App) -> FocusNodeRef {
2160        self.widget(app)
2161            .focus_node
2162            .clone()
2163            .or_else(|| app.get(self).internal_focus_node.as_ref().map(Ref::erase))
2164            .expect("made when the widget has no focus node")
2165    }
2166
2167    /// Dart's `_anchor`.
2168    fn anchor(self: Handle<Self>, app: &App) -> Option<AnyMenuAnchorState> {
2169        AnyMenuAnchorState::maybe_of(app, self.context(app))
2170    }
2171
2172    fn handle_focus_change_listener(self: Handle<Self>) -> Listener {
2173        Listener::handle_method(self, Self::handle_focus_change)
2174    }
2175
2176    /// Dart's `_handleFocusChange`.
2177    fn handle_focus_change(self: Handle<Self>, app: &mut App) {
2178        if !self.focus_node(app).has_primary_focus(app) {
2179            // Close any child menus of this button's menu.
2180            if let Some(controller) = MenuController::maybe_of(app, self.context(app)) {
2181                controller.close_children(app);
2182            }
2183        }
2184    }
2185
2186    /// Dart's `_handlePointerExit`.
2187    fn handle_pointer_exit(self: Handle<Self>, app: &mut App, _event: PointerExitEvent) {
2188        if app.get(self).is_hovered {
2189            if let Some(on_hover) = self.widget(app).on_hover.clone() {
2190                on_hover(app, false);
2191            }
2192            app.get_mut(self).is_hovered = false;
2193        }
2194    }
2195
2196    // TextButton.onHover and MouseRegion.onHover can't be used without triggering
2197    // focus on scroll.
2198    fn handle_pointer_hover(self: Handle<Self>, app: &mut App, _event: PointerHoverEvent) {
2199        if !app.get(self).is_hovered {
2200            app.get_mut(self).is_hovered = true;
2201            if let Some(on_hover) = self.widget(app).on_hover.clone() {
2202                on_hover(app, true);
2203            }
2204            if self.widget(app).request_focus_on_hover {
2205                self.focus_node(app).request_focus(app, None);
2206
2207                // Without invalidating the focus policy, switching to directional focus
2208                // may not originate at this node.
2209                let context = self.context(app);
2210                let policy = FocusTraversalGroup::of(app, context);
2211                let scope = FocusScope::of(app, context, true);
2212                policy.invalidate_scope_data(app, scope);
2213            }
2214        }
2215    }
2216
2217    /// Dart's `_handleSelect`.
2218    fn handle_select(self: Handle<Self>, app: &mut App) {
2219        if self.widget(app).close_on_activate
2220            && let Some(anchor) = self.anchor(app)
2221        {
2222            anchor.root(app).menu_controller(app).close(app);
2223        }
2224        // Delay the call to onPressed until post-frame so that the focus is
2225        // restored to what it was before the menu was opened before the action is
2226        // executed.
2227        let last_on_pressed = self.widget(app).on_pressed.clone();
2228        let view = View::maybe_id_of(app, self.context(app));
2229        SchedulerBinding::add_post_frame_callback(
2230            app,
2231            FrameCallback::new(move |app, _timestamp| {
2232                FocusManager::instance(app).apply_focus_changes_if_needed(app);
2233                // Dart's `widget` outlives the state's `dispose`, as this state's own does not.
2234                let on_pressed = if app.contains(self) {
2235                    self.widget(app).on_pressed.clone()
2236                } else {
2237                    last_on_pressed.clone()
2238                };
2239                if let Some(on_pressed) = on_pressed {
2240                    on_pressed.call(app);
2241                }
2242            }),
2243            view,
2244        );
2245    }
2246
2247    /// Dart's `_createInternalFocusNodeIfNeeded`.
2248    fn create_internal_focus_node_if_needed(self: Handle<Self>, app: &mut App) {
2249        if self.widget(app).focus_node.is_none() {
2250            let internal_focus_node = FocusNode::new(app);
2251            app.get_mut(self).internal_focus_node = Some(internal_focus_node.clone());
2252            if cfg!(debug_assertions) {
2253                let label = describe_child("MenuItemButton", &self.widget(app).child);
2254                internal_focus_node.set_debug_label(app, Some(label));
2255            }
2256        }
2257    }
2258}
2259
2260impl State for MenuItemButtonState {
2261    type Widget = MenuItemButton;
2262    waft_widgets::state_accessors!();
2263
2264    fn init_state(self: Handle<Self>, app: &mut App) {
2265        self.create_internal_focus_node_if_needed(app);
2266        self.focus_node(app)
2267            .add_listener(app, self.handle_focus_change_listener());
2268    }
2269
2270    fn dispose(self: Handle<Self>, app: &mut App) {
2271        self.focus_node(app)
2272            .remove_listener(app, &self.handle_focus_change_listener());
2273        if let Some(internal_focus_node) = app.get_mut(self).internal_focus_node.take() {
2274            internal_focus_node.dispose(app);
2275        }
2276    }
2277
2278    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MenuItemButton) {
2279        if self.widget(app).focus_node != old_widget.focus_node {
2280            if let Some(old_focus_node) = old_widget
2281                .focus_node
2282                .clone()
2283                .or_else(|| app.get(self).internal_focus_node.as_ref().map(Ref::erase))
2284            {
2285                old_focus_node.remove_listener(app, &self.handle_focus_change_listener());
2286            }
2287            if self.widget(app).focus_node.is_some()
2288                && let Some(internal_focus_node) = app.get_mut(self).internal_focus_node.take()
2289            {
2290                internal_focus_node.dispose(app);
2291            }
2292            self.create_internal_focus_node_if_needed(app);
2293            self.focus_node(app)
2294                .add_listener(app, self.handle_focus_change_listener());
2295        }
2296    }
2297
2298    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2299        // Since we don't want to use the theme style or default style from the
2300        // TextButton, we merge the styles, merging them in the right order when
2301        // each type of style exists. Each "*StyleOf" function is only called once.
2302        let widget_ref = context.widget(app).clone();
2303        let widget = downcast_widget::<MenuItemButton>(&*widget_ref)
2304            .expect("a MenuItemButtonState builds its MenuItemButton");
2305        let mut merged_style = match widget.theme_style_of(app, context) {
2306            Some(theme_style) => {
2307                theme_style.merge(Some(&widget.default_style_of(app, context).copy_with(app)))
2308            }
2309            // Dart passes the defaults object on as the text button's style, whose getters the
2310            // button reads all of when it builds.
2311            None => widget.default_style_of(app, context).copy_with(app),
2312        };
2313        if let Some(style) = &widget.style {
2314            merged_style = style.merge(Some(&merged_style));
2315        }
2316
2317        let enabled = widget.enabled();
2318        let overflow_axis = self.anchor(app).map_or(
2319            self.widget(app).overflow_axis,
2320            AnyMenuAnchorState::orientation,
2321        );
2322        let widget = self.widget(app);
2323        let label = MenuItemLabel {
2324            has_submenu: false,
2325            show_decoration: true,
2326            leading_icon: widget.leading_icon.clone(),
2327            trailing_icon: widget.trailing_icon.clone(),
2328            shortcut: widget.shortcut.clone(),
2329            semantics_label: widget.semantics_label.clone(),
2330            overflow_axis,
2331            submenu_icon: None,
2332            child: widget.child.clone(),
2333        };
2334        let mut button = TextButton::new(
2335            enabled.then(|| Listener::handle_method(self, Self::handle_select)),
2336            Some(label),
2337        )
2338        .focus_node(self.focus_node(app))
2339        .style(merged_style)
2340        .autofocus(enabled && widget.autofocus)
2341        .clip_behavior(widget.clip_behavior);
2342        if enabled && let Some(on_focus_change) = widget.on_focus_change.clone() {
2343            button = button.on_focus_change(on_focus_change);
2344        }
2345        if let Some(states_controller) = widget.states_controller.clone() {
2346            button = button.states_controller(states_controller);
2347        }
2348        let mut child = button.into_widget();
2349
2350        if platform_supports_accelerators(app) && enabled {
2351            child = MenuAcceleratorCallbackBinding::new(child)
2352                .on_invoke(Listener::handle_method(self, Self::handle_select))
2353                .into_widget();
2354        }
2355
2356        let widget = self.widget(app);
2357        if widget.on_hover.is_some() || widget.request_focus_on_hover {
2358            child = MouseRegion::new()
2359                .on_hover(Rc::new(move |app: &mut App, event| {
2360                    self.handle_pointer_hover(app, event)
2361                }))
2362                .on_exit(Rc::new(move |app: &mut App, event| {
2363                    self.handle_pointer_exit(app, event)
2364                }))
2365                .child(child)
2366                .into_widget();
2367        }
2368
2369        MergeSemantics::new().child(child).into_widget()
2370    }
2371}
2372
2373impl Debug for MenuItemButtonState {
2374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2375        f.debug_struct("_MenuItemButtonState")
2376            .field("is_hovered", &self.is_hovered)
2377            .finish_non_exhaustive()
2378    }
2379}
2380
2381// ---------------------------------------------------------------------------------------------
2382// CheckboxMenuButton
2383
2384/// A menu item that combines a [`Checkbox`] widget with a [`MenuItemButton`].
2385///
2386/// To style the checkbox separately from the button, add a `CheckboxTheme`
2387/// ancestor.
2388///
2389/// See also:
2390///
2391/// - [`MenuBar`], a widget that creates a menu bar of cascading menu items.
2392/// - [`MenuAnchor`], a widget that defines a region which can host a cascading
2393///   menu.
2394pub struct CheckboxMenuButton {
2395    /// See `Widget::key`.
2396    pub key: Option<KeyRef>,
2397
2398    /// Whether this checkbox is checked.
2399    ///
2400    /// When [`tristate`](Self::tristate) is true, a value of null corresponds to the mixed
2401    /// state. When [`tristate`](Self::tristate) is false, this value must not be null.
2402    pub value: Option<bool>,
2403
2404    /// If true, then the checkbox's [`value`](Self::value) can be true, false, or null.
2405    ///
2406    /// [`CheckboxMenuButton`] displays a dash when its value is null.
2407    ///
2408    /// When a tri-state checkbox ([`tristate`](Self::tristate) is true) is tapped, its
2409    /// [`on_changed`](Self::on_changed) callback will be applied to true if the current value
2410    /// is false, to null if value is true, and to false if value is null (i.e. it cycles
2411    /// through false => true => null => false when tapped).
2412    ///
2413    /// If tristate is false (the default), [`value`](Self::value) must not be null.
2414    pub tristate: bool,
2415
2416    /// True if this checkbox wants to show an error state.
2417    ///
2418    /// The checkbox will have different default container color and check color when
2419    /// this is true. This is only used when `ThemeData::use_material3` is set to true.
2420    ///
2421    /// Defaults to false.
2422    pub is_error: bool,
2423
2424    /// Called when the value of the checkbox should change.
2425    ///
2426    /// The checkbox passes the new value to the callback but does not actually
2427    /// change state until the parent widget rebuilds the checkbox with the new
2428    /// value.
2429    ///
2430    /// If this callback is null, the menu item will be displayed as disabled
2431    /// and will not respond to input gestures.
2432    ///
2433    /// When the checkbox is tapped, if [`tristate`](Self::tristate) is false (the default)
2434    /// then the [`on_changed`](Self::on_changed) callback will be applied to `!value`. If
2435    /// [`tristate`](Self::tristate) is true this callback cycle from false to true to null and
2436    /// then back to false again.
2437    pub on_changed: Option<ValueChanged<Option<bool>>>,
2438
2439    /// Called when a pointer enters or exits the button response area.
2440    ///
2441    /// The value passed to the callback is true if a pointer has entered button
2442    /// area and false if a pointer has exited.
2443    pub on_hover: Option<ValueChanged<bool>>,
2444
2445    /// Handler called when the focus changes.
2446    ///
2447    /// Called with true if this widget's node gains focus, and false if it loses
2448    /// focus.
2449    pub on_focus_change: Option<ValueChanged<bool>>,
2450
2451    /// An optional focus node to use as the focus node for this widget.
2452    pub focus_node: Option<FocusNodeRef>,
2453
2454    /// The optional shortcut that selects this [`MenuItemButton`].
2455    pub shortcut: Option<MenuSerializableShortcutRef>,
2456
2457    /// Customizes this button's appearance.
2458    ///
2459    /// Non-null properties of this style override the corresponding properties in
2460    /// [`MenuItemButton::theme_style_of`] and [`MenuItemButton::default_style_of`].
2461    /// `WidgetStateProperty`s that resolve to non-null values will similarly
2462    /// override the corresponding `WidgetStateProperty`s in
2463    /// [`MenuItemButton::theme_style_of`] and [`MenuItemButton::default_style_of`].
2464    ///
2465    /// Null by default.
2466    pub style: Option<ButtonStyle>,
2467
2468    /// Represents the interactive "state" of this widget in terms of a set of
2469    /// `WidgetState`s.
2470    pub states_controller: Option<Ref<WidgetStatesController>>,
2471
2472    /// The content will be clipped (or not) according to this option.
2473    ///
2474    /// Defaults to `Clip::None`.
2475    pub clip_behavior: Clip,
2476
2477    /// An optional icon to display after the [`child`](Self::child) label.
2478    pub trailing_icon: Option<WidgetRef>,
2479
2480    /// Determines if the menu will be closed when a [`MenuItemButton`]
2481    /// is pressed.
2482    ///
2483    /// Defaults to true.
2484    pub close_on_activate: bool,
2485
2486    /// The widget displayed in the center of this button.
2487    ///
2488    /// Typically this is the button's label, using a `Text` widget.
2489    pub child: Option<WidgetRef>,
2490}
2491
2492impl CheckboxMenuButton {
2493    /// Creates a const [`CheckboxMenuButton`].
2494    ///
2495    /// The [`child`](Self::child), [`value`](Self::value), and
2496    /// [`on_changed`](Self::on_changed) attributes are required.
2497    #[cfg_attr(debug_assertions, track_caller)]
2498    pub fn new<K>(
2499        value: Option<bool>,
2500        on_changed: Option<ValueChanged<Option<bool>>>,
2501        child: Option<impl IntoWidget<K>>,
2502    ) -> CheckboxMenuButton {
2503        CheckboxMenuButton {
2504            key: None,
2505            value,
2506            tristate: false,
2507            is_error: false,
2508            on_changed,
2509            on_hover: None,
2510            on_focus_change: None,
2511            focus_node: None,
2512            shortcut: None,
2513            style: None,
2514            states_controller: None,
2515            clip_behavior: Clip::None,
2516            trailing_icon: None,
2517            close_on_activate: true,
2518            child: match child {
2519                Some(child) => Some(child.into_widget()),
2520                None => None,
2521            },
2522        }
2523    }
2524
2525    /// Dart `CheckboxMenuButton(key:)`.
2526    pub fn key(mut self, key: KeyRef) -> CheckboxMenuButton {
2527        self.key = Some(key);
2528        self
2529    }
2530
2531    /// Dart `CheckboxMenuButton(tristate:)`.
2532    pub fn tristate(mut self, tristate: bool) -> CheckboxMenuButton {
2533        self.tristate = tristate;
2534        self
2535    }
2536
2537    /// Dart `CheckboxMenuButton(isError:)`.
2538    pub fn is_error(mut self, is_error: bool) -> CheckboxMenuButton {
2539        self.is_error = is_error;
2540        self
2541    }
2542
2543    /// Dart `CheckboxMenuButton(onHover:)`.
2544    pub fn on_hover(mut self, on_hover: ValueChanged<bool>) -> CheckboxMenuButton {
2545        self.on_hover = Some(on_hover);
2546        self
2547    }
2548
2549    /// Dart `CheckboxMenuButton(onFocusChange:)`.
2550    pub fn on_focus_change(mut self, on_focus_change: ValueChanged<bool>) -> CheckboxMenuButton {
2551        self.on_focus_change = Some(on_focus_change);
2552        self
2553    }
2554
2555    /// Dart `CheckboxMenuButton(focusNode:)`.
2556    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> CheckboxMenuButton {
2557        self.focus_node = Some(focus_node);
2558        self
2559    }
2560
2561    /// Dart `CheckboxMenuButton(shortcut:)`.
2562    pub fn shortcut(mut self, shortcut: MenuSerializableShortcutRef) -> CheckboxMenuButton {
2563        self.shortcut = Some(shortcut);
2564        self
2565    }
2566
2567    /// Dart `CheckboxMenuButton(style:)`.
2568    pub fn style(mut self, style: ButtonStyle) -> CheckboxMenuButton {
2569        self.style = Some(style);
2570        self
2571    }
2572
2573    /// Dart `CheckboxMenuButton(statesController:)`.
2574    pub fn states_controller(
2575        mut self,
2576        states_controller: Ref<WidgetStatesController>,
2577    ) -> CheckboxMenuButton {
2578        self.states_controller = Some(states_controller);
2579        self
2580    }
2581
2582    /// Dart `CheckboxMenuButton(clipBehavior:)`.
2583    pub fn clip_behavior(mut self, clip_behavior: Clip) -> CheckboxMenuButton {
2584        self.clip_behavior = clip_behavior;
2585        self
2586    }
2587
2588    /// Dart `CheckboxMenuButton(trailingIcon:)`.
2589    #[cfg_attr(debug_assertions, track_caller)]
2590    pub fn trailing_icon<K>(mut self, trailing_icon: impl IntoWidget<K>) -> CheckboxMenuButton {
2591        self.trailing_icon = Some(trailing_icon.into_widget());
2592        self
2593    }
2594
2595    /// Dart `CheckboxMenuButton(closeOnActivate:)`.
2596    pub fn close_on_activate(mut self, close_on_activate: bool) -> CheckboxMenuButton {
2597        self.close_on_activate = close_on_activate;
2598        self
2599    }
2600
2601    /// Whether the button is enabled or disabled.
2602    ///
2603    /// To enable a button, set its [`on_changed`](Self::on_changed) property to a non-null
2604    /// value.
2605    pub fn enabled(&self) -> bool {
2606        self.on_changed.is_some()
2607    }
2608}
2609
2610impl Debug for CheckboxMenuButton {
2611    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2612        f.debug_struct("CheckboxMenuButton")
2613            .field("value", &self.value)
2614            .field("tristate", &self.tristate)
2615            .finish_non_exhaustive()
2616    }
2617}
2618
2619impl StatelessWidget for CheckboxMenuButton {
2620    fn key(&self) -> Option<&KeyRef> {
2621        self.key.as_ref()
2622    }
2623
2624    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
2625        let on_pressed = self.on_changed.clone().map(|on_changed| {
2626            let (value, tristate) = (self.value, self.tristate);
2627            Listener::new(move |app| match value {
2628                Some(false) => on_changed(app, Some(true)),
2629                Some(true) => on_changed(app, if tristate { None } else { Some(false) }),
2630                None => on_changed(app, Some(false)),
2631            })
2632        });
2633        let checkbox = Checkbox::new(self.value, self.on_changed.clone())
2634            .tristate(self.tristate)
2635            .is_error(self.is_error);
2636        let leading_icon = ExcludeFocus::new(
2637            IgnorePointer::new().child(
2638                ConstrainedBox::new(
2639                    BoxConstraints::new()
2640                        .max_height(Checkbox::WIDTH)
2641                        .max_width(Checkbox::WIDTH),
2642                )
2643                .child(checkbox),
2644            ),
2645        );
2646        let mut button = MenuItemButton::new()
2647            .style_option(self.style.clone())
2648            .leading_icon(leading_icon)
2649            .clip_behavior(self.clip_behavior)
2650            .close_on_activate(self.close_on_activate);
2651        button.key = self.key.clone();
2652        button.on_pressed = on_pressed;
2653        button.on_hover = self.on_hover.clone();
2654        button.on_focus_change = self.on_focus_change.clone();
2655        button.focus_node = self.focus_node.clone();
2656        button.shortcut = self.shortcut.clone();
2657        button.states_controller = self.states_controller.clone();
2658        button.trailing_icon = self.trailing_icon.clone();
2659        button.child = self.child.clone();
2660        button.into_widget()
2661    }
2662}
2663
2664impl MenuItemButton {
2665    /// The fluent form of a Dart `style:` argument that may be null.
2666    fn style_option(mut self, style: Option<ButtonStyle>) -> MenuItemButton {
2667        self.style = style;
2668        self
2669    }
2670}
2671
2672// ---------------------------------------------------------------------------------------------
2673// RadioMenuButton
2674
2675/// A menu item that combines a [`Radio`] widget with a [`MenuItemButton`].
2676///
2677/// To style the radio button separately from the overall button, add a
2678/// `RadioTheme` ancestor.
2679///
2680/// See also:
2681///
2682/// - [`MenuBar`], a widget that creates a menu bar of cascading menu items.
2683/// - [`MenuAnchor`], a widget that defines a region which can host a cascading
2684///   menu.
2685pub struct RadioMenuButton<T: Clone + PartialEq + 'static> {
2686    /// See `Widget::key`.
2687    pub key: Option<KeyRef>,
2688
2689    /// The value represented by this radio button.
2690    ///
2691    /// This radio button is considered selected if its [`value`](Self::value) matches the
2692    /// [`group_value`](Self::group_value).
2693    pub value: T,
2694
2695    /// The currently selected value for a group of radio buttons.
2696    ///
2697    /// This radio button is considered selected if its [`value`](Self::value) matches the
2698    /// [`group_value`](Self::group_value).
2699    pub group_value: Option<T>,
2700
2701    /// Set to true if this radio button is allowed to be returned to an
2702    /// indeterminate state by selecting it again when selected.
2703    ///
2704    /// To indicate returning to an indeterminate state, [`on_changed`](Self::on_changed) will
2705    /// be called with null.
2706    ///
2707    /// If true, [`on_changed`](Self::on_changed) is called with [`value`](Self::value) when
2708    /// selected while [`group_value`](Self::group_value) != [`value`](Self::value), and with
2709    /// null when selected again while [`group_value`](Self::group_value) ==
2710    /// [`value`](Self::value).
2711    ///
2712    /// If false, [`on_changed`](Self::on_changed) will be called with [`value`](Self::value)
2713    /// when it is selected while [`group_value`](Self::group_value) != [`value`](Self::value),
2714    /// and only by selecting another radio button in the group (i.e. changing the value of
2715    /// [`group_value`](Self::group_value)) can this radio button be unselected.
2716    ///
2717    /// The default is false.
2718    pub toggleable: bool,
2719
2720    /// Called when the user selects this radio button.
2721    ///
2722    /// The radio button passes [`value`](Self::value) as a parameter to this callback. The
2723    /// radio button does not actually change state until the parent widget rebuilds the
2724    /// radio button with the new [`group_value`](Self::group_value).
2725    ///
2726    /// If null, the radio button will be displayed as disabled.
2727    ///
2728    /// The provided callback will not be invoked if this radio button is already
2729    /// selected.
2730    pub on_changed: Option<ValueChanged<Option<T>>>,
2731
2732    /// Called when a pointer enters or exits the button response area.
2733    ///
2734    /// The value passed to the callback is true if a pointer has entered button
2735    /// area and false if a pointer has exited.
2736    pub on_hover: Option<ValueChanged<bool>>,
2737
2738    /// Handler called when the focus changes.
2739    ///
2740    /// Called with true if this widget's node gains focus, and false if it loses
2741    /// focus.
2742    pub on_focus_change: Option<ValueChanged<bool>>,
2743
2744    /// An optional focus node to use as the focus node for this widget.
2745    pub focus_node: Option<FocusNodeRef>,
2746
2747    /// The optional shortcut that selects this [`MenuItemButton`].
2748    pub shortcut: Option<MenuSerializableShortcutRef>,
2749
2750    /// Customizes this button's appearance.
2751    ///
2752    /// Non-null properties of this style override the corresponding properties in
2753    /// [`MenuItemButton::theme_style_of`] and [`MenuItemButton::default_style_of`].
2754    /// `WidgetStateProperty`s that resolve to non-null values will similarly
2755    /// override the corresponding `WidgetStateProperty`s in
2756    /// [`MenuItemButton::theme_style_of`] and [`MenuItemButton::default_style_of`].
2757    ///
2758    /// Null by default.
2759    pub style: Option<ButtonStyle>,
2760
2761    /// Represents the interactive "state" of this widget in terms of a set of
2762    /// `WidgetState`s.
2763    pub states_controller: Option<Ref<WidgetStatesController>>,
2764
2765    /// The content will be clipped (or not) according to this option.
2766    ///
2767    /// Defaults to `Clip::None`.
2768    pub clip_behavior: Clip,
2769
2770    /// An optional icon to display after the [`child`](Self::child) label.
2771    pub trailing_icon: Option<WidgetRef>,
2772
2773    /// Determines if the menu will be closed when a [`MenuItemButton`]
2774    /// is pressed.
2775    ///
2776    /// Defaults to true.
2777    pub close_on_activate: bool,
2778
2779    /// The widget displayed in the center of this button.
2780    ///
2781    /// Typically this is the button's label, using a `Text` widget.
2782    pub child: Option<WidgetRef>,
2783}
2784
2785impl<T: Clone + PartialEq + Debug + 'static> RadioMenuButton<T> {
2786    /// Creates a const [`RadioMenuButton`].
2787    ///
2788    /// The [`child`](Self::child) attribute is required.
2789    #[cfg_attr(debug_assertions, track_caller)]
2790    pub fn new<K>(
2791        value: T,
2792        group_value: Option<T>,
2793        on_changed: Option<ValueChanged<Option<T>>>,
2794        child: Option<impl IntoWidget<K>>,
2795    ) -> RadioMenuButton<T> {
2796        RadioMenuButton {
2797            key: None,
2798            value,
2799            group_value,
2800            toggleable: false,
2801            on_changed,
2802            on_hover: None,
2803            on_focus_change: None,
2804            focus_node: None,
2805            shortcut: None,
2806            style: None,
2807            states_controller: None,
2808            clip_behavior: Clip::None,
2809            trailing_icon: None,
2810            close_on_activate: true,
2811            child: match child {
2812                Some(child) => Some(child.into_widget()),
2813                None => None,
2814            },
2815        }
2816    }
2817
2818    /// Dart `RadioMenuButton(key:)`.
2819    pub fn key(mut self, key: KeyRef) -> RadioMenuButton<T> {
2820        self.key = Some(key);
2821        self
2822    }
2823
2824    /// Dart `RadioMenuButton(toggleable:)`.
2825    pub fn toggleable(mut self, toggleable: bool) -> RadioMenuButton<T> {
2826        self.toggleable = toggleable;
2827        self
2828    }
2829
2830    /// Dart `RadioMenuButton(onHover:)`.
2831    pub fn on_hover(mut self, on_hover: ValueChanged<bool>) -> RadioMenuButton<T> {
2832        self.on_hover = Some(on_hover);
2833        self
2834    }
2835
2836    /// Dart `RadioMenuButton(onFocusChange:)`.
2837    pub fn on_focus_change(mut self, on_focus_change: ValueChanged<bool>) -> RadioMenuButton<T> {
2838        self.on_focus_change = Some(on_focus_change);
2839        self
2840    }
2841
2842    /// Dart `RadioMenuButton(focusNode:)`.
2843    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> RadioMenuButton<T> {
2844        self.focus_node = Some(focus_node);
2845        self
2846    }
2847
2848    /// Dart `RadioMenuButton(shortcut:)`.
2849    pub fn shortcut(mut self, shortcut: MenuSerializableShortcutRef) -> RadioMenuButton<T> {
2850        self.shortcut = Some(shortcut);
2851        self
2852    }
2853
2854    /// Dart `RadioMenuButton(style:)`.
2855    pub fn style(mut self, style: ButtonStyle) -> RadioMenuButton<T> {
2856        self.style = Some(style);
2857        self
2858    }
2859
2860    /// Dart `RadioMenuButton(statesController:)`.
2861    pub fn states_controller(
2862        mut self,
2863        states_controller: Ref<WidgetStatesController>,
2864    ) -> RadioMenuButton<T> {
2865        self.states_controller = Some(states_controller);
2866        self
2867    }
2868
2869    /// Dart `RadioMenuButton(clipBehavior:)`.
2870    pub fn clip_behavior(mut self, clip_behavior: Clip) -> RadioMenuButton<T> {
2871        self.clip_behavior = clip_behavior;
2872        self
2873    }
2874
2875    /// Dart `RadioMenuButton(trailingIcon:)`.
2876    #[cfg_attr(debug_assertions, track_caller)]
2877    pub fn trailing_icon<K>(mut self, trailing_icon: impl IntoWidget<K>) -> RadioMenuButton<T> {
2878        self.trailing_icon = Some(trailing_icon.into_widget());
2879        self
2880    }
2881
2882    /// Dart `RadioMenuButton(closeOnActivate:)`.
2883    pub fn close_on_activate(mut self, close_on_activate: bool) -> RadioMenuButton<T> {
2884        self.close_on_activate = close_on_activate;
2885        self
2886    }
2887
2888    /// Whether the button is enabled or disabled.
2889    ///
2890    /// To enable a button, set its [`on_changed`](Self::on_changed) property to a non-null
2891    /// value.
2892    pub fn enabled(&self) -> bool {
2893        self.on_changed.is_some()
2894    }
2895}
2896
2897impl<T: Clone + PartialEq + 'static> Debug for RadioMenuButton<T> {
2898    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2899        f.debug_struct("RadioMenuButton").finish_non_exhaustive()
2900    }
2901}
2902
2903impl<T: Clone + PartialEq + Debug + 'static> StatelessWidget for RadioMenuButton<T> {
2904    fn key(&self) -> Option<&KeyRef> {
2905        self.key.as_ref()
2906    }
2907
2908    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
2909        let on_pressed = self.on_changed.clone().map(|on_changed| {
2910            let (value, group_value, toggleable) = (
2911                self.value.clone(),
2912                self.group_value.clone(),
2913                self.toggleable,
2914            );
2915            Listener::new(move |app| {
2916                if toggleable && group_value.as_ref() == Some(&value) {
2917                    return on_changed(app, None);
2918                }
2919                on_changed(app, Some(value.clone()));
2920            })
2921        });
2922        let mut radio = Radio::new(self.value.clone()).toggleable(self.toggleable);
2923        if let Some(group_value) = self.group_value.clone() {
2924            radio = radio.group_value(group_value);
2925        }
2926        if let Some(on_changed) = self.on_changed.clone() {
2927            radio = radio.on_changed(on_changed);
2928        }
2929        let leading_icon = ExcludeFocus::new(
2930            IgnorePointer::new().child(
2931                ConstrainedBox::new(
2932                    BoxConstraints::new()
2933                        .max_height(Checkbox::WIDTH)
2934                        .max_width(Checkbox::WIDTH),
2935                )
2936                .child(radio),
2937            ),
2938        );
2939        let mut button = MenuItemButton::new()
2940            .style_option(self.style.clone())
2941            .leading_icon(leading_icon)
2942            .clip_behavior(self.clip_behavior)
2943            .close_on_activate(self.close_on_activate);
2944        button.key = self.key.clone();
2945        button.on_pressed = on_pressed;
2946        button.on_hover = self.on_hover.clone();
2947        button.on_focus_change = self.on_focus_change.clone();
2948        button.focus_node = self.focus_node.clone();
2949        button.shortcut = self.shortcut.clone();
2950        button.states_controller = self.states_controller.clone();
2951        button.trailing_icon = self.trailing_icon.clone();
2952        button.child = self.child.clone();
2953        button.into_widget()
2954    }
2955}
2956
2957// ---------------------------------------------------------------------------------------------
2958// SubmenuButton
2959
2960/// A menu button that displays a cascading menu.
2961///
2962/// It can be used as part of a [`MenuBar`], or as a standalone widget.
2963///
2964/// This widget represents a menu item that has a submenu. Like the leaf
2965/// [`MenuItemButton`], it shows a label with an optional leading or trailing
2966/// icon, but additionally shows an arrow icon showing that it has a submenu.
2967///
2968/// By default the submenu will appear to the side of the controlling button.
2969/// The alignment and offset of the submenu can be controlled by setting
2970/// [`MenuStyle::alignment`] on the [`style`](Self::style) and the
2971/// [`alignment_offset`](Self::alignment_offset) argument, respectively.
2972///
2973/// When activated (by being clicked, through keyboard navigation, or via
2974/// hovering with a mouse), it will open a submenu containing the
2975/// [`menu_children`](Self::menu_children).
2976///
2977/// If [`menu_children`](Self::menu_children) is empty, then this menu item will appear
2978/// disabled.
2979///
2980/// See also:
2981///
2982/// * [`MenuItemButton`], a widget that represents a leaf menu item that does not
2983///   host a submenu.
2984/// * [`MenuBar`], a widget that renders menu items in a row in a Material Design
2985///   style.
2986/// * [`MenuAnchor`], a widget that creates a region with a submenu and shows it
2987///   when requested.
2988/// * `PlatformMenuBar`, a widget that renders similar menu bar items from a
2989///   `PlatformMenuItem` using platform-native APIs instead of Flutter.
2990pub struct SubmenuButton {
2991    /// See `Widget::key`.
2992    pub key: Option<KeyRef>,
2993
2994    /// Called when a pointer enters or exits the button response area.
2995    ///
2996    /// The value passed to the callback is true if a pointer has entered this
2997    /// part of the button and false if a pointer has exited.
2998    pub on_hover: Option<ValueChanged<bool>>,
2999
3000    /// Handler called when the focus changes.
3001    ///
3002    /// Called with true if this widget's [`focus_node`](Self::focus_node) gains focus, and
3003    /// false if it loses focus.
3004    pub on_focus_change: Option<ValueChanged<bool>>,
3005
3006    /// A callback that is invoked when the menu is opened.
3007    pub on_open: Option<VoidCallback>,
3008
3009    /// A callback that is invoked when the menu is closed.
3010    pub on_close: Option<VoidCallback>,
3011
3012    /// An optional [`MenuController`] for this submenu.
3013    pub controller: Option<MenuControllerRef>,
3014
3015    /// Customizes this button's appearance.
3016    ///
3017    /// Non-null properties of this style override the corresponding properties in
3018    /// [`theme_style_of`](Self::theme_style_of) and [`default_style_of`](Self::default_style_of).
3019    /// `WidgetStateProperty`s that resolve to non-null values will similarly override the
3020    /// corresponding `WidgetStateProperty`s in [`theme_style_of`](Self::theme_style_of) and
3021    /// [`default_style_of`](Self::default_style_of).
3022    ///
3023    /// Null by default.
3024    pub style: Option<ButtonStyle>,
3025
3026    /// The [`MenuStyle`] of the menu specified by [`menu_children`](Self::menu_children).
3027    ///
3028    /// Defaults to the value of `MenuThemeData::style` of the ambient [`MenuTheme`].
3029    pub menu_style: Option<MenuStyle>,
3030
3031    /// The offset of the menu relative to the alignment origin determined by
3032    /// [`MenuStyle::alignment`] on the [`style`](Self::style) attribute.
3033    ///
3034    /// Use this for fine adjustments of the menu placement.
3035    ///
3036    /// Defaults to an offset that takes into account the padding of the menu so
3037    /// that the top starting corner of the first menu item is aligned with the
3038    /// top of the [`MenuAnchor`] region.
3039    pub alignment_offset: Option<Offset>,
3040
3041    /// The content will be clipped (or not) according to this option.
3042    ///
3043    /// Defaults to `Clip::HardEdge`.
3044    pub clip_behavior: Clip,
3045
3046    /// An optional focus node to use as the focus node for this widget.
3047    pub focus_node: Option<FocusNodeRef>,
3048
3049    /// Represents the interactive "state" of this widget in terms of a set of
3050    /// `WidgetState`s.
3051    pub states_controller: Option<Ref<WidgetStatesController>>,
3052
3053    /// An optional icon to display before the [`child`](Self::child).
3054    pub leading_icon: Option<WidgetRef>,
3055
3056    /// If provided, the widget replaces the default [`SubmenuButton`] arrow icon.
3057    ///
3058    /// Resolves in the following states:
3059    ///  * `WidgetState::Disabled`.
3060    ///  * `WidgetState::Hovered`.
3061    ///  * `WidgetState::Focused`.
3062    ///
3063    /// If this is null, then the value of `MenuThemeData::submenu_icon` is used.
3064    /// If that is also null, then defaults to a right arrow icon with the size
3065    /// of 24 pixels.
3066    pub submenu_icon: Option<WidgetStatePropertyRef<Option<WidgetRef>>>,
3067
3068    /// An optional icon to display after the [`child`](Self::child).
3069    pub trailing_icon: Option<WidgetRef>,
3070
3071    /// Whether the menu panel should be rendered in the root `Overlay`.
3072    ///
3073    /// See [`RawMenuAnchor::use_root_overlay`].
3074    ///
3075    /// Defaults to false.
3076    pub use_root_overlay: bool,
3077
3078    /// An optional callback that is invoked when the [`AnimationStatus`] of the
3079    /// menu changes during open and close animations.
3080    ///
3081    /// If [`animated`](Self::animated) is false, this callback will only be invoked with
3082    /// [`AnimationStatus::Completed`] when the menu is opened, and
3083    /// [`AnimationStatus::Dismissed`] when the menu is closed.
3084    ///
3085    /// Because the [`MenuControllerLeaf::is_open`] property is true while the menu is
3086    /// opening, opened, and closing, it cannot be used to determine whether the
3087    /// menu is in the process of closing or opening. As such, this callback
3088    /// provides a way to determine when the menu is opening or closing.
3089    ///
3090    /// Defaults to null.
3091    pub on_animation_status_changed: Option<ValueChanged<AnimationStatus>>,
3092
3093    /// The list of widgets that appear in the menu when it is opened.
3094    ///
3095    /// These can be any widget, but are typically either [`MenuItemButton`] or
3096    /// [`SubmenuButton`] widgets.
3097    ///
3098    /// If [`menu_children`](Self::menu_children) is empty, then the button for this menu item
3099    /// will be disabled.
3100    pub menu_children: Vec<WidgetRef>,
3101
3102    /// The duration to wait before opening the menu when the button is hovered.
3103    ///
3104    /// Because [`MenuBar`] children can only be opened by hover if a sibling
3105    /// [`SubmenuButton`] is already open, providing a
3106    /// [`hover_open_delay`](Self::hover_open_delay) to direct children of a [`MenuBar`] will
3107    /// panic in a debug build. This is to avoid the case where the
3108    /// [`hover_open_delay`](Self::hover_open_delay) for a [`SubmenuButton`] is longer than
3109    /// the duration of a sibling's closing animation, which leads to that menu never opening.
3110    ///
3111    /// Defaults to `Duration::ZERO`.
3112    pub hover_open_delay: Duration,
3113
3114    /// Whether the menu should open and close with an animation.
3115    ///
3116    /// Defaults to false.
3117    pub animated: bool,
3118
3119    /// The widget displayed in the middle portion of this button.
3120    ///
3121    /// Typically this is the button's label, using a `Text` widget.
3122    pub child: Option<WidgetRef>,
3123}
3124
3125impl SubmenuButton {
3126    /// Creates a const [`SubmenuButton`].
3127    ///
3128    /// The [`child`](Self::child) and [`menu_children`](Self::menu_children) attributes are
3129    /// required.
3130    #[cfg_attr(debug_assertions, track_caller)]
3131    pub fn new<K>(
3132        menu_children: Vec<WidgetRef>,
3133        child: Option<impl IntoWidget<K>>,
3134    ) -> SubmenuButton {
3135        SubmenuButton {
3136            key: None,
3137            on_hover: None,
3138            on_focus_change: None,
3139            on_open: None,
3140            on_close: None,
3141            controller: None,
3142            style: None,
3143            menu_style: None,
3144            alignment_offset: None,
3145            clip_behavior: Clip::HardEdge,
3146            focus_node: None,
3147            states_controller: None,
3148            leading_icon: None,
3149            trailing_icon: None,
3150            submenu_icon: None,
3151            use_root_overlay: false,
3152            hover_open_delay: Duration::ZERO,
3153            animated: false,
3154            on_animation_status_changed: None,
3155            menu_children,
3156            child: match child {
3157                Some(child) => Some(child.into_widget()),
3158                None => None,
3159            },
3160        }
3161    }
3162
3163    /// Dart `SubmenuButton(key:)`.
3164    pub fn key(mut self, key: KeyRef) -> SubmenuButton {
3165        self.key = Some(key);
3166        self
3167    }
3168
3169    /// Dart `SubmenuButton(onHover:)`.
3170    pub fn on_hover(mut self, on_hover: ValueChanged<bool>) -> SubmenuButton {
3171        self.on_hover = Some(on_hover);
3172        self
3173    }
3174
3175    /// Dart `SubmenuButton(onFocusChange:)`.
3176    pub fn on_focus_change(mut self, on_focus_change: ValueChanged<bool>) -> SubmenuButton {
3177        self.on_focus_change = Some(on_focus_change);
3178        self
3179    }
3180
3181    /// Dart `SubmenuButton(onOpen:)`.
3182    pub fn on_open(mut self, on_open: VoidCallback) -> SubmenuButton {
3183        self.on_open = Some(on_open);
3184        self
3185    }
3186
3187    /// Dart `SubmenuButton(onClose:)`.
3188    pub fn on_close(mut self, on_close: VoidCallback) -> SubmenuButton {
3189        self.on_close = Some(on_close);
3190        self
3191    }
3192
3193    /// Dart `SubmenuButton(controller:)`.
3194    pub fn controller(mut self, controller: MenuControllerRef) -> SubmenuButton {
3195        self.controller = Some(controller);
3196        self
3197    }
3198
3199    /// Dart `SubmenuButton(style:)`.
3200    pub fn style(mut self, style: ButtonStyle) -> SubmenuButton {
3201        self.style = Some(style);
3202        self
3203    }
3204
3205    /// Dart `SubmenuButton(menuStyle:)`.
3206    pub fn menu_style(mut self, menu_style: MenuStyle) -> SubmenuButton {
3207        self.menu_style = Some(menu_style);
3208        self
3209    }
3210
3211    /// Dart `SubmenuButton(alignmentOffset:)`.
3212    pub fn alignment_offset(mut self, alignment_offset: Offset) -> SubmenuButton {
3213        self.alignment_offset = Some(alignment_offset);
3214        self
3215    }
3216
3217    /// Dart `SubmenuButton(clipBehavior:)`.
3218    pub fn clip_behavior(mut self, clip_behavior: Clip) -> SubmenuButton {
3219        self.clip_behavior = clip_behavior;
3220        self
3221    }
3222
3223    /// Dart `SubmenuButton(focusNode:)`.
3224    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> SubmenuButton {
3225        self.focus_node = Some(focus_node);
3226        self
3227    }
3228
3229    /// Dart `SubmenuButton(statesController:)`.
3230    pub fn states_controller(
3231        mut self,
3232        states_controller: Ref<WidgetStatesController>,
3233    ) -> SubmenuButton {
3234        self.states_controller = Some(states_controller);
3235        self
3236    }
3237
3238    /// Dart `SubmenuButton(leadingIcon:)`.
3239    #[cfg_attr(debug_assertions, track_caller)]
3240    pub fn leading_icon<K>(mut self, leading_icon: impl IntoWidget<K>) -> SubmenuButton {
3241        self.leading_icon = Some(leading_icon.into_widget());
3242        self
3243    }
3244
3245    /// Dart `SubmenuButton(trailingIcon:)`.
3246    #[cfg_attr(debug_assertions, track_caller)]
3247    pub fn trailing_icon<K>(mut self, trailing_icon: impl IntoWidget<K>) -> SubmenuButton {
3248        self.trailing_icon = Some(trailing_icon.into_widget());
3249        self
3250    }
3251
3252    /// Dart `SubmenuButton(submenuIcon:)`.
3253    pub fn submenu_icon(
3254        mut self,
3255        submenu_icon: WidgetStatePropertyRef<Option<WidgetRef>>,
3256    ) -> SubmenuButton {
3257        self.submenu_icon = Some(submenu_icon);
3258        self
3259    }
3260
3261    /// Dart `SubmenuButton(useRootOverlay:)`.
3262    pub fn use_root_overlay(mut self, use_root_overlay: bool) -> SubmenuButton {
3263        self.use_root_overlay = use_root_overlay;
3264        self
3265    }
3266
3267    /// Dart `SubmenuButton(hoverOpenDelay:)`.
3268    pub fn hover_open_delay(mut self, hover_open_delay: Duration) -> SubmenuButton {
3269        self.hover_open_delay = hover_open_delay;
3270        self
3271    }
3272
3273    /// Dart `SubmenuButton(animated:)`.
3274    pub fn animated(mut self, animated: bool) -> SubmenuButton {
3275        self.animated = animated;
3276        self
3277    }
3278
3279    /// Dart `SubmenuButton(onAnimationStatusChanged:)`.
3280    pub fn on_animation_status_changed(
3281        mut self,
3282        on_animation_status_changed: ValueChanged<AnimationStatus>,
3283    ) -> SubmenuButton {
3284        self.on_animation_status_changed = Some(on_animation_status_changed);
3285        self
3286    }
3287
3288    /// Defines the button's default appearance.
3289    ///
3290    /// The button `child`'s `Text` and `Icon` widgets are rendered with the [`ButtonStyle`]'s
3291    /// foreground color. The button's `InkWell` adds the style's overlay color when the button
3292    /// is focused, hovered or pressed. The button's background color becomes its `Material`
3293    /// color and is transparent by default.
3294    pub fn default_style_of(
3295        &self,
3296        app: &mut App,
3297        context: BuildContext,
3298    ) -> Box<dyn ButtonStyleGetters> {
3299        let _ = app;
3300        Box::new(MenuButtonDefaultsM3::new(context))
3301    }
3302
3303    /// Returns the [`MenuButtonThemeData::style`](crate::MenuButtonThemeData::style) of the
3304    /// closest [`MenuButtonTheme`] ancestor.
3305    pub fn theme_style_of(&self, app: &mut App, context: BuildContext) -> Option<ButtonStyle> {
3306        MenuButtonTheme::of(app, context).style
3307    }
3308
3309    /// A static convenience method that constructs a [`SubmenuButton`]'s
3310    /// [`ButtonStyle`] given simple values.
3311    ///
3312    /// The `foreground_color` color is used to create a `WidgetStateProperty`
3313    /// [`ButtonStyle::foreground_color`] value. Specify a value for `foreground_color`
3314    /// to specify the color of the button's icons. Use `background_color` for the
3315    /// button's background fill color. Use `disabled_foreground_color` and
3316    /// `disabled_background_color` to specify the button's disabled icon and fill
3317    /// color.
3318    ///
3319    /// Similarly, the `enabled_mouse_cursor` and `disabled_mouse_cursor`
3320    /// parameters are used to construct [`ButtonStyle::mouse_cursor`].
3321    ///
3322    /// The `icon_color`, `disabled_icon_color` are used to construct
3323    /// [`ButtonStyle::icon_color`] and `icon_size` is used to construct
3324    /// [`ButtonStyle::icon_size`].
3325    ///
3326    /// All of the other parameters are either used directly or used to create a
3327    /// `WidgetStateProperty` with a single value for all states.
3328    ///
3329    /// All parameters default to null, by default this method returns a
3330    /// [`ButtonStyle`] that doesn't override anything.
3331    ///
3332    /// For example, to override the default foreground color for a
3333    /// [`SubmenuButton`], as well as its overlay color, with all of the standard
3334    /// opacity adjustments for the pressed, focused, and hovered states, one
3335    /// could write:
3336    ///
3337    /// ```text
3338    /// SubmenuButton::new(menu_children, Some(Text::new("Button Label")))
3339    ///     .leading_icon(Icon::new(Some(Icons::pets())))
3340    ///     .style(SubmenuButton::style_from().foreground_color(Colors::GREEN.primary()).build())
3341    /// ```
3342    pub fn style_from() -> MenuButtonStyleFromBuilder {
3343        MenuButtonStyleFromBuilder::default()
3344    }
3345}
3346
3347impl Debug for SubmenuButton {
3348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3349        f.debug_struct("SubmenuButton")
3350            .field("focusNode", &self.focus_node)
3351            .field("menuStyle", &self.menu_style)
3352            .field("alignmentOffset", &self.alignment_offset)
3353            .field("clipBehavior", &self.clip_behavior)
3354            .field("menuChildren", &self.menu_children)
3355            .finish_non_exhaustive()
3356    }
3357}
3358
3359impl StatefulWidget for SubmenuButton {
3360    type State = SubmenuButtonState;
3361
3362    fn key(&self) -> Option<&KeyRef> {
3363        self.key.as_ref()
3364    }
3365
3366    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3367        // Dart's `debugDescribeChildren` has no widget-level hook in this port.
3368        properties.add(DiagnosticsProperty::<String>::new(
3369            "focusNode",
3370            self.focus_node.as_ref().map(|node| node.to_string(app)),
3371        ));
3372        properties.add(
3373            DiagnosticsProperty::<MenuStyle>::new("menuStyle", self.menu_style.clone())
3374                .default_value(None),
3375        );
3376        properties.add(DiagnosticsProperty::<Offset>::new(
3377            "alignmentOffset",
3378            self.alignment_offset,
3379        ));
3380        properties.add(EnumProperty::<Clip>::new(
3381            "clipBehavior",
3382            Some(self.clip_behavior),
3383        ));
3384    }
3385
3386    fn create_state(&self) -> SubmenuButtonState {
3387        SubmenuButtonState {
3388            state: StateData::new(),
3389            directional_focus_action: None,
3390            waiting_to_focus_menu: false,
3391            is_open_on_focus_enabled: true,
3392            internal_menu_controller: None,
3393            internal_focus_node: None,
3394            anchor_key: GlobalKey::new(),
3395            is_hovered: false,
3396            animation_status: AnimationStatus::Dismissed,
3397            hover_open_timer: None,
3398        }
3399    }
3400}
3401
3402/// Dart's `_SubmenuButtonState`.
3403pub struct SubmenuButtonState {
3404    state: StateData<SubmenuButton>,
3405    // Dart's `late final actions`, made on the first build that reads it.
3406    directional_focus_action: Option<Ref<SubmenuDirectionalFocusAction>>,
3407    waiting_to_focus_menu: bool,
3408    is_open_on_focus_enabled: bool,
3409    internal_menu_controller: Option<Ref<MenuController>>,
3410    internal_focus_node: Option<Ref<FocusNode>>,
3411    anchor_key: GlobalKey,
3412    is_hovered: bool,
3413    animation_status: AnimationStatus,
3414    hover_open_timer: Option<Timer>,
3415}
3416
3417impl SubmenuButtonState {
3418    /// Dart's `_menuController`.
3419    fn menu_controller(self: Handle<Self>, app: &App) -> MenuControllerRef {
3420        self.widget(app).controller.clone().unwrap_or_else(|| {
3421            app.get(self)
3422                .internal_menu_controller
3423                .as_ref()
3424                .expect("made when the widget has no controller")
3425                .erase()
3426        })
3427    }
3428
3429    /// Dart's `_parent`.
3430    fn parent(self: Handle<Self>, app: &App) -> Option<AnyMenuAnchorState> {
3431        AnyMenuAnchorState::maybe_of(app, self.context(app))
3432    }
3433
3434    /// Dart's `_anchorState`.
3435    fn anchor_state(self: Handle<Self>, app: &App) -> Option<AnyMenuAnchorState> {
3436        app.get(self)
3437            .anchor_key
3438            .current_state::<MenuAnchorState>(app)
3439            .map(MenuAnchorStateLeaf::as_menu_anchor_state)
3440    }
3441
3442    /// Dart's `_buttonFocusNode`.
3443    fn button_focus_node(self: Handle<Self>, app: &App) -> FocusNodeRef {
3444        self.widget(app)
3445            .focus_node
3446            .clone()
3447            .or_else(|| app.get(self).internal_focus_node.as_ref().map(Ref::erase))
3448            .expect("made when the widget has no focus node")
3449    }
3450
3451    /// Dart's `_enabled`.
3452    fn enabled(self: Handle<Self>, app: &App) -> bool {
3453        !self.widget(app).menu_children.is_empty()
3454    }
3455
3456    fn handle_focus_change_listener(self: Handle<Self>) -> Listener {
3457        Listener::handle_method(self, Self::handle_focus_change)
3458    }
3459
3460    fn internal_focus_node_debug_label(self: Handle<Self>, app: &mut App) {
3461        if cfg!(debug_assertions)
3462            && let Some(internal_focus_node) = app.get(self).internal_focus_node.clone()
3463        {
3464            let label = describe_child("SubmenuButton", &self.widget(app).child);
3465            internal_focus_node.set_debug_label(app, Some(label));
3466        }
3467    }
3468
3469    /// The `builder` Dart's `build` hands its `MenuAnchor`.
3470    fn build_button(
3471        self: Handle<Self>,
3472        app: &mut App,
3473        context: BuildContext,
3474        controller: AnyMenuController,
3475        child: Option<&WidgetRef>,
3476        submenu_icon: WidgetRef,
3477    ) -> WidgetRef {
3478        // Since we don't want to use the theme style or default style from the
3479        // TextButton, we merge the styles, merging them in the right order when
3480        // each type of style exists. Each "*StyleOf" function is only called
3481        // once.
3482        let widget_ref = self.context(app).widget(app).clone();
3483        let widget = downcast_widget::<SubmenuButton>(&*widget_ref)
3484            .expect("a SubmenuButtonState builds its SubmenuButton");
3485        let mut merged_style = match widget.theme_style_of(app, context) {
3486            Some(theme_style) => {
3487                theme_style.merge(Some(&widget.default_style_of(app, context).copy_with(app)))
3488            }
3489            // Dart passes the defaults object on as the text button's style, whose getters the
3490            // button reads all of when it builds.
3491            None => widget.default_style_of(app, context).copy_with(app),
3492        };
3493        if let Some(style) = &widget.style {
3494            merged_style = style.merge(Some(&merged_style));
3495        }
3496
3497        let toggle_show_menu = Listener::new(move |app| {
3498            if !self.mounted(app) {
3499                return;
3500            }
3501            if app.get(self).animation_status.is_forward_or_completed() {
3502                controller.close(app);
3503            } else {
3504                controller.open(app, None);
3505            }
3506        });
3507
3508        let handle_pointer_exit = move |app: &mut App, _event: PointerExitEvent| {
3509            if app.get(self).is_hovered {
3510                if let Some(on_hover) = self.widget(app).on_hover.clone() {
3511                    on_hover(app, false);
3512                }
3513                app.get_mut(self).is_hovered = false;
3514                self.clear_hover_open_timer(app);
3515            }
3516        };
3517
3518        // MouseRegion.onEnter and TextButton.onHover are called
3519        // if a button is hovered after scrolling. This interferes with
3520        // focus traversal and scroll position. MouseRegion.onHover avoids
3521        // this issue.
3522        let handle_pointer_hover = move |app: &mut App, _event: PointerHoverEvent| {
3523            if !app.get(self).is_hovered {
3524                app.get_mut(self).is_hovered = true;
3525                if let Some(on_hover) = self.widget(app).on_hover.clone() {
3526                    on_hover(app, true);
3527                }
3528                let root = AnyMenuAnchorState::maybe_of(app, context)
3529                    .expect("a SubmenuButton's button is built below its MenuAnchor")
3530                    .root(app);
3531                // Don't open the root menu bar menus on hover unless a sibling menu
3532                // is already open. This means that the user has to first click to
3533                // open a menu on the menu bar before hovering allows them to traverse
3534                // it.
3535                if self
3536                    .parent(app)
3537                    .is_some_and(|parent| parent.orientation() == Axis::Horizontal)
3538                    && !root.menu_controller(app).is_open(app)
3539                {
3540                    return;
3541                }
3542
3543                if self.button_focus_node(app).has_primary_focus(app) {
3544                    self.clear_hover_open_timer(app);
3545                    self.maybe_open_menu_on_hover_or_focus(app);
3546                } else {
3547                    self.button_focus_node(app).request_focus(app, None);
3548                }
3549            }
3550        };
3551
3552        let enabled = self.enabled(app);
3553        let widget = self.widget(app);
3554        let show_decoration = self
3555            .parent(app)
3556            .map_or(Axis::Horizontal, AnyMenuAnchorState::orientation)
3557            == Axis::Vertical;
3558        let label = MenuItemLabel {
3559            has_submenu: true,
3560            show_decoration,
3561            leading_icon: widget.leading_icon.clone(),
3562            trailing_icon: widget.trailing_icon.clone(),
3563            shortcut: None,
3564            semantics_label: None,
3565            overflow_axis: Axis::Vertical,
3566            submenu_icon: Some(submenu_icon),
3567            child: child.cloned(),
3568        };
3569        let mut button = TextButton::new(enabled.then(|| toggle_show_menu.clone()), Some(label))
3570            .style(merged_style)
3571            .focus_node(self.button_focus_node(app));
3572        if enabled && let Some(on_focus_change) = self.widget(app).on_focus_change.clone() {
3573            button = button.on_focus_change(on_focus_change);
3574        }
3575        let expanded = enabled && app.get(self).animation_status.is_forward_or_completed();
3576        let mut child = MergeSemantics::new()
3577            .child(Semantics::new().expanded(expanded).child(button))
3578            .into_widget();
3579
3580        if !enabled {
3581            return child;
3582        }
3583
3584        child = MouseRegion::new()
3585            .on_hover(Rc::new(handle_pointer_hover))
3586            .on_exit(Rc::new(handle_pointer_exit))
3587            .child(child)
3588            .into_widget();
3589
3590        if platform_supports_accelerators(app) {
3591            return MenuAcceleratorCallbackBinding::new(child)
3592                .on_invoke(toggle_show_menu)
3593                .has_submenu(true)
3594                .into_widget();
3595        }
3596
3597        child
3598    }
3599
3600    /// Dart's `_handleAnimationStatusChanged`.
3601    fn handle_animation_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
3602        self.set_state(app, |state| {
3603            state.animation_status = status;
3604        });
3605        if let Some(on_animation_status_changed) =
3606            self.widget(app).on_animation_status_changed.clone()
3607        {
3608            on_animation_status_changed(app, status);
3609        }
3610    }
3611
3612    /// Dart's `_handleClose`.
3613    fn handle_close(self: Handle<Self>, app: &mut App) {
3614        // After closing the children of this submenu, this submenu button will
3615        // regain focus. Because submenu buttons open on focus, this submenu will
3616        // immediately reopen. To prevent this from happening, we prevent focus on
3617        // SubmenuButtons that do not already have focus using the _openOnFocus
3618        // flag. This flag is reset after one frame.
3619        if !self.button_focus_node(app).has_focus(app) {
3620            app.get_mut(self).is_open_on_focus_enabled = false;
3621            let view = View::maybe_id_of(app, self.context(app));
3622            SchedulerBinding::add_post_frame_callback(
3623                app,
3624                FrameCallback::new(move |app, _timestamp| {
3625                    FocusManager::instance(app).apply_focus_changes_if_needed(app);
3626                    if app.contains(self) {
3627                        app.get_mut(self).is_open_on_focus_enabled = true;
3628                    }
3629                }),
3630                view,
3631            );
3632        }
3633        if let Some(on_close) = self.widget(app).on_close.clone() {
3634            on_close(app);
3635        }
3636    }
3637
3638    /// Dart's `_handleOpen`.
3639    fn handle_open(self: Handle<Self>, app: &mut App) {
3640        if !app.get(self).waiting_to_focus_menu {
3641            let view = View::maybe_id_of(app, self.context(app));
3642            SchedulerBinding::add_post_frame_callback(
3643                app,
3644                FrameCallback::new(move |app, _timestamp| {
3645                    if self.mounted(app) {
3646                        self.button_focus_node(app).request_focus(app, None);
3647                        app.get_mut(self).waiting_to_focus_menu = false;
3648                    }
3649                }),
3650                view,
3651            );
3652            app.get_mut(self).waiting_to_focus_menu = true;
3653        }
3654        self.set_state(app, |_| {
3655            // Rebuild with updated controller.isOpen value
3656        });
3657        if let Some(on_open) = self.widget(app).on_open.clone() {
3658            on_open(app);
3659        }
3660    }
3661
3662    /// Dart's `_computeMenuPadding`.
3663    fn compute_menu_padding(
3664        self: Handle<Self>,
3665        app: &mut App,
3666        context: BuildContext,
3667    ) -> EdgeInsets {
3668        let insets = match self
3669            .widget(app)
3670            .menu_style
3671            .as_ref()
3672            .and_then(|menu_style| menu_style.padding.clone())
3673        {
3674            Some(insets) => insets,
3675            None => match MenuTheme::of(app, context)
3676                .style
3677                .and_then(|style| style.padding)
3678            {
3679                Some(insets) => insets,
3680                None => MenuDefaultsM3::new(context)
3681                    .padding(app)
3682                    .expect("the menu defaults have a padding"),
3683            },
3684        };
3685        let states = self
3686            .widget(app)
3687            .states_controller
3688            .as_ref()
3689            .map(|states_controller| app.get(states_controller).value().clone())
3690            .unwrap_or_default();
3691        let direction = Directionality::of(app, context);
3692        insets
3693            .resolve(&states)
3694            .expect("the menu padding resolves")
3695            .resolve(Some(direction))
3696    }
3697
3698    /// Dart's `_handleFocusChange`.
3699    fn handle_focus_change(self: Handle<Self>, app: &mut App) {
3700        self.clear_hover_open_timer(app);
3701        if !self.button_focus_node(app).has_primary_focus(app) {
3702            let anchor_state = self
3703                .anchor_state(app)
3704                .expect("the SubmenuButton's MenuAnchor is mounted");
3705            if !anchor_state.menu_scope_node(app).as_node().has_focus(app)
3706                && app.get(self).animation_status.is_forward_or_completed()
3707            {
3708                self.menu_controller(app).close(app);
3709            }
3710            return;
3711        }
3712
3713        self.maybe_open_menu_on_hover_or_focus(app);
3714    }
3715
3716    /// Dart's `_maybeOpenMenuOnHoverOrFocus`.
3717    fn maybe_open_menu_on_hover_or_focus(self: Handle<Self>, app: &mut App) {
3718        if !app.get(self).is_open_on_focus_enabled {
3719            return;
3720        }
3721
3722        if self.menu_controller(app).is_open(app) {
3723            if app.get(self).animation_status != AnimationStatus::Reverse {
3724                // If the menu isn't closing, there's no reason to reopen it.
3725                return;
3726            }
3727
3728            if app.get(self).is_hovered {
3729                // If the button is hovered, avoid reopening the menu that the user deliberately
3730                // closed.
3731                return;
3732            }
3733
3734            if self
3735                .parent(app)
3736                .is_some_and(|parent| parent.orientation() == Axis::Horizontal)
3737            {
3738                // Top-level (horizontal) buttons in a menubar will try to reopen when
3739                // closed, since focus returns to their button.
3740                return;
3741            }
3742        }
3743
3744        let hover_open_delay = self.widget(app).hover_open_delay;
3745        if hover_open_delay == Duration::ZERO {
3746            self.menu_controller(app).open(app, None);
3747            return;
3748        }
3749
3750        let timer = Timer::new(
3751            app,
3752            hover_open_delay,
3753            Listener::new(move |app| {
3754                // The menu controller could change, so we can't use a tearoff.
3755                self.menu_controller(app).open(app, None);
3756            }),
3757        );
3758        app.get_mut(self).hover_open_timer = Some(timer);
3759    }
3760
3761    /// Dart's `_clearHoverOpenTimer`.
3762    fn clear_hover_open_timer(self: Handle<Self>, app: &mut App) {
3763        if let Some(timer) = app.get_mut(self).hover_open_timer.take() {
3764            timer.cancel(app);
3765        }
3766    }
3767
3768    /// Dart's `_debugValidateHoverOpenDelay`.
3769    fn debug_validate_hover_open_delay(self: Handle<Self>, app: &App) -> bool {
3770        if self
3771            .parent(app)
3772            .is_some_and(|parent| parent.orientation() == Axis::Horizontal)
3773            && self.widget(app).hover_open_delay > Duration::ZERO
3774        {
3775            panic!(
3776                "A non-zero hoverOpenDelay was used in a top-level SubmenuButton situated in a \
3777                 MenuBar.\nMenuBar children can only be opened by hover if a sibling \
3778                 SubmenuButton is already open. When the hoverOpenDelay for a SubmenuButton is \
3779                 longer than the closing animation of a sibling SubmenuButton, that sibling will \
3780                 close before this SubmenuButton begins opening, leading to this SubmenuButton \
3781                 never opening.\nThe affected SubmenuButton is: {:?}",
3782                self.widget(app)
3783            );
3784        }
3785        true
3786    }
3787}
3788
3789impl State for SubmenuButtonState {
3790    type Widget = SubmenuButton;
3791    waft_widgets::state_accessors!();
3792
3793    fn init_state(self: Handle<Self>, app: &mut App) {
3794        if self.widget(app).focus_node.is_none() {
3795            let internal_focus_node = FocusNode::new(app);
3796            app.get_mut(self).internal_focus_node = Some(internal_focus_node);
3797            self.internal_focus_node_debug_label(app);
3798        }
3799        if self.widget(app).controller.is_none() {
3800            let controller = MenuController::new(app);
3801            app.get_mut(self).internal_menu_controller = Some(controller);
3802        }
3803        self.button_focus_node(app)
3804            .add_listener(app, self.handle_focus_change_listener());
3805    }
3806
3807    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3808        debug_assert!(self.debug_validate_hover_open_delay(app));
3809    }
3810
3811    fn dispose(self: Handle<Self>, app: &mut App) {
3812        self.clear_hover_open_timer(app);
3813        self.button_focus_node(app)
3814            .remove_listener(app, &self.handle_focus_change_listener());
3815        if let Some(internal_focus_node) = app.get_mut(self).internal_focus_node.take() {
3816            internal_focus_node.dispose(app);
3817        }
3818    }
3819
3820    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SubmenuButton) {
3821        debug_assert!(self.debug_validate_hover_open_delay(app));
3822        if self.widget(app).focus_node != old_widget.focus_node {
3823            match old_widget.focus_node.clone() {
3824                None => {
3825                    if let Some(internal_focus_node) = app.get_mut(self).internal_focus_node.take()
3826                    {
3827                        internal_focus_node
3828                            .erase::<AnyFocusNode>()
3829                            .remove_listener(app, &self.handle_focus_change_listener());
3830                        internal_focus_node.dispose(app);
3831                    }
3832                }
3833                Some(old_focus_node) => {
3834                    old_focus_node.remove_listener(app, &self.handle_focus_change_listener());
3835                }
3836            }
3837            if self.widget(app).focus_node.is_none() {
3838                if app.get(self).internal_focus_node.is_none() {
3839                    let internal_focus_node = FocusNode::new(app);
3840                    app.get_mut(self).internal_focus_node = Some(internal_focus_node);
3841                }
3842                self.internal_focus_node_debug_label(app);
3843            }
3844            self.button_focus_node(app)
3845                .add_listener(app, self.handle_focus_change_listener());
3846        }
3847        if self.widget(app).controller != old_widget.controller {
3848            let internal_menu_controller = if old_widget.controller.is_none() {
3849                None
3850            } else {
3851                Some(MenuController::new(app))
3852            };
3853            app.get_mut(self).internal_menu_controller = internal_menu_controller;
3854        }
3855    }
3856
3857    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3858        let mut menu_padding_offset = self.widget(app).alignment_offset.unwrap_or(Offset::ZERO);
3859        let menu_padding = self.compute_menu_padding(app, context);
3860        let orientation = self
3861            .parent(app)
3862            .map_or(Axis::Vertical, AnyMenuAnchorState::orientation);
3863
3864        // Move the submenu over by the size of the menu padding, so that
3865        // the first menu item aligns with the submenu button that opens it.
3866        menu_padding_offset = menu_padding_offset
3867            + match (orientation, Directionality::of(app, context)) {
3868                (Axis::Horizontal, TextDirection::Rtl) => Offset::new(menu_padding.right, 0.0),
3869                (Axis::Horizontal, TextDirection::Ltr) => Offset::new(-menu_padding.left, 0.0),
3870                (Axis::Vertical, TextDirection::Rtl) => Offset::new(0.0, -menu_padding.top),
3871                (Axis::Vertical, TextDirection::Ltr) => Offset::new(0.0, -menu_padding.top),
3872            };
3873        let mut states = WidgetStates::new();
3874        if !self.enabled(app) {
3875            states.insert(WidgetState::Disabled);
3876        }
3877        if app.get(self).is_hovered {
3878            states.insert(WidgetState::Hovered);
3879        }
3880        if self.button_focus_node(app).has_focus(app) {
3881            states.insert(WidgetState::Focused);
3882        }
3883        let submenu_icon = self
3884            .widget(app)
3885            .submenu_icon
3886            .as_ref()
3887            .and_then(|submenu_icon| submenu_icon.resolve(&states));
3888        let submenu_icon = match submenu_icon {
3889            Some(submenu_icon) => submenu_icon,
3890            None => match MenuTheme::of(app, context)
3891                .submenu_icon
3892                .and_then(|submenu_icon| submenu_icon.resolve(&states))
3893            {
3894                Some(submenu_icon) => submenu_icon,
3895                None => waft_widgets::Icon::new(Some(
3896                    Icons::arrow_right(), // Automatically switches with text direction.
3897                ))
3898                .size(K_DEFAULT_SUBMENU_ICON_SIZE)
3899                .into_widget(),
3900            },
3901        };
3902
3903        let directional_focus_action = match app.get(self).directional_focus_action.clone() {
3904            Some(action) => action,
3905            None => {
3906                let action = app.create(SubmenuDirectionalFocusAction {
3907                    action: ActionData::new(),
3908                    submenu: self,
3909                });
3910                app.get_mut(self).directional_focus_action = Some(action.clone());
3911                action
3912            }
3913        };
3914        let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
3915        actions.insert(
3916            <SubmenuDirectionalFocusAction as Action>::intent_type(),
3917            directional_focus_action.into_erased(),
3918        );
3919
3920        let widget = self.widget(app);
3921        let mut menu_anchor = MenuAnchor::new(widget.menu_children.clone())
3922            .key(app.get(self).anchor_key.clone().into())
3923            .on_animation_status_changed(Rc::new(move |app: &mut App, status| {
3924                self.handle_animation_status_changed(app, status);
3925            }))
3926            .controller(self.menu_controller(app))
3927            .child_focus_node(self.button_focus_node(app))
3928            .alignment_offset(menu_padding_offset)
3929            .clip_behavior(widget.clip_behavior)
3930            .on_close(Rc::new(move |app: &mut App| self.handle_close(app)))
3931            .on_open(Rc::new(move |app: &mut App| self.handle_open(app)))
3932            .use_root_overlay(widget.use_root_overlay)
3933            .animated(widget.animated)
3934            .builder(move |app, context, controller, child| {
3935                self.build_button(app, context, controller, child, submenu_icon.clone())
3936            });
3937        menu_anchor.style = widget.menu_style.clone();
3938        menu_anchor.child = widget.child.clone();
3939
3940        Actions::new(actions, menu_anchor).into_widget()
3941    }
3942}
3943
3944impl Debug for SubmenuButtonState {
3945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3946        f.debug_struct("_SubmenuButtonState")
3947            .field("animation_status", &self.animation_status)
3948            .finish_non_exhaustive()
3949    }
3950}
3951
3952/// Dart's `_SubmenuDirectionalFocusAction`, which extends `DirectionalFocusAction` and
3953/// overrides its `invoke`.
3954struct SubmenuDirectionalFocusAction {
3955    action: ActionData,
3956    submenu: Handle<SubmenuButtonState>,
3957}
3958
3959impl SubmenuDirectionalFocusAction {
3960    fn parent(self: Handle<Self>, app: &App) -> Option<AnyMenuAnchorState> {
3961        app.get(self).submenu.parent(app)
3962    }
3963
3964    fn anchor_state(self: Handle<Self>, app: &App) -> Option<AnyMenuAnchorState> {
3965        app.get(self).submenu.anchor_state(app)
3966    }
3967
3968    fn controller(self: Handle<Self>, app: &App) -> AnyMenuController {
3969        app.get(self).submenu.menu_controller(app).handle()
3970    }
3971
3972    /// The orientation of the menu that contains this submenu button.
3973    fn orientation(self: Handle<Self>, app: &App) -> Option<Axis> {
3974        self.parent(app).map(AnyMenuAnchorState::orientation)
3975    }
3976
3977    /// Whether the anchor that intercepted this DirectionalFocusAction is a submenu.
3978    fn is_submenu(self: Handle<Self>, app: &App) -> bool {
3979        self.button(app).has_primary_focus(app)
3980    }
3981
3982    fn button(self: Handle<Self>, app: &App) -> AnyFocusNode {
3983        app.get(self).submenu.button_focus_node(app).handle()
3984    }
3985}
3986
3987impl Action for SubmenuDirectionalFocusAction {
3988    type Intent = DirectionalFocusIntent;
3989    waft_widgets::action_accessors!();
3990
3991    fn invoke(
3992        self: Handle<Self>,
3993        app: &mut App,
3994        intent: &DirectionalFocusIntent,
3995    ) -> Option<Rc<dyn Any>> {
3996        let submenu = app.get(self).submenu;
3997        let directionality = Directionality::of(app, submenu.context(app));
3998        let is_submenu = self.is_submenu(app);
3999        match (self.orientation(app), directionality, intent.direction) {
4000            (Some(Axis::Horizontal), TextDirection::Ltr, TraversalDirection::Left)
4001            | (Some(Axis::Horizontal), TextDirection::Rtl, TraversalDirection::Right) => {
4002                // Focus this MenuBar SubmenuButton, then move focus to the previous focusable
4003                // MenuBar item.
4004                let button = self.button(app);
4005                button.request_focus(app, None);
4006                button.previous_focus(app);
4007                return None;
4008            }
4009            (Some(Axis::Horizontal), TextDirection::Ltr, TraversalDirection::Right)
4010            | (Some(Axis::Horizontal), TextDirection::Rtl, TraversalDirection::Left) => {
4011                // Focus this MenuBar SubmenuButton, then move focus to the next focusable
4012                // MenuBar item.
4013                let button = self.button(app);
4014                button.request_focus(app, None);
4015                button.next_focus(app);
4016                return None;
4017            }
4018            (Some(Axis::Horizontal), _, TraversalDirection::Down) => {
4019                if is_submenu {
4020                    // If this is a top-level (horizontal) button in a menubar, focus the
4021                    // first item in this button's submenu.
4022                    if let Some(anchor_state) = self.anchor_state(app) {
4023                        anchor_state.focus_first_menu_item(app);
4024                    }
4025                    return None;
4026                }
4027            }
4028            (Some(Axis::Horizontal), _, TraversalDirection::Up) => {
4029                if is_submenu {
4030                    // If this is a top-level (horizontal) button in a menubar, focus the
4031                    // last item in this button's submenu. This makes navigating into
4032                    // upward-oriented submenus more intuitive.
4033                    if let Some(anchor_state) = self.anchor_state(app) {
4034                        anchor_state.focus_last_menu_item(app);
4035                    }
4036                    return None;
4037                }
4038            }
4039            (Some(Axis::Vertical), TextDirection::Ltr, TraversalDirection::Left)
4040            | (Some(Axis::Vertical), TextDirection::Rtl, TraversalDirection::Right) => {
4041                let parent = self.parent(app);
4042                let grandparent = parent.and_then(|parent| parent.parent(app));
4043                if grandparent.map(AnyMenuAnchorState::orientation) == Some(Axis::Horizontal) {
4044                    if is_submenu {
4045                        let parent = parent.expect("a grandparent has a parent");
4046                        if let Some(child_focus_node) = parent.widget(app).child_focus_node.clone()
4047                        {
4048                            child_focus_node.request_focus(app, None);
4049                            child_focus_node.previous_focus(app);
4050                        }
4051                    } else {
4052                        // MenuBar SubmenuButton => SubmenuButton => child
4053                        // Focus the parent SubmenuButton anchor attached to this child.
4054                        if let Some(anchor_state) = self.anchor_state(app) {
4055                            anchor_state.focus_button(app);
4056                        }
4057                    }
4058                } else if is_submenu {
4059                    // Moving in the closing direction while focused on a
4060                    // SubmenuButton within a root MenuAnchor menu should not close
4061                    // the menu.
4062                    grandparent?;
4063                    if let Some(parent) = parent {
4064                        parent.focus_button(app);
4065                        parent.menu_controller(app).close(app);
4066                    }
4067                } else {
4068                    // If focus is not on a submenu button, closing the anchor this item
4069                    // presides in will close the menu and focus the anchor button.
4070                    self.controller(app).close(app);
4071                }
4072                return None;
4073            }
4074            (Some(Axis::Vertical), TextDirection::Ltr, TraversalDirection::Right)
4075            | (Some(Axis::Vertical), TextDirection::Rtl, TraversalDirection::Left)
4076                if is_submenu =>
4077            {
4078                let controller = self.controller(app);
4079                if controller.is_open(app) {
4080                    if let Some(anchor_state) = self.anchor_state(app) {
4081                        anchor_state.focus_first_menu_item(app);
4082                    }
4083                } else {
4084                    controller.open(app, None);
4085                    let view = View::maybe_id_of(app, submenu.context(app));
4086                    SchedulerBinding::add_post_frame_callback(
4087                        app,
4088                        FrameCallback::new(move |app, _timestamp| {
4089                            if controller.is_open(app)
4090                                && let Some(anchor_state) = self.anchor_state(app)
4091                            {
4092                                anchor_state.focus_first_menu_item(app);
4093                            }
4094                        }),
4095                        view,
4096                    );
4097                }
4098                return None;
4099            }
4100            _ => {}
4101        }
4102
4103        Actions::maybe_invoke(app, submenu.context(app), intent);
4104        None
4105    }
4106}
4107
4108// ---------------------------------------------------------------------------------------------
4109// _LocalizedShortcutLabeler
4110
4111/// A helper class used to generate shortcut labels for a
4112/// `MenuSerializableShortcut` (a subset of the implementors of
4113/// `ShortcutActivator`).
4114///
4115/// This helper class is typically used by the [`MenuItemButton`] and
4116/// [`SubmenuButton`] classes to display a label for their assigned shortcuts.
4117///
4118/// Call [`get_shortcut_label`](Self::get_shortcut_label) with the
4119/// `MenuSerializableShortcut` to get a label for it.
4120///
4121/// For instance, calling [`get_shortcut_label`](Self::get_shortcut_label) with
4122/// `SingleActivator::new(LogicalKeyboardKey::KEY_A).control(true)` would return "⌃ A" on
4123/// macOS, "Ctrl A" in an US English locale, and "Strg A" in a German locale.
4124struct LocalizedShortcutLabeler;
4125
4126impl LocalizedShortcutLabeler {
4127    /// Dart's `_shortcutGraphicEquivalents`.
4128    fn shortcut_graphic_equivalent(key: LogicalKeyboardKey) -> Option<&'static str> {
4129        match key {
4130            LogicalKeyboardKey::ARROW_LEFT => Some("←"),
4131            LogicalKeyboardKey::ARROW_RIGHT => Some("→"),
4132            LogicalKeyboardKey::ARROW_UP => Some("↑"),
4133            LogicalKeyboardKey::ARROW_DOWN => Some("↓"),
4134            LogicalKeyboardKey::ENTER => Some("↵"),
4135            _ => None,
4136        }
4137    }
4138
4139    /// Dart's `_modifiers`.
4140    const MODIFIERS: [LogicalKeyboardKey; 12] = [
4141        LogicalKeyboardKey::ALT,
4142        LogicalKeyboardKey::CONTROL,
4143        LogicalKeyboardKey::META,
4144        LogicalKeyboardKey::SHIFT,
4145        LogicalKeyboardKey::ALT_LEFT,
4146        LogicalKeyboardKey::CONTROL_LEFT,
4147        LogicalKeyboardKey::META_LEFT,
4148        LogicalKeyboardKey::SHIFT_LEFT,
4149        LogicalKeyboardKey::ALT_RIGHT,
4150        LogicalKeyboardKey::CONTROL_RIGHT,
4151        LogicalKeyboardKey::META_RIGHT,
4152        LogicalKeyboardKey::SHIFT_RIGHT,
4153    ];
4154
4155    /// Return the instance for this singleton.
4156    fn instance() -> LocalizedShortcutLabeler {
4157        LocalizedShortcutLabeler
4158    }
4159
4160    /// Returns the label to be shown to the user in the UI when a
4161    /// `MenuSerializableShortcut` is used as a keyboard shortcut.
4162    ///
4163    /// When the target platform is `TargetPlatform::MacOS` or `TargetPlatform::IOS`, this
4164    /// will return graphical key representations when it can. For instance, the default
4165    /// `LogicalKeyboardKey::SHIFT` will return '⇧', and the arrow keys will return arrows.
4166    /// The key `LogicalKeyboardKey::META` will show as '⌘', `LogicalKeyboardKey::CONTROL`
4167    /// will show as '˄', and `LogicalKeyboardKey::ALT` will show as '⌥'.
4168    ///
4169    /// The keys are joined by spaces on macOS and iOS, and by "+" on other
4170    /// platforms.
4171    fn get_shortcut_label(
4172        &self,
4173        app: &App,
4174        shortcut: &MenuSerializableShortcutRef,
4175        localizations: &dyn MaterialLocalizations,
4176    ) -> String {
4177        let serialized = shortcut.serialize_for_menu();
4178        let uses_symbolic_modifiers = uses_symbolic_modifiers(app);
4179        let key_separator = if uses_symbolic_modifiers {
4180            // Use "⌃ ⇧ A" style on macOS and iOS.
4181            " "
4182        } else {
4183            // Use "Ctrl+Shift+A" style.
4184            "+"
4185        };
4186        let modifier = |key| self.get_modifier_label(app, key, localizations);
4187        if let Some(trigger) = serialized.trigger() {
4188            let mut modifiers = Vec::new();
4189            let (control, alt, shift, meta) = (
4190                serialized.control().expect("a trigger has modifiers"),
4191                serialized.alt().expect("a trigger has modifiers"),
4192                serialized.shift().expect("a trigger has modifiers"),
4193                serialized.meta().expect("a trigger has modifiers"),
4194            );
4195            if uses_symbolic_modifiers {
4196                // macOS/iOS platform convention uses this ordering, with ⌘ always last.
4197                if control {
4198                    modifiers.push(modifier(LogicalKeyboardKey::CONTROL));
4199                }
4200                if alt {
4201                    modifiers.push(modifier(LogicalKeyboardKey::ALT));
4202                }
4203                if shift {
4204                    modifiers.push(modifier(LogicalKeyboardKey::SHIFT));
4205                }
4206                if meta {
4207                    modifiers.push(modifier(LogicalKeyboardKey::META));
4208                }
4209            } else {
4210                // This order matches the LogicalKeySet version.
4211                if alt {
4212                    modifiers.push(modifier(LogicalKeyboardKey::ALT));
4213                }
4214                if control {
4215                    modifiers.push(modifier(LogicalKeyboardKey::CONTROL));
4216                }
4217                if meta {
4218                    modifiers.push(modifier(LogicalKeyboardKey::META));
4219                }
4220                if shift {
4221                    modifiers.push(modifier(LogicalKeyboardKey::SHIFT));
4222                }
4223            }
4224            let shortcut_trigger = match Self::shortcut_graphic_equivalent(trigger) {
4225                Some(graphic) => graphic.to_string(),
4226                // Otherwise, look it up, and if we don't have a translation for it,
4227                // then fall back to the key label.
4228                None => self
4229                    .get_localized_name(trigger, localizations)
4230                    .unwrap_or_else(|| trigger.key_label()),
4231            };
4232            if !shortcut_trigger.is_empty() {
4233                modifiers.push(shortcut_trigger);
4234            }
4235            return modifiers.join(key_separator);
4236        } else if let Some(character) = serialized.character_value() {
4237            let mut modifiers = Vec::new();
4238            let (control, alt, meta) = (
4239                serialized.control().expect("a character has modifiers"),
4240                serialized.alt().expect("a character has modifiers"),
4241                serialized.meta().expect("a character has modifiers"),
4242            );
4243            // Character based shortcuts cannot check shifted keys.
4244            if uses_symbolic_modifiers {
4245                // macOS/iOS platform convention uses this ordering, with ⌘ always last.
4246                if control {
4247                    modifiers.push(modifier(LogicalKeyboardKey::CONTROL));
4248                }
4249                if alt {
4250                    modifiers.push(modifier(LogicalKeyboardKey::ALT));
4251                }
4252                if meta {
4253                    modifiers.push(modifier(LogicalKeyboardKey::META));
4254                }
4255            } else {
4256                // This order matches the LogicalKeySet version.
4257                if alt {
4258                    modifiers.push(modifier(LogicalKeyboardKey::ALT));
4259                }
4260                if control {
4261                    modifiers.push(modifier(LogicalKeyboardKey::CONTROL));
4262                }
4263                if meta {
4264                    modifiers.push(modifier(LogicalKeyboardKey::META));
4265                }
4266            }
4267            modifiers.push(character.to_string());
4268            return modifiers.join(key_separator);
4269        }
4270        panic!(
4271            "Shortcut labels for ShortcutActivators that do not implement \
4272             MenuSerializableShortcut (e.g. ShortcutActivators other than SingleActivator or \
4273             CharacterActivator) are not supported."
4274        );
4275    }
4276
4277    // Tries to look up the key in an internal table, and if it can't find it,
4278    // then fall back to the key's keyLabel.
4279    fn get_localized_name(
4280        &self,
4281        key: LogicalKeyboardKey,
4282        localizations: &dyn MaterialLocalizations,
4283    ) -> Option<String> {
4284        let name = match key {
4285            LogicalKeyboardKey::ALT_GRAPH => localizations.keyboard_key_alt_graph(),
4286            LogicalKeyboardKey::BACKSPACE => localizations.keyboard_key_backspace(),
4287            LogicalKeyboardKey::CAPS_LOCK => localizations.keyboard_key_caps_lock(),
4288            LogicalKeyboardKey::CHANNEL_DOWN => localizations.keyboard_key_channel_down(),
4289            LogicalKeyboardKey::CHANNEL_UP => localizations.keyboard_key_channel_up(),
4290            LogicalKeyboardKey::DELETE => localizations.keyboard_key_delete(),
4291            LogicalKeyboardKey::EJECT => localizations.keyboard_key_eject(),
4292            LogicalKeyboardKey::END => localizations.keyboard_key_end(),
4293            LogicalKeyboardKey::ESCAPE => localizations.keyboard_key_escape(),
4294            LogicalKeyboardKey::FN => localizations.keyboard_key_fn(),
4295            LogicalKeyboardKey::HOME => localizations.keyboard_key_home(),
4296            LogicalKeyboardKey::INSERT => localizations.keyboard_key_insert(),
4297            LogicalKeyboardKey::NUM_LOCK => localizations.keyboard_key_num_lock(),
4298            LogicalKeyboardKey::NUMPAD1 => localizations.keyboard_key_numpad1(),
4299            LogicalKeyboardKey::NUMPAD2 => localizations.keyboard_key_numpad2(),
4300            LogicalKeyboardKey::NUMPAD3 => localizations.keyboard_key_numpad3(),
4301            LogicalKeyboardKey::NUMPAD4 => localizations.keyboard_key_numpad4(),
4302            LogicalKeyboardKey::NUMPAD5 => localizations.keyboard_key_numpad5(),
4303            LogicalKeyboardKey::NUMPAD6 => localizations.keyboard_key_numpad6(),
4304            LogicalKeyboardKey::NUMPAD7 => localizations.keyboard_key_numpad7(),
4305            LogicalKeyboardKey::NUMPAD8 => localizations.keyboard_key_numpad8(),
4306            LogicalKeyboardKey::NUMPAD9 => localizations.keyboard_key_numpad9(),
4307            LogicalKeyboardKey::NUMPAD0 => localizations.keyboard_key_numpad0(),
4308            LogicalKeyboardKey::NUMPAD_ADD => localizations.keyboard_key_numpad_add(),
4309            LogicalKeyboardKey::NUMPAD_COMMA => localizations.keyboard_key_numpad_comma(),
4310            LogicalKeyboardKey::NUMPAD_DECIMAL => localizations.keyboard_key_numpad_decimal(),
4311            LogicalKeyboardKey::NUMPAD_DIVIDE => localizations.keyboard_key_numpad_divide(),
4312            LogicalKeyboardKey::NUMPAD_ENTER => localizations.keyboard_key_numpad_enter(),
4313            LogicalKeyboardKey::NUMPAD_EQUAL => localizations.keyboard_key_numpad_equal(),
4314            LogicalKeyboardKey::NUMPAD_MULTIPLY => localizations.keyboard_key_numpad_multiply(),
4315            LogicalKeyboardKey::NUMPAD_PAREN_LEFT => localizations.keyboard_key_numpad_paren_left(),
4316            LogicalKeyboardKey::NUMPAD_PAREN_RIGHT => {
4317                localizations.keyboard_key_numpad_paren_right()
4318            }
4319            LogicalKeyboardKey::NUMPAD_SUBTRACT => localizations.keyboard_key_numpad_subtract(),
4320            LogicalKeyboardKey::PAGE_DOWN => localizations.keyboard_key_page_down(),
4321            LogicalKeyboardKey::PAGE_UP => localizations.keyboard_key_page_up(),
4322            LogicalKeyboardKey::POWER => localizations.keyboard_key_power(),
4323            LogicalKeyboardKey::POWER_OFF => localizations.keyboard_key_power_off(),
4324            LogicalKeyboardKey::PRINT_SCREEN => localizations.keyboard_key_print_screen(),
4325            LogicalKeyboardKey::SCROLL_LOCK => localizations.keyboard_key_scroll_lock(),
4326            LogicalKeyboardKey::SELECT => localizations.keyboard_key_select(),
4327            LogicalKeyboardKey::SPACE => localizations.keyboard_key_space(),
4328            _ => return None,
4329        };
4330        Some(name.to_string())
4331    }
4332
4333    fn get_modifier_label(
4334        &self,
4335        app: &App,
4336        modifier: LogicalKeyboardKey,
4337        localizations: &dyn MaterialLocalizations,
4338    ) -> String {
4339        debug_assert!(
4340            Self::MODIFIERS.contains(&modifier),
4341            "{} is not a modifier key",
4342            modifier.key_label()
4343        );
4344        let platform = app.platform().target_platform();
4345        if modifier == LogicalKeyboardKey::META
4346            || modifier == LogicalKeyboardKey::META_LEFT
4347            || modifier == LogicalKeyboardKey::META_RIGHT
4348        {
4349            return match platform {
4350                TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::Linux => {
4351                    localizations.keyboard_key_meta().to_string()
4352                }
4353                TargetPlatform::Windows => localizations.keyboard_key_meta_windows().to_string(),
4354                TargetPlatform::IOS | TargetPlatform::MacOS => "⌘".to_string(),
4355            };
4356        }
4357        if modifier == LogicalKeyboardKey::ALT
4358            || modifier == LogicalKeyboardKey::ALT_LEFT
4359            || modifier == LogicalKeyboardKey::ALT_RIGHT
4360        {
4361            return match platform {
4362                TargetPlatform::Android
4363                | TargetPlatform::Fuchsia
4364                | TargetPlatform::Linux
4365                | TargetPlatform::Windows => localizations.keyboard_key_alt().to_string(),
4366                TargetPlatform::IOS | TargetPlatform::MacOS => "⌥".to_string(),
4367            };
4368        }
4369        if modifier == LogicalKeyboardKey::CONTROL
4370            || modifier == LogicalKeyboardKey::CONTROL_LEFT
4371            || modifier == LogicalKeyboardKey::CONTROL_RIGHT
4372        {
4373            // '⎈' (a boat helm wheel, not an asterisk) is apparently the standard
4374            // icon for "control", but only seems to appear on the French Canadian
4375            // keyboard. A '✲' (an open center asterisk) appears on some Microsoft
4376            // keyboards. For all but macOS (which has standardized on "⌃", it seems),
4377            // we just return the local translation of "Ctrl".
4378            return match platform {
4379                TargetPlatform::Android
4380                | TargetPlatform::Fuchsia
4381                | TargetPlatform::Linux
4382                | TargetPlatform::Windows => localizations.keyboard_key_control().to_string(),
4383                TargetPlatform::IOS | TargetPlatform::MacOS => "⌃".to_string(),
4384            };
4385        }
4386        if modifier == LogicalKeyboardKey::SHIFT
4387            || modifier == LogicalKeyboardKey::SHIFT_LEFT
4388            || modifier == LogicalKeyboardKey::SHIFT_RIGHT
4389        {
4390            return match platform {
4391                TargetPlatform::Android
4392                | TargetPlatform::Fuchsia
4393                | TargetPlatform::Linux
4394                | TargetPlatform::Windows => localizations.keyboard_key_shift().to_string(),
4395                TargetPlatform::IOS | TargetPlatform::MacOS => "⇧".to_string(),
4396            };
4397        }
4398        panic!("Keyboard key {} is not a modifier.", modifier.key_label());
4399    }
4400}
4401
4402// ---------------------------------------------------------------------------------------------
4403// _MenuBarAnchor
4404
4405/// MenuBar-specific private specialization of [`MenuAnchor`] so that it can act
4406/// differently in regards to orientation, how open works, and what gets built.
4407///
4408/// Dart's `_MenuBarAnchor extends MenuAnchor`: the [`MenuAnchor`] it is.
4409struct MenuBarAnchor {
4410    menu_anchor: MenuAnchor,
4411}
4412
4413impl Debug for MenuBarAnchor {
4414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4415        Debug::fmt(&self.menu_anchor, f)
4416    }
4417}
4418
4419impl StatefulWidget for MenuBarAnchor {
4420    type State = MenuBarAnchorState;
4421
4422    fn key(&self) -> Option<&KeyRef> {
4423        self.menu_anchor.key.as_ref()
4424    }
4425
4426    fn create_state(&self) -> MenuBarAnchorState {
4427        MenuBarAnchorState {
4428            state: StateData::new(),
4429            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
4430            menu_anchor_state: MenuAnchorStateData::new(),
4431            dismiss_menu_action: None,
4432        }
4433    }
4434}
4435
4436/// Dart's `_MenuBarAnchorState extends _MenuAnchorState`.
4437struct MenuBarAnchorState {
4438    state: StateData<MenuBarAnchor>,
4439    single_ticker_provider: SingleTickerProviderStateMixinData,
4440    menu_anchor_state: MenuAnchorStateData,
4441    // Dart's `late final actions`, made on the first build with the controller of the moment.
4442    dismiss_menu_action: Option<Ref<DismissMenuAction>>,
4443}
4444
4445impl MenuAnchorStateLeaf for MenuBarAnchorState {
4446    fn menu_anchor_state_data(self: Handle<Self>, app: &App) -> &MenuAnchorStateData {
4447        &app.get(self).menu_anchor_state
4448    }
4449
4450    fn menu_anchor_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut MenuAnchorStateData {
4451        &mut app.get_mut(self).menu_anchor_state
4452    }
4453
4454    fn menu_anchor(self: Handle<Self>, app: &App) -> &MenuAnchor {
4455        &self.widget(app).menu_anchor
4456    }
4457
4458    fn orientation() -> Axis {
4459        Axis::Horizontal
4460    }
4461
4462    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
4463        let this = self.as_menu_anchor_state();
4464        let dismiss_menu_action = match app.get(self).dismiss_menu_action.clone() {
4465            Some(action) => action,
4466            None => {
4467                let controller = this.menu_controller(app);
4468                let action = DismissMenuAction::new(app, controller);
4469                app.get_mut(self).dismiss_menu_action = Some(action.clone());
4470                action
4471            }
4472        };
4473        let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
4474        actions.insert(
4475            <DismissMenuAction as Action>::intent_type(),
4476            dismiss_menu_action.into_erased(),
4477        );
4478        let widget = self.menu_anchor(app);
4479        let child = Actions::new(
4480            actions,
4481            Shortcuts::new(
4482                menu_traversal_shortcuts(),
4483                MenuPanel {
4484                    menu_style: widget.style.clone(),
4485                    clip_behavior: widget.clip_behavior,
4486                    orientation: Self::orientation(),
4487                    cross_axis_unconstrained: true,
4488                    height_animation: None,
4489                    children: widget.menu_children.clone(),
4490                },
4491            ),
4492        )
4493        .into_widget();
4494        let menu_scope_node = self
4495            .menu_anchor_state_data(app)
4496            .menu_scope_node
4497            .clone()
4498            .expect("created in init_state");
4499        MenuAnchorScope {
4500            state: this,
4501            animation_status: self.animation_controller(app).status(app),
4502            child: RawMenuAnchorGroup::new(
4503                Builder::new(move |app, context| {
4504                    let is_open = MenuController::maybe_is_open_of(app, context).unwrap_or(false);
4505                    FocusScope::new(ExcludeFocus::new(child.clone()).excluding(!is_open))
4506                        .node(menu_scope_node.clone())
4507                        .skip_traversal(!is_open)
4508                        .can_request_focus(is_open)
4509                        .descendants_are_focusable(true)
4510                        .into_widget()
4511                }),
4512                this.menu_controller(app),
4513            )
4514            .into_widget(),
4515        }
4516        .into_widget()
4517    }
4518}
4519
4520impl SingleTickerProviderStateMixin for MenuBarAnchorState {
4521    fn single_ticker_provider_data(
4522        self: Handle<Self>,
4523        app: &App,
4524    ) -> &SingleTickerProviderStateMixinData {
4525        &app.get(self).single_ticker_provider
4526    }
4527
4528    fn single_ticker_provider_data_mut(
4529        self: Handle<Self>,
4530        app: &mut App,
4531    ) -> &mut SingleTickerProviderStateMixinData {
4532        &mut app.get_mut(self).single_ticker_provider
4533    }
4534}
4535
4536/// Dart's `vsync: this`.
4537impl TickerProviderObject for MenuBarAnchorState {
4538    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
4539        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
4540    }
4541}
4542
4543impl State for MenuBarAnchorState {
4544    type Widget = MenuBarAnchor;
4545    waft_widgets::state_accessors!();
4546
4547    fn init_state(self: Handle<Self>, app: &mut App) {
4548        MenuAnchorStateLeaf::init_state(self, app);
4549    }
4550
4551    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MenuBarAnchor) {
4552        MenuAnchorStateLeaf::did_update_widget(self, app, &old_widget.menu_anchor);
4553    }
4554
4555    fn activate(self: Handle<Self>, app: &mut App) {
4556        SingleTickerProviderStateMixin::activate(self, app);
4557    }
4558
4559    fn dispose(self: Handle<Self>, app: &mut App) {
4560        MenuAnchorStateLeaf::dispose(self, app);
4561    }
4562
4563    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
4564        MenuAnchorStateLeaf::build(self, app, context)
4565    }
4566}
4567
4568impl Debug for MenuBarAnchorState {
4569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4570        f.write_str("_MenuBarAnchorState")
4571    }
4572}
4573
4574// ---------------------------------------------------------------------------------------------
4575// MenuAcceleratorCallbackBinding
4576
4577/// An `InheritedWidget` that provides a descendant [`MenuAcceleratorLabel`] with
4578/// the function to invoke when the accelerator is pressed.
4579///
4580/// This is used when creating your own custom menu item for use with
4581/// [`MenuAnchor`] or [`MenuBar`]. Provided menu items such as [`MenuItemButton`] and
4582/// [`SubmenuButton`] already supply this wrapper internally.
4583#[derive(Clone, Debug)]
4584pub struct MenuAcceleratorCallbackBinding {
4585    /// See `Widget::key`.
4586    pub key: Option<KeyRef>,
4587
4588    /// The function that pressing the accelerator defined in a descendant
4589    /// [`MenuAcceleratorLabel`] will invoke.
4590    ///
4591    /// If set to null, then the accelerator won't be enabled.
4592    pub on_invoke: Option<Listener>,
4593
4594    /// Whether or not the associated label will host its own submenu or not.
4595    ///
4596    /// This setting determines when accelerators are active, since accelerators
4597    /// for menu items that open submenus shouldn't be active when the submenu is
4598    /// open.
4599    pub has_submenu: bool,
4600
4601    /// The widget below this widget in the tree.
4602    pub child: WidgetRef,
4603}
4604
4605impl MenuAcceleratorCallbackBinding {
4606    /// Create a const [`MenuAcceleratorCallbackBinding`].
4607    ///
4608    /// The [`child`](Self::child) parameter is required.
4609    #[cfg_attr(debug_assertions, track_caller)]
4610    pub fn new<K>(child: impl IntoWidget<K>) -> MenuAcceleratorCallbackBinding {
4611        MenuAcceleratorCallbackBinding {
4612            key: None,
4613            on_invoke: None,
4614            has_submenu: false,
4615            child: child.into_widget(),
4616        }
4617    }
4618
4619    /// Dart `MenuAcceleratorCallbackBinding(key:)`.
4620    pub fn key(mut self, key: KeyRef) -> MenuAcceleratorCallbackBinding {
4621        self.key = Some(key);
4622        self
4623    }
4624
4625    /// Dart `MenuAcceleratorCallbackBinding(onInvoke:)`.
4626    pub fn on_invoke(mut self, on_invoke: Listener) -> MenuAcceleratorCallbackBinding {
4627        self.on_invoke = Some(on_invoke);
4628        self
4629    }
4630
4631    /// Dart `MenuAcceleratorCallbackBinding(hasSubmenu:)`.
4632    pub fn has_submenu(mut self, has_submenu: bool) -> MenuAcceleratorCallbackBinding {
4633        self.has_submenu = has_submenu;
4634        self
4635    }
4636
4637    /// Returns the active [`MenuAcceleratorCallbackBinding`] in the given context, if any,
4638    /// and creates a dependency relationship that will rebuild the context when
4639    /// [`on_invoke`](Self::on_invoke) changes.
4640    ///
4641    /// If no [`MenuAcceleratorCallbackBinding`] is found, returns null.
4642    ///
4643    /// See also:
4644    ///
4645    /// * [`of`](Self::of), which is similar, but panics if no
4646    ///   [`MenuAcceleratorCallbackBinding`] is found.
4647    pub fn maybe_of(
4648        app: &mut App,
4649        context: BuildContext,
4650    ) -> Option<MenuAcceleratorCallbackBinding> {
4651        context
4652            .depend_on_inherited_widget_of_exact_type::<MenuAcceleratorCallbackBinding>(app)
4653            .cloned()
4654    }
4655
4656    /// Returns the active [`MenuAcceleratorCallbackBinding`] in the given context, and
4657    /// creates a dependency relationship that will rebuild the context when
4658    /// [`on_invoke`](Self::on_invoke) changes.
4659    ///
4660    /// If no [`MenuAcceleratorCallbackBinding`] is found, this panics.
4661    ///
4662    /// See also:
4663    ///
4664    /// * [`maybe_of`](Self::maybe_of), which is similar, but returns null if no
4665    ///   [`MenuAcceleratorCallbackBinding`] is found.
4666    pub fn of(app: &mut App, context: BuildContext) -> MenuAcceleratorCallbackBinding {
4667        let result = MenuAcceleratorCallbackBinding::maybe_of(app, context);
4668        match result {
4669            Some(result) => result,
4670            None => panic!(
4671                "MenuAcceleratorWrapper.of() was called with a context that does not contain a \
4672                 MenuAcceleratorWrapper in the given context.\nNo MenuAcceleratorWrapper \
4673                 ancestor could be found in the context that was passed to \
4674                 MenuAcceleratorWrapper.of(). This can happen because you are using a widget \
4675                 that looks for a MenuAcceleratorWrapper ancestor, and do not have a \
4676                 MenuAcceleratorWrapper widget ancestor.\nThe context used was:\n  {context:?}"
4677            ),
4678        }
4679    }
4680}
4681
4682impl InheritedWidget for MenuAcceleratorCallbackBinding {
4683    fn key(&self) -> Option<&KeyRef> {
4684        self.key.as_ref()
4685    }
4686
4687    fn child(&self) -> &WidgetRef {
4688        &self.child
4689    }
4690
4691    fn update_should_notify(&self, old_widget: &MenuAcceleratorCallbackBinding) -> bool {
4692        self.on_invoke != old_widget.on_invoke || self.has_submenu != old_widget.has_submenu
4693    }
4694}
4695
4696// ---------------------------------------------------------------------------------------------
4697// MenuAcceleratorLabel
4698
4699/// The type of builder function used for building a [`MenuAcceleratorLabel`]'s
4700/// [`MenuAcceleratorLabel::builder`] function.
4701///
4702/// The arguments to the function are as follows:
4703///
4704/// * The `context` supplies the [`BuildContext`] to use.
4705/// * The `label` is the [`MenuAcceleratorLabel::label`] attribute for the relevant
4706///   [`MenuAcceleratorLabel`] with the accelerator markers stripped out of it.
4707/// * The `index` is the index of the accelerator character within the
4708///   grapheme clusters of `label` that applies to this accelerator. If it is -1, then the
4709///   accelerator should not be highlighted. Otherwise, the given character
4710///   should be highlighted somehow in the rendered label (typically with an
4711///   underscore). Importantly, `index` is not an index into the [`String`]
4712///   `label`, it is an index into its user-visible characters (a.k.a. grapheme clusters),
4713///   not Unicode code points.
4714///
4715/// See also:
4716///
4717/// * [`MenuAcceleratorLabel::default_label_builder`], which is the implementation
4718///   used as the default value for [`MenuAcceleratorLabel::builder`].
4719pub type MenuAcceleratorChildBuilder = Rc<dyn Fn(&mut App, BuildContext, &str, isize) -> WidgetRef>;
4720
4721/// A widget that draws the label text for a menu item (typically a
4722/// [`MenuItemButton`] or [`SubmenuButton`]) and renders its child with information
4723/// about the currently active keyboard accelerator.
4724///
4725/// On platforms other than macOS and iOS, this widget listens for the Alt key
4726/// to be pressed, and when it is down, will update the label by calling the
4727/// builder again with the position of the accelerator in the label string.
4728/// While the Alt key is pressed, it registers a shortcut with the
4729/// `ShortcutRegistry` mapped to a `VoidCallbackIntent` containing the callback
4730/// defined by the nearest [`MenuAcceleratorCallbackBinding`].
4731///
4732/// Because the accelerators are registered with the `ShortcutRegistry`, any
4733/// other shortcuts in the widget tree between the primary focus and the
4734/// `ShortcutRegistry` that define Alt-based shortcuts using the same keys will
4735/// take precedence over the accelerators.
4736///
4737/// Because accelerators aren't used on macOS and iOS, the label ignores the Alt
4738/// key on those platforms, and the [`builder`](Self::builder) is always given -1 as an
4739/// accelerator index. Accelerator labels are still stripped of their
4740/// accelerator markers.
4741///
4742/// The built-in menu items [`MenuItemButton`] and [`SubmenuButton`] already provide
4743/// the appropriate [`MenuAcceleratorCallbackBinding`], so unless you are creating
4744/// your own custom menu item type that takes a [`MenuAcceleratorLabel`], it is
4745/// not necessary to provide one.
4746pub struct MenuAcceleratorLabel {
4747    /// See `Widget::key`.
4748    pub key: Option<KeyRef>,
4749
4750    /// The label string that should be displayed.
4751    ///
4752    /// The label string provides the label text, as well as the possible
4753    /// characters which could be used as accelerators in the menu system.
4754    ///
4755    /// To indicate which letters in the label are to be used as accelerators, add
4756    /// an "&" character before the character in the string. If more than one
4757    /// character has an "&" in front of it, then the characters appearing earlier
4758    /// in the string are preferred. To represent a literal "&", insert "&&" into
4759    /// the string. All other ampersands will be removed from the string before
4760    /// calling [`MenuAcceleratorLabel::builder`]. Bare ampersands at the end of the
4761    /// string or before whitespace are stripped and ignored.
4762    ///
4763    /// See also:
4764    ///
4765    /// * [`display_label`](Self::display_label), which returns the [`label`](Self::label)
4766    ///   with all of the ampersands stripped out of it, and double ampersands converted to
4767    ///   ampersands.
4768    /// * [`strip_accelerator_markers`](Self::strip_accelerator_markers), which returns the
4769    ///   supplied string with all of the ampersands stripped out of it, and double ampersands
4770    ///   converted to ampersands, and optionally calls a callback with the index of the
4771    ///   accelerator character found.
4772    pub label: String,
4773
4774    /// The optional [`MenuAcceleratorChildBuilder`] which is used to build the
4775    /// widget that displays the label itself.
4776    ///
4777    /// The [`default_label_builder`](Self::default_label_builder) function serves as the
4778    /// default value for [`builder`](Self::builder), rendering the label as a `RichText`
4779    /// widget with appropriate `TextSpan`s for rendering the label with an underscore under
4780    /// the selected accelerator for the label when accelerators have been activated.
4781    ///
4782    /// When writing the builder function, it's not necessary to take the current
4783    /// platform into account. On platforms which don't support accelerators (e.g.
4784    /// macOS and iOS), the passed accelerator index will always be -1, and the
4785    /// accelerator markers will already be stripped.
4786    pub builder: MenuAcceleratorChildBuilder,
4787}
4788
4789impl MenuAcceleratorLabel {
4790    /// Creates a const [`MenuAcceleratorLabel`].
4791    ///
4792    /// The [`label`](Self::label) parameter is required.
4793    pub fn new(label: impl Into<String>) -> MenuAcceleratorLabel {
4794        MenuAcceleratorLabel {
4795            key: None,
4796            label: label.into(),
4797            builder: Rc::new(MenuAcceleratorLabel::default_label_builder),
4798        }
4799    }
4800
4801    /// Dart `MenuAcceleratorLabel(key:)`.
4802    pub fn key(mut self, key: KeyRef) -> MenuAcceleratorLabel {
4803        self.key = Some(key);
4804        self
4805    }
4806
4807    /// Dart `MenuAcceleratorLabel(builder:)`.
4808    pub fn builder(
4809        mut self,
4810        builder: impl Fn(&mut App, BuildContext, &str, isize) -> WidgetRef + 'static,
4811    ) -> MenuAcceleratorLabel {
4812        self.builder = Rc::new(builder);
4813        self
4814    }
4815
4816    /// Returns the [`label`](Self::label) with any accelerator markers removed.
4817    ///
4818    /// This getter just calls [`strip_accelerator_markers`](Self::strip_accelerator_markers)
4819    /// with the [`label`](Self::label).
4820    pub fn display_label(&self) -> String {
4821        MenuAcceleratorLabel::strip_accelerator_markers(&self.label, None)
4822    }
4823
4824    /// Whether [`label`](Self::label) contains an accelerator definition.
4825    ///
4826    /// Dart's `RegExp(r'&(?!([&\s]|$))')`: an ampersand followed by a character that is
4827    /// neither an ampersand nor whitespace.
4828    pub fn has_accelerator(&self) -> bool {
4829        let mut chars = self.label.chars().peekable();
4830        while let Some(character) = chars.next() {
4831            if character == '&'
4832                && chars
4833                    .peek()
4834                    .is_some_and(|next| *next != '&' && !next.is_whitespace())
4835            {
4836                return true;
4837            }
4838        }
4839        false
4840    }
4841
4842    /// Serves as the default value for [`builder`](Self::builder), rendering the label as a
4843    /// `RichText` widget with appropriate `TextSpan`s for rendering the label with an
4844    /// underscore under the selected accelerator for the label when the `index` is
4845    /// non-negative, and a `Text` widget when the `index` is negative.
4846    pub fn default_label_builder(
4847        app: &mut App,
4848        context: BuildContext,
4849        label: &str,
4850        index: isize,
4851    ) -> WidgetRef {
4852        if index < 0 {
4853            return Text::new(label).into_widget();
4854        }
4855        let index = index as usize;
4856        let default_style = DefaultTextStyle::of(app, context).style;
4857        let characters: Vec<&str> = label.graphemes(true).collect();
4858        let mut children: Vec<InlineSpanRef> = Vec::new();
4859        if index > 0 {
4860            children.push(Rc::new(
4861                TextSpan::new()
4862                    .text(characters[..index].concat())
4863                    .style(default_style.clone()),
4864            ));
4865        }
4866        children.push(Rc::new(
4867            TextSpan::new()
4868                .text(characters[index..index + 1].concat())
4869                .style(
4870                    default_style
4871                        .copy_with()
4872                        .decoration(TextDecoration::UNDERLINE),
4873                ),
4874        ));
4875        if index < characters.len() - 1 {
4876            children.push(Rc::new(
4877                TextSpan::new()
4878                    .text(characters[index + 1..].concat())
4879                    .style(default_style),
4880            ));
4881        }
4882        RichText::new(Rc::new(TextSpan::new().children(children))).into_widget()
4883    }
4884
4885    /// Strips out any accelerator markers from the given `label`, and unescapes
4886    /// any escaped ampersands.
4887    ///
4888    /// If `set_index` is supplied, it will be called before this function returns
4889    /// with the index in the returned string of the accelerator character.
4890    ///
4891    /// See [`label`](Self::label) for the markers.
4892    pub fn strip_accelerator_markers(
4893        label: &str,
4894        set_index: Option<&mut dyn FnMut(isize)>,
4895    ) -> String {
4896        let mut quoted_ampersands: isize = 0;
4897        let mut display_label = String::new();
4898        let mut accelerator_index: isize = -1;
4899        // Use characters so that we don't split up surrogate pairs and interpret
4900        // them incorrectly.
4901        let label_chars: Vec<&str> = label.graphemes(true).collect();
4902        let ampersand = "&";
4903        let mut last_was_ampersand = false;
4904        for (i, character) in label_chars.iter().enumerate() {
4905            // Stop looking one before the end, since a single ampersand at the end is
4906            // just treated as a quoted ampersand.
4907            if last_was_ampersand {
4908                last_was_ampersand = false;
4909                display_label.push_str(character);
4910                continue;
4911            }
4912            if *character != ampersand {
4913                display_label.push_str(character);
4914                continue;
4915            }
4916            if i == label_chars.len() - 1 {
4917                // Strip bare ampersands at the end of a string.
4918                break;
4919            }
4920            last_was_ampersand = true;
4921            let accelerator_character = label_chars[i + 1];
4922            if accelerator_index == -1
4923                && accelerator_character != ampersand
4924                && !accelerator_character.trim().is_empty()
4925            {
4926                // Don't set the accelerator index if the character is an ampersand,
4927                // or whitespace.
4928                accelerator_index = i as isize - quoted_ampersands;
4929            }
4930            // As we encounter '&<character>' pairs, the following indices must be
4931            // adjusted so that they correspond with indices in the stripped string.
4932            quoted_ampersands += 1;
4933        }
4934        if let Some(set_index) = set_index {
4935            set_index(accelerator_index);
4936        }
4937        display_label
4938    }
4939}
4940
4941impl Debug for MenuAcceleratorLabel {
4942    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4943        write!(f, "MenuAcceleratorLabel(\"{}\")", self.label)
4944    }
4945}
4946
4947impl StatefulWidget for MenuAcceleratorLabel {
4948    type State = MenuAcceleratorLabelState;
4949
4950    fn key(&self) -> Option<&KeyRef> {
4951        self.key.as_ref()
4952    }
4953
4954    fn debug_fill_properties(&self, __app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4955        properties.add(StringProperty::new("label", Some(self.label.clone())));
4956    }
4957
4958    fn create_state(&self) -> MenuAcceleratorLabelState {
4959        MenuAcceleratorLabelState {
4960            state: StateData::new(),
4961            display_label: String::new(),
4962            accelerator_index: -1,
4963            binding: None,
4964            menu_controller: None,
4965            shortcut_registry: None,
4966            shortcut_registry_entry: None,
4967            show_accelerators: false,
4968            key_event_handler: None,
4969        }
4970    }
4971}
4972
4973/// Dart's `_MenuAcceleratorLabelState`.
4974pub struct MenuAcceleratorLabelState {
4975    state: StateData<MenuAcceleratorLabel>,
4976    display_label: String,
4977    accelerator_index: isize,
4978    binding: Option<MenuAcceleratorCallbackBinding>,
4979    menu_controller: Option<MenuControllerRef>,
4980    shortcut_registry: Option<Ref<ShortcutRegistry>>,
4981    shortcut_registry_entry: Option<Ref<ShortcutRegistryEntry>>,
4982    show_accelerators: bool,
4983    // Dart's `_listenToKeyEvent` tear-off, kept to remove the same handler again.
4984    key_event_handler: Option<KeyEventCallback>,
4985}
4986
4987impl MenuAcceleratorLabelState {
4988    /// Dart's `_altIsPressed`.
4989    fn alt_is_pressed(app: &mut App) -> bool {
4990        let keyboard = HardwareKeyboard::instance(app);
4991        let pressed = keyboard.logical_keys_pressed(app);
4992        [
4993            LogicalKeyboardKey::ALT_LEFT,
4994            LogicalKeyboardKey::ALT_RIGHT,
4995            LogicalKeyboardKey::ALT,
4996        ]
4997        .iter()
4998        .any(|key| pressed.contains(key))
4999    }
5000
5001    /// Dart's `_listenToKeyEvent`.
5002    fn listen_to_key_event(self: Handle<Self>, app: &mut App, _event: &KeyEvent) -> bool {
5003        debug_assert!(platform_supports_accelerators(app));
5004        let show_accelerators = Self::alt_is_pressed(app);
5005        self.set_state(app, |state| {
5006            state.show_accelerators = show_accelerators;
5007        });
5008        self.update_accelerator_shortcut(app);
5009        // Just listening, so it doesn't ever handle a key.
5010        false
5011    }
5012
5013    /// Dart's `_updateAcceleratorShortcut`.
5014    fn update_accelerator_shortcut(self: Handle<Self>, app: &mut App) {
5015        debug_assert!(platform_supports_accelerators(app));
5016        if let Some(entry) = app.get_mut(self).shortcut_registry_entry.take() {
5017            entry.dispose(app);
5018        }
5019        // Before registering an accelerator as a shortcut it should meet these
5020        // conditions:
5021        //
5022        // 1) Is showing accelerators (i.e. Alt key is down).
5023        // 2) Has an accelerator marker in the label.
5024        // 3) Has an associated action callback for the label (from the
5025        //    MenuAcceleratorCallbackBinding).
5026        // 4) Is part of an anchor that either doesn't have a submenu, or doesn't
5027        //    have any submenus currently open (only the "deepest" open menu should
5028        //    have accelerator shortcuts registered).
5029        let this = app.get(self);
5030        let Some(on_invoke) = this
5031            .binding
5032            .as_ref()
5033            .and_then(|binding| binding.on_invoke.clone())
5034        else {
5035            return;
5036        };
5037        let has_submenu = this
5038            .binding
5039            .as_ref()
5040            .is_some_and(|binding| binding.has_submenu);
5041        if this.show_accelerators
5042            && this.accelerator_index != -1
5043            && (!has_submenu
5044                || !this
5045                    .menu_controller
5046                    .as_ref()
5047                    .is_some_and(|menu_controller| menu_controller.is_open(app)))
5048        {
5049            // Dart indexes the label's UTF-16 code units here.
5050            let code_unit = this
5051                .display_label
5052                .encode_utf16()
5053                .nth(this.accelerator_index as usize)
5054                .expect("the accelerator index is inside the label");
5055            let accelerator_character = String::from_utf16_lossy(&[code_unit]).to_lowercase();
5056            if let Some(shortcut_registry) = this.shortcut_registry.clone() {
5057                let activator: ShortcutActivatorRef =
5058                    Rc::new(CharacterActivator::new(accelerator_character).alt(true));
5059                let entry = shortcut_registry.add_all(
5060                    app,
5061                    vec![(activator, Rc::new(VoidCallbackIntent::new(on_invoke)))],
5062                );
5063                app.get_mut(self).shortcut_registry_entry = Some(entry);
5064            }
5065        }
5066    }
5067
5068    /// Dart's `_updateDisplayLabel`.
5069    fn update_display_label(self: Handle<Self>, app: &mut App) {
5070        let mut accelerator_index = -1;
5071        let display_label = MenuAcceleratorLabel::strip_accelerator_markers(
5072            &self.widget(app).label,
5073            Some(&mut |index| {
5074                accelerator_index = index;
5075            }),
5076        );
5077        let this = app.get_mut(self);
5078        this.display_label = display_label;
5079        this.accelerator_index = accelerator_index;
5080    }
5081}
5082
5083impl State for MenuAcceleratorLabelState {
5084    type Widget = MenuAcceleratorLabel;
5085    waft_widgets::state_accessors!();
5086
5087    fn init_state(self: Handle<Self>, app: &mut App) {
5088        if platform_supports_accelerators(app) {
5089            let show_accelerators = Self::alt_is_pressed(app);
5090            app.get_mut(self).show_accelerators = show_accelerators;
5091            let handler: KeyEventCallback = Rc::new(move |app: &mut App, event: &KeyEvent| {
5092                self.listen_to_key_event(app, event)
5093            });
5094            app.get_mut(self).key_event_handler = Some(Rc::clone(&handler));
5095            HardwareKeyboard::instance(app).add_handler(app, handler);
5096        }
5097        self.update_display_label(app);
5098    }
5099
5100    fn dispose(self: Handle<Self>, app: &mut App) {
5101        debug_assert!(
5102            platform_supports_accelerators(app) || app.get(self).shortcut_registry_entry.is_none()
5103        );
5104        app.get_mut(self).display_label = String::new();
5105        if platform_supports_accelerators(app) {
5106            if let Some(entry) = app.get_mut(self).shortcut_registry_entry.take() {
5107                entry.dispose(app);
5108            }
5109            let this = app.get_mut(self);
5110            this.shortcut_registry = None;
5111            this.menu_controller = None;
5112            if let Some(handler) = this.key_event_handler.take() {
5113                HardwareKeyboard::instance(app).remove_handler(app, &handler);
5114            }
5115        }
5116    }
5117
5118    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
5119        if !platform_supports_accelerators(app) {
5120            return;
5121        }
5122        let context = self.context(app);
5123        let binding = MenuAcceleratorCallbackBinding::maybe_of(app, context);
5124        let menu_controller =
5125            MenuController::maybe_of(app, context).and_then(|controller| controller.upgrade(app));
5126        let shortcut_registry =
5127            ShortcutRegistry::maybe_of(app, context).and_then(|registry| registry.upgrade(app));
5128        let this = app.get_mut(self);
5129        this.binding = binding;
5130        this.menu_controller = menu_controller;
5131        this.shortcut_registry = shortcut_registry;
5132        self.update_accelerator_shortcut(app);
5133    }
5134
5135    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MenuAcceleratorLabel) {
5136        if self.widget(app).label != old_widget.label {
5137            self.update_display_label(app);
5138        }
5139    }
5140
5141    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
5142        let this = app.get(self);
5143        let index = if this.show_accelerators {
5144            this.accelerator_index
5145        } else {
5146            -1
5147        };
5148        let display_label = this.display_label.clone();
5149        let builder = Rc::clone(&self.widget(app).builder);
5150        builder(app, context, &display_label, index)
5151    }
5152}
5153
5154impl Debug for MenuAcceleratorLabelState {
5155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5156        f.debug_struct("_MenuAcceleratorLabelState")
5157            .field("display_label", &self.display_label)
5158            .field("accelerator_index", &self.accelerator_index)
5159            .finish_non_exhaustive()
5160    }
5161}
5162
5163// ---------------------------------------------------------------------------------------------
5164// _MenuItemLabel
5165
5166/// A label widget that is used as the label for a [`MenuItemButton`] or
5167/// [`SubmenuButton`].
5168///
5169/// It not only shows the [`SubmenuButton::child`] or [`MenuItemButton::child`], but if
5170/// there is a shortcut associated with the [`MenuItemButton`], it will display a
5171/// mnemonic for the shortcut. For [`SubmenuButton`]s, it will display a visual
5172/// indicator that there is a submenu.
5173struct MenuItemLabel {
5174    /// Whether or not this menu has a submenu.
5175    ///
5176    /// Determines whether the submenu arrow is shown or not.
5177    has_submenu: bool,
5178
5179    /// Whether or not this item should show decorations like shortcut labels or
5180    /// submenu arrows. Items in a [`MenuBar`] don't show these decorations when
5181    /// they are laid out horizontally.
5182    show_decoration: bool,
5183
5184    /// The optional icon that comes before the [`child`](Self::child).
5185    leading_icon: Option<WidgetRef>,
5186
5187    /// The optional icon that comes after the [`child`](Self::child).
5188    trailing_icon: Option<WidgetRef>,
5189
5190    /// The shortcut for this label, so that it can generate a string describing
5191    /// the shortcut.
5192    shortcut: Option<MenuSerializableShortcutRef>,
5193
5194    /// An optional Semantics label, which replaces the generated string when
5195    /// read by a screen reader.
5196    semantics_label: Option<String>,
5197
5198    /// The direction in which the menu item expands.
5199    overflow_axis: Axis,
5200
5201    /// The submenu icon that is displayed when [`show_decoration`](Self::show_decoration) and
5202    /// [`has_submenu`](Self::has_submenu) are true.
5203    submenu_icon: Option<WidgetRef>,
5204
5205    /// An optional child widget that is displayed in the label.
5206    child: Option<WidgetRef>,
5207}
5208
5209impl Debug for MenuItemLabel {
5210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5211        f.debug_struct("_MenuItemLabel")
5212            .field("shortcut", &self.shortcut)
5213            .field("hasSubmenu", &self.has_submenu)
5214            .field("showDecoration", &self.show_decoration)
5215            .finish_non_exhaustive()
5216    }
5217}
5218
5219impl StatelessWidget for MenuItemLabel {
5220    fn debug_fill_properties(&self, __app: &App, properties: &mut DiagnosticPropertiesBuilder) {
5221        properties.add(
5222            DiagnosticsProperty::<String>::new(
5223                "shortcut",
5224                self.shortcut
5225                    .as_ref()
5226                    .map(|shortcut| format!("{shortcut:?}")),
5227            )
5228            .default_value(None),
5229        );
5230        properties.add(DiagnosticsProperty::<bool>::new(
5231            "hasSubmenu",
5232            self.has_submenu,
5233        ));
5234        properties.add(DiagnosticsProperty::<bool>::new(
5235            "showDecoration",
5236            self.show_decoration,
5237        ));
5238    }
5239
5240    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
5241        let density = Theme::of(app, context).visual_density;
5242        let horizontal_padding =
5243            K_LABEL_ITEM_MIN_SPACING.max(K_LABEL_ITEM_DEFAULT_SPACING + density.horizontal * 2.0);
5244        let start_padding = if self.leading_icon.is_some() {
5245            EdgeInsetsGeometry::directional(horizontal_padding, 0.0, 0.0, 0.0)
5246        } else {
5247            EdgeInsetsGeometry::ZERO
5248        };
5249        let leadings = if self.overflow_axis == Axis::Vertical {
5250            let mut children: Vec<WidgetRef> = self.leading_icon.iter().cloned().collect();
5251            if let Some(child) = &self.child {
5252                children.push(
5253                    Expanded::new(
5254                        ClipRect::new().child(Padding::new(start_padding).child(child.clone())),
5255                    )
5256                    .into_widget(),
5257                );
5258            }
5259            Expanded::new(
5260                Row::new()
5261                    .main_axis_size(MainAxisSize::Min)
5262                    .children(children),
5263            )
5264            .into_widget()
5265        } else {
5266            let mut children: Vec<WidgetRef> = self.leading_icon.iter().cloned().collect();
5267            if let Some(child) = &self.child {
5268                children.push(
5269                    Padding::new(start_padding)
5270                        .child(child.clone())
5271                        .into_widget(),
5272                );
5273            }
5274            Row::new()
5275                .main_axis_size(MainAxisSize::Min)
5276                .children(children)
5277                .into_widget()
5278        };
5279
5280        let item_padding = EdgeInsetsGeometry::directional(horizontal_padding, 0.0, 0.0, 0.0);
5281        let mut children = vec![leadings];
5282        if let Some(trailing_icon) = &self.trailing_icon {
5283            children.push(
5284                Padding::new(item_padding)
5285                    .child(trailing_icon.clone())
5286                    .into_widget(),
5287            );
5288        }
5289        if self.show_decoration
5290            && let Some(shortcut) = &self.shortcut
5291        {
5292            let localizations = <dyn MaterialLocalizations>::of(app, context);
5293            let label = LocalizedShortcutLabeler::instance().get_shortcut_label(
5294                app,
5295                shortcut,
5296                &*localizations,
5297            );
5298            children.push(
5299                Padding::new(item_padding)
5300                    .child(Text::new(label))
5301                    .into_widget(),
5302            );
5303        }
5304        if self.show_decoration && self.has_submenu {
5305            let mut padding = Padding::new(item_padding);
5306            if let Some(submenu_icon) = &self.submenu_icon {
5307                padding = padding.child(submenu_icon.clone());
5308            }
5309            children.push(padding.into_widget());
5310        }
5311        let mut menu_item_label = Row::new()
5312            .main_axis_alignment(MainAxisAlignment::SpaceBetween)
5313            .children(children)
5314            .into_widget();
5315        if let Some(semantics_label) = self.semantics_label.clone() {
5316            menu_item_label = Semantics::new()
5317                .label(semantics_label)
5318                .exclude_semantics(true)
5319                .child(menu_item_label)
5320                .into_widget();
5321        }
5322        menu_item_label
5323    }
5324}
5325
5326// ---------------------------------------------------------------------------------------------
5327// _MenuLayout
5328
5329// Positions the menu in the view while trying to keep as much as possible
5330// visible in the view.
5331#[derive(Debug)]
5332struct MenuLayout {
5333    // Rectangle of underlying button, relative to the overlay's dimensions.
5334    anchor_rect: Rect,
5335
5336    // Whether to prefer going to the left or to the right.
5337    text_direction: TextDirection,
5338
5339    // The alignment to use when finding the ideal location for the menu.
5340    alignment: AlignmentGeometry,
5341
5342    // The offset from the alignment position to find the ideal location for the
5343    // menu.
5344    alignment_offset: Offset,
5345
5346    // The position passed to the open method, if any.
5347    menu_position: Option<Offset>,
5348
5349    // The padding on the inside of the menu, so it can be accounted for when
5350    // positioning.
5351    menu_padding: EdgeInsetsGeometry,
5352
5353    // The orientation of this menu.
5354    orientation: Axis,
5355
5356    // The orientation of this menu's parent.
5357    parent_orientation: Axis,
5358
5359    // How close to the edge of the safe area the menu will be placed.
5360    reserved_padding: EdgeInsetsGeometry,
5361
5362    // The factor by which the height of the menu is scaled.
5363    height_factor: f64,
5364
5365    // Used to ensure the menu is positioned within the safe area and respects
5366    // view insets such as the software keyboard.
5367    media_query_data: MediaQueryData,
5368}
5369
5370impl MenuLayout {
5371    fn position_child(&self, child_size: Size, overlay_rect: Rect) -> Offset {
5372        let anchor_rect = self.anchor_rect;
5373        let mut x;
5374        let mut y;
5375        match self.menu_position {
5376            None => {
5377                let mut desired_position = self
5378                    .alignment
5379                    .resolve(Some(self.text_direction))
5380                    .within_rect(anchor_rect);
5381                let directional_offset =
5382                    if matches!(self.alignment, AlignmentGeometry::Directional(_)) {
5383                        match self.text_direction {
5384                            TextDirection::Rtl => {
5385                                Offset::new(-self.alignment_offset.dx(), self.alignment_offset.dy())
5386                            }
5387                            TextDirection::Ltr => self.alignment_offset,
5388                        }
5389                    } else {
5390                        self.alignment_offset
5391                    };
5392                desired_position = desired_position + directional_offset;
5393                x = desired_position.dx();
5394                y = desired_position.dy();
5395                match self.text_direction {
5396                    TextDirection::Rtl => x -= child_size.width(),
5397                    TextDirection::Ltr => {}
5398                }
5399            }
5400            Some(menu_position) => {
5401                let adjusted_position = menu_position + anchor_rect.top_left();
5402                x = adjusted_position.dx();
5403                y = adjusted_position.dy();
5404            }
5405        }
5406
5407        // The whole overlay: the display-feature sub-screens are deferred.
5408        let allowed_rect = overlay_rect;
5409        let off_left_side = |x: f64| x < allowed_rect.left;
5410        let off_right_side = |x: f64| x + child_size.width() > allowed_rect.right;
5411        let off_top = |y: f64| y < allowed_rect.top;
5412        let off_bottom = |y: f64| y + child_size.height() > allowed_rect.bottom;
5413        // Avoid going outside an area defined as the rectangle offset from the
5414        // edge of the screen by the button padding. If the menu is off of the screen,
5415        // move the menu to the other side of the button first, and then if it
5416        // doesn't fit there, then just move it over as much as needed to make it
5417        // fit.
5418        if child_size.width() >= allowed_rect.width() {
5419            // It just doesn't fit, so put as much on the screen as possible.
5420            x = allowed_rect.left;
5421        } else if off_left_side(x) {
5422            // If the parent is a different orientation than the current one, then
5423            // just push it over instead of trying the other side.
5424            if self.parent_orientation != self.orientation {
5425                x = allowed_rect.left;
5426            } else {
5427                let new_x = anchor_rect.right + self.alignment_offset.dx();
5428                if !off_right_side(new_x) {
5429                    x = new_x;
5430                } else {
5431                    x = allowed_rect.left;
5432                }
5433            }
5434        } else if off_right_side(x) {
5435            if self.parent_orientation != self.orientation {
5436                x = allowed_rect.right - child_size.width();
5437            } else {
5438                let new_x = anchor_rect.left - child_size.width() - self.alignment_offset.dx();
5439                if !off_left_side(new_x) {
5440                    x = new_x;
5441                } else {
5442                    x = allowed_rect.right - child_size.width();
5443                }
5444            }
5445        }
5446        if child_size.height() >= allowed_rect.height() {
5447            // Too tall to fit, fit as much on as possible.
5448            y = allowed_rect.top;
5449        } else if off_top(y) {
5450            let new_y = anchor_rect.bottom;
5451            if !off_bottom(new_y) {
5452                y = new_y;
5453            } else {
5454                y = allowed_rect.top;
5455            }
5456        } else if off_bottom(y) {
5457            let new_y = anchor_rect.top - child_size.height();
5458            if !off_top(new_y) {
5459                // Only move the menu up if its parent is horizontal (MenuAnchor/MenuBar).
5460                if self.parent_orientation == Axis::Horizontal {
5461                    y = new_y - self.alignment_offset.dy();
5462                } else {
5463                    y = new_y;
5464                }
5465            } else {
5466                y = allowed_rect.bottom - child_size.height();
5467            }
5468        }
5469        Offset::new(x, y)
5470    }
5471}
5472
5473impl SingleChildLayoutDelegate for MenuLayout {
5474    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
5475        // The menu can be at most the size of the overlay minus the view padding
5476        // in each direction.
5477        BoxConstraints::loose(constraints.biggest()).deflate(self.reserved_padding)
5478    }
5479
5480    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
5481        // size: The size of the overlay.
5482        // childSize: The size of the menu, when fully open, as determined by
5483        // getConstraintsForChild.
5484        let overlay_rect = self.media_query_data.padding.deflate_rect(
5485            self.media_query_data
5486                .view_insets
5487                .deflate_rect(Offset::ZERO & size),
5488        );
5489        let unconstrained_height = if self.height_factor > 0.01 {
5490            child_size.height() / self.height_factor
5491        } else {
5492            0.0
5493        };
5494        let child_height_estimate = unconstrained_height.min(size.height());
5495        let child_size_estimate = Size::new(child_size.width(), child_height_estimate);
5496        let final_position = self.position_child(child_size_estimate, overlay_rect);
5497
5498        if self.menu_position.is_some() {
5499            return final_position;
5500        }
5501
5502        // If the menu sits above the anchor when fully open, grow upward.
5503        // Keep the bottom (attachment) fixed by shifting the top-left during animation.
5504        let grows_up =
5505            final_position.dy() + child_size_estimate.height() <= self.anchor_rect.center().dy();
5506        if grows_up {
5507            let dy = child_height_estimate - child_size.height();
5508            return Offset::new(final_position.dx(), final_position.dy() + dy);
5509        }
5510
5511        let initial_position = Offset::new(final_position.dx(), self.anchor_rect.bottom);
5512        Offset::lerp(
5513            Some(initial_position),
5514            Some(final_position),
5515            self.height_factor,
5516        )
5517        .expect("both ends")
5518    }
5519
5520    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
5521        let Some(old_delegate) = old_delegate.as_any().downcast_ref::<MenuLayout>() else {
5522            return true;
5523        };
5524        self.anchor_rect != old_delegate.anchor_rect
5525            || self.text_direction != old_delegate.text_direction
5526            || self.alignment != old_delegate.alignment
5527            || self.alignment_offset != old_delegate.alignment_offset
5528            || self.menu_position != old_delegate.menu_position
5529            || self.menu_padding != old_delegate.menu_padding
5530            || self.orientation != old_delegate.orientation
5531            || self.parent_orientation != old_delegate.parent_orientation
5532            || self.reserved_padding != old_delegate.reserved_padding
5533            || self.height_factor != old_delegate.height_factor
5534    }
5535
5536    fn as_any(&self) -> &dyn Any {
5537        self
5538    }
5539}
5540
5541// ---------------------------------------------------------------------------------------------
5542// _MenuPanel
5543
5544/// The first value a menu style gives, in the order Dart's `effectiveValue` asks the
5545/// widget's, the theme's and the default style.
5546fn effective_value<T>(
5547    app: &mut App,
5548    styles: [Option<&dyn MenuStyleGetters>; 3],
5549    get_property: impl Fn(&dyn MenuStyleGetters, &mut App) -> Option<T>,
5550) -> Option<T> {
5551    styles
5552        .into_iter()
5553        .flatten()
5554        .find_map(|style| get_property(style, app))
5555}
5556
5557/// Dart's `resolve`: the first style property that resolves to a value with no state.
5558fn resolve<T: 'static>(
5559    app: &mut App,
5560    styles: [Option<&dyn MenuStyleGetters>; 3],
5561    get_property: impl Fn(&dyn MenuStyleGetters, &mut App) -> Option<WidgetStatePropertyRef<Option<T>>>,
5562) -> Option<T> {
5563    let states = WidgetStates::new();
5564    effective_value(app, styles, |style, app| {
5565        get_property(style, app).and_then(|property| property.resolve(&states))
5566    })
5567}
5568
5569/// A widget that manages a list of menu buttons in a menu.
5570///
5571/// It sizes itself to the widest/tallest item it contains, and then sizes all
5572/// the other entries to match.
5573pub(crate) struct MenuPanel {
5574    /// The menu style that has all the attributes for this menu panel.
5575    menu_style: Option<MenuStyle>,
5576
5577    /// The content will be clipped (or not) according to this option.
5578    ///
5579    /// Defaults to `Clip::None`.
5580    clip_behavior: Clip,
5581
5582    /// Determine if a `UnconstrainedBox` can be applied to the menu panel to allow it to
5583    /// render at its "natural" size.
5584    ///
5585    /// Defaults to true. When it is set to false, it can be useful when the menu should
5586    /// be constrained in both main-axis and cross-axis, such as a `DropdownMenu`.
5587    cross_axis_unconstrained: bool,
5588
5589    /// The layout orientation of this panel.
5590    pub(crate) orientation: Axis,
5591
5592    /// The animation that controls the height of the menu panel.
5593    height_animation: Option<AnimationRef<f64>>,
5594
5595    /// The list of widgets to use as children of this menu panel.
5596    ///
5597    /// These are the top level [`SubmenuButton`]s.
5598    children: Vec<WidgetRef>,
5599}
5600
5601impl Debug for MenuPanel {
5602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5603        f.debug_struct("_MenuPanel")
5604            .field("orientation", &self.orientation)
5605            .finish_non_exhaustive()
5606    }
5607}
5608
5609impl StatefulWidget for MenuPanel {
5610    type State = MenuPanelState;
5611
5612    fn create_state(&self) -> MenuPanelState {
5613        MenuPanelState {
5614            state: StateData::new(),
5615            scroll_controller: None,
5616        }
5617    }
5618}
5619
5620/// Dart's `_MenuPanelState`.
5621pub(crate) struct MenuPanelState {
5622    state: StateData<MenuPanel>,
5623    // Dart's field initializer; an arena object needs the `App`, so `init_state` makes it.
5624    scroll_controller: Option<Ref<ScrollController>>,
5625}
5626
5627impl MenuPanelState {
5628    fn intrinsic_cross_size(self: Handle<Self>, app: &App, child: WidgetRef) -> WidgetRef {
5629        match self.widget(app).orientation {
5630            Axis::Horizontal => IntrinsicHeight::new().child(child).into_widget(),
5631            Axis::Vertical => IntrinsicWidth::new().child(child).into_widget(),
5632        }
5633    }
5634}
5635
5636impl State for MenuPanelState {
5637    type Widget = MenuPanel;
5638    waft_widgets::state_accessors!();
5639
5640    fn init_state(self: Handle<Self>, app: &mut App) {
5641        let scroll_controller = ScrollController::default(app);
5642        app.get_mut(self).scroll_controller = Some(scroll_controller);
5643    }
5644
5645    fn dispose(self: Handle<Self>, app: &mut App) {
5646        if let Some(scroll_controller) = app.get_mut(self).scroll_controller.take() {
5647            scroll_controller.dispose(app);
5648        }
5649    }
5650
5651    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
5652        let (theme_style, default_style) = match self.widget(app).orientation {
5653            Axis::Horizontal => (
5654                MenuBarTheme::of(app, context).style.clone(),
5655                Box::new(MenuBarDefaultsM3::new(context)) as Box<dyn MenuStyleGetters>,
5656            ),
5657            Axis::Vertical => (
5658                MenuTheme::of(app, context).style,
5659                Box::new(MenuDefaultsM3::new(context)) as Box<dyn MenuStyleGetters>,
5660            ),
5661        };
5662        let widget_style = self.widget(app).menu_style.clone();
5663        let styles: [Option<&dyn MenuStyleGetters>; 3] = [
5664            widget_style
5665                .as_ref()
5666                .map(|style| style as &dyn MenuStyleGetters),
5667            theme_style
5668                .as_ref()
5669                .map(|style| style as &dyn MenuStyleGetters),
5670            Some(&*default_style),
5671        ];
5672
5673        let background_color = resolve(app, styles, |style, app| style.background_color(app));
5674        let shadow_color = resolve(app, styles, |style, app| style.shadow_color(app));
5675        let surface_tint_color = resolve(app, styles, |style, app| style.surface_tint_color(app));
5676        let elevation = resolve(app, styles, |style, app| style.elevation(app)).unwrap_or(0.0);
5677        let minimum_size = resolve(app, styles, |style, app| style.minimum_size(app));
5678        let fixed_size = resolve(app, styles, |style, app| style.fixed_size(app));
5679        let maximum_size = resolve(app, styles, |style, app| style.maximum_size(app));
5680        let side = resolve(app, styles, |style, app| style.side(app));
5681        let shape: ShapeBorderRef = resolve(app, styles, |style, app| style.shape(app))
5682            .expect("the default menu style has a shape")
5683            .copy_with(side)
5684            .into();
5685        let visual_density = effective_value(app, styles, |style, app| style.visual_density(app))
5686            .unwrap_or(VisualDensity::STANDARD);
5687        let padding = resolve(app, styles, |style, app| style.padding(app))
5688            .unwrap_or(EdgeInsetsGeometry::ZERO);
5689        let density_adjustment = visual_density.base_size_adjustment();
5690        // Scrollbar uses the `MediaQuery.padding` as its painter padding by
5691        // default. Menu overlays are already positioned within the safe area, so
5692        // applying that padding again shortens the scrollbar track and stops the
5693        // thumb from reaching the end of the menu. Remove the padding only for the
5694        // Scrollbar and restore the ambient MediaQuery for menu children.
5695        let ambient_media_query = MediaQuery::of(app, context);
5696        let scrollbar_media_query = ambient_media_query.remove_padding(true, true, true, true);
5697        // Per the Material Design team: don't allow the VisualDensity
5698        // adjustment to reduce the width of the left/right padding. If we
5699        // did, VisualDensity.compact, the default for desktop/web, would
5700        // reduce the horizontal padding to zero. Vertical padding
5701        // is not affected at all.
5702        let dx = density_adjustment.dx().max(0.0);
5703        let resolved_padding = padding
5704            .add(EdgeInsetsGeometry::symmetric(0.0, dx))
5705            .clamp(&EdgeInsetsGeometry::ZERO, &EdgeInsetsGeometry::INFINITY);
5706
5707        let mut effective_constraints = visual_density.effective_constraints(
5708            BoxConstraints::new()
5709                .min_width(minimum_size.map_or(0.0, |size| size.width()))
5710                .min_height(minimum_size.map_or(0.0, |size| size.height()))
5711                .max_width(maximum_size.map_or(f64::INFINITY, |size| size.width()))
5712                .max_height(maximum_size.map_or(f64::INFINITY, |size| size.height())),
5713        );
5714        if let Some(fixed_size) = fixed_size {
5715            let size = effective_constraints.constrain(fixed_size);
5716            if size.width().is_finite() {
5717                effective_constraints = effective_constraints
5718                    .min_width(size.width())
5719                    .max_width(size.width());
5720            }
5721            if size.height().is_finite() {
5722                effective_constraints = effective_constraints
5723                    .min_height(size.height())
5724                    .max_height(size.height());
5725            }
5726        }
5727
5728        // If the menu panel is horizontal, then the children should be wrapped in
5729        // an IntrinsicWidth widget to ensure that the children are as wide as the
5730        // widest child.
5731        let widget = self.widget(app);
5732        let mut children = widget.children.clone();
5733        if widget.orientation == Axis::Horizontal {
5734            children = children
5735                .into_iter()
5736                .map(|child| IntrinsicWidth::new().child(child).into_widget())
5737                .collect();
5738        }
5739
5740        let display_scrollbar = match AnyMenuAnchorState::maybe_animation_status_of(app, context) {
5741            Some(AnimationStatus::Completed) => true,
5742            Some(AnimationStatus::Forward)
5743            | Some(AnimationStatus::Reverse)
5744            | Some(AnimationStatus::Dismissed)
5745            | None => false,
5746        };
5747
5748        let widget = self.widget(app);
5749        let orientation = widget.orientation;
5750        let scroll_controller = app
5751            .get(self)
5752            .scroll_controller
5753            .as_ref()
5754            .expect("created in init_state")
5755            .erase::<AnyScrollController>();
5756        let behavior = ScrollConfiguration::of(app, context)
5757            .copy_with()
5758            .scrollbars(false)
5759            .overscroll(false)
5760            .physics(Rc::new(ClampingScrollPhysics::new()) as ScrollPhysicsRef);
5761        let text_direction = Directionality::of(app, context);
5762        let mut menu_panel = Padding::new(resolved_padding)
5763            .child(ScrollConfiguration::new(
5764                waft_widgets::ScrollBehaviorRef::new(behavior),
5765                PrimaryScrollController::new(
5766                    scroll_controller.clone(),
5767                    MediaQuery::new(
5768                        scrollbar_media_query,
5769                        Scrollbar::new(
5770                            MediaQuery::new(
5771                                ambient_media_query,
5772                                SingleChildScrollView::new()
5773                                    .controller(scroll_controller)
5774                                    .scroll_direction(orientation)
5775                                    .child(
5776                                        Flex::new(orientation)
5777                                            .cross_axis_alignment(CrossAxisAlignment::Start)
5778                                            .text_direction(text_direction)
5779                                            .main_axis_size(MainAxisSize::Min)
5780                                            .children(children),
5781                                    ),
5782                            )
5783                            .into_widget(),
5784                        )
5785                        .thumb_visibility(display_scrollbar),
5786                    )
5787                    .into_widget(),
5788                ),
5789            ))
5790            .into_widget();
5791
5792        if let Some(height_animation) = self.widget(app).height_animation.clone() {
5793            // An AnimatedBuilder is used instead of SizeTransition because Material
5794            // already introduces its own ClipRRect for the shape.
5795            menu_panel = AnimatedBuilder::new(
5796                Rc::new(height_animation.clone()),
5797                move |app, _context, child| {
5798                    waft_widgets::Align::new()
5799                        .alignment(AlignmentGeometry::TOP_START)
5800                        .height_factor(height_animation.value(app))
5801                        .width_factor(1.0)
5802                        .child(child.cloned().expect("given a child"))
5803                        .into_widget()
5804                },
5805            )
5806            .child(menu_panel)
5807            .into_widget();
5808        }
5809
5810        let mut material = Material::new()
5811            .elevation(elevation)
5812            .shape(shape)
5813            .r#type(if background_color.is_none() {
5814                MaterialType::Transparency
5815            } else {
5816                MaterialType::Canvas
5817            })
5818            .clip_behavior(self.widget(app).clip_behavior)
5819            .child(menu_panel);
5820        if let Some(background_color) = background_color {
5821            material = material.color(background_color);
5822        }
5823        if let Some(shadow_color) = shadow_color {
5824            material = material.shadow_color(shadow_color);
5825        }
5826        if let Some(surface_tint_color) = surface_tint_color {
5827            material = material.surface_tint_color(surface_tint_color);
5828        }
5829        menu_panel = self.intrinsic_cross_size(app, material.into_widget());
5830
5831        let widget = self.widget(app);
5832        if widget.cross_axis_unconstrained {
5833            menu_panel = UnconstrainedBox::new()
5834                .constrained_axis(widget.orientation)
5835                .clip_behavior(Clip::HardEdge)
5836                .alignment(AlignmentGeometry::CENTER_START)
5837                .child(menu_panel)
5838                .into_widget();
5839        }
5840
5841        ConstrainedBox::new(effective_constraints)
5842            .child(menu_panel)
5843            .into_widget()
5844    }
5845}
5846
5847impl Debug for MenuPanelState {
5848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5849        f.write_str("_MenuPanelState")
5850    }
5851}
5852
5853// ---------------------------------------------------------------------------------------------
5854// _Submenu
5855
5856// A widget that defines the menu drawn in the overlay.
5857struct Submenu {
5858    menu_scope_node: Ref<FocusScopeNode>,
5859    menu_position: RawMenuOverlayInfo,
5860    anchor: AnyMenuAnchorState,
5861    layer_link: Option<Ref<LayerLink>>,
5862    menu_style: Option<MenuStyle>,
5863    // Dart's field, which `build` does not read: it reads the anchor's `consume_outside_tap`.
5864    #[allow(dead_code)]
5865    consume_outside_taps: bool,
5866    alignment_offset: Offset,
5867    clip_behavior: Clip,
5868    cross_axis_unconstrained: bool,
5869    menu_children: Vec<WidgetRef>,
5870    fade_animation: AnimationRef<f64>,
5871    height_animation: AnimationRef<f64>,
5872    reserved_padding: EdgeInsetsGeometry,
5873}
5874
5875impl Debug for Submenu {
5876    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5877        f.debug_struct("_Submenu")
5878            .field("anchor", &self.anchor)
5879            .finish_non_exhaustive()
5880    }
5881}
5882
5883impl StatelessWidget for Submenu {
5884    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
5885        let anchor = self.anchor;
5886        // Use the text direction of the context where the button is.
5887        let text_direction = Directionality::of(app, context);
5888        let (theme_style, default_style) =
5889            match anchor.parent(app).map(AnyMenuAnchorState::orientation) {
5890                Some(Axis::Horizontal) | None => (
5891                    MenuBarTheme::of(app, context).style.clone(),
5892                    Box::new(MenuBarDefaultsM3::new(context)) as Box<dyn MenuStyleGetters>,
5893                ),
5894                Some(Axis::Vertical) => (
5895                    MenuTheme::of(app, context).style,
5896                    Box::new(MenuDefaultsM3::new(context)) as Box<dyn MenuStyleGetters>,
5897                ),
5898            };
5899        let styles: [Option<&dyn MenuStyleGetters>; 3] = [
5900            self.menu_style
5901                .as_ref()
5902                .map(|style| style as &dyn MenuStyleGetters),
5903            theme_style
5904                .as_ref()
5905                .map(|style| style as &dyn MenuStyleGetters),
5906            Some(&*default_style),
5907        ];
5908
5909        // The mouse cursor resolves without the `App`, so it reads each style's property now.
5910        let cursor_properties = [
5911            self.menu_style
5912                .as_ref()
5913                .and_then(|style| style.mouse_cursor.clone()),
5914            theme_style
5915                .as_ref()
5916                .and_then(|style| style.mouse_cursor.clone()),
5917            default_style.mouse_cursor(app),
5918        ];
5919        let mouse_cursor = WidgetStateMouseCursor::resolve_with(
5920            move |states| {
5921                cursor_properties
5922                    .iter()
5923                    .flatten()
5924                    .find_map(|mouse_cursor| mouse_cursor.resolve(states))
5925                    .unwrap_or_else(<dyn MouseCursor>::uncontrolled)
5926            },
5927            Some("Menu_MouseCursor"),
5928        );
5929
5930        let visual_density = effective_value(app, styles, |style, app| style.visual_density(app))
5931            .unwrap_or_else(|| Theme::of(app, context).visual_density);
5932        let alignment = effective_value(app, styles, |style, app| style.alignment(app))
5933            .expect("the default menu style has an alignment");
5934        let padding = resolve(app, styles, |style, app| style.padding(app))
5935            .unwrap_or(EdgeInsetsGeometry::ZERO);
5936        let density_adjustment = visual_density.base_size_adjustment();
5937        // Per the Material Design team: don't allow the VisualDensity
5938        // adjustment to reduce the width of the left/right padding. If we
5939        // did, VisualDensity.compact, the default for desktop/web, would
5940        // reduce the horizontal padding to zero.
5941        let dx = density_adjustment.dx().max(0.0);
5942        let resolved_padding = padding
5943            .add(EdgeInsetsGeometry::from_ltrb(dx, 0.0, dx, 0.0))
5944            .clamp(&EdgeInsetsGeometry::ZERO, &EdgeInsetsGeometry::INFINITY);
5945
5946        let anchor_rect = if self.layer_link.is_none() {
5947            Rect::from_ltrb(
5948                self.menu_position.anchor_rect.left + dx,
5949                self.menu_position.anchor_rect.top,
5950                self.menu_position.anchor_rect.right,
5951                self.menu_position.anchor_rect.bottom,
5952            )
5953        } else {
5954            Rect::ZERO
5955        };
5956
5957        let dismiss_menu_action = DismissMenuAction::new(app, anchor.menu_controller(app));
5958        let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
5959        actions.insert(
5960            <DismissMenuAction as Action>::intent_type(),
5961            dismiss_menu_action.into_erased(),
5962        );
5963
5964        let consume_outside_taps = anchor.root(app).menu_controller(app).is_open(app)
5965            && anchor.widget(app).consume_outside_tap;
5966        let menu_panel = TapRegion::new(
5967            MouseRegion::new()
5968                .cursor(mouse_cursor.into())
5969                .hit_test_behavior(HitTestBehavior::DeferToChild)
5970                .child(Actions::new(
5971                    actions,
5972                    Shortcuts::new(
5973                        menu_traversal_shortcuts(),
5974                        FocusScope::new(FadeTransition::new(self.fade_animation.clone()).child(
5975                            MenuPanel {
5976                                menu_style: self.menu_style.clone(),
5977                                clip_behavior: self.clip_behavior,
5978                                orientation: anchor.orientation(),
5979                                cross_axis_unconstrained: self.cross_axis_unconstrained,
5980                                height_animation: Some(self.height_animation.clone()),
5981                                children: self.menu_children.clone(),
5982                            },
5983                        ))
5984                        .node(self.menu_scope_node.clone())
5985                        .skip_traversal(true),
5986                    ),
5987                )),
5988        )
5989        .group_id(self.menu_position.tap_region_group_id)
5990        .consume_outside_taps(consume_outside_taps)
5991        .on_tap_outside(Rc::new(move |app: &mut App, _event: PointerDownEvent| {
5992            anchor.menu_controller(app).close(app);
5993        }))
5994        .into_widget();
5995
5996        let menu_padding = resolved_padding;
5997        let alignment_offset = self.alignment_offset;
5998        let menu_position = self.menu_position.position;
5999        let orientation = anchor.orientation();
6000        let parent_orientation = anchor
6001            .parent(app)
6002            .map_or(Axis::Horizontal, AnyMenuAnchorState::orientation);
6003        let reserved_padding = self.reserved_padding;
6004        let height_animation = self.height_animation.clone();
6005        let theme = Theme::of(app, context)
6006            .copy_with()
6007            .visual_density(visual_density)
6008            .build();
6009        let layout = Theme::new(
6010            theme,
6011            ConstrainedBox::new(BoxConstraints::loose(self.menu_position.overlay_size)).child(
6012                AnimatedBuilder::new(
6013                    Rc::new(height_animation.clone()),
6014                    move |app, context, _child| {
6015                        let media_query = MediaQuery::of(app, context);
6016                        CustomSingleChildLayout::new(Rc::new(MenuLayout {
6017                            anchor_rect,
6018                            text_direction,
6019                            menu_padding,
6020                            alignment,
6021                            alignment_offset,
6022                            menu_position,
6023                            orientation,
6024                            parent_orientation,
6025                            reserved_padding,
6026                            height_factor: height_animation.value(app),
6027                            media_query_data: media_query,
6028                        }))
6029                        .child(menu_panel.clone())
6030                        .into_widget()
6031                    },
6032                ),
6033            ),
6034        )
6035        .into_widget();
6036
6037        match self.layer_link.clone() {
6038            None => layout,
6039            Some(layer_link) => CompositedTransformFollower::new(layer_link)
6040                .target_anchor(Alignment::BOTTOM_LEFT)
6041                .child(layout)
6042                .into_widget(),
6043        }
6044    }
6045}
6046
6047/// Whether the target platform is an Apple platform (Mac or iOS).
6048fn is_cupertino(app: &App) -> bool {
6049    match app.platform().target_platform() {
6050        TargetPlatform::IOS | TargetPlatform::MacOS => true,
6051        TargetPlatform::Android
6052        | TargetPlatform::Fuchsia
6053        | TargetPlatform::Linux
6054        | TargetPlatform::Windows => false,
6055    }
6056}
6057
6058/// Whether the target platform is one that uses symbolic shortcuts.
6059///
6060/// Mac and iOS use special symbols for modifier keys instead of their names,
6061/// render them in a particular order defined by Apple's human interface
6062/// guidelines, and format them so that the modifier keys always align.
6063fn uses_symbolic_modifiers(app: &App) -> bool {
6064    is_cupertino(app)
6065}
6066
6067fn platform_supports_accelerators(app: &App) -> bool {
6068    // On iOS and macOS, pressing the Option key (a.k.a. the Alt key) causes a
6069    // different set of characters to be generated, and the native menus don't
6070    // support accelerators anyhow, so we just disable accelerators on these
6071    // platforms.
6072    !is_cupertino(app)
6073}
6074
6075#[cfg(test)]
6076mod tests {
6077    //! Ported from `test/menu_anchor_test.dart`; the goldens and the semantics-tree cases are
6078    //! not ported.
6079
6080    use std::cell::RefCell;
6081
6082    use waft_services::PhysicalKeyboardKey;
6083    use waft_widgets::{AnyElement, Column, Container, Icon, primary_focus};
6084
6085    use waft_rendering::testing::{PaintCall, assert_paints, paints};
6086    use waft_widgets::testing::{
6087        TargetPlatformVariant, TestPointer, WidgetTester, assert_more_or_less_equals_within,
6088        expect, find, finds_nothing, finds_one_widget, test_widgets, test_widgets_variant,
6089    };
6090
6091    use super::*;
6092    use crate::test_support::{PaintInspection, material_app};
6093
6094    /// What the first ink features render object and its subtree paint: Dart's `paints` on
6095    /// `getOverlayColor(tester)`.
6096    fn overlay_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
6097        let render = waft_rendering::RenderBox::as_object(
6098            tester.first::<crate::material::RenderInkFeatures>(),
6099        );
6100        tester.painted_ops_deep(render)
6101    }
6102    use crate::theme_data::ThemeData;
6103    use crate::tooltip::tests::m3;
6104
6105    // ---- Dart's `TestMenu` and `createTestMenus` ----
6106
6107    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6108    enum TestMenu {
6109        MainMenu0,
6110        MainMenu1,
6111        MainMenu2,
6112        MainMenu3,
6113        MainMenu4,
6114        MainMenu5,
6115        SubMenu00,
6116        SubMenu01,
6117        SubMenu02,
6118        SubMenu10,
6119        SubMenu11,
6120        SubMenu12,
6121        SubMenu20,
6122        SubMenu30,
6123        SubMenu40,
6124        SubMenu41,
6125        SubMenu42,
6126        SubSubMenu110,
6127        SubSubMenu111,
6128        SubSubMenu112,
6129        SubSubMenu113,
6130        AnchorButton,
6131        OutsideButton,
6132    }
6133
6134    impl TestMenu {
6135        fn accelerator_label(self) -> &'static str {
6136            match self {
6137                TestMenu::MainMenu0 => "&Menu 0",
6138                TestMenu::MainMenu1 => "M&enu &1",
6139                TestMenu::MainMenu2 => "Me&nu 2",
6140                TestMenu::MainMenu3 => "Men&u 3",
6141                TestMenu::MainMenu4 => "Menu &4",
6142                TestMenu::MainMenu5 => "Menu &5 && &6 &",
6143                TestMenu::SubMenu00 => "Sub &Menu 0&0",
6144                TestMenu::SubMenu01 => "Sub Menu 0&1",
6145                TestMenu::SubMenu02 => "Sub Menu 0&2",
6146                TestMenu::SubMenu10 => "Sub Menu 1&0",
6147                TestMenu::SubMenu11 => "Sub Menu 1&1",
6148                TestMenu::SubMenu12 => "Sub Menu 1&2",
6149                TestMenu::SubMenu20 => "Sub Menu 2&0",
6150                TestMenu::SubMenu30 => "Sub Menu 3&0",
6151                TestMenu::SubMenu40 => "Sub Menu 4&0",
6152                TestMenu::SubMenu41 => "Sub Menu 4&1",
6153                TestMenu::SubMenu42 => "Sub Menu 4&2",
6154                TestMenu::SubSubMenu110 => "Sub Sub Menu 11&0",
6155                TestMenu::SubSubMenu111 => "Sub Sub Menu 11&1",
6156                TestMenu::SubSubMenu112 => "Sub Sub Menu 11&2",
6157                TestMenu::SubSubMenu113 => "Sub Sub Menu 11&3",
6158                TestMenu::AnchorButton => "Press Me",
6159                TestMenu::OutsideButton => "Outside",
6160            }
6161        }
6162
6163        /// Dart's `label`: the accelerator markers stripped.
6164        fn label(self) -> String {
6165            MenuAcceleratorLabel::strip_accelerator_markers(self.accelerator_label(), None)
6166        }
6167    }
6168
6169    /// The lists Dart's `onPressed`, `onOpen` and `onClose` test callbacks add to.
6170    #[derive(Clone, Default)]
6171    struct Log {
6172        selected: Rc<RefCell<Vec<TestMenu>>>,
6173        opened: Rc<RefCell<Vec<TestMenu>>>,
6174        closed: Rc<RefCell<Vec<TestMenu>>>,
6175    }
6176
6177    impl Log {
6178        fn selected(&self) -> Vec<TestMenu> {
6179            self.selected.borrow().clone()
6180        }
6181
6182        fn opened(&self) -> Vec<TestMenu> {
6183            self.opened.borrow().clone()
6184        }
6185
6186        fn closed(&self) -> Vec<TestMenu> {
6187            self.closed.borrow().clone()
6188        }
6189
6190        fn clear(&self) {
6191            self.selected.borrow_mut().clear();
6192            self.opened.borrow_mut().clear();
6193            self.closed.borrow_mut().clear();
6194        }
6195    }
6196
6197    /// Dart's `createTestMenus` arguments.
6198    #[derive(Clone, Default)]
6199    struct TestMenus {
6200        on_pressed: Option<Rc<RefCell<Vec<TestMenu>>>>,
6201        on_open: Option<Rc<RefCell<Vec<TestMenu>>>>,
6202        on_close: Option<Rc<RefCell<Vec<TestMenu>>>>,
6203        shortcuts: Vec<(TestMenu, MenuSerializableShortcutRef)>,
6204        include_extra_groups: bool,
6205        accelerators: bool,
6206    }
6207
6208    impl TestMenus {
6209        /// `createTestMenus(onPressed: onPressed)`.
6210        fn pressed(log: &Log) -> TestMenus {
6211            TestMenus {
6212                on_pressed: Some(Rc::clone(&log.selected)),
6213                ..TestMenus::default()
6214            }
6215        }
6216
6217        /// `createTestMenus(onPressed: onPressed, onOpen: onOpen, onClose: onClose)`.
6218        fn all(log: &Log) -> TestMenus {
6219            TestMenus {
6220                on_pressed: Some(Rc::clone(&log.selected)),
6221                on_open: Some(Rc::clone(&log.opened)),
6222                on_close: Some(Rc::clone(&log.closed)),
6223                ..TestMenus::default()
6224            }
6225        }
6226
6227        fn label(&self, menu: TestMenu) -> WidgetRef {
6228            if self.accelerators {
6229                MenuAcceleratorLabel::new(menu.accelerator_label()).into_widget()
6230            } else {
6231                Text::new(menu.label()).into_widget()
6232            }
6233        }
6234
6235        fn submenu_button(&self, menu: TestMenu, menu_children: Vec<WidgetRef>) -> WidgetRef {
6236            let mut button = SubmenuButton::new(menu_children, Some(self.label(menu)));
6237            if let Some(opened) = self.on_open.clone() {
6238                button = button.on_open(Rc::new(move |_app: &mut App| {
6239                    opened.borrow_mut().push(menu)
6240                }));
6241            }
6242            if let Some(closed) = self.on_close.clone() {
6243                button = button.on_close(Rc::new(move |_app: &mut App| {
6244                    closed.borrow_mut().push(menu)
6245                }));
6246            }
6247            button.into_widget()
6248        }
6249
6250        fn menu_item_button(
6251            &self,
6252            menu: TestMenu,
6253            enabled: bool,
6254            leading_icon: Option<WidgetRef>,
6255            key: Option<KeyRef>,
6256        ) -> WidgetRef {
6257            let mut button = MenuItemButton::new().child(self.label(menu));
6258            button.key = key;
6259            if enabled && let Some(selected) = self.on_pressed.clone() {
6260                button =
6261                    button.on_pressed(Listener::new(move |_app| selected.borrow_mut().push(menu)));
6262            }
6263            button.shortcut = self
6264                .shortcuts
6265                .iter()
6266                .find(|(shortcut_menu, _)| *shortcut_menu == menu)
6267                .map(|(_, shortcut)| Rc::clone(shortcut));
6268            button.leading_icon = leading_icon;
6269            button.into_widget()
6270        }
6271
6272        /// Dart's `createTestMenus`.
6273        fn build(&self) -> Vec<WidgetRef> {
6274            let item = |menu| self.menu_item_button(menu, true, None, None);
6275            let disabled = |menu| self.menu_item_button(menu, false, None, None);
6276            let mut result = vec![
6277                self.submenu_button(
6278                    TestMenu::MainMenu0,
6279                    vec![
6280                        self.menu_item_button(
6281                            TestMenu::SubMenu00,
6282                            true,
6283                            Some(Icon::new(Some(Icons::add())).into_widget()),
6284                            None,
6285                        ),
6286                        item(TestMenu::SubMenu01),
6287                        item(TestMenu::SubMenu02),
6288                    ],
6289                ),
6290                self.submenu_button(
6291                    TestMenu::MainMenu1,
6292                    vec![
6293                        item(TestMenu::SubMenu10),
6294                        self.submenu_button(
6295                            TestMenu::SubMenu11,
6296                            vec![
6297                                self.menu_item_button(
6298                                    TestMenu::SubSubMenu110,
6299                                    true,
6300                                    None,
6301                                    Some(waft_foundation::UniqueKey::new().into()),
6302                                ),
6303                                item(TestMenu::SubSubMenu111),
6304                                item(TestMenu::SubSubMenu112),
6305                                item(TestMenu::SubSubMenu113),
6306                            ],
6307                        ),
6308                        item(TestMenu::SubMenu12),
6309                    ],
6310                ),
6311                self.submenu_button(
6312                    TestMenu::MainMenu2,
6313                    vec![self.menu_item_button(
6314                        TestMenu::SubMenu20,
6315                        false,
6316                        Some(Icon::new(Some(Icons::ac_unit())).into_widget()),
6317                        None,
6318                    )],
6319                ),
6320            ];
6321            if self.include_extra_groups {
6322                result.push(
6323                    self.submenu_button(TestMenu::MainMenu3, vec![disabled(TestMenu::SubMenu30)]),
6324                );
6325                result.push(self.submenu_button(
6326                    TestMenu::MainMenu4,
6327                    vec![
6328                        disabled(TestMenu::SubMenu40),
6329                        disabled(TestMenu::SubMenu41),
6330                        disabled(TestMenu::SubMenu42),
6331                    ],
6332                ));
6333            }
6334            result.push(self.submenu_button(TestMenu::MainMenu5, Vec::new()));
6335            result
6336        }
6337    }
6338
6339    // ---- finders and gestures ----
6340
6341    fn only(found: Vec<AnyElement>) -> AnyElement {
6342        assert_eq!(found.len(), 1, "one widget found");
6343        found[0]
6344    }
6345
6346    /// Dart's `find.text(text)` with `findsOneWidget` (true) or `findsNothing` (false).
6347    ///
6348    /// The kit's onstage finders do not see an `OverlayPortal`'s child, where a menu is, so
6349    /// these finders count every mounted `Text`; no case here builds offstage text.
6350    fn shows(tester: &WidgetTester, text: &str) -> bool {
6351        match find::text(text).evaluate(tester).len() {
6352            0 => false,
6353            1 => true,
6354            count => panic!("{count} widgets show {text:?}"),
6355        }
6356    }
6357
6358    /// Dart's `tester.getRect(find.byType(W))` of the only one.
6359    fn rect_of<W: 'static>(tester: &WidgetTester) -> Rect {
6360        tester.get_rect(tester.render_box_of(tester.element(find::by_type::<W>())))
6361    }
6362
6363    fn rect_of_element(tester: &WidgetTester, element: AnyElement) -> Rect {
6364        tester.get_rect(tester.render_box_of(element))
6365    }
6366
6367    /// Dart's `find.ancestor(of: find.text(text), matching: find.byType(W))`, nearest first.
6368    fn ancestors_of_type<W: 'static>(tester: &WidgetTester, text: &str) -> Vec<AnyElement> {
6369        let ancestors = tester.ancestors(tester.element(find::text(text)));
6370        let app = tester.cell.borrow();
6371        ancestors
6372            .into_iter()
6373            .filter(|ancestor| {
6374                waft_widgets::downcast_widget::<W>(&**ancestor.widget(&app)).is_some()
6375            })
6376            .collect()
6377    }
6378
6379    /// Dart's `findMenuPanels()`.
6380    fn menu_panels(tester: &WidgetTester) -> Vec<AnyElement> {
6381        find::by_type::<MenuPanel>().evaluate(tester)
6382    }
6383
6384    /// Dart's `hoverOver`: a new mouse, as Dart's `createGesture` makes one, moved over `at`,
6385    /// then a frame.
6386    fn hover_over(tester: &mut WidgetTester, at: Offset) -> TestPointer {
6387        use std::sync::atomic::{AtomicI64, Ordering};
6388        static NEXT_DEVICE: AtomicI64 = AtomicI64::new(1);
6389        let mut mouse = TestPointer::mouse(NEXT_DEVICE.fetch_add(1, Ordering::Relaxed), 0);
6390        tester.add_pointer(&mut mouse, Offset::ZERO);
6391        tester.move_to(&mut mouse, at, false);
6392        tester.pump();
6393        mouse
6394    }
6395
6396    /// Dart's `tester.sendKeyEvent(key)`.
6397    fn send_key(tester: &mut WidgetTester, logical: LogicalKeyboardKey) {
6398        tester.send_key_event(physical_of(logical), logical);
6399    }
6400
6401    /// The physical key flutter_test's key simulator sends with `logical`.
6402    fn physical_of(logical: LogicalKeyboardKey) -> PhysicalKeyboardKey {
6403        match logical {
6404            LogicalKeyboardKey::ARROW_DOWN => PhysicalKeyboardKey::ARROW_DOWN,
6405            LogicalKeyboardKey::ARROW_UP => PhysicalKeyboardKey::ARROW_UP,
6406            LogicalKeyboardKey::ARROW_LEFT => PhysicalKeyboardKey::ARROW_LEFT,
6407            LogicalKeyboardKey::ARROW_RIGHT => PhysicalKeyboardKey::ARROW_RIGHT,
6408            LogicalKeyboardKey::TAB => PhysicalKeyboardKey::TAB,
6409            LogicalKeyboardKey::ESCAPE => PhysicalKeyboardKey::ESCAPE,
6410            LogicalKeyboardKey::ENTER => PhysicalKeyboardKey::ENTER,
6411            LogicalKeyboardKey::SPACE => PhysicalKeyboardKey::SPACE,
6412            LogicalKeyboardKey::SHIFT_LEFT => PhysicalKeyboardKey::SHIFT_LEFT,
6413            LogicalKeyboardKey::ALT_LEFT => PhysicalKeyboardKey::ALT_LEFT,
6414            LogicalKeyboardKey::KEY_M => PhysicalKeyboardKey::KEY_M,
6415            LogicalKeyboardKey::KEY_E => PhysicalKeyboardKey::KEY_E,
6416            LogicalKeyboardKey::KEY_N => PhysicalKeyboardKey::KEY_N,
6417            LogicalKeyboardKey::KEY_U => PhysicalKeyboardKey::KEY_U,
6418            LogicalKeyboardKey::DIGIT1 => PhysicalKeyboardKey::DIGIT1,
6419            LogicalKeyboardKey::DIGIT0 => PhysicalKeyboardKey::DIGIT0,
6420            _ => panic!("no physical key for {logical:?} in this kit"),
6421        }
6422    }
6423
6424    /// Dart's `focusedMenu`: the debug label of the primary focus.
6425    fn focused_menu(tester: &WidgetTester) -> Option<String> {
6426        let mut app = tester.cell.borrow_mut();
6427        primary_focus(&mut app).and_then(|node| node.debug_label(&app))
6428    }
6429
6430    /// Dart's `tester.pumpWidget(MaterialApp(theme: theme(app), home: Material(child: child)))`.
6431    fn pump_material(
6432        tester: &mut WidgetTester,
6433        theme: impl FnOnce(&App) -> ThemeData,
6434        child: impl FnOnce(&mut App) -> WidgetRef,
6435    ) {
6436        let root = {
6437            let mut app = tester.cell.borrow_mut();
6438            let theme = theme(&app);
6439            let child = child(&mut app);
6440            material_app(theme, Material::new().child(child).into_widget())
6441        };
6442        tester.pump_widget(root);
6443    }
6444
6445    fn pump(tester: &mut WidgetTester) {
6446        tester.pump();
6447    }
6448
6449    /// The debug label a button gives its own focus node: Dart's `'$Type(${widget.child})'`
6450    /// of a `Text(text)` child, as `focusedMenu` reads it.
6451    fn button_label(type_name: &str, text: &str) -> String {
6452        describe_child(type_name, &Some(Text::new(text).into_widget()))
6453    }
6454
6455    /// Dart's `const Placeholder()` where a case only needs it to fill its slot.
6456    fn placeholder() -> WidgetRef {
6457        ConstrainedBox::new(BoxConstraints::expand(None, None)).into_widget()
6458    }
6459
6460    // ---- cases ----
6461
6462    #[test]
6463    fn a_menu_bar_opens_its_submenus_level_by_level() {
6464        test_widgets(|tester| {
6465            let log = Log::default();
6466            let controller = MenuController::new(&mut tester.cell.borrow_mut())
6467                .into_erased::<AnyMenuController>();
6468            let menus = TestMenus::all(&log);
6469            pump_material(tester, m3, |_app| {
6470                MenuBar::new(menus.build())
6471                    .controller(controller.clone())
6472                    .into_widget()
6473            });
6474
6475            assert!(shows(tester, &TestMenu::MainMenu0.label()));
6476            assert!(shows(tester, &TestMenu::MainMenu1.label()));
6477            assert!(shows(tester, &TestMenu::MainMenu2.label()));
6478            assert!(!shows(tester, &TestMenu::SubMenu10.label()));
6479            assert!(!shows(tester, &TestMenu::SubSubMenu110.label()));
6480            assert!(log.opened().is_empty());
6481
6482            tester.tap(find::text(&TestMenu::MainMenu1.label()));
6483            pump(tester);
6484
6485            assert!(shows(tester, &TestMenu::MainMenu0.label()));
6486            assert!(shows(tester, &TestMenu::MainMenu1.label()));
6487            assert!(shows(tester, &TestMenu::MainMenu2.label()));
6488            assert!(shows(tester, &TestMenu::SubMenu10.label()));
6489            assert!(shows(tester, &TestMenu::SubMenu11.label()));
6490            assert!(shows(tester, &TestMenu::SubMenu12.label()));
6491            assert!(!shows(tester, &TestMenu::SubSubMenu110.label()));
6492            assert!(!shows(tester, &TestMenu::SubSubMenu111.label()));
6493            assert!(!shows(tester, &TestMenu::SubSubMenu112.label()));
6494            assert_eq!(log.opened().last(), Some(&TestMenu::MainMenu1));
6495            log.clear();
6496
6497            tester.tap(find::text(&TestMenu::SubMenu11.label()));
6498            pump(tester);
6499
6500            assert!(shows(tester, &TestMenu::MainMenu0.label()));
6501            assert!(shows(tester, &TestMenu::MainMenu1.label()));
6502            assert!(shows(tester, &TestMenu::MainMenu2.label()));
6503            assert!(shows(tester, &TestMenu::SubMenu10.label()));
6504            assert!(shows(tester, &TestMenu::SubMenu11.label()));
6505            assert!(shows(tester, &TestMenu::SubMenu12.label()));
6506            assert!(shows(tester, &TestMenu::SubSubMenu110.label()));
6507            assert!(shows(tester, &TestMenu::SubSubMenu111.label()));
6508            assert!(shows(tester, &TestMenu::SubSubMenu112.label()));
6509            assert_eq!(log.opened().last(), Some(&TestMenu::SubMenu11));
6510        });
6511    }
6512
6513    mod functions {
6514        use std::cell::Cell;
6515        use waft_painting::ShapeBorder;
6516
6517        use waft_widgets::{Center, Column};
6518
6519        use super::*;
6520        use crate::colors::Colors;
6521        use crate::elevated_button::ElevatedButton;
6522        use crate::filled_button::FilledButton;
6523        use crate::tooltip::tests::m2;
6524
6525        /// Dart's `find.descendant(of: of, matching: find.byType(Material)).first`, read through
6526        /// `read`.
6527        fn first_material_under<R>(
6528            tester: &WidgetTester,
6529            of: AnyElement,
6530            read: impl FnOnce(&Material) -> R,
6531        ) -> R {
6532            let material = tester.descendants_of_type::<Material>(of)[0];
6533            tester.widget::<Material, R>(material, read)
6534        }
6535
6536        /// The `W` that has a `Text(text)` below it: Dart's `find.widgetWithText(W, text)`.
6537        fn widget_with_text<W: 'static>(tester: &WidgetTester, text: &str) -> AnyElement {
6538            ancestors_of_type::<W>(tester, text)[0]
6539        }
6540
6541        /// Dart's `getMenuBarMaterial(tester)`: the first `Material` under the first menu panel.
6542        fn menu_bar_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
6543            let panel = menu_panels(tester)[0];
6544            let material = tester.descendants_of_type::<Material>(panel)[0];
6545            tester.widget::<Material, R>(material, read)
6546        }
6547
6548        fn shape_is(material: &Material, expected: &dyn ShapeBorder) -> bool {
6549            material
6550                .shape
6551                .as_ref()
6552                .is_some_and(|shape| shape.eq_shape(expected))
6553        }
6554
6555        fn default_menu_border() -> waft_painting::RoundedRectangleBorder {
6556            waft_painting::RoundedRectangleBorder::new(
6557                waft_painting::BorderSide::NONE,
6558                waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(4.0)),
6559            )
6560        }
6561
6562        /// The defaults a menu panel's `Material` takes from `theme`.
6563        fn assert_menu_material_defaults(material: &Material, theme: &ThemeData) {
6564            assert_eq!(material.color, Some(theme.color_scheme.surface_container()));
6565            assert_eq!(material.shadow_color, Some(theme.color_scheme.shadow()));
6566            assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
6567            assert_eq!(material.elevation, 3.0);
6568            assert!(shape_is(material, &default_menu_border()));
6569        }
6570
6571        /// Dart's `buildTestApp` arguments.
6572        #[derive(Clone)]
6573        struct TestApp {
6574            alignment: Option<AlignmentGeometry>,
6575            alignment_offset: Offset,
6576            text_direction: TextDirection,
6577            consumes_outside_tap: bool,
6578            log: Option<Log>,
6579        }
6580
6581        impl Default for TestApp {
6582            fn default() -> TestApp {
6583                TestApp {
6584                    alignment: None,
6585                    alignment_offset: Offset::ZERO,
6586                    text_direction: TextDirection::Ltr,
6587                    consumes_outside_tap: false,
6588                    log: None,
6589                }
6590            }
6591        }
6592
6593        /// Dart's `buildTestApp(..)`, with its `controller` and `menuItemKey`.
6594        fn build_test_app(
6595            tester: &mut WidgetTester,
6596            options: TestApp,
6597            controller: MenuControllerRef,
6598            menu_item_key: &GlobalKey,
6599        ) {
6600            let menu_item_key = menu_item_key.clone();
6601            pump_material(tester, m2, move |app| {
6602                let focus_node = FocusNode::new(app).into_erased::<AnyFocusNode>();
6603                let push = |list: Option<Rc<RefCell<Vec<TestMenu>>>>, menu: TestMenu| {
6604                    Listener::new(move |_app| {
6605                        if let Some(list) = &list {
6606                            list.borrow_mut().push(menu);
6607                        }
6608                    })
6609                };
6610                let log = options.log.clone();
6611                let selected = log.as_ref().map(|log| Rc::clone(&log.selected));
6612                let opened = log.as_ref().map(|log| Rc::clone(&log.opened));
6613                let closed = log.as_ref().map(|log| Rc::clone(&log.closed));
6614                let mut style = MenuStyle::new();
6615                if let Some(alignment) = options.alignment {
6616                    style = style.alignment(alignment);
6617                }
6618                let on_outside = push(selected.clone(), TestMenu::OutsideButton);
6619                let on_anchor = push(selected.clone(), TestMenu::AnchorButton);
6620                let on_open = push(opened, TestMenu::AnchorButton);
6621                let on_close = push(closed, TestMenu::AnchorButton);
6622                let anchor = MenuAnchor::new(vec![
6623                    MenuItemButton::new()
6624                        .key(menu_item_key.clone().into())
6625                        .shortcut(Rc::new(
6626                            SingleActivator::new(LogicalKeyboardKey::KEY_B).control(true),
6627                        ))
6628                        .on_pressed(push(selected.clone(), TestMenu::SubMenu00))
6629                        .child(Text::new(TestMenu::SubMenu00.label()))
6630                        .into_widget(),
6631                    MenuItemButton::new()
6632                        .leading_icon(Icon::new(Some(Icons::send())))
6633                        .trailing_icon(Icon::new(Some(Icons::mail())))
6634                        .on_pressed(push(selected, TestMenu::SubMenu01))
6635                        .child(Text::new(TestMenu::SubMenu01.label()))
6636                        .into_widget(),
6637                ])
6638                .child_focus_node(focus_node.clone())
6639                .controller(controller.clone())
6640                .alignment_offset(options.alignment_offset)
6641                .consume_outside_tap(options.consumes_outside_tap)
6642                .style(style)
6643                .on_open(Rc::new(move |app: &mut App| on_open.call(app)))
6644                .on_close(Rc::new(move |app: &mut App| on_close.call(app)))
6645                .builder(move |_app, _context, controller, child| {
6646                    let on_anchor = on_anchor.clone();
6647                    ElevatedButton::new(
6648                        Some(Listener::new(move |app| {
6649                            if controller.is_open(app) {
6650                                controller.close(app);
6651                            } else {
6652                                controller.open(app, None);
6653                            }
6654                            on_anchor.call(app);
6655                        })),
6656                        child.cloned(),
6657                    )
6658                    .focus_node(focus_node.clone())
6659                    .into_widget()
6660                })
6661                .child(Text::new(TestMenu::AnchorButton.label()));
6662                Directionality::new(
6663                    options.text_direction,
6664                    Column::new()
6665                        .children(vec![
6666                            waft_widgets::GestureDetector::new()
6667                                .on_tap(on_outside)
6668                                .child(Text::new(TestMenu::OutsideButton.label()))
6669                                .into_widget(),
6670                            anchor.into_widget(),
6671                        ])
6672                        .into_widget(),
6673                )
6674                .into_widget()
6675            });
6676        }
6677
6678        fn controller(tester: &WidgetTester) -> MenuControllerRef {
6679            MenuController::new(&mut tester.cell.borrow_mut()).into_erased()
6680        }
6681
6682        /// Dart's `find.ancestor(of: find.byKey(key), matching: find.byType(FocusScope)).first`.
6683        fn menu_scope_rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
6684            let element = {
6685                let app = tester.cell.borrow();
6686                key.current_context(&app)
6687                    .expect("the keyed widget is mounted")
6688            };
6689            let scope = tester
6690                .ancestors(element)
6691                .into_iter()
6692                .find(|ancestor| {
6693                    let app = tester.cell.borrow();
6694                    waft_widgets::downcast_widget::<FocusScope>(&**ancestor.widget(&app)).is_some()
6695                })
6696                .expect("a FocusScope above the item");
6697            rect_of_element(tester, scope)
6698        }
6699
6700        /// Dart's `find.ancestor(of: find.text(text), matching: find.byType(FocusScope)).first`.
6701        fn menu_scope_rect(tester: &WidgetTester, text: &str) -> Rect {
6702            rect_of_element(tester, ancestors_of_type::<FocusScope>(tester, text)[0])
6703        }
6704
6705        /// A menu bar of the test menus in an `Expanded` of a `Row`, above a placeholder.
6706        fn expanded_bar(menus: &TestMenus) -> WidgetRef {
6707            Column::new()
6708                .children(vec![
6709                    Row::new()
6710                        .children(vec![
6711                            Expanded::new(MenuBar::new(menus.build())).into_widget(),
6712                        ])
6713                        .into_widget(),
6714                    Expanded::new(placeholder()).into_widget(),
6715                ])
6716                .into_widget()
6717        }
6718
6719        // menu_anchor_test.dart 'Menu defaults'.
6720        #[test]
6721        fn menus_take_their_default_colors_shapes_and_text_styles_from_the_theme() {
6722            test_widgets(|tester| {
6723                let log = Log::default();
6724                let controller = controller(tester);
6725                let menus = TestMenus::all(&log);
6726                let theme = ThemeData::new(&tester.cell.borrow());
6727                let theme_for_app = theme.clone();
6728                pump_material(
6729                    tester,
6730                    move |_app| theme_for_app,
6731                    |_app| {
6732                        MenuBar::new(menus.build())
6733                            .controller(controller)
6734                            .into_widget()
6735                    },
6736                );
6737
6738                // Menu bar (horizontal menu).
6739                let text_button = find::by_type::<TextButton>().evaluate(tester)[0];
6740                let menu_material = tester.ancestor_of_type::<Material>(text_button);
6741                assert!(log.opened().is_empty());
6742                tester.widget::<Material, _>(menu_material, |material| {
6743                    assert_menu_material_defaults(material, &theme);
6744                });
6745
6746                first_material_under(tester, text_button, |material| {
6747                    assert_eq!(material.color, Some(Colors::TRANSPARENT));
6748                    assert_eq!(material.elevation, 0.0);
6749                    assert!(shape_is(
6750                        material,
6751                        &waft_painting::RoundedRectangleBorder::default()
6752                    ));
6753                    let text_style = material.text_style.as_ref().expect("a text style");
6754                    assert_eq!(
6755                        text_style.color,
6756                        Some(theme.color_scheme.on_surface().into())
6757                    );
6758                    assert_eq!(text_style.font_size, Some(14.0));
6759                    assert_eq!(text_style.height, Some(1.43));
6760                });
6761
6762                // Vertical menu.
6763                tester.tap(find::text(&TestMenu::MainMenu1.label()));
6764                pump(tester);
6765
6766                let item = widget_with_text::<TextButton>(tester, &TestMenu::SubMenu10.label());
6767                let menu_material = tester.ancestor_of_type::<Material>(item);
6768                assert_eq!(log.opened().last(), Some(&TestMenu::MainMenu1));
6769                tester.widget::<Material, _>(menu_material, |material| {
6770                    assert_menu_material_defaults(material, &theme);
6771                });
6772
6773                first_material_under(tester, item, |material| {
6774                    assert_eq!(material.color, Some(Colors::TRANSPARENT));
6775                    assert_eq!(material.elevation, 0.0);
6776                    assert!(shape_is(
6777                        material,
6778                        &waft_painting::RoundedRectangleBorder::default()
6779                    ));
6780                    let text_style = material.text_style.as_ref().expect("a text style");
6781                    assert_eq!(
6782                        text_style.color,
6783                        Some(theme.color_scheme.on_surface().into())
6784                    );
6785                    assert_eq!(text_style.font_size, Some(14.0));
6786                    assert_eq!(text_style.height, Some(1.43));
6787                });
6788
6789                tester.tap(find::text(&TestMenu::MainMenu0.label()));
6790                pump(tester);
6791                let icon = tester.element(find::by_icon(&Icons::add()).first());
6792                let glyph = tester.glyph_style(icon);
6793                assert_eq!(
6794                    glyph.color,
6795                    Some(theme.color_scheme.on_surface_variant().into())
6796                );
6797            });
6798        }
6799
6800        // menu_anchor_test.dart 'Menu defaults - disabled'.
6801        #[test]
6802        fn disabled_menu_items_take_the_disabled_default_colors() {
6803            test_widgets(|tester| {
6804                let log = Log::default();
6805                let controller = controller(tester);
6806                let menus = TestMenus::all(&log);
6807                let theme = ThemeData::new(&tester.cell.borrow());
6808                let theme_for_app = theme.clone();
6809                pump_material(
6810                    tester,
6811                    move |_app| theme_for_app,
6812                    |_app| {
6813                        MenuBar::new(menus.build())
6814                            .controller(controller)
6815                            .into_widget()
6816                    },
6817                );
6818                let disabled = theme.color_scheme.on_surface().with_opacity(0.38);
6819
6820                // Menu bar (horizontal menu).
6821                let button = widget_with_text::<TextButton>(tester, &TestMenu::MainMenu5.label());
6822                let menu_material = tester.ancestor_of_type::<Material>(button);
6823                assert!(log.opened().is_empty());
6824                tester.widget::<Material, _>(menu_material, |material| {
6825                    assert_menu_material_defaults(material, &theme);
6826                });
6827                first_material_under(tester, button, |material| {
6828                    assert_eq!(material.color, Some(Colors::TRANSPARENT));
6829                    assert_eq!(material.elevation, 0.0);
6830                    assert!(shape_is(
6831                        material,
6832                        &waft_painting::RoundedRectangleBorder::default()
6833                    ));
6834                    let text_style = material.text_style.as_ref().expect("a text style");
6835                    assert_eq!(text_style.color, Some(disabled.into()));
6836                });
6837
6838                // Vertical menu.
6839                tester.tap(find::text(&TestMenu::MainMenu2.label()));
6840                pump(tester);
6841
6842                let item = widget_with_text::<TextButton>(tester, &TestMenu::SubMenu20.label());
6843                let menu_material = tester.ancestor_of_type::<Material>(item);
6844                tester.widget::<Material, _>(menu_material, |material| {
6845                    assert_menu_material_defaults(material, &theme);
6846                });
6847                first_material_under(tester, item, |material| {
6848                    assert_eq!(material.color, Some(Colors::TRANSPARENT));
6849                    assert_eq!(material.elevation, 0.0);
6850                    assert!(shape_is(
6851                        material,
6852                        &waft_painting::RoundedRectangleBorder::default()
6853                    ));
6854                    let text_style = material.text_style.as_ref().expect("a text style");
6855                    assert_eq!(text_style.color, Some(disabled.into()));
6856                });
6857
6858                let icon = tester.element(find::by_icon(&Icons::ac_unit()).first());
6859                let glyph = tester.glyph_style(icon);
6860                assert_eq!(glyph.color, Some(disabled.into()));
6861            });
6862        }
6863
6864        // menu_anchor_test.dart 'Focus is returned to previous focus before invoking onPressed'.
6865        #[test]
6866        fn focus_returns_to_where_it_was_before_an_item_is_invoked() {
6867            test_widgets(|tester| {
6868                let controller = controller(tester);
6869                let button_focus = {
6870                    let mut app = tester.cell.borrow_mut();
6871                    let node = FocusNode::new(&mut app).into_erased::<AnyFocusNode>();
6872                    node.set_debug_label(&mut app, Some("Button Focus".to_string()));
6873                    node
6874                };
6875                let focus_in_on_pressed: Rc<Cell<Option<AnyFocusNode>>> = Rc::default();
6876                let sink = Rc::clone(&focus_in_on_pressed);
6877                let on_menu_selected: MenuCallback =
6878                    Rc::new(move |app: &mut App, _item| sink.set(primary_focus(app)));
6879                pump_material(tester, m3, {
6880                    let button_focus = button_focus.clone();
6881                    move |_app| {
6882                        Column::new()
6883                            .children(vec![
6884                                MenuBar::new(create_test_menus_calling(on_menu_selected))
6885                                    .controller(controller)
6886                                    .into_widget(),
6887                                ElevatedButton::new(
6888                                    Some(Listener::new(|_app| {})),
6889                                    Some(Text::new("Press Me")),
6890                                )
6891                                .autofocus(true)
6892                                .focus_node(button_focus.clone())
6893                                .into_widget(),
6894                            ])
6895                            .into_widget()
6896                    }
6897                });
6898
6899                pump(tester);
6900                assert_eq!(
6901                    primary_focus(&mut tester.cell.borrow_mut()),
6902                    Some(button_focus.handle())
6903                );
6904
6905                tester.tap(find::text(&TestMenu::MainMenu1.label()));
6906                pump(tester);
6907
6908                tester.tap(find::text(&TestMenu::SubMenu11.label()));
6909                pump(tester);
6910
6911                tester.tap(find::text(&TestMenu::SubSubMenu110.label()));
6912                pump(tester);
6913
6914                assert_eq!(focus_in_on_pressed.get(), Some(button_focus.handle()));
6915                assert_eq!(
6916                    primary_focus(&mut tester.cell.borrow_mut()),
6917                    Some(button_focus.handle())
6918                );
6919            });
6920        }
6921
6922        /// Dart's `void Function(TestMenu)`.
6923        type MenuCallback = Rc<dyn Fn(&mut App, TestMenu)>;
6924
6925        /// Dart's `createTestMenus(onPressed: on_pressed)` for a callback that does more than
6926        /// log the item: the same menus, each enabled item calling `on_pressed`.
6927        fn create_test_menus_calling(on_pressed: MenuCallback) -> Vec<WidgetRef> {
6928            let item = |menu: TestMenu, enabled: bool, leading_icon: Option<WidgetRef>| {
6929                let mut button = MenuItemButton::new().child(Text::new(menu.label()));
6930                if enabled {
6931                    let on_pressed = Rc::clone(&on_pressed);
6932                    button = button.on_pressed(Listener::new(move |app| on_pressed(app, menu)));
6933                }
6934                button.leading_icon = leading_icon;
6935                button.into_widget()
6936            };
6937            let submenu = |menu: TestMenu, children: Vec<WidgetRef>| {
6938                SubmenuButton::new(children, Some(Text::new(menu.label()))).into_widget()
6939            };
6940            vec![
6941                submenu(
6942                    TestMenu::MainMenu0,
6943                    vec![
6944                        item(
6945                            TestMenu::SubMenu00,
6946                            true,
6947                            Some(Icon::new(Some(Icons::add())).into_widget()),
6948                        ),
6949                        item(TestMenu::SubMenu01, true, None),
6950                        item(TestMenu::SubMenu02, true, None),
6951                    ],
6952                ),
6953                submenu(
6954                    TestMenu::MainMenu1,
6955                    vec![
6956                        item(TestMenu::SubMenu10, true, None),
6957                        submenu(
6958                            TestMenu::SubMenu11,
6959                            vec![
6960                                item(TestMenu::SubSubMenu110, true, None),
6961                                item(TestMenu::SubSubMenu111, true, None),
6962                                item(TestMenu::SubSubMenu112, true, None),
6963                                item(TestMenu::SubSubMenu113, true, None),
6964                            ],
6965                        ),
6966                        item(TestMenu::SubMenu12, true, None),
6967                    ],
6968                ),
6969                submenu(
6970                    TestMenu::MainMenu2,
6971                    vec![item(
6972                        TestMenu::SubMenu20,
6973                        false,
6974                        Some(Icon::new(Some(Icons::ac_unit())).into_widget()),
6975                    )],
6976                ),
6977                submenu(TestMenu::MainMenu5, Vec::new()),
6978            ]
6979        }
6980
6981        // menu_anchor_test.dart 'geometry'.
6982        #[test]
6983        fn a_menu_bar_and_its_menus_have_flutters_geometry() {
6984            test_widgets(|tester| {
6985                let log = Log::default();
6986                let menus = TestMenus::pressed(&log);
6987                pump_material(tester, m2, |_app| expanded_bar(&menus));
6988                pump(tester);
6989
6990                assert_eq!(
6991                    rect_of::<MenuBar>(tester),
6992                    Rect::from_ltrb(0.0, 0.0, 800.0, 48.0)
6993                );
6994
6995                // Open and make sure things are the right size.
6996                tester.tap(find::text(&TestMenu::MainMenu1.label()));
6997                pump(tester);
6998
6999                assert_eq!(
7000                    rect_of::<MenuBar>(tester),
7001                    Rect::from_ltrb(0.0, 0.0, 800.0, 48.0)
7002                );
7003                assert_eq!(
7004                    tester.get_rect(find::text(&TestMenu::SubMenu10.label())),
7005                    Rect::from_ltrb(124.0, 73.0, 314.0, 87.0)
7006                );
7007                let materials = ancestors_of_type::<Material>(tester, &TestMenu::SubMenu10.label());
7008                assert_eq!(
7009                    rect_of_element(tester, materials[1]),
7010                    Rect::from_ltrb(112.0, 48.0, 326.0, 208.0)
7011                );
7012            });
7013        }
7014
7015        // menu_anchor_test.dart 'geometry with RTL direction'.
7016        #[test]
7017        fn a_right_to_left_menu_bar_and_its_menus_have_flutters_geometry() {
7018            test_widgets(|tester| {
7019                let log = Log::default();
7020                let menus = TestMenus::pressed(&log);
7021                pump_material(tester, m2, |_app| {
7022                    Directionality::new(TextDirection::Rtl, expanded_bar(&menus)).into_widget()
7023                });
7024                pump(tester);
7025
7026                assert_eq!(
7027                    rect_of::<MenuBar>(tester),
7028                    Rect::from_ltrb(0.0, 0.0, 800.0, 48.0)
7029                );
7030
7031                // Open and make sure things are the right size.
7032                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7033                pump(tester);
7034
7035                assert_eq!(
7036                    rect_of::<MenuBar>(tester),
7037                    Rect::from_ltrb(0.0, 0.0, 800.0, 48.0)
7038                );
7039                assert_eq!(
7040                    tester.get_rect(find::text(&TestMenu::SubMenu10.label())),
7041                    Rect::from_ltrb(486.0, 73.0, 676.0, 87.0)
7042                );
7043                let materials = ancestors_of_type::<Material>(tester, &TestMenu::SubMenu10.label());
7044                assert_eq!(
7045                    rect_of_element(tester, materials[1]),
7046                    Rect::from_ltrb(474.0, 48.0, 688.0, 208.0)
7047                );
7048
7049                // Close and make sure it goes back where it was.
7050                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7051                pump(tester);
7052
7053                assert_eq!(
7054                    rect_of::<MenuBar>(tester),
7055                    Rect::from_ltrb(0.0, 0.0, 800.0, 48.0)
7056                );
7057            });
7058        }
7059
7060        // menu_anchor_test.dart 'menu alignment and offset in LTR'.
7061        #[test]
7062        fn a_menu_follows_its_alignment_and_offset_left_to_right() {
7063            test_widgets(|tester| {
7064                let controller = controller(tester);
7065                let key = GlobalKey::new();
7066                build_test_app(tester, TestApp::default(), controller.clone(), &key);
7067
7068                assert_eq!(
7069                    rect_of::<ElevatedButton>(tester),
7070                    Rect::from_ltrb(328.0, 14.0, 472.0, 62.0)
7071                );
7072
7073                // Open the menu and make sure things are the right size, in the right place.
7074                tester.tap(find::text("Press Me"));
7075                pump(tester);
7076                assert_eq!(
7077                    menu_scope_rect_of_key(tester, &key),
7078                    Rect::from_ltrb(328.0, 62.0, 602.0, 174.0)
7079                );
7080
7081                let with_alignment = |tester: &mut WidgetTester, alignment| {
7082                    let options = TestApp {
7083                        alignment: Some(alignment),
7084                        ..TestApp::default()
7085                    };
7086                    build_test_app(tester, options, controller.clone(), &key);
7087                    pump(tester);
7088                    menu_scope_rect_of_key(tester, &key)
7089                };
7090                assert_eq!(
7091                    with_alignment(tester, AlignmentGeometry::TOP_START),
7092                    Rect::from_ltrb(328.0, 14.0, 602.0, 126.0)
7093                );
7094                assert_eq!(
7095                    with_alignment(
7096                        tester,
7097                        AlignmentGeometry::Directional(waft_painting::AlignmentDirectional::CENTER)
7098                    ),
7099                    Rect::from_ltrb(400.0, 38.0, 674.0, 150.0)
7100                );
7101                assert_eq!(
7102                    with_alignment(tester, AlignmentGeometry::BOTTOM_END),
7103                    Rect::from_ltrb(472.0, 62.0, 746.0, 174.0)
7104                );
7105
7106                let menu_rect = with_alignment(tester, AlignmentGeometry::TOP_START);
7107                let options = TestApp {
7108                    alignment: Some(AlignmentGeometry::TOP_START),
7109                    alignment_offset: Offset::new(10.0, 20.0),
7110                    ..TestApp::default()
7111                };
7112                build_test_app(tester, options, controller.clone(), &key);
7113                pump(tester);
7114                let offset_menu_rect = menu_scope_rect_of_key(tester, &key);
7115                assert_eq!(
7116                    offset_menu_rect.top_left() - menu_rect.top_left(),
7117                    Offset::new(10.0, 20.0)
7118                );
7119            });
7120        }
7121
7122        // menu_anchor_test.dart 'menu alignment and offset in RTL'.
7123        #[test]
7124        fn a_menu_follows_its_alignment_and_offset_right_to_left() {
7125            test_widgets(|tester| {
7126                let controller = controller(tester);
7127                let key = GlobalKey::new();
7128                let rtl = TestApp {
7129                    text_direction: TextDirection::Rtl,
7130                    ..TestApp::default()
7131                };
7132                build_test_app(tester, rtl.clone(), controller.clone(), &key);
7133
7134                assert_eq!(
7135                    rect_of::<ElevatedButton>(tester),
7136                    Rect::from_ltrb(328.0, 14.0, 472.0, 62.0)
7137                );
7138
7139                let label = TestMenu::SubMenu00.label();
7140                // Open the menu and make sure things are the right size, in the right place.
7141                tester.tap(find::text("Press Me"));
7142                pump(tester);
7143                assert_eq!(
7144                    menu_scope_rect(tester, &label),
7145                    Rect::from_ltrb(198.0, 62.0, 472.0, 174.0)
7146                );
7147
7148                let with_alignment = |tester: &mut WidgetTester, alignment| {
7149                    let options = TestApp {
7150                        alignment: Some(alignment),
7151                        ..rtl.clone()
7152                    };
7153                    build_test_app(tester, options, controller.clone(), &key);
7154                    pump(tester);
7155                    menu_scope_rect(tester, &label)
7156                };
7157                assert_eq!(
7158                    with_alignment(tester, AlignmentGeometry::TOP_START),
7159                    Rect::from_ltrb(198.0, 14.0, 472.0, 126.0)
7160                );
7161                assert_eq!(
7162                    with_alignment(
7163                        tester,
7164                        AlignmentGeometry::Directional(waft_painting::AlignmentDirectional::CENTER)
7165                    ),
7166                    Rect::from_ltrb(126.0, 38.0, 400.0, 150.0)
7167                );
7168                assert_eq!(
7169                    with_alignment(tester, AlignmentGeometry::BOTTOM_END),
7170                    Rect::from_ltrb(54.0, 62.0, 328.0, 174.0)
7171                );
7172
7173                let menu_rect = with_alignment(tester, AlignmentGeometry::TOP_START);
7174                let options = TestApp {
7175                    alignment: Some(AlignmentGeometry::TOP_START),
7176                    alignment_offset: Offset::new(10.0, 20.0),
7177                    ..rtl.clone()
7178                };
7179                build_test_app(tester, options, controller.clone(), &key);
7180                pump(tester);
7181                assert_eq!(
7182                    menu_scope_rect(tester, &label).top_left() - menu_rect.top_left(),
7183                    Offset::new(-10.0, 20.0)
7184                );
7185            });
7186        }
7187
7188        // menu_anchor_test.dart 'menu position in LTR'.
7189        #[test]
7190        fn a_menu_opens_at_the_position_given_left_to_right() {
7191            test_widgets(|tester| {
7192                let controller = controller(tester);
7193                let key = GlobalKey::new();
7194                let options = TestApp {
7195                    alignment_offset: Offset::new(100.0, 50.0),
7196                    ..TestApp::default()
7197                };
7198                build_test_app(tester, options, controller.clone(), &key);
7199
7200                assert_eq!(
7201                    rect_of::<ElevatedButton>(tester),
7202                    Rect::from_ltrb(328.0, 14.0, 472.0, 62.0)
7203                );
7204
7205                let label = TestMenu::SubMenu00.label();
7206                // Open the menu and make sure things are the right size, in the right place.
7207                tester.tap(find::text("Press Me"));
7208                pump(tester);
7209                assert_eq!(
7210                    menu_scope_rect(tester, &label),
7211                    Rect::from_ltrb(428.0, 112.0, 702.0, 224.0)
7212                );
7213
7214                // Now move the menu by calling open() again with a local position on the
7215                // anchor.
7216                controller.open(
7217                    &mut tester.cell.borrow_mut(),
7218                    Some(Offset::new(200.0, 200.0)),
7219                );
7220                pump(tester);
7221                assert_eq!(
7222                    menu_scope_rect(tester, &label),
7223                    Rect::from_ltrb(526.0, 214.0, 800.0, 326.0)
7224                );
7225            });
7226        }
7227
7228        // menu_anchor_test.dart 'menu position in RTL'.
7229        #[test]
7230        fn a_menu_opens_at_the_position_given_right_to_left() {
7231            test_widgets(|tester| {
7232                let controller = controller(tester);
7233                let key = GlobalKey::new();
7234                let options = TestApp {
7235                    alignment_offset: Offset::new(100.0, 50.0),
7236                    text_direction: TextDirection::Rtl,
7237                    ..TestApp::default()
7238                };
7239                build_test_app(tester, options, controller.clone(), &key);
7240
7241                assert_eq!(
7242                    rect_of::<ElevatedButton>(tester),
7243                    Rect::from_ltrb(328.0, 14.0, 472.0, 62.0)
7244                );
7245
7246                let label = TestMenu::SubMenu00.label();
7247                // Open the menu and make sure things are the right size, in the right place.
7248                tester.tap(find::text("Press Me"));
7249                pump(tester);
7250                assert_eq!(
7251                    menu_scope_rect(tester, &label),
7252                    Rect::from_ltrb(98.0, 112.0, 372.0, 224.0)
7253                );
7254
7255                // Now move the menu by calling open() again with a local position on the
7256                // anchor.
7257                controller.open(
7258                    &mut tester.cell.borrow_mut(),
7259                    Some(Offset::new(400.0, 200.0)),
7260                );
7261                pump(tester);
7262                assert_eq!(
7263                    menu_scope_rect(tester, &label),
7264                    Rect::from_ltrb(526.0, 214.0, 800.0, 326.0)
7265                );
7266            });
7267        }
7268
7269        /// Dart's `Padding(padding: EdgeInsets.all(10), child: MaterialApp(..))` around a padded
7270        /// bar of the test menus.
7271        fn pump_padded_bar(tester: &mut WidgetTester, menus: &TestMenus, direction: TextDirection) {
7272            let root = {
7273                let app = tester.cell.borrow();
7274                let bar = Column::new()
7275                    .children(vec![
7276                        Padding::new(EdgeInsetsGeometry::all(12.0))
7277                            .child(Row::new().children(vec![
7278                                Expanded::new(MenuBar::new(menus.build())).into_widget(),
7279                            ]))
7280                            .into_widget(),
7281                        Expanded::new(placeholder()).into_widget(),
7282                    ])
7283                    .into_widget();
7284                Padding::new(EdgeInsetsGeometry::all(10.0))
7285                    .child(material_app(
7286                        m2(&app),
7287                        Material::new()
7288                            .child(Directionality::new(direction, bar))
7289                            .into_widget(),
7290                    ))
7291                    .into_widget()
7292            };
7293            tester.pump_widget(root);
7294        }
7295
7296        // menu_anchor_test.dart 'works with Padding around menu and overlay'.
7297        #[test]
7298        fn menus_place_themselves_with_padding_around_the_bar_and_the_overlay() {
7299            test_widgets(|tester| {
7300                let log = Log::default();
7301                let menus = TestMenus::pressed(&log);
7302                pump_padded_bar(tester, &menus, TextDirection::Ltr);
7303                pump(tester);
7304
7305                assert_eq!(
7306                    rect_of::<MenuBar>(tester),
7307                    Rect::from_ltrb(22.0, 22.0, 778.0, 70.0)
7308                );
7309
7310                // Open and make sure things are the right size.
7311                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7312                pump(tester);
7313
7314                assert_eq!(
7315                    rect_of::<MenuBar>(tester),
7316                    Rect::from_ltrb(22.0, 22.0, 778.0, 70.0)
7317                );
7318                assert_eq!(
7319                    tester.get_rect(find::text(&TestMenu::SubMenu10.label())),
7320                    Rect::from_ltrb(146.0, 95.0, 336.0, 109.0)
7321                );
7322                let materials = ancestors_of_type::<Material>(tester, &TestMenu::SubMenu10.label());
7323                assert_eq!(
7324                    rect_of_element(tester, materials[1]),
7325                    Rect::from_ltrb(134.0, 70.0, 348.0, 230.0)
7326                );
7327
7328                // Close and make sure it goes back where it was.
7329                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7330                pump(tester);
7331
7332                assert_eq!(
7333                    rect_of::<MenuBar>(tester),
7334                    Rect::from_ltrb(22.0, 22.0, 778.0, 70.0)
7335                );
7336            });
7337        }
7338
7339        // menu_anchor_test.dart 'works with Padding around menu and overlay with RTL direction'.
7340        #[test]
7341        fn right_to_left_menus_place_themselves_with_padding_around_the_bar_and_the_overlay() {
7342            test_widgets(|tester| {
7343                let log = Log::default();
7344                let menus = TestMenus::pressed(&log);
7345                pump_padded_bar(tester, &menus, TextDirection::Rtl);
7346                pump(tester);
7347
7348                assert_eq!(
7349                    rect_of::<MenuBar>(tester),
7350                    Rect::from_ltrb(22.0, 22.0, 778.0, 70.0)
7351                );
7352
7353                // Open and make sure things are the right size.
7354                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7355                pump(tester);
7356
7357                assert_eq!(
7358                    rect_of::<MenuBar>(tester),
7359                    Rect::from_ltrb(22.0, 22.0, 778.0, 70.0)
7360                );
7361                assert_eq!(
7362                    tester.get_rect(find::text(&TestMenu::SubMenu10.label())),
7363                    Rect::from_ltrb(464.0, 95.0, 654.0, 109.0)
7364                );
7365                let materials = ancestors_of_type::<Material>(tester, &TestMenu::SubMenu10.label());
7366                assert_eq!(
7367                    rect_of_element(tester, materials[1]),
7368                    Rect::from_ltrb(452.0, 70.0, 666.0, 230.0)
7369                );
7370
7371                // Close and make sure it goes back where it was.
7372                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7373                pump(tester);
7374
7375                assert_eq!(
7376                    rect_of::<MenuBar>(tester),
7377                    Rect::from_ltrb(22.0, 22.0, 778.0, 70.0)
7378                );
7379            });
7380        }
7381
7382        // menu_anchor_test.dart 'visual attributes can be set'.
7383        #[test]
7384        fn a_menu_bar_takes_the_elevation_and_background_color_of_its_style() {
7385            test_widgets(|tester| {
7386                let log = Log::default();
7387                let menus = TestMenus::pressed(&log);
7388                pump_material(tester, m3, |_app| {
7389                    Column::new()
7390                        .children(vec![
7391                            Row::new()
7392                                .children(vec![
7393                                    Expanded::new(
7394                                        MenuBar::new(menus.build()).style(
7395                                            MenuStyle::new()
7396                                                .elevation(Rc::new(
7397                                                    waft_widgets::WidgetStatePropertyAll::new(
7398                                                        Some(10.0),
7399                                                    ),
7400                                                ))
7401                                                .background_color(Rc::new(
7402                                                    waft_widgets::WidgetStatePropertyAll::new(
7403                                                        Some(Colors::RED.primary()),
7404                                                    ),
7405                                                )),
7406                                        ),
7407                                    )
7408                                    .into_widget(),
7409                                ])
7410                                .into_widget(),
7411                            Expanded::new(placeholder()).into_widget(),
7412                        ])
7413                        .into_widget()
7414                });
7415                assert_eq!(
7416                    rect_of_element(tester, only(menu_panels(tester))),
7417                    Rect::from_ltrb(0.0, 0.0, 800.0, 48.0)
7418                );
7419                menu_bar_material(tester, |material| {
7420                    assert_eq!(material.elevation, 10.0);
7421                    assert_eq!(material.color, Some(Colors::RED.primary()));
7422                });
7423            });
7424        }
7425
7426        /// Dart's `MenuAnchor(menuChildren: [MenuItemButton(child: Text('Button 1'))], builder:
7427        /// FilledButton 'Tap me')` in a centered `Material`.
7428        fn clip_behavior_anchor(clip_behavior: Option<Clip>) -> WidgetRef {
7429            let mut anchor = MenuAnchor::new(vec![
7430                MenuItemButton::new()
7431                    .child(Text::new("Button 1"))
7432                    .into_widget(),
7433            ])
7434            .builder(|_app, _context, controller, _child| {
7435                FilledButton::new(
7436                    Some(Listener::new(move |app| controller.open(app, None))),
7437                    Some(Text::new("Tap me")),
7438                )
7439                .into_widget()
7440            });
7441            if let Some(clip_behavior) = clip_behavior {
7442                anchor = anchor.clip_behavior(clip_behavior);
7443            }
7444            Center::new().child(anchor).into_widget()
7445        }
7446
7447        // menu_anchor_test.dart 'MenuAnchor clip behavior'.
7448        #[test]
7449        fn a_menu_anchor_clips_its_menu_hard_edged_unless_told_otherwise() {
7450            test_widgets(|tester| {
7451                pump_material(tester, m3, |_app| clip_behavior_anchor(None));
7452                tester.tap(find::text("Tap me"));
7453                pump(tester);
7454
7455                // Test default clip behavior.
7456                assert_eq!(
7457                    menu_bar_material(tester, |material| material.clip_behavior),
7458                    Clip::HardEdge
7459                );
7460
7461                // Close the menu.
7462                tester.tap_at(Offset::new(10.0, 10.0), 1);
7463                tester.pump_and_settle();
7464                pump_material(tester, m3, |_app| {
7465                    clip_behavior_anchor(Some(Clip::AntiAlias))
7466                });
7467                tester.tap(find::text("Tap me"));
7468                pump(tester);
7469
7470                // Test custom clip behavior.
7471                assert_eq!(
7472                    menu_bar_material(tester, |material| material.clip_behavior),
7473                    Clip::AntiAlias
7474                );
7475            });
7476        }
7477
7478        // menu_anchor_test.dart 'open and close works'.
7479        #[test]
7480        fn submenus_open_and_close_with_taps_on_their_buttons() {
7481            test_widgets(|tester| {
7482                let log = Log::default();
7483                let controller = controller(tester);
7484                let menus = TestMenus::all(&log);
7485                pump_material(tester, m3, |_app| {
7486                    MenuBar::new(menus.build())
7487                        .controller(controller)
7488                        .into_widget()
7489                });
7490
7491                assert!(log.opened().is_empty());
7492                assert!(log.closed().is_empty());
7493
7494                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7495                pump(tester);
7496                assert_eq!(log.opened(), [TestMenu::MainMenu1]);
7497                assert!(log.closed().is_empty());
7498                log.clear();
7499
7500                tester.tap(find::text(&TestMenu::SubMenu11.label()));
7501                pump(tester);
7502
7503                assert_eq!(log.opened(), [TestMenu::SubMenu11]);
7504                assert!(log.closed().is_empty());
7505                log.clear();
7506
7507                tester.tap(find::text(&TestMenu::SubMenu11.label()));
7508                pump(tester);
7509
7510                assert!(log.opened().is_empty());
7511                assert_eq!(log.closed(), [TestMenu::SubMenu11]);
7512                log.clear();
7513
7514                tester.tap(find::text(&TestMenu::MainMenu0.label()));
7515                pump(tester);
7516
7517                assert_eq!(log.opened(), [TestMenu::MainMenu0]);
7518                assert_eq!(log.closed(), [TestMenu::MainMenu1]);
7519            });
7520        }
7521
7522        /// `focusedMenu` against `button_label(type_name, text)`.
7523        #[track_caller]
7524        fn assert_focused(tester: &WidgetTester, type_name: &str, text: &str) {
7525            assert_eq!(focused_menu(tester), Some(button_label(type_name, text)));
7526        }
7527
7528        fn submenu(tester: &WidgetTester, text: &str) {
7529            assert_focused(tester, "SubmenuButton", text);
7530        }
7531
7532        fn item(tester: &WidgetTester, text: &str) {
7533            assert_focused(tester, "MenuItemButton", text);
7534        }
7535
7536        // menu_anchor_test.dart 'Menus close and consume tap when open and tapped outside'.
7537        #[test]
7538        fn an_open_menu_closes_and_consumes_a_tap_outside_when_told_to() {
7539            test_widgets(|tester| {
7540                let controller = controller(tester);
7541                let key = GlobalKey::new();
7542                let log = Log::default();
7543                let options = TestApp {
7544                    consumes_outside_tap: true,
7545                    log: Some(log.clone()),
7546                    ..TestApp::default()
7547                };
7548                build_test_app(tester, options, controller.clone(), &key);
7549
7550                assert!(log.opened().is_empty());
7551                assert!(log.closed().is_empty());
7552
7553                // Doesn't consume tap when the menu is closed.
7554                tester.tap(find::text(&TestMenu::OutsideButton.label()));
7555                pump(tester);
7556                assert_eq!(log.selected(), [TestMenu::OutsideButton]);
7557                log.clear();
7558
7559                tester.tap(find::text(&TestMenu::AnchorButton.label()));
7560                pump(tester);
7561                assert_eq!(log.opened(), [TestMenu::AnchorButton]);
7562                assert!(log.closed().is_empty());
7563                assert_eq!(log.selected(), [TestMenu::AnchorButton]);
7564                log.clear();
7565
7566                tester.tap(find::text(&TestMenu::OutsideButton.label()));
7567                pump(tester);
7568
7569                assert!(log.opened().is_empty());
7570                assert_eq!(log.closed(), [TestMenu::AnchorButton]);
7571                // When the menu is open, don't expect the outside button to be selected:
7572                // it's supposed to consume the key down.
7573                assert!(log.selected().is_empty());
7574            });
7575        }
7576
7577        // menu_anchor_test.dart "Menus close and don't consume tap when open and tapped outside".
7578        #[test]
7579        fn an_open_menu_closes_and_passes_on_a_tap_outside_by_default() {
7580            test_widgets(|tester| {
7581                let controller = controller(tester);
7582                let key = GlobalKey::new();
7583                let log = Log::default();
7584                let options = TestApp {
7585                    log: Some(log.clone()),
7586                    ..TestApp::default()
7587                };
7588                build_test_app(tester, options, controller.clone(), &key);
7589
7590                assert!(log.opened().is_empty());
7591                assert!(log.closed().is_empty());
7592
7593                // Doesn't consume tap when the menu is closed.
7594                tester.tap(find::text(&TestMenu::OutsideButton.label()));
7595                pump(tester);
7596                assert_eq!(log.selected(), [TestMenu::OutsideButton]);
7597                log.clear();
7598
7599                tester.tap(find::text(&TestMenu::AnchorButton.label()));
7600                pump(tester);
7601                assert_eq!(log.opened(), [TestMenu::AnchorButton]);
7602                assert!(log.closed().is_empty());
7603                assert_eq!(log.selected(), [TestMenu::AnchorButton]);
7604                log.clear();
7605
7606                tester.tap(find::text(&TestMenu::OutsideButton.label()));
7607                pump(tester);
7608
7609                assert!(log.opened().is_empty());
7610                assert_eq!(log.closed(), [TestMenu::AnchorButton]);
7611                // Because consumesOutsideTap is false, this is expected to receive its
7612                // tap.
7613                assert_eq!(log.selected(), [TestMenu::OutsideButton]);
7614            });
7615        }
7616
7617        // menu_anchor_test.dart 'select works'.
7618        #[test]
7619        fn selecting_an_item_closes_every_menu() {
7620            test_widgets(|tester| {
7621                let log = Log::default();
7622                let controller = controller(tester);
7623                let menus = TestMenus::all(&log);
7624                pump_material(tester, m3, |_app| {
7625                    MenuBar::new(menus.build())
7626                        .controller(controller)
7627                        .into_widget()
7628                });
7629
7630                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7631                pump(tester);
7632
7633                tester.tap(find::text(&TestMenu::SubMenu11.label()));
7634                pump(tester);
7635
7636                assert_eq!(log.opened(), [TestMenu::MainMenu1, TestMenu::SubMenu11]);
7637                log.opened.borrow_mut().clear();
7638                tester.tap(find::text(&TestMenu::SubSubMenu110.label()));
7639                pump(tester);
7640
7641                assert_eq!(log.selected(), [TestMenu::SubSubMenu110]);
7642
7643                // Selecting a non-submenu item should close all the menus.
7644                assert!(log.opened().is_empty());
7645                assert!(!shows(tester, &TestMenu::SubSubMenu110.label()));
7646                assert!(!shows(tester, &TestMenu::SubMenu11.label()));
7647            });
7648        }
7649
7650        // menu_anchor_test.dart 'menus can be traversed multiple times'.
7651        #[test]
7652        fn menus_can_be_traversed_again_after_escape_closes_them() {
7653            test_widgets(|tester| {
7654                let log = Log::default();
7655                let controller = controller(tester);
7656                let menus = TestMenus::all(&log);
7657                pump_material(tester, m3, |_app| {
7658                    Column::new()
7659                        .children(vec![
7660                            MenuItemButton::new()
7661                                .autofocus(true)
7662                                .on_pressed(Listener::new(|_app| {}))
7663                                .child(Text::new("External Focus"))
7664                                .into_widget(),
7665                            MenuBar::new(menus.build())
7666                                .controller(controller)
7667                                .into_widget(),
7668                        ])
7669                        .into_widget()
7670                });
7671
7672                // Have to open a menu initially to start things going.
7673                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7674                pump(tester);
7675                submenu(tester, "Menu 1");
7676
7677                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
7678                item(tester, "Sub Menu 10");
7679
7680                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
7681                submenu(tester, "Sub Menu 11");
7682
7683                send_key(tester, LogicalKeyboardKey::ESCAPE);
7684                pump(tester);
7685                item(tester, "External Focus");
7686
7687                tester.tap(find::text(&TestMenu::MainMenu1.label()));
7688                pump(tester);
7689                submenu(tester, "Menu 1");
7690
7691                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
7692                item(tester, "Sub Menu 10");
7693
7694                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
7695                submenu(tester, "Sub Menu 11");
7696            });
7697        }
7698
7699        // menu_anchor_test.dart 'keyboard tab traversal works'.
7700        #[test]
7701        fn tab_and_shift_tab_move_between_the_menu_bar_buttons() {
7702            test_widgets(|tester| {
7703                let log = Log::default();
7704                let controller = controller(tester);
7705                let menus = TestMenus::all(&log);
7706                pump_material(tester, m3, |_app| {
7707                    Column::new()
7708                        .children(vec![
7709                            MenuBar::new(menus.build())
7710                                .controller(controller)
7711                                .into_widget(),
7712                            Expanded::new(placeholder()).into_widget(),
7713                        ])
7714                        .into_widget()
7715                });
7716
7717                // Have to open a menu initially to start things going.
7718                tester.tap(find::text(&TestMenu::MainMenu0.label()));
7719                tester.pump_and_settle();
7720
7721                submenu(tester, "Menu 0");
7722                send_key(tester, LogicalKeyboardKey::TAB);
7723                pump(tester);
7724                submenu(tester, "Menu 1");
7725                send_key(tester, LogicalKeyboardKey::TAB);
7726                pump(tester);
7727                submenu(tester, "Menu 2");
7728                send_key(tester, LogicalKeyboardKey::TAB);
7729                pump(tester);
7730                submenu(tester, "Menu 0");
7731
7732                tester.send_key_down_event(
7733                    physical_of(LogicalKeyboardKey::SHIFT_LEFT),
7734                    LogicalKeyboardKey::SHIFT_LEFT,
7735                );
7736                send_key(tester, LogicalKeyboardKey::TAB);
7737                pump(tester);
7738                submenu(tester, "Menu 2");
7739                send_key(tester, LogicalKeyboardKey::TAB);
7740                pump(tester);
7741                submenu(tester, "Menu 1");
7742                send_key(tester, LogicalKeyboardKey::TAB);
7743                pump(tester);
7744                submenu(tester, "Menu 0");
7745                tester.send_key_up_event(
7746                    physical_of(LogicalKeyboardKey::SHIFT_LEFT),
7747                    LogicalKeyboardKey::SHIFT_LEFT,
7748                );
7749                log.clear();
7750
7751                // Test closing a menu with enter.
7752                send_key(tester, LogicalKeyboardKey::ENTER);
7753                pump(tester);
7754                assert!(log.opened().is_empty());
7755                assert_eq!(log.closed(), [TestMenu::MainMenu0]);
7756            });
7757        }
7758
7759        // menu_anchor_test.dart 'keyboard directional traversal works'.
7760        #[test]
7761        fn arrow_keys_move_through_a_menu_bar_and_its_menus() {
7762            test_widgets(|tester| {
7763                let log = Log::default();
7764                let controller = controller(tester);
7765                let menus = TestMenus::all(&log);
7766                pump_material(tester, m3, |_app| {
7767                    MenuBar::new(menus.build())
7768                        .controller(controller)
7769                        .into_widget()
7770                });
7771                let key = |tester: &mut WidgetTester, key| send_key(tester, key);
7772                use LogicalKeyboardKey as K;
7773
7774                // Have to open a menu initially to start things going.
7775                tester.tap(find::text(&TestMenu::MainMenu0.label()));
7776                tester.pump_and_settle();
7777
7778                key(tester, K::ARROW_RIGHT);
7779                pump(tester);
7780                submenu(tester, "Menu 1");
7781
7782                key(tester, K::ARROW_DOWN);
7783                item(tester, "Sub Menu 10");
7784
7785                key(tester, K::ARROW_DOWN);
7786                submenu(tester, "Sub Menu 11");
7787
7788                key(tester, K::ARROW_DOWN);
7789                item(tester, "Sub Menu 12");
7790
7791                key(tester, K::ARROW_DOWN);
7792                item(tester, "Sub Menu 12");
7793
7794                key(tester, K::ARROW_UP);
7795                pump(tester);
7796                submenu(tester, "Sub Menu 11");
7797
7798                // Open the next submenu.
7799                key(tester, K::ARROW_RIGHT);
7800                pump(tester);
7801                item(tester, "Sub Sub Menu 110");
7802
7803                // Go back, close the submenu.
7804                key(tester, K::ARROW_LEFT);
7805                pump(tester);
7806                submenu(tester, "Sub Menu 11");
7807
7808                // Move up, should close the submenu.
7809                key(tester, K::ARROW_UP);
7810                pump(tester);
7811                item(tester, "Sub Menu 10");
7812
7813                // Move down, should reopen the submenu.
7814                key(tester, K::ARROW_DOWN);
7815                pump(tester);
7816                submenu(tester, "Sub Menu 11");
7817
7818                // Open the next submenu again.
7819                key(tester, K::ARROW_RIGHT);
7820                pump(tester);
7821                item(tester, "Sub Sub Menu 110");
7822
7823                key(tester, K::ARROW_DOWN);
7824                item(tester, "Sub Sub Menu 111");
7825
7826                key(tester, K::ARROW_DOWN);
7827                item(tester, "Sub Sub Menu 112");
7828
7829                key(tester, K::ARROW_DOWN);
7830                item(tester, "Sub Sub Menu 113");
7831
7832                key(tester, K::ARROW_DOWN);
7833                item(tester, "Sub Sub Menu 113");
7834
7835                // Since this is a leaf off of a vertical menu, moving left should
7836                // return to this menu's parent button.
7837                key(tester, K::ARROW_LEFT);
7838                submenu(tester, "Sub Menu 11");
7839
7840                // Moving left while in a first-level submenu should focus the
7841                // previous top-level menubar anchor.
7842                key(tester, K::ARROW_LEFT);
7843                pump(tester);
7844                submenu(tester, "Menu 0");
7845
7846                key(tester, K::ARROW_RIGHT);
7847                pump(tester);
7848                submenu(tester, "Menu 1");
7849
7850                // Pressing arrowup from a top-level menubar anchor should focus the last
7851                // item in that anchor's submenu.
7852                key(tester, K::ARROW_UP);
7853                item(tester, "Sub Menu 12");
7854
7855                key(tester, K::ARROW_UP);
7856                submenu(tester, "Sub Menu 11");
7857                pump(tester);
7858
7859                // Enter the submenu.
7860                key(tester, K::ARROW_RIGHT);
7861                item(tester, "Sub Sub Menu 110");
7862
7863                // Move to next top-level menu button.
7864                key(tester, K::ARROW_RIGHT);
7865                pump(tester);
7866                submenu(tester, "Menu 2");
7867            });
7868        }
7869
7870        // menu_anchor_test.dart 'keyboard directional traversal works in RTL mode'.
7871        #[test]
7872        fn arrow_keys_move_through_a_right_to_left_menu_bar_and_its_menus() {
7873            test_widgets(|tester| {
7874                let log = Log::default();
7875                let controller = controller(tester);
7876                let menus = TestMenus::all(&log);
7877                let root = {
7878                    let app = tester.cell.borrow();
7879                    material_app(
7880                        m3(&app),
7881                        Directionality::new(
7882                            TextDirection::Rtl,
7883                            Material::new()
7884                                .child(MenuBar::new(menus.build()).controller(controller)),
7885                        )
7886                        .into_widget(),
7887                    )
7888                };
7889                tester.pump_widget(root);
7890                let key = |tester: &mut WidgetTester, key| send_key(tester, key);
7891                use LogicalKeyboardKey as K;
7892
7893                // Have to open a menu initially to start things going.
7894                tester.tap(find::text(&TestMenu::MainMenu0.label()));
7895                pump(tester);
7896
7897                key(tester, K::ARROW_LEFT);
7898                submenu(tester, "Menu 1");
7899
7900                key(tester, K::ARROW_DOWN);
7901                pump(tester);
7902                submenu(tester, "Menu 1");
7903
7904                key(tester, K::ARROW_DOWN);
7905                item(tester, "Sub Menu 10");
7906
7907                key(tester, K::ARROW_DOWN);
7908                submenu(tester, "Sub Menu 11");
7909
7910                key(tester, K::ARROW_DOWN);
7911                item(tester, "Sub Menu 12");
7912
7913                key(tester, K::ARROW_DOWN);
7914                item(tester, "Sub Menu 12");
7915
7916                key(tester, K::ARROW_UP);
7917                pump(tester);
7918                submenu(tester, "Sub Menu 11");
7919
7920                // Open the next submenu.
7921                key(tester, K::ARROW_LEFT);
7922                pump(tester);
7923                item(tester, "Sub Sub Menu 110");
7924
7925                // Go back, close the submenu.
7926                key(tester, K::ARROW_RIGHT);
7927                pump(tester);
7928                submenu(tester, "Sub Menu 11");
7929
7930                // Move up, should close the submenu.
7931                key(tester, K::ARROW_UP);
7932                pump(tester);
7933                item(tester, "Sub Menu 10");
7934
7935                // Move down, should reopen the submenu.
7936                key(tester, K::ARROW_DOWN);
7937                pump(tester);
7938                submenu(tester, "Sub Menu 11");
7939
7940                // Open the next submenu again.
7941                key(tester, K::ARROW_LEFT);
7942                pump(tester);
7943                item(tester, "Sub Sub Menu 110");
7944
7945                key(tester, K::ARROW_DOWN);
7946                item(tester, "Sub Sub Menu 111");
7947
7948                key(tester, K::ARROW_DOWN);
7949                item(tester, "Sub Sub Menu 112");
7950
7951                key(tester, K::ARROW_DOWN);
7952                item(tester, "Sub Sub Menu 113");
7953
7954                key(tester, K::ARROW_DOWN);
7955                item(tester, "Sub Sub Menu 113");
7956
7957                // Since this is a leaf off of a vertical menu, moving right should
7958                // return to this menu's parent button.
7959                key(tester, K::ARROW_RIGHT);
7960                submenu(tester, "Sub Menu 11");
7961
7962                // Moving left while in a first-level submenu should focus the
7963                // previous top-level menubar anchor.
7964                key(tester, K::ARROW_RIGHT);
7965                pump(tester);
7966                submenu(tester, "Menu 0");
7967
7968                key(tester, K::ARROW_LEFT);
7969                pump(tester);
7970                submenu(tester, "Menu 1");
7971
7972                // Pressing arrowup from a top-level menubar anchor should focus the last
7973                // item in that anchor's submenu.
7974                key(tester, K::ARROW_UP);
7975                item(tester, "Sub Menu 12");
7976
7977                key(tester, K::ARROW_UP);
7978                pump(tester);
7979                submenu(tester, "Sub Menu 11");
7980
7981                // Enter the submenu.
7982                key(tester, K::ARROW_LEFT);
7983                item(tester, "Sub Sub Menu 110");
7984
7985                // Move to next top-level menu button.
7986                key(tester, K::ARROW_LEFT);
7987                pump(tester);
7988                submenu(tester, "Menu 2");
7989            });
7990        }
7991
7992        /// Dart's `MenuAnchor(childFocusNode: buttonFocusNode, menuChildren: [MenuItemButton('start'),
7993        /// ...createTestMenus(..)], builder: TextButton(label))` in a `Column`, under
7994        /// `direction`; answers the button's focus node, labeled 'Press Me'.
7995        fn pump_anchor_with_test_menus(
7996            tester: &mut WidgetTester,
7997            log: &Log,
7998            label: &'static str,
7999            direction: TextDirection,
8000        ) -> AnyFocusNode {
8001            let button_focus_node = {
8002                let mut app = tester.cell.borrow_mut();
8003                let node = FocusNode::new(&mut app).into_erased::<AnyFocusNode>();
8004                node.set_debug_label(&mut app, Some(TestMenu::AnchorButton.label()));
8005                node
8006            };
8007            let menus = TestMenus::all(log);
8008            let mut menu_children = vec![
8009                MenuItemButton::new()
8010                    .on_pressed(Listener::new(|_app| {}))
8011                    .child(Text::new("start"))
8012                    .into_widget(),
8013            ];
8014            menu_children.extend(menus.build());
8015            let anchor = MenuAnchor::new(menu_children)
8016                .child_focus_node(button_focus_node.clone())
8017                .builder({
8018                    let button_focus_node = button_focus_node.clone();
8019                    move |_app, _context, controller, _child| {
8020                        TextButton::new(
8021                            Some(Listener::new(move |app| {
8022                                if controller.is_open(app) {
8023                                    controller.close(app);
8024                                } else {
8025                                    controller.open(app, None);
8026                                }
8027                            })),
8028                            Some(Text::new(label)),
8029                        )
8030                        .focus_node(button_focus_node.clone())
8031                        .into_widget()
8032                    }
8033                });
8034            let root = {
8035                let app = tester.cell.borrow();
8036                material_app(
8037                    m3(&app),
8038                    Directionality::new(
8039                        direction,
8040                        Material::new().child(Column::new().children(vec![anchor.into_widget()])),
8041                    )
8042                    .into_widget(),
8043                )
8044            };
8045            tester.pump_widget(root);
8046            button_focus_node.handle()
8047        }
8048
8049        fn focused_is_anchor_button(tester: &WidgetTester) -> bool {
8050            focused_menu(tester) == Some(TestMenu::AnchorButton.label())
8051        }
8052
8053        // menu_anchor_test.dart 'MenuAnchor tab traversal works'.
8054        #[test]
8055        fn tab_and_shift_tab_move_between_the_items_of_a_menu_anchor() {
8056            test_widgets(|tester| {
8057                let log = Log::default();
8058                pump_anchor_with_test_menus(tester, &log, "Press Me", TextDirection::Ltr);
8059
8060                send_key(tester, LogicalKeyboardKey::TAB);
8061                pump(tester);
8062                assert!(focused_is_anchor_button(tester));
8063
8064                send_key(tester, LogicalKeyboardKey::ENTER);
8065                pump(tester);
8066                assert!(focused_is_anchor_button(tester));
8067
8068                // Directional traversal doesn't work until a menu item is focused.
8069                // To start focusing, hover over the first menu item.
8070                let start = tester.get_rect(find::text("start")).center();
8071                hover_over(tester, start);
8072                pump(tester);
8073                item(tester, "start");
8074
8075                send_key(tester, LogicalKeyboardKey::TAB);
8076                pump(tester);
8077                submenu(tester, "Menu 0");
8078
8079                send_key(tester, LogicalKeyboardKey::TAB);
8080                pump(tester);
8081                submenu(tester, "Menu 1");
8082
8083                send_key(tester, LogicalKeyboardKey::TAB);
8084                pump(tester);
8085                submenu(tester, "Menu 2");
8086
8087                send_key(tester, LogicalKeyboardKey::TAB);
8088                pump(tester);
8089                item(tester, "start");
8090
8091                tester.send_key_down_event(
8092                    physical_of(LogicalKeyboardKey::SHIFT_LEFT),
8093                    LogicalKeyboardKey::SHIFT_LEFT,
8094                );
8095                send_key(tester, LogicalKeyboardKey::TAB);
8096                pump(tester);
8097                submenu(tester, "Menu 2");
8098
8099                send_key(tester, LogicalKeyboardKey::TAB);
8100                pump(tester);
8101                submenu(tester, "Menu 1");
8102
8103                send_key(tester, LogicalKeyboardKey::TAB);
8104                pump(tester);
8105                submenu(tester, "Menu 0");
8106
8107                tester.send_key_up_event(
8108                    physical_of(LogicalKeyboardKey::SHIFT_LEFT),
8109                    LogicalKeyboardKey::SHIFT_LEFT,
8110                );
8111                log.clear();
8112
8113                // Test closing a menu with enter.
8114                send_key(tester, LogicalKeyboardKey::ENTER);
8115                pump(tester);
8116                assert!(log.opened().is_empty());
8117                assert_eq!(log.closed(), [TestMenu::MainMenu0]);
8118            });
8119        }
8120
8121        /// The steps the two 'MenuAnchor * directional traversal works' cases share, with `into`
8122        /// the arrow that enters a submenu and `out` the one that leaves it.
8123        fn anchor_directional_traversal(tester: &mut WidgetTester, direction: TextDirection) {
8124            use LogicalKeyboardKey as K;
8125            let (into, out) = match direction {
8126                TextDirection::Ltr => (K::ARROW_RIGHT, K::ARROW_LEFT),
8127                TextDirection::Rtl => (K::ARROW_LEFT, K::ARROW_RIGHT),
8128            };
8129            let log = Log::default();
8130            pump_anchor_with_test_menus(tester, &log, "Open", direction);
8131
8132            send_key(tester, K::TAB);
8133            assert!(focused_is_anchor_button(tester));
8134
8135            send_key(tester, K::ENTER);
8136            pump(tester);
8137            assert!(focused_is_anchor_button(tester));
8138            assert!(shows(tester, "start"));
8139
8140            // Directional traversal doesn't work until a menu item is focused.
8141            // To start focusing, hover over the first menu item.
8142            let start = tester.get_rect(find::text("start")).center();
8143            hover_over(tester, start);
8144            pump(tester);
8145            item(tester, "start");
8146
8147            send_key(tester, K::ARROW_DOWN);
8148            pump(tester);
8149            submenu(tester, "Menu 0");
8150            assert!(shows(tester, "Sub Menu 00"));
8151
8152            send_key(tester, out);
8153            pump(tester);
8154            submenu(tester, "Menu 0");
8155
8156            send_key(tester, into);
8157            pump(tester);
8158            item(tester, "Sub Menu 00");
8159
8160            send_key(tester, K::ARROW_DOWN);
8161            item(tester, "Sub Menu 01");
8162
8163            send_key(tester, K::ARROW_DOWN);
8164            item(tester, "Sub Menu 02");
8165
8166            // We're at the deepest menu, so the arrow into a submenu should not change focus.
8167            send_key(tester, into);
8168            item(tester, "Sub Menu 02");
8169
8170            // The arrow out of a submenu should move focus to the parent anchor.
8171            send_key(tester, out);
8172            pump(tester);
8173            submenu(tester, "Menu 0");
8174            assert!(!shows(tester, "Sub Menu 00"));
8175
8176            // We're at the root menu, so the arrow out should not change focus and
8177            // should not open the submenu.
8178            send_key(tester, out);
8179            submenu(tester, "Menu 0");
8180            assert!(!shows(tester, "Sub Menu 00"));
8181
8182            // Open the submenu again.
8183            send_key(tester, K::SPACE);
8184            pump(tester);
8185            submenu(tester, "Menu 0");
8186            assert!(shows(tester, "Sub Menu 00"));
8187
8188            // Close all menus.
8189            send_key(tester, K::ESCAPE);
8190            pump(tester);
8191            assert!(focused_is_anchor_button(tester));
8192            expect(tester, &find::by_type::<MenuItemButton>(), finds_nothing());
8193        }
8194
8195        // menu_anchor_test.dart 'MenuAnchor LTR directional traversal works'.
8196        #[test]
8197        fn arrow_keys_move_through_a_menu_anchor_left_to_right() {
8198            test_widgets(|tester| anchor_directional_traversal(tester, TextDirection::Ltr));
8199        }
8200
8201        // menu_anchor_test.dart 'MenuAnchor RTL directional traversal works'.
8202        #[test]
8203        fn arrow_keys_move_through_a_menu_anchor_right_to_left() {
8204            test_widgets(|tester| anchor_directional_traversal(tester, TextDirection::Rtl));
8205        }
8206
8207        /// Dart's `listenForFocusChanges()`: the `focusedMenu` a `FocusManager` listener keeps,
8208        /// `None` until focus first changes.
8209        fn listen_for_focus_changes(tester: &WidgetTester) -> Rc<RefCell<Option<String>>> {
8210            let focused_menu: Rc<RefCell<Option<String>>> = Rc::default();
8211            let sink = Rc::clone(&focused_menu);
8212            let mut app = tester.cell.borrow_mut();
8213            let manager = FocusManager::instance(&mut app);
8214            waft_foundation::ListenableObject::add_listener(
8215                manager,
8216                &mut app,
8217                Listener::new(move |app| {
8218                    let label = primary_focus(app)
8219                        .map(|node| node.debug_label(app).unwrap_or_else(|| format!("{node:?}")));
8220                    *sink.borrow_mut() = label;
8221                }),
8222            );
8223            focused_menu
8224        }
8225
8226        /// One mouse that Dart's successive `hoverOver` calls move around.
8227        struct Mouse(TestPointer);
8228
8229        impl Mouse {
8230            fn new(tester: &mut WidgetTester) -> Mouse {
8231                let mut mouse = TestPointer::mouse(1, 0);
8232                tester.add_pointer(&mut mouse, Offset::ZERO);
8233                Mouse(mouse)
8234            }
8235
8236            /// Dart's `hoverOver(tester, find.text(text))`, then the case's `tester.pump()`.
8237            fn hover_text(&mut self, tester: &mut WidgetTester, text: &str) {
8238                let at = tester.get_rect(find::text(text)).center();
8239                tester.move_to(&mut self.0, at, false);
8240                pump(tester);
8241            }
8242
8243            /// Dart's `pointer.scroll(delta)`: a scroll signal where the mouse is.
8244            fn scroll(&self, tester: &mut WidgetTester, delta: Offset) {
8245                use waft_embedder::{
8246                    PointerChange, PointerData, PointerDataPacket, PointerSignalKind,
8247                };
8248                let mut app = tester.cell.borrow_mut();
8249                waft_gestures::GestureBinding::instance(&mut app).handle_pointer_data_packet(
8250                    &mut app,
8251                    PointerDataPacket::new(vec![PointerData {
8252                        change: PointerChange::Hover,
8253                        kind: self.0.kind,
8254                        device: self.0.id,
8255                        pointer_identifier: self.0.id,
8256                        signal_kind: Some(PointerSignalKind::Scroll),
8257                        physical_x: self.0.position.dx() * 2.0,
8258                        physical_y: self.0.position.dy() * 2.0,
8259                        scroll_delta_x: delta.dx() * 2.0,
8260                        scroll_delta_y: delta.dy() * 2.0,
8261                        ..PointerData::default()
8262                    }]),
8263                );
8264                app.drain_microtasks();
8265                drop(app);
8266                tester.cell.checkpoint();
8267            }
8268        }
8269
8270        // menu_anchor_test.dart 'hover traversal works'.
8271        #[test]
8272        fn hovering_opens_and_focuses_menus_once_one_is_open() {
8273            test_widgets(|tester| {
8274                let log = Log::default();
8275                let controller = controller(tester);
8276                let menus = TestMenus::all(&log);
8277                pump_material(tester, m3, |_app| {
8278                    MenuBar::new(menus.build())
8279                        .controller(controller)
8280                        .into_widget()
8281                });
8282
8283                let focused_menu = listen_for_focus_changes(tester);
8284                let focused = |text: &str, type_name: &str| {
8285                    assert_eq!(*focused_menu.borrow(), Some(button_label(type_name, text)));
8286                };
8287                let mut mouse = Mouse::new(tester);
8288
8289                // Hovering when the menu is not yet open does nothing.
8290                mouse.hover_text(tester, &TestMenu::MainMenu0.label());
8291                pump(tester);
8292                assert_eq!(*focused_menu.borrow(), None);
8293
8294                // Have to open a menu initially to start things going.
8295                tester.tap(find::text(&TestMenu::MainMenu0.label()));
8296                pump(tester);
8297                focused("Menu 0", "SubmenuButton");
8298
8299                // Hovering when the menu is already  open does nothing.
8300                mouse.hover_text(tester, &TestMenu::MainMenu0.label());
8301                pump(tester);
8302                focused("Menu 0", "SubmenuButton");
8303
8304                // Hovering over the other main menu items opens them now.
8305                mouse.hover_text(tester, &TestMenu::MainMenu2.label());
8306                pump(tester);
8307                focused("Menu 2", "SubmenuButton");
8308
8309                mouse.hover_text(tester, &TestMenu::MainMenu1.label());
8310                pump(tester);
8311                focused("Menu 1", "SubmenuButton");
8312
8313                // Hovering over the menu items focuses them.
8314                mouse.hover_text(tester, &TestMenu::SubMenu10.label());
8315                pump(tester);
8316                focused("Sub Menu 10", "MenuItemButton");
8317
8318                mouse.hover_text(tester, &TestMenu::SubMenu11.label());
8319                pump(tester);
8320                focused("Sub Menu 11", "SubmenuButton");
8321
8322                mouse.hover_text(tester, &TestMenu::SubSubMenu110.label());
8323                pump(tester);
8324                focused("Sub Sub Menu 110", "MenuItemButton");
8325            });
8326        }
8327
8328        // menu_anchor_test.dart 'hover traversal invalidates directional focus scope data'.
8329        #[test]
8330        fn hovering_resets_where_directional_traversal_starts() {
8331            test_widgets(|tester| {
8332                let log = Log::default();
8333                let controller = controller(tester);
8334                let menus = TestMenus::all(&log);
8335                pump_material(tester, m3, |_app| {
8336                    MenuBar::new(menus.build())
8337                        .controller(controller)
8338                        .into_widget()
8339                });
8340                let mut mouse = Mouse::new(tester);
8341
8342                // Have to open a menu initially to start things going.
8343                tester.tap(find::text(&TestMenu::MainMenu1.label()));
8344                pump(tester);
8345                submenu(tester, "Menu 1");
8346
8347                mouse.hover_text(tester, &TestMenu::SubMenu12.label());
8348                pump(tester);
8349                item(tester, "Sub Menu 12");
8350
8351                // Move pointer to disabled menu.
8352                mouse.hover_text(tester, &TestMenu::MainMenu5.label());
8353                pump(tester);
8354                item(tester, "Sub Menu 12");
8355
8356                send_key(tester, LogicalKeyboardKey::ARROW_UP);
8357                pump(tester);
8358                submenu(tester, "Sub Menu 11");
8359
8360                send_key(tester, LogicalKeyboardKey::ARROW_UP);
8361                item(tester, "Sub Menu 10");
8362
8363                mouse.hover_text(tester, &TestMenu::SubMenu12.label());
8364                pump(tester);
8365                item(tester, "Sub Menu 12");
8366
8367                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
8368                item(tester, "Sub Menu 12");
8369            });
8370        }
8371
8372        /// Dart's `SubmenuButton(hoverOpenDelay: 500ms, menuChildren: [Item 0], child: 'Submenu')`,
8373        /// under a `Text('Outside')` when `outside` is set.
8374        fn pump_delayed_submenu(tester: &mut WidgetTester, outside: bool) {
8375            pump_material(tester, m3, move |_app| {
8376                let submenu = SubmenuButton::new(
8377                    vec![
8378                        MenuItemButton::new()
8379                            .on_pressed(Listener::new(|_app| {}))
8380                            .child(Text::new("Item 0"))
8381                            .into_widget(),
8382                    ],
8383                    Some(Text::new("Submenu")),
8384                )
8385                .hover_open_delay(Duration::from_millis(500))
8386                .into_widget();
8387                if outside {
8388                    Column::new()
8389                        .children(vec![Text::new("Outside").into_widget(), submenu])
8390                        .into_widget()
8391                } else {
8392                    submenu
8393                }
8394            });
8395        }
8396
8397        // menu_anchor_test.dart 'hoverOpenDelay delays when a SubmenuButton opens'.
8398        #[test]
8399        fn a_hover_open_delay_holds_back_the_submenu() {
8400            test_widgets(|tester| {
8401                pump_delayed_submenu(tester, false);
8402                let mut mouse = Mouse::new(tester);
8403
8404                // Hover over the submenu button
8405                mouse.hover_text(tester, "Submenu");
8406                tester.pump_by(Duration::from_millis(499));
8407
8408                assert!(!shows(tester, "Item 0"));
8409
8410                tester.pump_by(Duration::from_millis(1));
8411
8412                // Menu should now be open
8413                assert!(shows(tester, "Item 0"));
8414            });
8415        }
8416
8417        // menu_anchor_test.dart 'hoverOpenDelay can be cancelled'.
8418        #[test]
8419        fn leaving_the_button_cancels_a_hover_open_delay() {
8420            test_widgets(|tester| {
8421                pump_delayed_submenu(tester, true);
8422                let mut mouse = Mouse::new(tester);
8423
8424                // Hover over the submenu button
8425                mouse.hover_text(tester, "Submenu");
8426                tester.pump_by(Duration::from_millis(499));
8427
8428                assert!(!shows(tester, "Item 0"));
8429
8430                // Move hover away before the delay completes
8431                mouse.hover_text(tester, "Outside");
8432                tester.pump_by(Duration::from_millis(1));
8433
8434                assert!(!shows(tester, "Item 0"));
8435            });
8436        }
8437
8438        // menu_anchor_test.dart 'hoverOpenDelay restarts after cancellation'.
8439        #[test]
8440        fn a_hover_open_delay_starts_over_after_it_is_cancelled() {
8441            test_widgets(|tester| {
8442                pump_delayed_submenu(tester, true);
8443                let mut mouse = Mouse::new(tester);
8444
8445                mouse.hover_text(tester, "Submenu");
8446                tester.pump_by(Duration::from_millis(499));
8447
8448                assert!(!shows(tester, "Item 0"));
8449
8450                mouse.hover_text(tester, "Outside");
8451                tester.pump_by(Duration::from_millis(1));
8452
8453                assert!(!shows(tester, "Item 0"));
8454
8455                mouse.hover_text(tester, "Submenu");
8456                tester.pump_by(Duration::from_millis(500));
8457
8458                assert!(shows(tester, "Item 0"));
8459            });
8460        }
8461
8462        // menu_anchor_test.dart 'Throws if non-zero hoverOpenDelay is applied to MenuBar items'.
8463        #[test]
8464        #[should_panic(
8465            expected = "A non-zero hoverOpenDelay was used in a top-level SubmenuButton situated in a MenuBar"
8466        )]
8467        fn a_hover_open_delay_on_a_menu_bar_button_panics_in_a_debug_build() {
8468            test_widgets(|tester| {
8469                pump_material(tester, m3, |_app| {
8470                    MenuBar::new(vec![
8471                        SubmenuButton::new(
8472                            vec![
8473                                MenuItemButton::new()
8474                                    .on_pressed(Listener::new(|_app| {}))
8475                                    .child(Text::new("Item 0"))
8476                                    .into_widget(),
8477                            ],
8478                            Some(Text::new("Submenu")),
8479                        )
8480                        .hover_open_delay(Duration::from_millis(1))
8481                        .into_widget(),
8482                    ])
8483                    .into_widget()
8484                });
8485            });
8486        }
8487
8488        // menu_anchor_test.dart 'scrolling does not trigger hover traversal'.
8489        #[test]
8490        fn scrolling_a_menu_under_the_pointer_does_not_move_focus() {
8491            test_widgets(|tester| {
8492                let controller = controller(tester);
8493                let scrolled_menu_item_key = GlobalKey::new();
8494                let key = scrolled_menu_item_key.clone();
8495                pump_material(tester, m3, {
8496                    let controller = controller.clone();
8497                    move |_app| {
8498                        let menu_children = (0..20)
8499                            .map(|i| {
8500                                let mut button = MenuItemButton::new()
8501                                    .on_pressed(Listener::new(|_app| {}))
8502                                    .child(Text::new(format!("Item {i}")));
8503                                if i == 15 {
8504                                    button = button.key(key.clone().into());
8505                                }
8506                                button.into_widget()
8507                            })
8508                            .collect();
8509                        MenuAnchor::new(menu_children)
8510                            .style(MenuStyle::new().fixed_size(Rc::new(
8511                                waft_widgets::WidgetStatePropertyAll::new(Some(Size::from_height(
8512                                    200.0,
8513                                ))),
8514                            )))
8515                            .controller(controller.clone())
8516                            .into_widget()
8517                    }
8518                });
8519
8520                let focused_menu = listen_for_focus_changes(tester);
8521                let focused = |text: &str| {
8522                    assert_eq!(
8523                        *focused_menu.borrow(),
8524                        Some(button_label("MenuItemButton", text))
8525                    );
8526                };
8527
8528                controller.open(&mut tester.cell.borrow_mut(), None);
8529                tester.pump_and_settle();
8530
8531                let mut mouse = Mouse::new(tester);
8532                mouse.hover_text(tester, "Item 1");
8533                pump(tester);
8534                focused("Item 1");
8535
8536                // Scroll the menu while the pointer is over a menu item. The focus should
8537                // not change.
8538                let item_15 = tester.element(find::text("Item 15"));
8539                {
8540                    let mut app = tester.cell.borrow_mut();
8541                    let render = item_15.find_render_object(&app).expect("laid out");
8542                    render.show_on_screen(
8543                        &mut app,
8544                        None,
8545                        None,
8546                        Duration::ZERO,
8547                        waft_animation::Curves::ease(),
8548                    );
8549                }
8550                tester.pump_and_settle();
8551                focused("Item 1");
8552
8553                // Traverse with the keyboard to test that the menu scrolls without hover
8554                // focus affecting the focused menu.
8555                for i in 2..20 {
8556                    send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
8557                    pump(tester);
8558                    focused(&format!("Item {i}"));
8559                }
8560            });
8561        }
8562
8563        /// Dart's `SingleChildScrollView(controller: scroll_controller, child: Container(height:
8564        /// 1000, alignment: alignment, child: child))`.
8565        fn tall_scroll_view(
8566            scroll_controller: waft_widgets::ScrollControllerRef,
8567            alignment: AlignmentGeometry,
8568            child: WidgetRef,
8569        ) -> WidgetRef {
8570            SingleChildScrollView::new()
8571                .controller(scroll_controller)
8572                .child(
8573                    Container::new()
8574                        .height(1000.0)
8575                        .alignment(alignment)
8576                        .child(child),
8577                )
8578                .into_widget()
8579        }
8580
8581        // menu_anchor_test.dart 'menus close on ancestor scroll'.
8582        #[test]
8583        fn menus_close_when_an_ancestor_scrolls() {
8584            test_widgets(|tester| {
8585                let log = Log::default();
8586                let controller = controller(tester);
8587                let scroll_controller = ScrollController::default(&mut tester.cell.borrow_mut())
8588                    .into_erased::<waft_widgets::AnyScrollController>();
8589                let menus = TestMenus::all(&log);
8590                pump_material(tester, m3, |_app| {
8591                    tall_scroll_view(
8592                        scroll_controller.clone(),
8593                        AlignmentGeometry::CENTER,
8594                        MenuBar::new(menus.build())
8595                            .controller(controller)
8596                            .into_widget(),
8597                    )
8598                });
8599
8600                tester.tap(find::text(&TestMenu::MainMenu0.label()));
8601                pump(tester);
8602
8603                assert!(!log.opened().is_empty());
8604                assert!(log.closed().is_empty());
8605                log.opened.borrow_mut().clear();
8606
8607                scroll_controller.jump_to(&mut tester.cell.borrow_mut(), 1000.0);
8608                pump(tester);
8609
8610                assert!(log.opened().is_empty());
8611                assert!(!log.closed().is_empty());
8612            });
8613        }
8614
8615        // menu_anchor_test.dart 'menus do not close on root menu internal scroll'.
8616        #[test]
8617        fn menus_stay_open_when_the_root_menu_scrolls_itself() {
8618            test_widgets(|tester| {
8619                let log = Log::default();
8620                let controller = controller(tester);
8621                let scroll_controller = ScrollController::default(&mut tester.cell.borrow_mut())
8622                    .into_erased::<waft_widgets::AnyScrollController>();
8623                let root_opened = Rc::new(Cell::new(false));
8624                let (opened, closed) = (Rc::clone(&root_opened), Rc::clone(&root_opened));
8625                let menus = TestMenus {
8626                    include_extra_groups: true,
8627                    ..TestMenus::all(&log)
8628                };
8629                let root = {
8630                    let app = tester.cell.borrow();
8631                    let theme = ThemeData::builder()
8632                        .menu_button_theme(
8633                            crate::menu_button_theme::MenuButtonThemeData::new().style(
8634                                // Increase menu items height to make root menu scrollable.
8635                                TextButton::style_from()
8636                                    .minimum_size(Size::from_height(200.0))
8637                                    .build(),
8638                            ),
8639                        )
8640                        .build(&app);
8641                    let anchor = MenuAnchor::new(menus.build())
8642                        .controller(controller)
8643                        .alignment_offset(Offset::new(0.0, 10.0))
8644                        .builder(|_app, _context, controller, _child| {
8645                            FilledButton::tonal(
8646                                Some(Listener::new(move |app| {
8647                                    if controller.is_open(app) {
8648                                        controller.close(app);
8649                                    } else {
8650                                        controller.open(app, None);
8651                                    }
8652                                })),
8653                                Some(Text::new("Show menu")),
8654                            )
8655                            .into_widget()
8656                        })
8657                        .on_open(Rc::new(move |_app: &mut App| opened.set(true)))
8658                        .on_close(Rc::new(move |_app: &mut App| closed.set(false)));
8659                    material_app(
8660                        theme,
8661                        Material::new()
8662                            .child(tall_scroll_view(
8663                                scroll_controller.clone(),
8664                                AlignmentGeometry::TOP_LEFT,
8665                                anchor.into_widget(),
8666                            ))
8667                            .into_widget(),
8668                    )
8669                };
8670                tester.pump_widget(root);
8671
8672                tester.tap(find::text("Show menu"));
8673                pump(tester);
8674                assert!(root_opened.get());
8675
8676                // Hover the first item.
8677                let mut mouse = Mouse::new(tester);
8678                mouse.hover_text(tester, &TestMenu::MainMenu0.label());
8679                assert!(!log.opened().is_empty());
8680
8681                // Menus do not close on internal scroll.
8682                mouse.scroll(tester, Offset::new(0.0, 30.0));
8683                pump(tester);
8684                assert!(root_opened.get());
8685                assert!(log.closed().is_empty());
8686
8687                // Menus close on external scroll.
8688                scroll_controller.jump_to(&mut tester.cell.borrow_mut(), 1000.0);
8689                pump(tester);
8690                assert!(!root_opened.get());
8691                assert!(!log.closed().is_empty());
8692            });
8693        }
8694
8695        // menu_anchor_test.dart 'menus close on view size change'.
8696        #[test]
8697        fn menus_close_when_the_view_size_changes() {
8698            test_widgets(|tester| {
8699                let log = Log::default();
8700                let controller = controller(tester);
8701                let scroll_controller = ScrollController::default(&mut tester.cell.borrow_mut())
8702                    .into_erased::<waft_widgets::AnyScrollController>();
8703                let build = |tester: &mut WidgetTester, size: Option<Size>| {
8704                    let menus = TestMenus::all(&log);
8705                    let (scroll_controller, controller) =
8706                        (scroll_controller.clone(), controller.clone());
8707                    pump_material(tester, m3, move |_app| {
8708                        waft_widgets::Builder::new(move |app, context| {
8709                            let view = waft_widgets::View::of(app, context);
8710                            let mut data = MediaQueryData::from_view(app, &*view, None);
8711                            if let Some(size) = size {
8712                                data = data.size(size);
8713                            }
8714                            MediaQuery::new(
8715                                data,
8716                                tall_scroll_view(
8717                                    scroll_controller.clone(),
8718                                    AlignmentGeometry::CENTER,
8719                                    MenuBar::new(menus.build())
8720                                        .controller(controller.clone())
8721                                        .into_widget(),
8722                                ),
8723                            )
8724                            .into_widget()
8725                        })
8726                        .into_widget()
8727                    });
8728                };
8729
8730                build(tester, None);
8731
8732                tester.tap(find::text(&TestMenu::MainMenu0.label()));
8733                pump(tester);
8734
8735                assert!(!log.opened().is_empty());
8736                assert!(log.closed().is_empty());
8737                log.opened.borrow_mut().clear();
8738
8739                let small_size = Size::new(200.0, 200.0);
8740                build(tester, Some(small_size));
8741                pump(tester);
8742
8743                assert!(log.opened().is_empty());
8744                assert!(!log.closed().is_empty());
8745            });
8746        }
8747
8748        // menu_anchor_test.dart 'Shortcuts of MenuAnchor do not rely on WidgetsApp.shortcuts'.
8749        #[test]
8750        fn a_menu_anchor_traverses_with_arrow_keys_without_the_apps_shortcuts() {
8751            test_widgets(|tester| {
8752                let child_node = {
8753                    let mut app = tester.cell.borrow_mut();
8754                    let node = FocusNode::new(&mut app).into_erased::<AnyFocusNode>();
8755                    node.set_debug_label(&mut app, Some("Dropdown Inkwell".to_string()));
8756                    node
8757                };
8758                let root = {
8759                    let app = tester.cell.borrow();
8760                    let menu_children = (0..3)
8761                        .map(|i| {
8762                            MenuItemButton::new()
8763                                .child(Text::new(format!("Submenu item {i}")))
8764                                .on_pressed(Listener::new(|_app| {}))
8765                                .into_widget()
8766                        })
8767                        .collect();
8768                    let anchor = MenuAnchor::new(menu_children)
8769                        .child_focus_node(child_node.clone())
8770                        .builder(move |_app, _context, controller, _child| {
8771                            crate::ink_well::InkWell::new()
8772                                .focus_node(child_node.clone())
8773                                .on_tap(Listener::new(move |app| controller.open(app, None)))
8774                                .child(Text::new("Main button"))
8775                                .into_widget()
8776                        });
8777                    crate::app::MaterialApp::new()
8778                        // Clear WidgetsApp.shortcuts to make sure MenuAnchor doesn't rely on
8779                        // it.
8780                        .shortcuts(Vec::new())
8781                        .theme(m3(&app))
8782                        .home(crate::scaffold::Scaffold::new().body(anchor))
8783                        .into_widget()
8784                };
8785                tester.pump_widget(root);
8786
8787                // Open the drop down menu and focus on the MenuAnchor.
8788                tester.tap(find::text("Main button"));
8789                tester.pump_and_settle();
8790                assert!(shows(tester, "Submenu item 0"));
8791
8792                // Press arrowDown, and the first submenu button should be focused.
8793                // This is the critical part. It used to not work on Web.
8794                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
8795                pump(tester);
8796                item(tester, "Submenu item 0");
8797
8798                // Press arrowDown, and the second submenu button should be focused.
8799                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
8800                pump(tester);
8801                item(tester, "Submenu item 1");
8802            });
8803        }
8804
8805        /// Dart's `MaterialApp(theme: ThemeData(scrollbarTheme:), home: Material(child: MenuBar(
8806        /// [SubmenuButton('Main Menu', [MenuItemButton('Category') 1000 tall])])))`, the bar under
8807        /// a `ScrollbarTheme` of `local_theme` when one is given.
8808        fn pump_tall_menu(
8809            tester: &mut WidgetTester,
8810            scrollbar_theme: crate::scrollbar_theme::ScrollbarThemeData,
8811            local_theme: Option<crate::scrollbar_theme::ScrollbarThemeData>,
8812        ) {
8813            let root = {
8814                let app = tester.cell.borrow();
8815                let bar = MenuBar::new(vec![
8816                    SubmenuButton::new(
8817                        vec![
8818                            MenuItemButton::new()
8819                                .style(ButtonStyle::new().minimum_size(Rc::new(
8820                                    waft_widgets::WidgetStatePropertyAll::new(Some(
8821                                        Size::from_height(1000.0),
8822                                    )),
8823                                )))
8824                                .on_pressed(Listener::new(|_app| {}))
8825                                .child(Text::new("Category"))
8826                                .into_widget(),
8827                        ],
8828                        Some(Text::new("Main Menu")),
8829                    )
8830                    .into_widget(),
8831                ])
8832                .into_widget();
8833                let home = match local_theme {
8834                    Some(local_theme) => {
8835                        crate::scrollbar_theme::ScrollbarTheme::new(local_theme, bar).into_widget()
8836                    }
8837                    None => bar,
8838                };
8839                material_app(
8840                    ThemeData::builder()
8841                        .scrollbar_theme(scrollbar_theme)
8842                        .build(&app),
8843                    Material::new().child(home).into_widget(),
8844                )
8845            };
8846            tester.pump_widget(root);
8847        }
8848
8849        /// Dart's `expect(find.byType(Scrollbar).last, paints..rrect(color: color))`: what the
8850        /// foreground painter under the last `Scrollbar` paints, painted on its own.
8851        fn last_scrollbar_paints_a_path_in(tester: &WidgetTester, color: u32) -> bool {
8852            let scrollbar = tester.element(find::by_type::<crate::scrollbar::Scrollbar>().last());
8853            let mut app = tester.cell.borrow_mut();
8854            let render = scrollbar.find_render_object(&app).expect("laid out");
8855            let mut pending = vec![render];
8856            let mut painter = None;
8857            while let Some(object) = pending.pop() {
8858                if let Some(custom_paint) =
8859                    object.downcast::<waft_rendering::RenderCustomPaint>(&app)
8860                    && let Some(foreground) = custom_paint.foreground_painter(&app)
8861                {
8862                    painter = Some((
8863                        foreground,
8864                        waft_rendering::RenderBox::size(custom_paint, &app),
8865                    ));
8866                    break;
8867                }
8868                object.visit_children(&app, &mut |child| pending.push(child));
8869            }
8870            let (painter, size) = painter.expect("a foreground painter under the Scrollbar");
8871            let mut canvas = waft_embedder::Canvas::new();
8872            painter.paint(&mut app, &mut canvas, size);
8873            paints(
8874                canvas.build().ops(),
8875                &[PaintCall::rrect(Some(Color::new(color)))],
8876            )
8877            .is_ok()
8878        }
8879
8880        // menu_anchor_test.dart 'Menu scrollbar inherits ScrollbarTheme'
8881        // (TargetPlatformVariant.desktop()).
8882        #[test]
8883        fn a_menus_scrollbar_takes_the_ambient_scrollbar_theme() {
8884            for platform in [
8885                TargetPlatform::Linux,
8886                TargetPlatform::MacOS,
8887                TargetPlatform::Windows,
8888            ] {
8889                test_widgets(|_| {
8890                    let mut tester = WidgetTester::on(platform);
8891                    let tester = &mut tester;
8892                    let scrollbar_theme = crate::scrollbar_theme::ScrollbarThemeData::new()
8893                        .thumb_color(Rc::new(waft_widgets::WidgetStatePropertyAll::new(Some(
8894                            Color::new(0xffff0000),
8895                        ))))
8896                        .thumb_visibility(Rc::new(waft_widgets::WidgetStatePropertyAll::new(
8897                            Some(true),
8898                        )));
8899                    pump_tall_menu(tester, scrollbar_theme.clone(), None);
8900
8901                    tester.tap(find::text("Main Menu"));
8902                    tester.pump_and_settle();
8903
8904                    // Test Scrollbar thumb color.
8905                    assert!(last_scrollbar_paints_a_path_in(tester, 0xffff0000));
8906
8907                    // Close the menu.
8908                    tester.tap_at(Offset::new(10.0, 10.0), 1);
8909                    tester.pump_and_settle();
8910
8911                    let local_theme = scrollbar_theme.copy_with().thumb_color(Rc::new(
8912                        waft_widgets::WidgetStatePropertyAll::new(Some(Color::new(0xff00ff00))),
8913                    ));
8914                    pump_tall_menu(tester, scrollbar_theme, Some(local_theme));
8915
8916                    tester.tap(find::text("Main Menu"));
8917                    tester.pump_and_settle();
8918
8919                    // Scrollbar thumb color should be updated.
8920                    assert!(last_scrollbar_paints_a_path_in(tester, 0xff00ff00));
8921                });
8922            }
8923        }
8924
8925        // menu_anchor_test.dart 'Menu scrollbar does not inherit MediaQuery padding' (material_ui).
8926        #[test]
8927        fn a_menus_scrollbar_does_not_inherit_the_media_query_padding() {
8928            test_widgets(|tester| {
8929                use waft_rendering::testing::RecordedCall;
8930                use waft_widgets::{Scrollable, ScrollableState, ScrollbarPainterRef};
8931
8932                use crate::scrollbar::Scrollbar;
8933                use crate::text_button::TextButton;
8934
8935                tester.view().set_device_pixel_ratio(1.0);
8936                tester.view().set_padding(waft_embedder::ViewPadding {
8937                    left: 8.0,
8938                    top: 16.0,
8939                    right: 32.0,
8940                    bottom: 24.0,
8941                });
8942                let menu_item_padding: Rc<Cell<Option<EdgeInsets>>> = Rc::default();
8943                let controller: MenuControllerRef =
8944                    MenuController::new(&mut tester.cell.borrow_mut()).into_erased();
8945
8946                let mut menu_children = vec![
8947                    waft_widgets::Builder::new({
8948                        let menu_item_padding = Rc::clone(&menu_item_padding);
8949                        move |app, context| {
8950                            menu_item_padding.set(Some(MediaQuery::padding_of(app, context)));
8951                            MenuItemButton::new()
8952                                .on_pressed(Listener::new(|_app| {}))
8953                                .child(Text::new("Item 0"))
8954                                .into_widget()
8955                        }
8956                    })
8957                    .into_widget(),
8958                ];
8959                menu_children.extend((1..4).map(|i| {
8960                    MenuItemButton::new()
8961                        .on_pressed(Listener::new(|_app| {}))
8962                        .child(Text::new(format!("Item {i}")))
8963                        .into_widget()
8964                }));
8965                let anchor = MenuAnchor::new(menu_children)
8966                    .controller(controller)
8967                    .style(MenuStyle::new().maximum_size(Rc::new(
8968                        waft_widgets::WidgetStatePropertyAll::new(Some(Size::from_height(100.0))),
8969                    )))
8970                    .builder(|_app, _context, controller, _child| {
8971                        TextButton::new(
8972                            Some(Listener::new(move |app| controller.open(app, None))),
8973                            Some(Text::new("Open menu")),
8974                        )
8975                        .into_widget()
8976                    });
8977                tester.pump_widget(
8978                    crate::app::MaterialApp::new()
8979                        .home(Material::new().child(anchor))
8980                        .into_widget(),
8981                );
8982
8983                tester.tap(find::text("Open menu"));
8984                tester.pump_and_settle();
8985
8986                let scrollbar_painter = tester.widget(
8987                    find::descendant(
8988                        find::by_type::<Scrollbar>(),
8989                        find::by_widget_predicate(
8990                            "a CustomPaint with a ScrollbarPainter",
8991                            |_app, widget| {
8992                                waft_widgets::downcast_widget::<waft_widgets::CustomPaint>(widget)
8993                                    .and_then(|custom_paint| {
8994                                        custom_paint.foreground_painter.as_ref()
8995                                    })
8996                                    .is_some_and(|painter| {
8997                                        painter
8998                                            .as_any()
8999                                            .downcast_ref::<ScrollbarPainterRef>()
9000                                            .is_some()
9001                                    })
9002                            },
9003                        ),
9004                    ),
9005                    |custom_paint: &waft_widgets::CustomPaint| {
9006                        custom_paint
9007                            .foreground_painter
9008                            .as_ref()
9009                            .and_then(|painter| {
9010                                painter
9011                                    .as_any()
9012                                    .downcast_ref::<ScrollbarPainterRef>()
9013                                    .cloned()
9014                            })
9015                            .expect("a ScrollbarPainter")
9016                    },
9017                );
9018                // The scrollbar ignores the view padding, but the menu children still
9019                // observe it.
9020                assert_eq!(
9021                    scrollbar_painter.painter().padding(&tester.cell.borrow()),
9022                    EdgeInsets::ZERO.into()
9023                );
9024                assert_eq!(
9025                    menu_item_padding.get(),
9026                    Some(EdgeInsets::from_ltrb(8.0, 16.0, 32.0, 24.0))
9027                );
9028
9029                // The menu scrolls all the way to the bottom and the scrollbar thumb
9030                // reaches the end of its track instead of stopping short of it.
9031                let scrollable = tester.element(find::descendant(
9032                    find::by_type::<Scrollbar>(),
9033                    find::by_type::<Scrollable>(),
9034                ));
9035                let position = scrollable
9036                    .state_handle::<ScrollableState>(&tester.cell.borrow())
9037                    .expect("a Scrollable element holds a ScrollableState")
9038                    .position(&tester.cell.borrow());
9039                assert!(position.max_scroll_extent(&tester.cell.borrow()) > 0.0);
9040                tester.drag(find::by_type::<Scrollbar>(), Offset::new(0.0, -200.0));
9041                tester.pump_and_settle();
9042                {
9043                    let app = tester.cell.borrow();
9044                    assert_eq!(position.pixels(&app), position.max_scroll_extent(&app));
9045                }
9046
9047                // The thumb is painted at the very end of the track rather than stopping
9048                // short of it by the height of the removed bottom padding.
9049                let scrollbar_extent = tester.get_size(find::by_type::<Scrollbar>()).height();
9050                let scrollbar = tester.render_object(find::by_type::<Scrollbar>());
9051                waft_rendering::testing::assert_paints(
9052                    &tester.painted_ops_deep(scrollbar),
9053                    &[PaintCall::something(move |call| {
9054                        // The thumb is a rect on Android and a rounded rect elsewhere. The
9055                        // track shares the same shape but always starts at the top, so only
9056                        // the thumb is considered here.
9057                        let shape = match call {
9058                            RecordedCall::Rect { rect, .. } => Some(*rect),
9059                            RecordedCall::RRect { bounds, .. } => Some(*bounds),
9060                            _ => None,
9061                        };
9062                        Ok(shape.is_some_and(|shape| {
9063                            shape.top > 0.0
9064                                && (shape.bottom - scrollbar_extent).abs()
9065                                    <= f64::from(f32::EPSILON) * scrollbar_extent.max(1.0)
9066                        }))
9067                    })],
9068                );
9069            });
9070        }
9071    }
9072
9073    /// The 'Accelerators', 'MenuController' and 'MenuItemButton' groups.
9074    mod items {
9075        use std::cell::Cell;
9076        use std::panic::{AssertUnwindSafe, catch_unwind};
9077
9078        use waft_widgets::{Center, SizedBox};
9079
9080        use super::*;
9081        use crate::badge::Badge;
9082        use crate::filled_button::FilledButton;
9083        use crate::scaffold::Scaffold;
9084
9085        const ALL_PLATFORMS: [TargetPlatform; 6] = [
9086            TargetPlatform::Android,
9087            TargetPlatform::Fuchsia,
9088            TargetPlatform::IOS,
9089            TargetPlatform::Linux,
9090            TargetPlatform::MacOS,
9091            TargetPlatform::Windows,
9092        ];
9093
9094        const NON_APPLE_PLATFORMS: [TargetPlatform; 4] = [
9095            TargetPlatform::Android,
9096            TargetPlatform::Fuchsia,
9097            TargetPlatform::Linux,
9098            TargetPlatform::Windows,
9099        ];
9100
9101        const APPLE_PLATFORMS: [TargetPlatform; 2] = [TargetPlatform::IOS, TargetPlatform::MacOS];
9102
9103        /// Dart's `tester.sendKeyEvent(key, character: character)`.
9104        fn send_key_with_character(
9105            tester: &mut WidgetTester,
9106            logical: LogicalKeyboardKey,
9107            character: &str,
9108        ) {
9109            tester.send_key_down_event_with_character(physical_of(logical), logical, character);
9110            tester.send_key_up_event(physical_of(logical), logical);
9111        }
9112
9113        /// Dart's `MenuBar(key: UniqueKey(), controller: controller, children: menus)`.
9114        fn pump_menu_bar(
9115            tester: &mut WidgetTester,
9116            controller: MenuControllerRef,
9117            menus: TestMenus,
9118        ) {
9119            pump_material(tester, m3, |_app| {
9120                MenuBar::new(menus.build())
9121                    .key(waft_foundation::UniqueKey::new().into())
9122                    .controller(controller.clone())
9123                    .into_widget()
9124            });
9125        }
9126
9127        fn new_controller(tester: &WidgetTester) -> MenuControllerRef {
9128            MenuController::new(&mut tester.cell.borrow_mut()).into_erased()
9129        }
9130
9131        /// Dart's `findMnemonic(label)`: the last `Text` in the `_MenuItemLabel` that shows
9132        /// `label`.
9133        fn mnemonic(tester: &WidgetTester, label: &str) -> Option<String> {
9134            let item_label = ancestors_of_type::<MenuItemLabel>(tester, label)[0];
9135            let texts = tester.descendants_of_type::<Text>(item_label);
9136            tester.widget::<Text, _>(*texts.last().expect("a Text"), |text| text.data.clone())
9137        }
9138
9139        fn shortcut(activator: SingleActivator) -> MenuSerializableShortcutRef {
9140            Rc::new(activator)
9141        }
9142
9143        fn character_shortcut(activator: CharacterActivator) -> MenuSerializableShortcutRef {
9144            Rc::new(activator)
9145        }
9146
9147        // ---- Accelerators ----
9148
9149        // menu_anchor_test.dart 'Accelerator markers are stripped properly'.
9150        #[test]
9151        fn accelerator_markers_are_stripped_properly() {
9152            let expected = [
9153                ("Plain String", "Plain String"),
9154                ("&Simple Accelerator", "Simple Accelerator"),
9155                ("&Multiple &Accelerators", "Multiple Accelerators"),
9156                ("Whitespace & Accelerators", "Whitespace  Accelerators"),
9157                ("&Quoted && Ampersand", "Quoted & Ampersand"),
9158                ("Ampersand at End &", "Ampersand at End "),
9159                (
9160                    "&&Multiple Ampersands &&& &&&A &&&&B &&&&",
9161                    "&Multiple Ampersands & &A &&B &&",
9162                ),
9163                (
9164                    "Bohrium 𨨏 Code point U+28A0F",
9165                    "Bohrium 𨨏 Code point U+28A0F",
9166                ),
9167            ];
9168            let expected_indices = [-1, 0, 0, -1, 0, -1, 24, -1];
9169            let expected_has_accelerator = [false, true, true, false, true, false, true, false];
9170            for (count, (key, label)) in expected.into_iter().enumerate() {
9171                let mut accelerator_index = -1;
9172                assert_eq!(
9173                    MenuAcceleratorLabel::strip_accelerator_markers(
9174                        key,
9175                        Some(&mut |index| accelerator_index = index),
9176                    ),
9177                    label,
9178                    "'{key}' label doesn't match {label}"
9179                );
9180                assert_eq!(
9181                    accelerator_index, expected_indices[count],
9182                    "'{key}' index doesn't match {}",
9183                    expected_indices[count]
9184                );
9185                assert_eq!(
9186                    MenuAcceleratorLabel::new(key).has_accelerator(),
9187                    expected_has_accelerator[count],
9188                    "'{key}' hasAccelerator isn't {}",
9189                    expected_has_accelerator[count]
9190                );
9191            }
9192        }
9193
9194        // menu_anchor_test.dart 'can invoke menu items'.
9195        #[test]
9196        fn accelerators_invoke_menu_items_off_apple_platforms() {
9197            test_widgets_variant(TargetPlatformVariant::new(NON_APPLE_PLATFORMS), |tester| {
9198                let platform = tester.target_platform();
9199
9200                let log = Log::default();
9201                let controller = new_controller(tester);
9202                pump_menu_bar(
9203                    tester,
9204                    controller.clone(),
9205                    TestMenus {
9206                        accelerators: true,
9207                        ..TestMenus::all(&log)
9208                    },
9209                );
9210
9211                tester.send_key_down_event(
9212                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9213                    LogicalKeyboardKey::ALT_LEFT,
9214                );
9215                pump(tester);
9216                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "m");
9217                pump(tester);
9218                // Makes sure that identical accelerators in parent menu items don't
9219                // shadow the ones in the children.
9220                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "m");
9221                tester.send_key_up_event(
9222                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9223                    LogicalKeyboardKey::ALT_LEFT,
9224                );
9225                pump(tester);
9226
9227                assert_eq!(log.opened(), [TestMenu::MainMenu0], "{platform:?}");
9228                assert_eq!(log.closed(), [TestMenu::MainMenu0], "{platform:?}");
9229                assert_eq!(log.selected(), [TestMenu::SubMenu00], "{platform:?}");
9230                // Selecting a non-submenu item should close all the menus.
9231                assert!(!shows(tester, &TestMenu::SubMenu00.label()));
9232                log.clear();
9233
9234                // Invoking several levels deep.
9235                tester.send_key_down_event(
9236                    PhysicalKeyboardKey::ALT_RIGHT,
9237                    LogicalKeyboardKey::ALT_RIGHT,
9238                );
9239                pump(tester);
9240                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "e");
9241                pump(tester);
9242                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "1");
9243                pump(tester);
9244                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "1");
9245                tester.send_key_up_event(
9246                    PhysicalKeyboardKey::ALT_RIGHT,
9247                    LogicalKeyboardKey::ALT_RIGHT,
9248                );
9249                pump(tester);
9250
9251                assert_eq!(
9252                    log.opened(),
9253                    [TestMenu::MainMenu1, TestMenu::SubMenu11],
9254                    "{platform:?}"
9255                );
9256                assert_eq!(
9257                    log.closed(),
9258                    [TestMenu::SubMenu11, TestMenu::MainMenu1],
9259                    "{platform:?}"
9260                );
9261                assert_eq!(log.selected(), [TestMenu::SubSubMenu111], "{platform:?}");
9262            });
9263        }
9264
9265        // menu_anchor_test.dart 'can combine with regular keyboard navigation'.
9266        #[test]
9267        fn accelerators_combine_with_regular_keyboard_navigation() {
9268            test_widgets_variant(TargetPlatformVariant::new(NON_APPLE_PLATFORMS), |tester| {
9269                let platform = tester.target_platform();
9270
9271                let log = Log::default();
9272                let controller = new_controller(tester);
9273                pump_menu_bar(
9274                    tester,
9275                    controller.clone(),
9276                    TestMenus {
9277                        accelerators: true,
9278                        ..TestMenus::all(&log)
9279                    },
9280                );
9281
9282                // Combining accelerators and regular keyboard navigation works.
9283                tester.send_key_down_event(
9284                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9285                    LogicalKeyboardKey::ALT_LEFT,
9286                );
9287                pump(tester);
9288                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "e");
9289                pump(tester);
9290                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "1");
9291                pump(tester);
9292                tester.send_key_up_event(
9293                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9294                    LogicalKeyboardKey::ALT_LEFT,
9295                );
9296                pump(tester);
9297                send_key(tester, LogicalKeyboardKey::ARROW_RIGHT);
9298                pump(tester);
9299                send_key(tester, LogicalKeyboardKey::ENTER);
9300                pump(tester);
9301
9302                assert_eq!(
9303                    log.opened(),
9304                    [TestMenu::MainMenu1, TestMenu::SubMenu11],
9305                    "{platform:?}"
9306                );
9307                assert_eq!(
9308                    log.closed(),
9309                    [TestMenu::SubMenu11, TestMenu::MainMenu1],
9310                    "{platform:?}"
9311                );
9312                assert_eq!(log.selected(), [TestMenu::SubSubMenu110], "{platform:?}");
9313            });
9314        }
9315
9316        // menu_anchor_test.dart 'can combine with mouse'.
9317        #[test]
9318        fn accelerators_combine_with_the_mouse() {
9319            test_widgets_variant(TargetPlatformVariant::new(NON_APPLE_PLATFORMS), |tester| {
9320                let platform = tester.target_platform();
9321
9322                let log = Log::default();
9323                let controller = new_controller(tester);
9324                pump_menu_bar(
9325                    tester,
9326                    controller.clone(),
9327                    TestMenus {
9328                        accelerators: true,
9329                        ..TestMenus::all(&log)
9330                    },
9331                );
9332
9333                // Combining accelerators and regular keyboard navigation works.
9334                tester.send_key_down_event(
9335                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9336                    LogicalKeyboardKey::ALT_LEFT,
9337                );
9338                pump(tester);
9339                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "e");
9340                pump(tester);
9341                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "1");
9342                pump(tester);
9343                tester.send_key_up_event(
9344                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9345                    LogicalKeyboardKey::ALT_LEFT,
9346                );
9347                pump(tester);
9348                tester.tap(find::text(&TestMenu::SubSubMenu112.label()));
9349                pump(tester);
9350
9351                assert_eq!(
9352                    log.opened(),
9353                    [TestMenu::MainMenu1, TestMenu::SubMenu11],
9354                    "{platform:?}"
9355                );
9356                assert_eq!(
9357                    log.closed(),
9358                    [TestMenu::SubMenu11, TestMenu::MainMenu1],
9359                    "{platform:?}"
9360                );
9361                assert_eq!(log.selected(), [TestMenu::SubSubMenu112], "{platform:?}");
9362            });
9363        }
9364
9365        // menu_anchor_test.dart "disabled items don't respond to accelerators".
9366        #[test]
9367        fn disabled_items_do_not_respond_to_accelerators() {
9368            test_widgets_variant(TargetPlatformVariant::new(NON_APPLE_PLATFORMS), |tester| {
9369                let platform = tester.target_platform();
9370
9371                let log = Log::default();
9372                let controller = new_controller(tester);
9373                pump_menu_bar(
9374                    tester,
9375                    controller.clone(),
9376                    TestMenus {
9377                        accelerators: true,
9378                        ..TestMenus::all(&log)
9379                    },
9380                );
9381
9382                tester.send_key_down_event(
9383                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9384                    LogicalKeyboardKey::ALT_LEFT,
9385                );
9386                pump(tester);
9387                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "5");
9388                pump(tester);
9389                tester.send_key_up_event(
9390                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9391                    LogicalKeyboardKey::ALT_LEFT,
9392                );
9393                pump(tester);
9394
9395                assert!(log.opened().is_empty(), "{platform:?}");
9396                assert!(log.closed().is_empty(), "{platform:?}");
9397                assert!(log.selected().is_empty(), "{platform:?}");
9398                // Selecting a non-submenu item should close all the menus.
9399                assert!(!shows(tester, &TestMenu::SubMenu00.label()));
9400            });
9401        }
9402
9403        // menu_anchor_test.dart "Apple platforms don't react to accelerators".
9404        #[test]
9405        fn apple_platforms_do_not_react_to_accelerators() {
9406            test_widgets_variant(TargetPlatformVariant::new(APPLE_PLATFORMS), |tester| {
9407                let platform = tester.target_platform();
9408
9409                let log = Log::default();
9410                let controller = new_controller(tester);
9411                pump_menu_bar(
9412                    tester,
9413                    controller.clone(),
9414                    TestMenus {
9415                        accelerators: true,
9416                        ..TestMenus::all(&log)
9417                    },
9418                );
9419
9420                tester.send_key_down_event(
9421                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9422                    LogicalKeyboardKey::ALT_LEFT,
9423                );
9424                pump(tester);
9425                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "m");
9426                pump(tester);
9427                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "m");
9428                tester.send_key_up_event(
9429                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9430                    LogicalKeyboardKey::ALT_LEFT,
9431                );
9432                pump(tester);
9433
9434                assert!(log.opened().is_empty(), "{platform:?}");
9435                assert!(log.closed().is_empty(), "{platform:?}");
9436                assert!(log.selected().is_empty(), "{platform:?}");
9437
9438                // Or with the option key equivalents.
9439                tester.send_key_down_event(
9440                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9441                    LogicalKeyboardKey::ALT_LEFT,
9442                );
9443                pump(tester);
9444                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "µ");
9445                pump(tester);
9446                send_key_with_character(tester, LogicalKeyboardKey::KEY_M, "µ");
9447                tester.send_key_up_event(
9448                    physical_of(LogicalKeyboardKey::ALT_LEFT),
9449                    LogicalKeyboardKey::ALT_LEFT,
9450                );
9451                pump(tester);
9452
9453                assert!(log.opened().is_empty(), "{platform:?}");
9454                assert!(log.closed().is_empty(), "{platform:?}");
9455                assert!(log.selected().is_empty(), "{platform:?}");
9456            });
9457        }
9458
9459        // ---- MenuController ----
9460
9461        // menu_anchor_test.dart 'Moving a controller to a new instance works'.
9462        #[test]
9463        fn a_controller_moves_to_a_new_menu_bar() {
9464            test_widgets(|tester| {
9465                let controller = new_controller(tester);
9466                pump_menu_bar(tester, controller.clone(), TestMenus::default());
9467
9468                // Open a menu initially.
9469                tester.tap(find::text(&TestMenu::MainMenu1.label()));
9470                pump(tester);
9471
9472                tester.tap(find::text(&TestMenu::SubMenu11.label()));
9473                pump(tester);
9474
9475                // Now pump a new menu with a different UniqueKey to dispose of the opened
9476                // menu's node, but keep the existing controller.
9477                pump_menu_bar(
9478                    tester,
9479                    controller.clone(),
9480                    TestMenus {
9481                        include_extra_groups: true,
9482                        ..TestMenus::default()
9483                    },
9484                );
9485                tester.pump_and_settle();
9486            });
9487        }
9488
9489        // menu_anchor_test.dart 'closing via controller works'.
9490        #[test]
9491        fn closing_through_the_controller_closes_every_open_menu() {
9492            test_widgets(|tester| {
9493                let log = Log::default();
9494                let controller = new_controller(tester);
9495                let menus = TestMenus {
9496                    shortcuts: vec![(
9497                        TestMenu::SubSubMenu110,
9498                        shortcut(SingleActivator::new(LogicalKeyboardKey::KEY_A).control(true)),
9499                    )],
9500                    ..TestMenus::all(&log)
9501                };
9502                pump_material(tester, m3, |_app| {
9503                    MenuBar::new(menus.build())
9504                        .controller(controller.clone())
9505                        .into_widget()
9506                });
9507
9508                // Open a menu initially.
9509                tester.tap(find::text(&TestMenu::MainMenu1.label()));
9510                pump(tester);
9511
9512                tester.tap(find::text(&TestMenu::SubMenu11.label()));
9513                pump(tester);
9514                let mut opened = log.opened();
9515                opened.sort_by_key(|menu| *menu as u32);
9516                assert_eq!(opened, [TestMenu::MainMenu1, TestMenu::SubMenu11]);
9517                log.clear();
9518
9519                // Close menus using the controller.
9520                controller.close(&mut tester.cell.borrow_mut());
9521                pump(tester);
9522
9523                // The menu should go away,
9524                let mut closed = log.closed();
9525                closed.sort_by_key(|menu| *menu as u32);
9526                assert_eq!(closed, [TestMenu::MainMenu1, TestMenu::SubMenu11]);
9527                assert!(log.opened().is_empty());
9528            });
9529        }
9530
9531        // menu_anchor_test.dart 'internal controller is created when the controller is null'.
9532        #[test]
9533        fn an_anchor_without_a_controller_makes_its_own() {
9534            test_widgets(|tester| {
9535                let controller = new_controller(tester);
9536                let test_controller: Rc<Cell<Option<AnyMenuController>>> = Rc::default();
9537
9538                let anchor = |controller: Option<MenuControllerRef>| {
9539                    let sink = Rc::clone(&test_controller);
9540                    let mut anchor = MenuAnchor::new(Vec::new()).builder(
9541                        move |_app, _context, controller, _child| {
9542                            sink.set(Some(controller));
9543                            Text::new("Anchor").into_widget()
9544                        },
9545                    );
9546                    anchor.controller = controller;
9547                    anchor.into_widget()
9548                };
9549                let root = {
9550                    let app = tester.cell.borrow();
9551                    material_app(m3(&app), anchor(Some(controller.clone())))
9552                };
9553                tester.pump_widget(root);
9554
9555                assert_eq!(test_controller.get(), Some(controller.handle()));
9556
9557                let root = {
9558                    let app = tester.cell.borrow();
9559                    material_app(m3(&app), anchor(None))
9560                };
9561                tester.pump_widget(root);
9562
9563                assert!(test_controller.get().is_some());
9564                assert_ne!(test_controller.get(), Some(controller.handle()));
9565            });
9566        }
9567
9568        // ---- MenuItemButton ----
9569
9570        // menu_anchor_test.dart 'Shortcut mnemonics are displayed'.
9571        #[test]
9572        fn shortcut_mnemonics_are_displayed_for_each_platform() {
9573            test_widgets_variant(TargetPlatformVariant::new(ALL_PLATFORMS), |tester| {
9574                let platform = tester.target_platform();
9575
9576                let controller = new_controller(tester);
9577                let menus = TestMenus {
9578                    shortcuts: vec![
9579                        (
9580                            TestMenu::SubSubMenu110,
9581                            shortcut(SingleActivator::new(LogicalKeyboardKey::KEY_A).control(true)),
9582                        ),
9583                        (
9584                            TestMenu::SubSubMenu111,
9585                            shortcut(SingleActivator::new(LogicalKeyboardKey::KEY_B).shift(true)),
9586                        ),
9587                        (
9588                            TestMenu::SubSubMenu112,
9589                            shortcut(SingleActivator::new(LogicalKeyboardKey::KEY_C).alt(true)),
9590                        ),
9591                        (
9592                            TestMenu::SubSubMenu113,
9593                            shortcut(SingleActivator::new(LogicalKeyboardKey::KEY_D).meta(true)),
9594                        ),
9595                    ],
9596                    ..TestMenus::default()
9597                };
9598                pump_material(tester, m3, |_app| {
9599                    MenuBar::new(menus.build())
9600                        .controller(controller.clone())
9601                        .into_widget()
9602                });
9603
9604                // Open a menu initially.
9605                tester.tap(find::text(&TestMenu::MainMenu1.label()));
9606                pump(tester);
9607
9608                tester.tap(find::text(&TestMenu::SubMenu11.label()));
9609                pump(tester);
9610
9611                let labels: Vec<Option<String>> = [
9612                    TestMenu::SubSubMenu110,
9613                    TestMenu::SubSubMenu111,
9614                    TestMenu::SubSubMenu112,
9615                    TestMenu::SubSubMenu113,
9616                ]
9617                .into_iter()
9618                .map(|menu| mnemonic(tester, &menu.label()))
9619                .collect();
9620                let expected = match platform {
9621                    TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::Linux => {
9622                        ["Ctrl+A", "Shift+B", "Alt+C", "Meta+D"]
9623                    }
9624                    TargetPlatform::Windows => ["Ctrl+A", "Shift+B", "Alt+C", "Win+D"],
9625                    TargetPlatform::IOS | TargetPlatform::MacOS => ["⌃ A", "⇧ B", "⌥ C", "⌘ D"],
9626                };
9627                assert_eq!(
9628                    labels,
9629                    expected.map(|label| Some(label.to_string())),
9630                    "{platform:?}"
9631                );
9632
9633                let menus = TestMenus {
9634                    include_extra_groups: true,
9635                    shortcuts: vec![
9636                        (
9637                            TestMenu::SubSubMenu110,
9638                            shortcut(SingleActivator::new(LogicalKeyboardKey::ARROW_RIGHT)),
9639                        ),
9640                        (
9641                            TestMenu::SubSubMenu111,
9642                            shortcut(SingleActivator::new(LogicalKeyboardKey::ARROW_LEFT)),
9643                        ),
9644                        (
9645                            TestMenu::SubSubMenu112,
9646                            shortcut(SingleActivator::new(LogicalKeyboardKey::ARROW_UP)),
9647                        ),
9648                        (
9649                            TestMenu::SubSubMenu113,
9650                            shortcut(SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN)),
9651                        ),
9652                    ],
9653                    ..TestMenus::default()
9654                };
9655                pump_material(tester, m3, |_app| {
9656                    MenuBar::new(menus.build())
9657                        .controller(controller.clone())
9658                        .into_widget()
9659                });
9660                tester.pump_and_settle();
9661
9662                assert_eq!(
9663                    mnemonic(tester, &TestMenu::SubSubMenu110.label()).as_deref(),
9664                    Some("→")
9665                );
9666                assert_eq!(
9667                    mnemonic(tester, &TestMenu::SubSubMenu111.label()).as_deref(),
9668                    Some("←")
9669                );
9670                assert_eq!(
9671                    mnemonic(tester, &TestMenu::SubSubMenu112.label()).as_deref(),
9672                    Some("↑")
9673                );
9674                assert_eq!(
9675                    mnemonic(tester, &TestMenu::SubSubMenu113.label()).as_deref(),
9676                    Some("↓")
9677                );
9678
9679                // Try some weirder ones.
9680                let menus = TestMenus {
9681                    shortcuts: vec![
9682                        (
9683                            TestMenu::SubSubMenu110,
9684                            shortcut(SingleActivator::new(LogicalKeyboardKey::ESCAPE)),
9685                        ),
9686                        (
9687                            TestMenu::SubSubMenu111,
9688                            shortcut(SingleActivator::new(LogicalKeyboardKey::FN)),
9689                        ),
9690                        (
9691                            TestMenu::SubSubMenu112,
9692                            shortcut(SingleActivator::new(LogicalKeyboardKey::ENTER)),
9693                        ),
9694                    ],
9695                    ..TestMenus::default()
9696                };
9697                pump_material(tester, m3, |_app| {
9698                    MenuBar::new(menus.build())
9699                        .controller(controller)
9700                        .into_widget()
9701                });
9702                tester.pump_and_settle();
9703
9704                assert_eq!(
9705                    mnemonic(tester, &TestMenu::SubSubMenu110.label()).as_deref(),
9706                    Some("Esc")
9707                );
9708                assert_eq!(
9709                    mnemonic(tester, &TestMenu::SubSubMenu111.label()).as_deref(),
9710                    Some("Fn")
9711                );
9712                assert_eq!(
9713                    mnemonic(tester, &TestMenu::SubSubMenu112.label()).as_deref(),
9714                    Some("↵")
9715                );
9716            });
9717        }
9718
9719        // menu_anchor_test.dart 'CharacterActivator shortcut mnemonics include modifiers'.
9720        #[test]
9721        fn character_activator_mnemonics_include_their_modifiers() {
9722            test_widgets_variant(TargetPlatformVariant::new(ALL_PLATFORMS), |tester| {
9723                let platform = tester.target_platform();
9724
9725                let controller = new_controller(tester);
9726                let menus = TestMenus {
9727                    shortcuts: vec![
9728                        (
9729                            TestMenu::SubSubMenu110,
9730                            character_shortcut(CharacterActivator::new("A").control(true)),
9731                        ),
9732                        (
9733                            TestMenu::SubSubMenu111,
9734                            character_shortcut(CharacterActivator::new("B").alt(true)),
9735                        ),
9736                        (
9737                            TestMenu::SubSubMenu112,
9738                            character_shortcut(CharacterActivator::new("C").meta(true)),
9739                        ),
9740                    ],
9741                    ..TestMenus::default()
9742                };
9743                pump_material(tester, m3, |_app| {
9744                    MenuBar::new(menus.build())
9745                        .controller(controller)
9746                        .into_widget()
9747                });
9748
9749                // Open a menu initially.
9750                tester.tap(find::text(&TestMenu::MainMenu1.label()));
9751                pump(tester);
9752
9753                tester.tap(find::text(&TestMenu::SubMenu11.label()));
9754                pump(tester);
9755
9756                let labels: Vec<Option<String>> = [
9757                    TestMenu::SubSubMenu110,
9758                    TestMenu::SubSubMenu111,
9759                    TestMenu::SubSubMenu112,
9760                ]
9761                .into_iter()
9762                .map(|menu| mnemonic(tester, &menu.label()))
9763                .collect();
9764                let expected = match platform {
9765                    TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::Linux => {
9766                        ["Ctrl+A", "Alt+B", "Meta+C"]
9767                    }
9768                    TargetPlatform::Windows => ["Ctrl+A", "Alt+B", "Win+C"],
9769                    TargetPlatform::IOS | TargetPlatform::MacOS => ["⌃ A", "⌥ B", "⌘ C"],
9770                };
9771                assert_eq!(
9772                    labels,
9773                    expected.map(|label| Some(label.to_string())),
9774                    "{platform:?}"
9775                );
9776            });
9777        }
9778
9779        /// Dart's `MenuBar(controller:, children: [SubmenuButton(menuChildren: [item], child:
9780        /// Text(mainMenu0))])`.
9781        fn pump_one_submenu(
9782            tester: &mut WidgetTester,
9783            controller: MenuControllerRef,
9784            item: MenuItemButton,
9785        ) {
9786            pump_material(tester, m3, |_app| {
9787                MenuBar::new(vec![
9788                    SubmenuButton::new(
9789                        vec![item.into_widget()],
9790                        Some(Text::new(TestMenu::MainMenu0.label())),
9791                    )
9792                    .into_widget(),
9793                ])
9794                .controller(controller.clone())
9795                .into_widget()
9796            });
9797        }
9798
9799        // menu_anchor_test.dart 'leadingIcon is used when set'.
9800        #[test]
9801        fn a_leading_icon_is_shown_when_set() {
9802            test_widgets(|tester| {
9803                let controller = new_controller(tester);
9804                pump_one_submenu(
9805                    tester,
9806                    controller.clone(),
9807                    MenuItemButton::new()
9808                        .leading_icon(Text::new("leadingIcon"))
9809                        .child(Text::new(TestMenu::SubMenu00.label())),
9810                );
9811
9812                tester.tap(find::text(&TestMenu::MainMenu0.label()));
9813                pump(tester);
9814
9815                assert!(shows(tester, "leadingIcon"));
9816            });
9817        }
9818
9819        // menu_anchor_test.dart 'autofocus is used when set and widget is enabled'.
9820        #[test]
9821        fn an_enabled_autofocus_item_takes_focus_when_the_menu_opens() {
9822            test_widgets(|tester| {
9823                let controller = new_controller(tester);
9824                pump_material(tester, m3, |_app| {
9825                    Column::new()
9826                        .children(vec![
9827                            MenuAnchor::new(vec![
9828                                MenuItemButton::new()
9829                                    .autofocus(true)
9830                                    // Required for clickability.
9831                                    .on_pressed(Listener::new(|_app| {}))
9832                                    .child(Text::new(TestMenu::MainMenu0.label()))
9833                                    .into_widget(),
9834                                MenuItemButton::new()
9835                                    .on_pressed(Listener::new(|_app| {}))
9836                                    .child(Text::new(TestMenu::MainMenu1.label()))
9837                                    .into_widget(),
9838                            ])
9839                            .controller(controller.clone())
9840                            .into_widget(),
9841                            Expanded::new(placeholder()).into_widget(),
9842                        ])
9843                        .into_widget()
9844                });
9845
9846                controller.open(&mut tester.cell.borrow_mut(), None);
9847                pump(tester);
9848
9849                assert!(controller.is_open(&tester.cell.borrow()));
9850                assert_eq!(
9851                    focused_menu(tester),
9852                    Some(button_label("MenuItemButton", &TestMenu::MainMenu0.label()))
9853                );
9854            });
9855        }
9856
9857        // menu_anchor_test.dart 'trailingIcon is used when set'.
9858        #[test]
9859        fn a_trailing_icon_is_shown_when_set() {
9860            test_widgets(|tester| {
9861                let controller = new_controller(tester);
9862                pump_one_submenu(
9863                    tester,
9864                    controller.clone(),
9865                    MenuItemButton::new()
9866                        .trailing_icon(Text::new("trailingIcon"))
9867                        .child(Text::new(TestMenu::SubMenu00.label())),
9868                );
9869
9870                tester.tap(find::text(&TestMenu::MainMenu0.label()));
9871                pump(tester);
9872
9873                assert!(shows(tester, "trailingIcon"));
9874            });
9875        }
9876
9877        // menu_anchor_test.dart 'SubmenuButton uses supplied controller'.
9878        #[test]
9879        fn a_submenu_button_uses_the_controller_it_is_given() {
9880            test_widgets(|tester| {
9881                let controller = new_controller(tester);
9882                let submenu_controller = new_controller(tester);
9883                let menu_bar = |submenu_controller: Option<MenuControllerRef>| {
9884                    let mut submenu = SubmenuButton::new(
9885                        vec![
9886                            MenuItemButton::new()
9887                                .child(Text::new(TestMenu::SubMenu00.label()))
9888                                .into_widget(),
9889                        ],
9890                        Some(Text::new(TestMenu::MainMenu0.label())),
9891                    );
9892                    submenu.controller = submenu_controller;
9893                    MenuBar::new(vec![submenu.into_widget()])
9894                        .controller(controller.clone())
9895                        .into_widget()
9896                };
9897                pump_material(tester, m3, |_app| {
9898                    menu_bar(Some(submenu_controller.clone()))
9899                });
9900
9901                submenu_controller.open(&mut tester.cell.borrow_mut(), None);
9902                pump(tester);
9903                assert!(shows(tester, &TestMenu::SubMenu00.label()));
9904
9905                submenu_controller.close(&mut tester.cell.borrow_mut());
9906                pump(tester);
9907                assert!(!shows(tester, &TestMenu::SubMenu00.label()));
9908
9909                // Now remove the controller and try to control it.
9910                pump_material(tester, m3, |_app| menu_bar(None));
9911
9912                let opened = catch_unwind(AssertUnwindSafe(|| {
9913                    submenu_controller.open(&mut tester.cell.borrow_mut(), None);
9914                }));
9915                assert!(
9916                    opened.is_err(),
9917                    "opening a detached controller fails an assert"
9918                );
9919                pump(tester);
9920                assert!(!shows(tester, &TestMenu::SubMenu00.label()));
9921            });
9922        }
9923
9924        /// Dart's `MenuAnchor(controller:, menuChildren: [MenuItemButton(closeOnActivate:,
9925        /// onPressed: () {}, child: Text('Button 1'))], builder: FilledButton('Tap me'))` in a
9926        /// `Center`.
9927        fn pump_tap_me_anchor(
9928            tester: &mut WidgetTester,
9929            controller: MenuControllerRef,
9930            close_on_activate: bool,
9931        ) {
9932            pump_material(tester, m3, |_app| {
9933                Center::new()
9934                    .child(
9935                        MenuAnchor::new(vec![
9936                            MenuItemButton::new()
9937                                .close_on_activate(close_on_activate)
9938                                .on_pressed(Listener::new(|_app| {}))
9939                                .child(Text::new("Button 1"))
9940                                .into_widget(),
9941                        ])
9942                        .controller(controller.clone())
9943                        .builder(|_app, _context, controller, _child| {
9944                            FilledButton::new(
9945                                Some(Listener::new(move |app| controller.open(app, None))),
9946                                Some(Text::new("Tap me")),
9947                            )
9948                            .into_widget()
9949                        }),
9950                    )
9951                    .into_widget()
9952            });
9953        }
9954
9955        // menu_anchor_test.dart 'MenuItemButton respects closeOnActivate property'.
9956        #[test]
9957        fn close_on_activate_decides_whether_pressing_an_item_closes_the_menu() {
9958            test_widgets(|tester| {
9959                let controller = new_controller(tester);
9960                pump_tap_me_anchor(tester, controller.clone(), true);
9961
9962                tester.tap(find::text("Tap me"));
9963                pump(tester);
9964                expect(
9965                    tester,
9966                    &find::by_type::<MenuItemButton>(),
9967                    finds_one_widget(),
9968                );
9969
9970                // Taps the MenuItemButton which should close the menu.
9971                tester.tap(find::text("Button 1"));
9972                pump(tester);
9973                expect(tester, &find::by_type::<MenuItemButton>(), finds_nothing());
9974
9975                tester.pump_and_settle();
9976
9977                pump_tap_me_anchor(tester, controller.clone(), false);
9978
9979                tester.tap(find::text("Tap me"));
9980                pump(tester);
9981                expect(
9982                    tester,
9983                    &find::by_type::<MenuItemButton>(),
9984                    finds_one_widget(),
9985                );
9986
9987                // Taps the MenuItemButton which shouldn't close the menu.
9988                tester.tap(find::text("Button 1"));
9989                pump(tester);
9990                expect(
9991                    tester,
9992                    &find::by_type::<MenuItemButton>(),
9993                    finds_one_widget(),
9994                );
9995            });
9996        }
9997
9998        /// Dart's `MaterialApp(home: Scaffold(body: SizedBox(width: width, child: button)))`.
9999        fn pump_in_scaffold(tester: &mut WidgetTester, width: Option<f64>, button: MenuItemButton) {
10000            let root = {
10001                let app = tester.cell.borrow();
10002                let mut sized_box = SizedBox::new().child(button);
10003                if let Some(width) = width {
10004                    sized_box = sized_box.width(width);
10005                }
10006                material_app(m3(&app), Scaffold::new().body(sized_box).into_widget())
10007            };
10008            tester.pump_widget(root);
10009        }
10010
10011        // menu_anchor_test.dart 'MenuItemButton does not overflow when child is long'.
10012        #[test]
10013        fn a_vertical_overflow_item_with_a_long_child_builds() {
10014            test_widgets(|tester| {
10015                pump_in_scaffold(
10016                    tester,
10017                    Some(200.0),
10018                    MenuItemButton::new()
10019                        .overflow_axis(Axis::Vertical)
10020                        .on_pressed(Listener::new(|_app| {}))
10021                        .child(Text::new(
10022                            "MenuItem Button does not overflow when child is long",
10023                        )),
10024                );
10025            });
10026        }
10027
10028        // menu_anchor_test.dart 'MenuItemButton layout is updated by overflowAxis'. The last
10029        // step's overflow assertion is not taken: Waft's flex reports no overflow (deferred
10030        // with the overflow indicator in waft-rendering).
10031        #[test]
10032        fn an_item_lays_out_by_its_overflow_axis() {
10033            test_widgets(|tester| {
10034                let build_menu_button =
10035                    |tester: &mut WidgetTester, overflow_axis: Axis, constrained_layout: bool| {
10036                        pump_in_scaffold(
10037                        tester,
10038                        constrained_layout.then_some(200.0),
10039                        MenuItemButton::new()
10040                            .overflow_axis(overflow_axis)
10041                            .on_pressed(Listener::new(|_app| {}))
10042                            .child(Text::new(
10043                                "This is a very long text that will wrap to the multiple lines.",
10044                            )),
10045                    );
10046                    };
10047
10048                // Test a long MenuItemButton in an unconstrained layout with vertical overflow axis.
10049                build_menu_button(tester, Axis::Vertical, false);
10050                assert_eq!(
10051                    rect_of::<MenuItemButton>(tester).size(),
10052                    Size::new(800.0, 48.0)
10053                );
10054
10055                // Test a long MenuItemButton in an unconstrained layout with horizontal overflow axis.
10056                build_menu_button(tester, Axis::Horizontal, false);
10057                assert_eq!(
10058                    rect_of::<MenuItemButton>(tester).size(),
10059                    Size::new(800.0, 48.0)
10060                );
10061
10062                // Test a long MenuItemButton in a constrained layout with vertical overflow axis.
10063                build_menu_button(tester, Axis::Vertical, true);
10064                assert_eq!(
10065                    rect_of::<MenuItemButton>(tester).size(),
10066                    Size::new(200.0, 120.0)
10067                );
10068
10069                // Test a long MenuItemButton in a constrained layout with horizontal overflow axis.
10070                build_menu_button(tester, Axis::Horizontal, true);
10071                assert_eq!(
10072                    rect_of::<MenuItemButton>(tester).size(),
10073                    Size::new(200.0, 48.0)
10074                );
10075            });
10076        }
10077
10078        // menu_anchor_test.dart 'MenuItemButton does not clip leadingIcon'.
10079        #[test]
10080        fn an_item_clips_its_label_but_not_its_leading_icon() {
10081            test_widgets(|tester| {
10082                let label = "This is a very long menu item label that must be clipped";
10083                let leading = GlobalKey::new();
10084                let leading_key = leading.clone();
10085                let root = {
10086                    let app = tester.cell.borrow();
10087                    material_app(
10088                        m3(&app),
10089                        Scaffold::new()
10090                            .body(
10091                                MenuAnchor::new(vec![
10092                                    SizedBox::new()
10093                                        .width(200.0)
10094                                        .child(
10095                                            MenuItemButton::new()
10096                                                .leading_icon(
10097                                                    Badge::new().label(Text::new("1")).child(
10098                                                        Icon::new(Some(Icons::add()))
10099                                                            .key(leading_key.into()),
10100                                                    ),
10101                                                )
10102                                                .on_pressed(Listener::new(|_app| {}))
10103                                                .child(Text::new(label).max_lines(1)),
10104                                        )
10105                                        .into_widget(),
10106                                ])
10107                                .builder(
10108                                    |_app, _context, controller, _child| {
10109                                        TextButton::new(
10110                                            Some(Listener::new(move |app| {
10111                                                controller.open(app, None)
10112                                            })),
10113                                            Some(Text::new("Open")),
10114                                        )
10115                                        .into_widget()
10116                                    },
10117                                ),
10118                            )
10119                            .into_widget(),
10120                    )
10121                };
10122                tester.pump_widget(root);
10123
10124                tester.tap(find::text("Open"));
10125                tester.pump_and_settle();
10126
10127                // Decorations that paint outside the leading icon's bounds stay visible.
10128                let leading_element = leading
10129                    .current_context(&tester.cell.borrow())
10130                    .expect("the leading icon is mounted");
10131                let clips_above = |tester: &WidgetTester, element: AnyElement| {
10132                    let ancestors = tester.ancestors(element);
10133                    let app = tester.cell.borrow();
10134                    ancestors
10135                        .into_iter()
10136                        .filter(|ancestor| {
10137                            waft_widgets::downcast_widget::<ClipRect>(&**ancestor.widget(&app))
10138                                .is_some()
10139                        })
10140                        .count()
10141                };
10142                assert_eq!(clips_above(tester, leading_element), 0);
10143
10144                // The label itself is still clipped so that long labels truncate.
10145                let label_element = find::text(label).evaluate(tester)[0];
10146                assert_eq!(clips_above(tester, label_element), 1);
10147                let app = tester.cell.borrow();
10148                let paragraph = label_element
10149                    .find_render_object(&app)
10150                    .and_then(|render| render.downcast::<waft_rendering::RenderParagraph>(&app))
10151                    .expect("a Text lays out a paragraph");
10152                assert!(paragraph.did_exceed_max_lines(&app));
10153            });
10154        }
10155
10156        // menu_anchor_test.dart 'MenuItemButton.styleFrom overlayColor overrides default overlay
10157        // color'.
10158        #[test]
10159        fn style_from_overlay_color_overrides_the_default_overlay_color() {
10160            test_widgets(|tester| {
10161                let overlay_color = Color::new(0xffff0000);
10162                pump_in_scaffold(
10163                    tester,
10164                    None,
10165                    MenuItemButton::new()
10166                        .style(
10167                            MenuItemButton::style_from()
10168                                .overlay_color(overlay_color)
10169                                .build(),
10170                        )
10171                        .on_pressed(Listener::new(|_app| {}))
10172                        .child(Text::new("MenuItem")),
10173                );
10174
10175                // Hovered.
10176                let center = rect_of::<MenuItemButton>(tester).center();
10177                let mut gesture = TestPointer::mouse(1, 0);
10178                tester.add_pointer(&mut gesture, Offset::ZERO);
10179                tester.move_to(&mut gesture, center, false);
10180                tester.pump_and_settle();
10181                assert_paints(
10182                    &overlay_ops(tester),
10183                    &[PaintCall::rect(Some(overlay_color.with_opacity(0.08)))],
10184                );
10185
10186                // Highlighted (pressed).
10187                gesture.buttons = waft_gestures::K_PRIMARY_BUTTON;
10188                tester.down(&mut gesture, center);
10189                tester.pump_and_settle();
10190                assert_paints(
10191                    &overlay_ops(tester),
10192                    &[
10193                        PaintCall::rect(Some(overlay_color.with_opacity(0.08))),
10194                        PaintCall::rect(Some(overlay_color.with_opacity(0.08))),
10195                        PaintCall::rect(Some(overlay_color.with_opacity(0.1))),
10196                    ],
10197                );
10198            });
10199        }
10200
10201        // menu_anchor_test.dart 'MenuItemButton can build when its child is null'.
10202        #[test]
10203        fn an_item_with_no_child_builds() {
10204            test_widgets(|tester| {
10205                pump_in_scaffold(tester, Some(200.0), MenuItemButton::new());
10206            });
10207        }
10208    }
10209
10210    mod layout {
10211        //! menu_anchor_test.dart's 'Layout' group with the cases that follow it up to 'Mouse
10212        //! cursors', and the 'Mouse cursors' group.
10213
10214        use std::cell::Cell;
10215
10216        use waft_embedder::FontStyle;
10217        use waft_painting::{BoxDecoration, TextStyle};
10218        use waft_rendering::AnyRenderObject;
10219        use waft_services::{SystemMouseCursor, SystemMouseCursors};
10220
10221        use waft_widgets::{
10222            Align, Center, DecoratedBox, Overlay, OverlayEntry, Positioned, RenderTheater,
10223            SizedBox, Stack, StatefulBuilder, UnfocusDisposition, WidgetStatePropertyAll,
10224        };
10225
10226        use super::*;
10227        use crate::app::MaterialApp;
10228        use crate::colors::Colors;
10229        use crate::filled_button::FilledButton;
10230        use crate::material_state::MaterialStatePropertyAll;
10231        use crate::scaffold::Scaffold;
10232        use crate::text_theme::TextTheme;
10233        use crate::tooltip::tests::m2;
10234
10235        /// `tester.pumpWidget(MaterialApp(theme: theme(app), home: home(app)))`.
10236        fn pump_app(
10237            tester: &mut WidgetTester,
10238            theme: impl FnOnce(&App) -> ThemeData,
10239            home: impl FnOnce(&mut App) -> WidgetRef,
10240        ) {
10241            let root = {
10242                let mut app = tester.cell.borrow_mut();
10243                let theme = theme(&app);
10244                let home = home(&mut app);
10245                material_app(theme, home)
10246            };
10247            tester.pump_widget(root);
10248        }
10249
10250        /// Dart's `collectSubmenuRects()`: the rects of the menu panels, in finder order.
10251        fn submenu_rects(tester: &WidgetTester) -> Vec<Rect> {
10252            menu_panels(tester)
10253                .into_iter()
10254                .map(|panel| rect_of_element(tester, panel))
10255                .collect()
10256        }
10257
10258        /// Dart's `tester.getCenter(find.byType(W).first)`.
10259        fn center_of_first<W: 'static>(tester: &WidgetTester) -> Offset {
10260            let element = *find::by_type::<W>()
10261                .evaluate(tester)
10262                .first()
10263                .expect("a widget of the type");
10264            rect_of_element(tester, element).center()
10265        }
10266
10267        /// Dart's `tester.getCenter(find.byType(W).last)`.
10268        fn center_of_last<W: 'static>(tester: &WidgetTester) -> Offset {
10269            let element = *find::by_type::<W>()
10270                .evaluate(tester)
10271                .last()
10272                .expect("a widget of the type");
10273            rect_of_element(tester, element).center()
10274        }
10275
10276        /// A `FilledButton` labelled `label` that toggles `controller`'s menu, as the builders of
10277        /// Dart's cases write it.
10278        fn toggle_button(controller: AnyMenuController, label: &str) -> WidgetRef {
10279            FilledButton::new(
10280                Some(Listener::new(move |app| {
10281                    if controller.is_open(app) {
10282                        controller.close(app);
10283                    } else {
10284                        controller.open(app, None);
10285                    }
10286                })),
10287                Some(Text::new(label)),
10288            )
10289            .into_widget()
10290        }
10291
10292        fn new_controller(tester: &WidgetTester) -> MenuControllerRef {
10293            MenuController::new(&mut tester.cell.borrow_mut()).into_erased()
10294        }
10295
10296        /// Dart's `findsNWidgets(count)` of `find.byType(W)`.
10297        fn count_of<W: 'static>(tester: &WidgetTester) -> usize {
10298            find::by_type::<W>().evaluate(tester).len()
10299        }
10300
10301        // ---- Layout ----
10302
10303        // menu_anchor_test.dart 'tapping MenuItemButton with null focus node'.
10304        #[test]
10305        fn tapping_a_menu_item_button_that_drops_its_focus_node_does_not_panic() {
10306            test_widgets(|tester| {
10307                let button_focus_node: Rc<RefCell<Option<FocusNodeRef>>> =
10308                    Rc::new(RefCell::new(Some(
10309                        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased::<AnyFocusNode>(),
10310                    )));
10311                let focus_node = Rc::clone(&button_focus_node);
10312                pump_app(tester, m3, move |_app| {
10313                    StatefulBuilder::new(move |_app, _context, set_state| {
10314                        let mut item = MenuItemButton::new()
10315                            .close_on_activate(false)
10316                            .child(Text::new("Set focus to null"));
10317                        item.focus_node = focus_node.borrow().clone();
10318                        let focus_node = Rc::clone(&focus_node);
10319                        let item = item.on_pressed(Listener::new(move |app| {
10320                            let focus_node = Rc::clone(&focus_node);
10321                            set_state(app, &mut |app| {
10322                                if let Some(node) = focus_node.borrow_mut().take() {
10323                                    node.dispose(app);
10324                                }
10325                            });
10326                        }));
10327                        MenuAnchor::new(vec![item.into_widget()])
10328                            .builder(|_app, _context, controller, _child| {
10329                                TextButton::new(
10330                                    Some(Listener::new(move |app| {
10331                                        if controller.is_open(app) {
10332                                            controller.close(app);
10333                                        } else {
10334                                            controller.open(app, None);
10335                                        }
10336                                    })),
10337                                    Some(Text::new("OPEN MENU")),
10338                                )
10339                                .into_widget()
10340                            })
10341                            .into_widget()
10342                    })
10343                    .into_widget()
10344                });
10345
10346                tester.tap(find::text("OPEN MENU"));
10347                pump(tester);
10348
10349                assert!(shows(tester, "Set focus to null"));
10350
10351                tester.tap(find::text("Set focus to null"));
10352                tester.pump_and_settle();
10353                assert!(button_focus_node.take().is_none());
10354            });
10355        }
10356
10357        /// The anchor of Dart's 'constrained menus show up in the right place with offset' cases:
10358        /// four nested submenus, the first and third offset by 10 along the menu.
10359        fn nested_offset_menus(tester: &mut WidgetTester, text_direction: TextDirection) {
10360            pump_app(tester, m2, move |_app| {
10361                let submenu_4 =
10362                    SubmenuButton::new(Vec::new(), Some(Text::new("SubMenuButton4"))).into_widget();
10363                let submenu_3 =
10364                    SubmenuButton::new(vec![submenu_4], Some(Text::new("SubMenuButton3")))
10365                        .alignment_offset(Offset::new(10.0, 0.0))
10366                        .into_widget();
10367                let submenu_2 =
10368                    SubmenuButton::new(vec![submenu_3], Some(Text::new("SubMenuButton2")))
10369                        .into_widget();
10370                let submenu_1 =
10371                    SubmenuButton::new(vec![submenu_2], Some(Text::new("SubMenuButton1")))
10372                        .alignment_offset(Offset::new(10.0, 0.0))
10373                        .into_widget();
10374                let alignment = match text_direction {
10375                    TextDirection::Ltr => AlignmentGeometry::TOP_LEFT,
10376                    TextDirection::Rtl => AlignmentGeometry::TOP_RIGHT,
10377                };
10378                Directionality::new(
10379                    text_direction,
10380                    Align::new().alignment(alignment).child(
10381                        MenuAnchor::new(vec![submenu_1]).builder(
10382                            |_app, _context, controller, _child| {
10383                                toggle_button(controller, "Tap me")
10384                            },
10385                        ),
10386                    ),
10387                )
10388                .into_widget()
10389            });
10390            pump(tester);
10391
10392            for text in [
10393                "Tap me",
10394                "SubMenuButton1",
10395                "SubMenuButton2",
10396                "SubMenuButton3",
10397            ] {
10398                tester.tap(find::text(text));
10399                pump(tester);
10400            }
10401        }
10402
10403        // menu_anchor_test.dart 'constrained menus show up in the right place with offset in LTR'.
10404        #[test]
10405        fn constrained_menus_show_up_in_the_right_place_with_offset_in_ltr() {
10406            test_widgets(|tester| {
10407                nested_offset_menus(tester, TextDirection::Ltr);
10408
10409                assert_eq!(count_of::<SubmenuButton>(tester), 4);
10410                assert_eq!(
10411                    submenu_rects(tester),
10412                    [
10413                        Rect::from_ltrb(0.0, 48.0, 256.0, 112.0),
10414                        Rect::from_ltrb(266.0, 48.0, 522.0, 112.0),
10415                        Rect::from_ltrb(522.0, 48.0, 778.0, 112.0),
10416                        Rect::from_ltrb(256.0, 48.0, 512.0, 112.0),
10417                    ]
10418                );
10419            });
10420        }
10421
10422        // menu_anchor_test.dart 'constrained menus show up in the right place with offset in RTL'.
10423        #[test]
10424        fn constrained_menus_show_up_in_the_right_place_with_offset_in_rtl() {
10425            test_widgets(|tester| {
10426                nested_offset_menus(tester, TextDirection::Rtl);
10427
10428                assert_eq!(count_of::<SubmenuButton>(tester), 4);
10429                assert_eq!(
10430                    submenu_rects(tester),
10431                    [
10432                        Rect::from_ltrb(544.0, 48.0, 800.0, 112.0),
10433                        Rect::from_ltrb(278.0, 48.0, 534.0, 112.0),
10434                        Rect::from_ltrb(22.0, 48.0, 278.0, 112.0),
10435                        Rect::from_ltrb(288.0, 48.0, 544.0, 112.0),
10436                    ]
10437                );
10438            });
10439        }
10440
10441        /// Dart's 'vertically constrained menus' boilerplate: a menu anchored at the bottom left of
10442        /// the view, opened by its button.
10443        fn bottom_anchored_menu(tester: &mut WidgetTester, alignment_offset: Option<Offset>) {
10444            pump_app(tester, m2, move |_app| {
10445                let mut anchor = MenuAnchor::new(vec![
10446                    MenuItemButton::new()
10447                        .child(Text::new("Button1"))
10448                        .into_widget(),
10449                ])
10450                .builder(|_app, _context, controller, _child| toggle_button(controller, "Tap me"));
10451                if let Some(alignment_offset) = alignment_offset {
10452                    anchor = anchor.alignment_offset(alignment_offset);
10453                }
10454                Directionality::new(
10455                    TextDirection::Ltr,
10456                    Align::new()
10457                        .alignment(AlignmentGeometry::BOTTOM_LEFT)
10458                        .child(anchor),
10459                )
10460                .into_widget()
10461            });
10462
10463            pump(tester);
10464            tester.tap(find::text("Tap me"));
10465            pump(tester);
10466        }
10467
10468        // menu_anchor_test.dart 'vertically constrained menus are positioned above the anchor by
10469        // default'.
10470        #[test]
10471        fn vertically_constrained_menus_are_positioned_above_the_anchor_by_default() {
10472            test_widgets(|tester| {
10473                bottom_anchored_menu(tester, None);
10474
10475                assert_eq!(count_of::<MenuItemButton>(tester), 1);
10476                // Test the default offset (0, 0) vertical position.
10477                assert_eq!(
10478                    submenu_rects(tester),
10479                    [Rect::from_ltrb(0.0, 488.0, 122.0, 552.0)]
10480                );
10481            });
10482        }
10483
10484        // menu_anchor_test.dart 'vertically constrained menus are positioned above the anchor with
10485        // the provided offset'.
10486        #[test]
10487        fn vertically_constrained_menus_are_positioned_above_the_anchor_with_the_provided_offset() {
10488            test_widgets(|tester| {
10489                bottom_anchored_menu(tester, Some(Offset::new(0.0, 50.0)));
10490
10491                assert_eq!(count_of::<MenuItemButton>(tester), 1);
10492                // Test the offset (0, 50) vertical position.
10493                assert_eq!(
10494                    submenu_rects(tester),
10495                    [Rect::from_ltrb(0.0, 438.0, 122.0, 502.0)]
10496                );
10497            });
10498        }
10499
10500        /// Dart's `tester.getRect(find.byKey(key))`.
10501        fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
10502            tester.get_rect(tester.render_object(key).as_box().expect("a render box"))
10503        }
10504
10505        /// Dart's `tester.getRect(findMenuPanels())`.
10506        fn menu_panel_rect(tester: &WidgetTester) -> Rect {
10507            rect_of_element(tester, only(menu_panels(tester)))
10508        }
10509
10510        // menu_anchor_test.dart 'Menu follows content position when a LayerLink is provided'.
10511        #[test]
10512        fn a_menu_follows_its_content_when_given_a_layer_link() {
10513            test_widgets(|tester| {
10514                let controller = new_controller(tester);
10515                let content_key = GlobalKey::new();
10516
10517                let boilerplate = |tester: &mut WidgetTester, bottom_insets: f64| {
10518                    let content_key = content_key.clone();
10519                    pump_app(tester, m3, {
10520                        let controller = controller.clone();
10521                        move |app| {
10522                            let layer_link = LayerLink::new(app);
10523                            MediaQuery::new(
10524                                MediaQueryData::new().view_insets(EdgeInsets::only(
10525                                    0.0,
10526                                    0.0,
10527                                    0.0,
10528                                    bottom_insets,
10529                                )),
10530                                Scaffold::new().body(
10531                                    Center::new().child(
10532                                        MenuAnchor::new(vec![
10533                                            MenuItemButton::new()
10534                                                .on_pressed(Listener::new(|_app| {}))
10535                                                .child(Text::new("Button 1"))
10536                                                .into_widget(),
10537                                        ])
10538                                        .controller(controller.clone())
10539                                        .layer_link(layer_link)
10540                                        .builder(
10541                                            move |_app, _context, _controller, _child| {
10542                                                SizedBox::new()
10543                                                    .key(content_key.clone().into())
10544                                                    .width(100.0)
10545                                                    .height(100.0)
10546                                                    .into_widget()
10547                                            },
10548                                        ),
10549                                    ),
10550                                ),
10551                            )
10552                            .into_widget()
10553                        }
10554                    });
10555                };
10556
10557                // Build once without bottom insets and open the menu.
10558                boilerplate(tester, 0.0);
10559                controller.open(&mut tester.cell.borrow_mut(), None);
10560                pump(tester);
10561
10562                // Menu vertical position is just under the content.
10563                assert_eq!(
10564                    menu_panel_rect(tester).top,
10565                    rect_of_key(tester, &content_key).bottom
10566                );
10567
10568                // Simulate the keyboard opening resizing the view.
10569                boilerplate(tester, 100.0);
10570                pump(tester);
10571
10572                // Menu vertical position is just under the content.
10573                assert_eq!(
10574                    menu_panel_rect(tester).top,
10575                    rect_of_key(tester, &content_key).bottom
10576                );
10577            });
10578        }
10579
10580        // menu_anchor_test.dart 'menu is positioned to avoid the software keyboard'.
10581        #[test]
10582        fn a_menu_is_positioned_to_avoid_the_software_keyboard() {
10583            test_widgets(|tester| {
10584                // Regression test for https://github.com/flutter/flutter/issues/142921
10585                // The menu should not extend into the area occupied by the software keyboard.
10586                let screen_size = Size::new(600.0, 800.0);
10587                // Dart's `changeSurfaceSize(tester, screenSize)`.
10588                tester.set_surface_size(Some(screen_size));
10589                const KEYBOARD_HEIGHT: f64 = 200.0;
10590                let controller = new_controller(tester);
10591
10592                let root = {
10593                    let app = tester.cell.borrow();
10594                    MaterialApp::new()
10595                        .theme(m3(&app))
10596                        .builder(|app, context, child| {
10597                            MediaQuery::new(
10598                                MediaQuery::of(app, context)
10599                                    .copy_with()
10600                                    .view_insets(EdgeInsets::only(0.0, 0.0, 0.0, KEYBOARD_HEIGHT)),
10601                                child.cloned().expect("the navigator"),
10602                            )
10603                            .into_widget()
10604                        })
10605                        .home(Material::new().child(Stack::new().children(vec![
10606                            // Position anchor just above the keyboard, so menu would extend
10607                            // into keyboard area if opened below.
10608                            Positioned::new(
10609                                MenuAnchor::new(
10610                                    (0..5)
10611                                        .map(|index| {
10612                                            MenuItemButton::new()
10613                                                .on_pressed(Listener::new(|_app| {}))
10614                                                .child(Text::new(format!("Item {index}")))
10615                                                .into_widget()
10616                                        })
10617                                        .collect(),
10618                                )
10619                                .controller(controller.clone())
10620                                .builder(
10621                                    |_app, _context, controller, _child| {
10622                                        FilledButton::new(
10623                                            Some(Listener::new(move |app| {
10624                                                controller.open(app, None);
10625                                            })),
10626                                            Some(Text::new("Open Menu")),
10627                                        )
10628                                        .into_widget()
10629                                    },
10630                                ),
10631                            )
10632                            .left(100.0)
10633                            // 100px above keyboard
10634                            .bottom(KEYBOARD_HEIGHT + 100.0)
10635                            .into_widget(),
10636                        ])))
10637                        .into_widget()
10638                };
10639                tester.pump_widget(root);
10640
10641                controller.open(&mut tester.cell.borrow_mut(), None);
10642                tester.pump_and_settle();
10643
10644                let menu_rect = menu_panel_rect(tester);
10645                // Menu should not extend into the keyboard area (bottom 200px of screen).
10646                assert!(
10647                    menu_rect.bottom <= screen_size.height() - KEYBOARD_HEIGHT,
10648                    "Menu bottom ({}) should not extend into keyboard area (below {})",
10649                    menu_rect.bottom,
10650                    screen_size.height() - KEYBOARD_HEIGHT
10651                );
10652            });
10653        }
10654
10655        // menu_anchor_test.dart 'Menu is correctly offset when a LayerLink is provided and
10656        // alignmentOffset is set'.
10657        #[test]
10658        fn a_menu_with_a_layer_link_is_offset_by_its_alignment_offset() {
10659            test_widgets(|tester| {
10660                let controller = new_controller(tester);
10661                let content_key = GlobalKey::new();
10662                const HORIZONTAL_OFFSET: f64 = 16.0;
10663                const VERTICAL_OFFSET: f64 = 20.0;
10664
10665                let key = content_key.clone();
10666                pump_app(tester, m3, {
10667                    let controller = controller.clone();
10668                    move |app| {
10669                        let layer_link = LayerLink::new(app);
10670                        Scaffold::new()
10671                            .body(
10672                                Center::new().child(
10673                                    MenuAnchor::new(vec![
10674                                        MenuItemButton::new()
10675                                            .on_pressed(Listener::new(|_app| {}))
10676                                            .child(Text::new("Button 1"))
10677                                            .into_widget(),
10678                                    ])
10679                                    .controller(controller.clone())
10680                                    .layer_link(layer_link)
10681                                    .alignment_offset(Offset::new(
10682                                        HORIZONTAL_OFFSET,
10683                                        VERTICAL_OFFSET,
10684                                    ))
10685                                    .builder(
10686                                        move |_app, _context, _controller, _child| {
10687                                            SizedBox::new()
10688                                                .key(key.clone().into())
10689                                                .width(100.0)
10690                                                .height(100.0)
10691                                                .into_widget()
10692                                        },
10693                                    ),
10694                                ),
10695                            )
10696                            .into_widget()
10697                    }
10698                });
10699
10700                controller.open(&mut tester.cell.borrow_mut(), None);
10701                pump(tester);
10702
10703                assert_eq!(
10704                    menu_panel_rect(tester).top,
10705                    rect_of_key(tester, &content_key).bottom + VERTICAL_OFFSET
10706                );
10707                assert_eq!(
10708                    menu_panel_rect(tester).left,
10709                    rect_of_key(tester, &content_key).left + HORIZONTAL_OFFSET
10710                );
10711            });
10712        }
10713
10714        // menu_anchor_test.dart 'Menu vertical padding should not be reduced with compact visual
10715        // density'.
10716        #[test]
10717        fn compact_visual_density_does_not_reduce_a_menus_vertical_padding() {
10718            test_widgets(|tester| {
10719                // Helper function to get menu padding by measuring first/last items.
10720                let menu_padding = |tester: &WidgetTester| -> (f64, f64) {
10721                    // Find any menu items that are available.
10722                    let menu_items = find::by_type::<SubmenuButton>().evaluate(tester);
10723                    if menu_items.len() < 2 {
10724                        return (0.0, 0.0);
10725                    }
10726
10727                    let first_item = rect_of_element(tester, menu_items[0]);
10728                    let last_item = rect_of_element(tester, *menu_items.last().expect("two items"));
10729                    let materials = find::by_type::<Material>().evaluate(tester);
10730                    let menu_panel =
10731                        rect_of_element(tester, *materials.last().expect("a material"));
10732
10733                    let top_padding = first_item.top - menu_panel.top;
10734                    let bottom_padding = menu_panel.bottom - last_item.bottom;
10735                    (top_padding, bottom_padding)
10736                };
10737
10738                let build_simple_menu_anchor =
10739                    |tester: &mut WidgetTester, visual_density: VisualDensity| {
10740                        pump_app(
10741                            tester,
10742                            |app| {
10743                                ThemeData::builder()
10744                                    .visual_density(visual_density)
10745                                    .build(app)
10746                            },
10747                            |_app| {
10748                                let text = |text: &str| {
10749                                    DecoratedBox::new(
10750                                        BoxDecoration::new().color(Colors::BLUE.primary()),
10751                                    )
10752                                    .child(Text::new(text))
10753                                    .into_widget()
10754                                };
10755                                Directionality::new(
10756                                    TextDirection::Ltr,
10757                                    Scaffold::new().body(
10758                                        MenuAnchor::new(vec![text("Text 1"), text("Text 2")])
10759                                            .style(MenuStyle::new().padding(Rc::new(
10760                                                WidgetStatePropertyAll::new(Some(
10761                                                    EdgeInsetsGeometry::symmetric(12.0, 4.0),
10762                                                )),
10763                                            )))
10764                                            .builder(|_app, _context, controller, _child| {
10765                                                TextButton::new(
10766                                                    Some(Listener::new(move |app| {
10767                                                        if controller.is_open(app) {
10768                                                            controller.close(app);
10769                                                        } else {
10770                                                            controller.open(app, None);
10771                                                        }
10772                                                    })),
10773                                                    Some(Text::new("OPEN MENU")),
10774                                                )
10775                                                .into_widget()
10776                                            }),
10777                                    ),
10778                                )
10779                                .into_widget()
10780                            },
10781                        );
10782
10783                        tester.tap(find::text("OPEN MENU"));
10784                        pump(tester);
10785                    };
10786
10787                // Pump widget with standard visual density.
10788                build_simple_menu_anchor(tester, VisualDensity::STANDARD);
10789
10790                let (top_standard, bottom_standard) = menu_padding(tester);
10791
10792                // Pump widget with compact visual density.
10793                build_simple_menu_anchor(tester, VisualDensity::COMPACT);
10794
10795                let (top_compact, bottom_compact) = menu_padding(tester);
10796
10797                // Compare standard vs compact padding.
10798                assert_eq!(
10799                    top_compact, top_standard,
10800                    "Compact visual density should not change top padding. Standard: \
10801                     {top_standard}, Compact: {top_compact}"
10802                );
10803                assert_eq!(
10804                    bottom_compact, bottom_standard,
10805                    "Compact visual density should not change bottom padding. Standard: \
10806                     {bottom_standard}, Compact: {bottom_compact}"
10807                );
10808            });
10809        }
10810
10811        // ---- LocalizedShortcutLabeler ----
10812
10813        const ALL_PLATFORMS: [TargetPlatform; 6] = [
10814            TargetPlatform::Android,
10815            TargetPlatform::Fuchsia,
10816            TargetPlatform::IOS,
10817            TargetPlatform::Linux,
10818            TargetPlatform::MacOS,
10819            TargetPlatform::Windows,
10820        ];
10821
10822        /// A menu bar of one submenu, "Menu 0", whose items show `shortcuts`, opened.
10823        fn open_shortcut_menu(
10824            tester: &mut WidgetTester,
10825            shortcuts: [(MenuSerializableShortcutRef, TestMenu); 2],
10826        ) {
10827            let controller = new_controller(tester);
10828            pump_material(tester, m3, move |_app| {
10829                let items = shortcuts
10830                    .iter()
10831                    .map(|(shortcut, menu)| {
10832                        MenuItemButton::new()
10833                            .shortcut(Rc::clone(shortcut))
10834                            .child(Text::new(menu.label()))
10835                            .into_widget()
10836                    })
10837                    .collect();
10838                MenuBar::new(vec![
10839                    SubmenuButton::new(items, Some(Text::new(TestMenu::MainMenu0.label())))
10840                        .into_widget(),
10841                ])
10842                .controller(controller)
10843                .into_widget()
10844            });
10845            tester.tap(find::text(&TestMenu::MainMenu0.label()));
10846            pump(tester);
10847        }
10848
10849        // menu_anchor_test.dart 'getShortcutLabel returns the right labels'.
10850        #[test]
10851        fn shortcut_labels_name_the_modifiers_of_each_platform() {
10852            for platform in ALL_PLATFORMS {
10853                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
10854                    let (
10855                        expected_meta,
10856                        expected_ctrl,
10857                        expected_alt,
10858                        expected_separator,
10859                        expected_shift,
10860                    ) = match platform {
10861                        TargetPlatform::Android
10862                        | TargetPlatform::Fuchsia
10863                        | TargetPlatform::Linux
10864                        | TargetPlatform::Windows => (
10865                            if platform == TargetPlatform::Windows {
10866                                "Win"
10867                            } else {
10868                                "Meta"
10869                            },
10870                            "Ctrl",
10871                            "Alt",
10872                            "+",
10873                            "Shift",
10874                        ),
10875                        TargetPlatform::IOS | TargetPlatform::MacOS => ("⌘", "⌃", "⌥", " ", "⇧"),
10876                    };
10877
10878                    let all_modifiers: MenuSerializableShortcutRef = Rc::new(
10879                        SingleActivator::new(LogicalKeyboardKey::KEY_A)
10880                            .control(true)
10881                            .meta(true)
10882                            .shift(true)
10883                            .alt(true),
10884                    );
10885                    let all_expected = match platform {
10886                        TargetPlatform::Android
10887                        | TargetPlatform::Fuchsia
10888                        | TargetPlatform::Linux
10889                        | TargetPlatform::Windows => [
10890                            expected_alt,
10891                            expected_ctrl,
10892                            expected_meta,
10893                            expected_shift,
10894                            "A",
10895                        ]
10896                        .join(expected_separator),
10897                        TargetPlatform::IOS | TargetPlatform::MacOS => [
10898                            expected_ctrl,
10899                            expected_alt,
10900                            expected_shift,
10901                            expected_meta,
10902                            "A",
10903                        ]
10904                        .join(expected_separator),
10905                    };
10906                    let char_shortcuts: MenuSerializableShortcutRef =
10907                        Rc::new(CharacterActivator::new("ñ"));
10908                    let char_expected = "ñ";
10909                    open_shortcut_menu(
10910                        tester,
10911                        [
10912                            (all_modifiers, TestMenu::SubMenu10),
10913                            (char_shortcuts, TestMenu::SubMenu11),
10914                        ],
10915                    );
10916
10917                    assert!(shows(tester, &all_expected), "{platform:?}");
10918                    assert!(shows(tester, char_expected), "{platform:?}");
10919                });
10920            }
10921        }
10922
10923        // menu_anchor_test.dart 'getShortcutLabel formats unlocalized non-Unicode keys'.
10924        #[test]
10925        fn shortcut_labels_fall_back_to_the_key_label_of_unlocalized_keys() {
10926            for platform in ALL_PLATFORMS {
10927                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
10928                    let (expected_ctrl, expected_separator) = match platform {
10929                        TargetPlatform::Android
10930                        | TargetPlatform::Fuchsia
10931                        | TargetPlatform::Linux
10932                        | TargetPlatform::Windows => ("Ctrl", "+"),
10933                        TargetPlatform::IOS | TargetPlatform::MacOS => ("⌃", " "),
10934                    };
10935
10936                    open_shortcut_menu(
10937                        tester,
10938                        [
10939                            (
10940                                Rc::new(
10941                                    SingleActivator::new(LogicalKeyboardKey::TAB).control(true),
10942                                ),
10943                                TestMenu::SubMenu10,
10944                            ),
10945                            (
10946                                Rc::new(SingleActivator::new(LogicalKeyboardKey::F1).control(true)),
10947                                TestMenu::SubMenu11,
10948                            ),
10949                        ],
10950                    );
10951
10952                    assert!(
10953                        shows(tester, &format!("{expected_ctrl}{expected_separator}Tab")),
10954                        "{platform:?}"
10955                    );
10956                    assert!(
10957                        shows(tester, &format!("{expected_ctrl}{expected_separator}F1")),
10958                        "{platform:?}"
10959                    );
10960                });
10961            }
10962        }
10963
10964        // ---- CheckboxMenuButton ----
10965
10966        // menu_anchor_test.dart 'tapping toggles checkbox'.
10967        #[test]
10968        fn tapping_a_checkbox_menu_button_cycles_its_tristate_value() {
10969            test_widgets(|tester| {
10970                let check_box_value: Rc<Cell<Option<bool>>> = Rc::new(Cell::new(None));
10971                let value = Rc::clone(&check_box_value);
10972                pump_app(tester, m3, move |_app| {
10973                    StatefulBuilder::new(move |_app, _context, set_state| {
10974                        let changed = Rc::clone(&value);
10975                        MenuBar::new(vec![
10976                            SubmenuButton::new(
10977                                vec![
10978                                    CheckboxMenuButton::new(
10979                                        value.get(),
10980                                        Some(Rc::new(
10981                                            move |app: &mut App, new_value: Option<bool>| {
10982                                                let changed = Rc::clone(&changed);
10983                                                set_state(app, &mut |_app| changed.set(new_value));
10984                                            },
10985                                        )),
10986                                        Some(Text::new("checkbox")),
10987                                    )
10988                                    .tristate(true)
10989                                    .into_widget(),
10990                                ],
10991                                Some(Text::new("submenu")),
10992                            )
10993                            .into_widget(),
10994                        ])
10995                        .into_widget()
10996                    })
10997                    .into_widget()
10998                });
10999
11000                let submenu = center_of_first::<SubmenuButton>(tester);
11001                tester.tap_at(submenu, 1);
11002                pump(tester);
11003
11004                let checkbox = tester.element(find::by_type::<CheckboxMenuButton>());
11005                assert_eq!(
11006                    tester.widget(checkbox, |button: &CheckboxMenuButton| button.value),
11007                    None
11008                );
11009
11010                for expected in [Some(false), Some(true), None] {
11011                    if expected != Some(false) {
11012                        let submenu = center_of_first::<SubmenuButton>(tester);
11013                        tester.tap_at(submenu, 1);
11014                        pump(tester);
11015                    }
11016                    let checkbox = center_of_first::<CheckboxMenuButton>(tester);
11017                    tester.tap_at(checkbox, 1);
11018                    tester.pump_and_settle();
11019                    assert_eq!(check_box_value.get(), expected);
11020                }
11021            });
11022        }
11023
11024        // ---- RadioMenuButton ----
11025
11026        // menu_anchor_test.dart 'tapping toggles radio button'.
11027        #[test]
11028        fn tapping_a_toggleable_radio_menu_button_selects_and_clears_it() {
11029            test_widgets(|tester| {
11030                let radio_value: Rc<Cell<Option<i32>>> = Rc::new(Cell::new(None));
11031                let value = Rc::clone(&radio_value);
11032                pump_app(tester, m3, move |_app| {
11033                    StatefulBuilder::new(move |_app, _context, set_state| {
11034                        let radio = |radio: i32| {
11035                            let changed = Rc::clone(&value);
11036                            let set_state = Rc::clone(&set_state);
11037                            RadioMenuButton::new(
11038                                radio,
11039                                value.get(),
11040                                Some(Rc::new(move |app: &mut App, new_value: Option<i32>| {
11041                                    let changed = Rc::clone(&changed);
11042                                    set_state(app, &mut |_app| changed.set(new_value));
11043                                })),
11044                                Some(Text::new(format!("radio {radio}"))),
11045                            )
11046                            .toggleable(true)
11047                            .into_widget()
11048                        };
11049                        MenuBar::new(vec![
11050                            SubmenuButton::new(
11051                                vec![radio(0), radio(1)],
11052                                Some(Text::new("submenu")),
11053                            )
11054                            .into_widget(),
11055                        ])
11056                        .into_widget()
11057                    })
11058                    .into_widget()
11059                });
11060
11061                let submenu = center_of_first::<SubmenuButton>(tester);
11062                tester.tap_at(submenu, 1);
11063                pump(tester);
11064
11065                let first = find::by_type::<RadioMenuButton<i32>>().evaluate(tester)[0];
11066                assert_eq!(
11067                    tester.widget(first, |button: &RadioMenuButton<i32>| button.group_value),
11068                    None
11069                );
11070
11071                let first = center_of_first::<RadioMenuButton<i32>>(tester);
11072                tester.tap_at(first, 1);
11073                tester.pump_and_settle();
11074                assert_eq!(radio_value.get(), Some(0));
11075
11076                let submenu = center_of_first::<SubmenuButton>(tester);
11077                tester.tap_at(submenu, 1);
11078                pump(tester);
11079                let first = center_of_first::<RadioMenuButton<i32>>(tester);
11080                tester.tap_at(first, 1);
11081                tester.pump_and_settle();
11082                assert_eq!(radio_value.get(), None);
11083
11084                let submenu = center_of_first::<SubmenuButton>(tester);
11085                tester.tap_at(submenu, 1);
11086                pump(tester);
11087                let last = center_of_last::<RadioMenuButton<i32>>(tester);
11088                tester.tap_at(last, 1);
11089                tester.pump_and_settle();
11090                assert_eq!(radio_value.get(), Some(1));
11091            });
11092        }
11093
11094        // ---- the cases after the Semantics group ----
11095
11096        /// Dart's `find.descendant(of: of, matching: find.byType(Material)).first`.
11097        fn first_material_below(tester: &WidgetTester, of: AnyElement) -> AnyElement {
11098            tester.descendants_of_type::<Material>(of)[0]
11099        }
11100
11101        /// Dart's `find.widgetWithText(TextButton, text)`.
11102        fn text_button_with_text(tester: &WidgetTester, text: &str) -> AnyElement {
11103            let buttons = ancestors_of_type::<TextButton>(tester, text);
11104            *buttons.first().expect("a TextButton above the text")
11105        }
11106
11107        // menu_anchor_test.dart 'Material3 - Menu uses correct text styles'.
11108        #[test]
11109        fn material3_menu_buttons_use_the_label_large_text_style() {
11110            test_widgets(|tester| {
11111                let log = Log::default();
11112                let controller = new_controller(tester);
11113                let menu_text_style = TextStyle::new()
11114                    .font_size(18.5)
11115                    .font_style(FontStyle::Italic)
11116                    .word_spacing(1.2)
11117                    .decoration(TextDecoration::LINE_THROUGH);
11118                let style = menu_text_style.clone();
11119                let menus = TestMenus::all(&log);
11120                pump_material(
11121                    tester,
11122                    move |app| {
11123                        ThemeData::builder()
11124                            .text_theme(TextTheme::new().label_large(style))
11125                            .build(app)
11126                    },
11127                    |_app| {
11128                        MenuBar::new(menus.build())
11129                            .controller(controller)
11130                            .into_widget()
11131                    },
11132                );
11133
11134                let check = |tester: &WidgetTester, button: AnyElement| {
11135                    let material = first_material_below(tester, button);
11136                    tester.widget(material, |material: &Material| {
11137                        let text_style = material.text_style.as_ref().expect("a text style");
11138                        assert_eq!(text_style.font_size, menu_text_style.font_size);
11139                        assert_eq!(text_style.font_style, menu_text_style.font_style);
11140                        assert_eq!(text_style.word_spacing, menu_text_style.word_spacing);
11141                        assert_eq!(text_style.decoration, menu_text_style.decoration);
11142                    });
11143                };
11144
11145                // Test menu button text style uses the TextTheme.labelLarge.
11146                check(tester, find::by_type::<TextButton>().evaluate(tester)[0]);
11147
11148                // Open the menu.
11149                tester.tap(find::text(&TestMenu::MainMenu1.label()));
11150                pump(tester);
11151
11152                // Test menu item text style uses the TextTheme.labelLarge.
11153                check(
11154                    tester,
11155                    text_button_with_text(tester, &TestMenu::SubMenu10.label()),
11156                );
11157            });
11158        }
11159
11160        // menu_anchor_test.dart 'SubmenuButton.onFocusChange is respected'.
11161        #[test]
11162        fn a_submenu_button_reports_its_focus_changes() {
11163            test_widgets(|tester| {
11164                let focus_node =
11165                    FocusNode::new(&mut tester.cell.borrow_mut()).into_erased::<AnyFocusNode>();
11166                let on_focus_change_called = Rc::new(Cell::new(0));
11167                let called = Rc::clone(&on_focus_change_called);
11168                pump_material(tester, m3, {
11169                    let focus_node = focus_node.clone();
11170                    move |_app| {
11171                        StatefulBuilder::new(move |_app, _context, set_state| {
11172                            let called = Rc::clone(&called);
11173                            SubmenuButton::new(
11174                                vec![
11175                                    MenuItemButton::new()
11176                                        .child(Text::new("item 0"))
11177                                        .into_widget(),
11178                                ],
11179                                Some(Text::new("Submenu 0")),
11180                            )
11181                            .focus_node(focus_node.clone())
11182                            .on_focus_change(Rc::new(move |app: &mut App, _value: bool| {
11183                                let called = Rc::clone(&called);
11184                                set_state(app, &mut |_app| called.set(called.get() + 1));
11185                            }))
11186                            .into_widget()
11187                        })
11188                        .into_widget()
11189                    }
11190                });
11191
11192                focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
11193                pump(tester);
11194                assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
11195                assert_eq!(on_focus_change_called.get(), 1);
11196
11197                focus_node.unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
11198                pump(tester);
11199                assert!(!focus_node.has_focus(&tester.cell.borrow_mut()));
11200                assert_eq!(on_focus_change_called.get(), 2);
11201            });
11202        }
11203
11204        // menu_anchor_test.dart 'Horizontal _MenuPanel wraps children with IntrinsicWidth'.
11205        #[test]
11206        fn a_horizontal_menu_panel_wraps_its_children_in_intrinsic_widths() {
11207            test_widgets(|tester| {
11208                pump_material(tester, m3, |_app| {
11209                    MenuBar::new(vec![
11210                        MenuItemButton::new()
11211                            .on_pressed(Listener::new(|_app| {}))
11212                            .child(Text::new("Menu Item"))
11213                            .into_widget(),
11214                    ])
11215                    .into_widget()
11216                });
11217
11218                // Horizontal _MenuPanel wraps children with IntrinsicWidth to ensure MenuItemButton
11219                // with vertical overflow axis is as wide as the widest child.
11220                let item = tester.element(find::by_type::<MenuItemButton>());
11221                let ancestors = tester.ancestors(item);
11222                let app = tester.cell.borrow();
11223                let intrinsic_widths = ancestors
11224                    .into_iter()
11225                    .filter(|ancestor| {
11226                        waft_widgets::downcast_widget::<IntrinsicWidth>(&**ancestor.widget(&app))
11227                            .is_some()
11228                    })
11229                    .count();
11230                assert_eq!(intrinsic_widths, 1);
11231            });
11232        }
11233
11234        // menu_anchor_test.dart 'SubmenuButton.styleFrom overlayColor overrides default overlay
11235        // color'.
11236        #[test]
11237        fn submenu_button_style_from_overlay_color_overrides_the_default_overlay_color() {
11238            test_widgets(|tester| {
11239                let overlay_color = Color::new(0xffff00ff);
11240                pump_app(tester, m3, move |_app| {
11241                    Scaffold::new()
11242                        .body(
11243                            SubmenuButton::new(
11244                                vec![
11245                                    MenuItemButton::new()
11246                                        .on_pressed(Listener::new(|_app| {}))
11247                                        .child(Text::new("MenuItemButton"))
11248                                        .into_widget(),
11249                                ],
11250                                Some(Text::new("Submenu")),
11251                            )
11252                            .style(
11253                                SubmenuButton::style_from()
11254                                    .overlay_color(overlay_color)
11255                                    .build(),
11256                            ),
11257                        )
11258                        .into_widget()
11259                });
11260
11261                // Hovered.
11262                let center = center_of_first::<SubmenuButton>(tester);
11263                let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
11264                tester.add_pointer(&mut gesture, Offset::ZERO);
11265                tester.move_to(&mut gesture, center, false);
11266                tester.pump_and_settle();
11267                assert_paints(
11268                    &overlay_ops(tester),
11269                    &[PaintCall::rect(Some(overlay_color.with_opacity(0.08)))],
11270                );
11271
11272                // Highlighted (pressed).
11273                tester.down(&mut gesture, center);
11274                tester.pump_and_settle();
11275                assert_paints(
11276                    &overlay_ops(tester),
11277                    &[
11278                        PaintCall::rect(Some(overlay_color.with_opacity(0.08))),
11279                        PaintCall::rect(Some(overlay_color.with_opacity(0.08))),
11280                        PaintCall::rect(Some(overlay_color.with_opacity(0.1))),
11281                    ],
11282                );
11283            });
11284        }
11285
11286        /// Dart's `iconStyle(tester, icon)`.
11287        fn icon_color(tester: &WidgetTester, icon: &waft_widgets::IconData) -> Option<Color> {
11288            let icon = tester.element(find::by_icon(icon).first());
11289            tester.glyph_style(icon).color.as_deref().copied()
11290        }
11291
11292        // menu_anchor_test.dart 'MenuItemButton.styleFrom can customize the button icon'.
11293        #[test]
11294        fn menu_item_button_style_from_customizes_the_button_icon() {
11295            test_widgets(|tester| {
11296                let icon_color_value = Color::new(0xFFF000FF);
11297                const ICON_SIZE: f64 = 32.0;
11298                let disabled_icon_color = Color::new(0xFFFFF000);
11299                let build_button = |tester: &mut WidgetTester, enabled: bool| {
11300                    pump_material(tester, m3, move |_app| {
11301                        let mut button = MenuItemButton::new()
11302                            .style(
11303                                MenuItemButton::style_from()
11304                                    .icon_color(icon_color_value)
11305                                    .icon_size(ICON_SIZE)
11306                                    .disabled_icon_color(disabled_icon_color)
11307                                    .build(),
11308                            )
11309                            .trailing_icon(Icon::new(Some(Icons::add())))
11310                            .child(Text::new("Button"));
11311                        if enabled {
11312                            button = button.on_pressed(Listener::new(|_app| {}));
11313                        }
11314                        Center::new().child(button).into_widget()
11315                    });
11316                };
11317
11318                // Test enabled button.
11319                build_button(tester, true);
11320                let icon = tester.element(find::by_icon(&Icons::add()).first());
11321                assert_eq!(
11322                    rect_of_element(tester, icon).size(),
11323                    Size::new(ICON_SIZE, ICON_SIZE)
11324                );
11325                assert_eq!(icon_color(tester, &Icons::add()), Some(icon_color_value));
11326
11327                // Test disabled button.
11328                build_button(tester, false);
11329                assert_eq!(icon_color(tester, &Icons::add()), Some(disabled_icon_color));
11330            });
11331        }
11332
11333        // menu_anchor_test.dart 'SubmenuButton.styleFrom can customize the button icon'.
11334        #[test]
11335        fn submenu_button_style_from_customizes_the_button_icon() {
11336            test_widgets(|tester| {
11337                let icon_color_value = Color::new(0xFFF000FF);
11338                const ICON_SIZE: f64 = 32.0;
11339                let disabled_icon_color = Color::new(0xFFFFF000);
11340                let build_button = |tester: &mut WidgetTester, enabled: bool| {
11341                    pump_material(tester, m3, move |_app| {
11342                        let menu_children = if enabled {
11343                            vec![Text::new("Item").into_widget()]
11344                        } else {
11345                            Vec::new()
11346                        };
11347                        Center::new()
11348                            .child(
11349                                SubmenuButton::new(menu_children, Some(Text::new("SubmenuButton")))
11350                                    .style(
11351                                        SubmenuButton::style_from()
11352                                            .icon_color(icon_color_value)
11353                                            .icon_size(ICON_SIZE)
11354                                            .disabled_icon_color(disabled_icon_color)
11355                                            .build(),
11356                                    )
11357                                    .trailing_icon(Icon::new(Some(Icons::add()))),
11358                            )
11359                            .into_widget()
11360                    });
11361                };
11362
11363                // Test enabled button.
11364                build_button(tester, true);
11365                let icon = tester.element(find::by_icon(&Icons::add()).first());
11366                assert_eq!(
11367                    rect_of_element(tester, icon).size(),
11368                    Size::new(ICON_SIZE, ICON_SIZE)
11369                );
11370                assert_eq!(icon_color(tester, &Icons::add()), Some(icon_color_value));
11371
11372                // Test disabled button.
11373                build_button(tester, false);
11374                assert_eq!(icon_color(tester, &Icons::add()), Some(disabled_icon_color));
11375            });
11376        }
11377
11378        /// Dart's `ancestorRenderTheaters(child)`: the theaters above `child`, nearest first.
11379        fn ancestor_render_theaters(
11380            tester: &WidgetTester,
11381            child: AnyRenderObject,
11382        ) -> Vec<AnyRenderObject> {
11383            let app = tester.cell.borrow();
11384            std::iter::successors(Some(child), |node| node.parent(&app))
11385                .filter(|node| node.downcast::<RenderTheater>(&app).is_some())
11386                .collect()
11387        }
11388
11389        /// Dart's boilerplate of the useRootOverlay cases: a menu in an entry of a nested `Overlay`
11390        /// keyed `overlay_key`, its one item keyed `menu_item_key`.
11391        fn nested_overlay_menu(
11392            tester: &mut WidgetTester,
11393            controller: MenuControllerRef,
11394            use_root_overlay: bool,
11395            overlay_key: &GlobalKey,
11396            menu_item_key: &GlobalKey,
11397        ) {
11398            let (overlay_key, menu_item_key) = (overlay_key.clone(), menu_item_key.clone());
11399            pump_app(tester, m3, move |app| {
11400                let entry = OverlayEntry::new(
11401                    app,
11402                    Rc::new(move |_app, _context| {
11403                        Scaffold::new()
11404                            .body(
11405                                Center::new().child(
11406                                    MenuAnchor::new(vec![
11407                                        MenuItemButton::new()
11408                                            .key(menu_item_key.clone().into())
11409                                            .on_pressed(Listener::new(|_app| {}))
11410                                            .child(Text::new("Item 1"))
11411                                            .into_widget(),
11412                                    ])
11413                                    .use_root_overlay(use_root_overlay)
11414                                    .controller(controller.clone()),
11415                                ),
11416                            )
11417                            .into_widget()
11418                    }),
11419                    false,
11420                    false,
11421                    false,
11422                );
11423                Overlay::new()
11424                    .key(overlay_key.into())
11425                    .initial_entries([entry])
11426                    .into_widget()
11427            });
11428        }
11429
11430        /// The render object of every `Overlay`: Dart's `tester.renderObject(find.byWidget(o))`.
11431        fn overlay_render_objects(tester: &WidgetTester) -> Vec<AnyRenderObject> {
11432            let overlays = find::by_type::<Overlay>().evaluate(tester);
11433            let app = tester.cell.borrow();
11434            overlays
11435                .into_iter()
11436                .map(|overlay| {
11437                    overlay
11438                        .find_render_object(&app)
11439                        .expect("an overlay's theater")
11440                })
11441                .collect()
11442        }
11443
11444        // menu_anchor_test.dart 'Content is shown in the root overlay when useRootOverlay is
11445        // true'.
11446        #[test]
11447        fn a_menu_using_the_root_overlay_shows_in_the_root_overlay() {
11448            test_widgets(|tester| {
11449                let controller = new_controller(tester);
11450                let overlay_key = GlobalKey::new();
11451                let menu_item_key = GlobalKey::new();
11452                nested_overlay_menu(
11453                    tester,
11454                    controller.clone(),
11455                    true,
11456                    &overlay_key,
11457                    &menu_item_key,
11458                );
11459                assert!(
11460                    menu_item_key
11461                        .current_context(&tester.cell.borrow())
11462                        .is_none()
11463                );
11464
11465                // Open the menu.
11466                controller.open(&mut tester.cell.borrow_mut(), None);
11467                pump(tester);
11468                assert!(
11469                    menu_item_key
11470                        .current_context(&tester.cell.borrow())
11471                        .is_some()
11472                );
11473
11474                // Expect two overlays: the root overlay created by MaterialApp and the
11475                // overlay created by the boilerplate code.
11476                let overlays = overlay_render_objects(tester);
11477                assert_eq!(overlays.len(), 2);
11478                let non_root_overlay = tester.render_object(&overlay_key);
11479                let root_overlay = *overlays
11480                    .iter()
11481                    .find(|overlay| **overlay != non_root_overlay)
11482                    .expect("the root overlay");
11483
11484                // Check that the ancestor _RenderTheater for the menu item is the one
11485                // from the root overlay.
11486                let theaters =
11487                    ancestor_render_theaters(tester, tester.render_object(&menu_item_key));
11488                assert_eq!(theaters, [root_overlay]);
11489            });
11490        }
11491
11492        // menu_anchor_test.dart 'Content is shown in the nearest ancestor overlay when
11493        // useRootOverlay is false'.
11494        #[test]
11495        fn a_menu_not_using_the_root_overlay_shows_in_the_nearest_overlay() {
11496            test_widgets(|tester| {
11497                let controller = new_controller(tester);
11498                let overlay_key = GlobalKey::new();
11499                let menu_item_key = GlobalKey::new();
11500                nested_overlay_menu(
11501                    tester,
11502                    controller.clone(),
11503                    false,
11504                    &overlay_key,
11505                    &menu_item_key,
11506                );
11507                assert!(
11508                    menu_item_key
11509                        .current_context(&tester.cell.borrow())
11510                        .is_none()
11511                );
11512
11513                // Open the menu.
11514                controller.open(&mut tester.cell.borrow_mut(), None);
11515                pump(tester);
11516                assert!(
11517                    menu_item_key
11518                        .current_context(&tester.cell.borrow())
11519                        .is_some()
11520                );
11521
11522                // Expect two overlays: the root overlay created by MaterialApp and the
11523                // overlay created by the boilerplate code.
11524                assert_eq!(overlay_render_objects(tester).len(), 2);
11525                let non_root_overlay = tester.render_object(&overlay_key);
11526
11527                // Check that the ancestor _RenderTheater for the menu item is the one
11528                // from the root overlay.
11529                let theaters =
11530                    ancestor_render_theaters(tester, tester.render_object(&menu_item_key));
11531                assert_eq!(theaters.first(), Some(&non_root_overlay));
11532            });
11533        }
11534
11535        // menu_anchor_test.dart 'Unattached MenuController does not throw when calling close'.
11536        #[test]
11537        fn closing_an_unattached_menu_controller_does_not_panic() {
11538            test_widgets(|tester| {
11539                let controller = new_controller(tester);
11540                controller.close(&mut tester.cell.borrow_mut());
11541                pump(tester);
11542            });
11543        }
11544
11545        // menu_anchor_test.dart 'Unattached MenuController returns false when calling isOpen'.
11546        #[test]
11547        fn an_unattached_menu_controller_is_not_open() {
11548            test_widgets(|tester| {
11549                let controller = new_controller(tester);
11550                assert!(!controller.is_open(&tester.cell.borrow()));
11551            });
11552        }
11553
11554        // menu_anchor_test.dart 'MenuAnchor updates isOpen state correctly'.
11555        #[test]
11556        fn a_menu_anchor_rebuilds_its_button_with_the_controllers_is_open() {
11557            test_widgets(|tester| {
11558                let is_open = Rc::new(Cell::new(false));
11559                let open_count = Rc::new(Cell::new(0));
11560                let close_count = Rc::new(Cell::new(0));
11561                let (built_open, opens, closes) = (
11562                    Rc::clone(&is_open),
11563                    Rc::clone(&open_count),
11564                    Rc::clone(&close_count),
11565                );
11566                pump_app(tester, m3, move |_app| {
11567                    Scaffold::new()
11568                        .body(
11569                            Center::new().child(
11570                                MenuAnchor::new(vec![
11571                                    MenuItemButton::new()
11572                                        .child(Text::new("menu item"))
11573                                        .into_widget(),
11574                                ])
11575                                .builder(move |app, _context, controller, _child| {
11576                                    built_open.set(controller.is_open(app));
11577                                    let label = if built_open.get() { "close" } else { "open" };
11578                                    toggle_button(controller, label)
11579                                })
11580                                .on_open(Rc::new(move |_app: &mut App| opens.set(opens.get() + 1)))
11581                                .on_close(Rc::new(
11582                                    move |_app: &mut App| closes.set(closes.get() + 1),
11583                                )),
11584                            ),
11585                        )
11586                        .into_widget()
11587                });
11588
11589                assert!(shows(tester, "open"));
11590                assert!(!is_open.get());
11591                assert_eq!(open_count.get(), 0);
11592                assert_eq!(close_count.get(), 0);
11593
11594                let button = center_of_first::<FilledButton>(tester);
11595                tester.tap_at(button, 1);
11596                pump(tester);
11597
11598                assert!(shows(tester, "close"));
11599                assert!(is_open.get());
11600                assert_eq!(open_count.get(), 1);
11601                assert_eq!(close_count.get(), 0);
11602
11603                let button = center_of_first::<FilledButton>(tester);
11604                tester.tap_at(button, 1);
11605                pump(tester);
11606
11607                assert!(shows(tester, "open"));
11608                assert!(!is_open.get());
11609                assert_eq!(open_count.get(), 1);
11610                assert_eq!(close_count.get(), 1);
11611            });
11612        }
11613
11614        /// How many `Icon`s show `icon`: Dart's `find.byIcon(icon)`.
11615        fn count_icon(tester: &WidgetTester, icon: &waft_widgets::IconData) -> usize {
11616            find::by_type::<Icon>()
11617                .evaluate(tester)
11618                .into_iter()
11619                .filter(|element| {
11620                    tester.widget(*element, |widget: &Icon| widget.icon.as_ref() == Some(icon))
11621                })
11622                .count()
11623        }
11624
11625        // menu_anchor_test.dart 'SubmenuButton.submenuIcon updates default arrow icon'.
11626        #[test]
11627        fn a_submenu_icon_resolves_against_the_buttons_states() {
11628            test_widgets(|tester| {
11629                let controller = new_controller(tester);
11630                let disabled_icon = Icons::close();
11631                let hovered_icon = Icons::bolt();
11632                let focused_icon = Icons::favorite();
11633                let default_icon = Icons::add();
11634                let submenu_icon: WidgetStatePropertyRef<Option<WidgetRef>> = {
11635                    let (disabled_icon, hovered_icon, focused_icon, default_icon) = (
11636                        disabled_icon.clone(),
11637                        hovered_icon.clone(),
11638                        focused_icon.clone(),
11639                        default_icon.clone(),
11640                    );
11641                    <dyn waft_widgets::WidgetStateProperty<Option<WidgetRef>>>::resolve_with(
11642                        move |states| {
11643                            let icon = if states.contains(&WidgetState::Disabled) {
11644                                &disabled_icon
11645                            } else if states.contains(&WidgetState::Hovered) {
11646                                &hovered_icon
11647                            } else if states.contains(&WidgetState::Focused) {
11648                                &focused_icon
11649                            } else {
11650                                &default_icon
11651                            };
11652                            Some(Icon::new(Some(icon.clone())).into_widget())
11653                        },
11654                    )
11655                };
11656
11657                let build_menu = |tester: &mut WidgetTester,
11658                                  icon: Option<WidgetStatePropertyRef<Option<WidgetRef>>>,
11659                                  enabled: bool| {
11660                    pump_material(tester, m3, {
11661                        let controller = controller.clone();
11662                        move |_app| {
11663                            let menu_children = if enabled {
11664                                vec![
11665                                    MenuItemButton::new()
11666                                        .child(Text::new(TestMenu::MainMenu0.label()))
11667                                        .into_widget(),
11668                                ]
11669                            } else {
11670                                Vec::new()
11671                            };
11672                            let mut inner = SubmenuButton::new(
11673                                menu_children,
11674                                Some(Text::new(TestMenu::SubSubMenu110.label())),
11675                            );
11676                            inner.submenu_icon = icon;
11677                            MenuBar::new(vec![
11678                                SubmenuButton::new(
11679                                    vec![inner.into_widget()],
11680                                    Some(Text::new(TestMenu::SubMenu00.label())),
11681                                )
11682                                .into_widget(),
11683                            ])
11684                            .controller(controller.clone())
11685                            .into_widget()
11686                        }
11687                    });
11688                };
11689
11690                build_menu(tester, None, true);
11691                tester.tap(find::text(&TestMenu::SubMenu00.label()));
11692                pump(tester);
11693
11694                assert_eq!(count_icon(tester, &Icons::arrow_right()), 1);
11695
11696                controller.close(&mut tester.cell.borrow_mut());
11697                pump(tester);
11698
11699                build_menu(tester, Some(Rc::clone(&submenu_icon)), true);
11700                tester.tap(find::text(&TestMenu::SubMenu00.label()));
11701                pump(tester);
11702                assert_eq!(count_icon(tester, &default_icon), 1);
11703
11704                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
11705                pump(tester);
11706                assert_eq!(count_icon(tester, &focused_icon), 1);
11707
11708                controller.close(&mut tester.cell.borrow_mut());
11709                pump(tester);
11710
11711                tester.tap(find::text(&TestMenu::SubMenu00.label()));
11712                pump(tester);
11713                let at = tester
11714                    .get_rect(find::text(&TestMenu::SubSubMenu110.label()))
11715                    .center();
11716                hover_over(tester, at);
11717                pump(tester);
11718                assert_eq!(count_icon(tester, &hovered_icon), 1);
11719
11720                controller.close(&mut tester.cell.borrow_mut());
11721                pump(tester);
11722
11723                build_menu(tester, Some(Rc::clone(&submenu_icon)), false);
11724                tester.tap(find::text(&TestMenu::SubMenu00.label()));
11725                pump(tester);
11726                assert_eq!(count_icon(tester, &disabled_icon), 1);
11727            });
11728        }
11729
11730        // ---- Mouse cursors ----
11731
11732        fn shows_cursor(tester: &WidgetTester, cursor: SystemMouseCursor) -> bool {
11733            let cursor: MouseCursorRef = cursor.into();
11734            *tester.active_cursor(1) == *cursor
11735        }
11736
11737        /// Dart's mouse gesture added at (1000, 1000), checked to show the basic cursor there,
11738        /// then moved to `at`.
11739        fn hover_from_outside(tester: &mut WidgetTester, at: impl FnOnce(&WidgetTester) -> Offset) {
11740            let mut gesture = TestPointer::mouse(1, 0);
11741            tester.add_pointer(&mut gesture, Offset::new(1000.0, 1000.0));
11742
11743            assert!(shows_cursor(tester, SystemMouseCursors::BASIC));
11744
11745            let at = at(tester);
11746            tester.move_to(&mut gesture, at, false);
11747            pump(tester);
11748        }
11749
11750        // menu_anchor_test.dart 'SubmenuButton has expected default mouse cursor on hover'.
11751        #[test]
11752        fn a_submenu_button_shows_the_basic_cursor_by_default() {
11753            test_widgets(|tester| {
11754                pump_material(tester, m3, |_app| {
11755                    SubmenuButton::new(
11756                        vec![
11757                            MenuItemButton::new()
11758                                .on_pressed(Listener::new(|_app| {}))
11759                                .child(Text::new("Test menu button item"))
11760                                .into_widget(),
11761                        ],
11762                        Some(Text::new("Main Menu")),
11763                    )
11764                    .into_widget()
11765                });
11766
11767                hover_from_outside(tester, center_of_first::<SubmenuButton>);
11768
11769                assert!(shows_cursor(tester, SystemMouseCursors::BASIC));
11770            });
11771        }
11772
11773        // menu_anchor_test.dart 'MenuItemButton has expected default mouse cursor on hover'.
11774        #[test]
11775        fn a_menu_item_button_shows_the_basic_cursor_by_default() {
11776            test_widgets(|tester| {
11777                pump_material(tester, m3, |_app| {
11778                    MenuBar::new(vec![
11779                        SubmenuButton::new(
11780                            vec![
11781                                MenuItemButton::new()
11782                                    .on_pressed(Listener::new(|_app| {}))
11783                                    .child(Text::new("Test menu item"))
11784                                    .into_widget(),
11785                            ],
11786                            Some(Text::new("File")),
11787                        )
11788                        .into_widget(),
11789                    ])
11790                    .into_widget()
11791                });
11792
11793                // Open SubmenuButton.
11794                tester.tap(find::text("File"));
11795                tester.pump_and_settle();
11796
11797                // Move to MenuItemButton.
11798                hover_from_outside(tester, center_of_first::<MenuItemButton>);
11799
11800                assert!(shows_cursor(tester, SystemMouseCursors::BASIC));
11801            });
11802        }
11803
11804        // menu_anchor_test.dart 'CheckboxMenuButton has expected default mouse cursor on hover'.
11805        #[test]
11806        fn a_checkbox_menu_button_shows_the_basic_cursor_by_default() {
11807            test_widgets(|tester| {
11808                pump_material(tester, m3, |_app| {
11809                    CheckboxMenuButton::new(
11810                        Some(false),
11811                        Some(Rc::new(|_app: &mut App, _value: Option<bool>| {})),
11812                        Some(Text::new("Checkbox")),
11813                    )
11814                    .into_widget()
11815                });
11816
11817                hover_from_outside(tester, center_of_first::<CheckboxMenuButton>);
11818
11819                assert!(shows_cursor(tester, SystemMouseCursors::BASIC));
11820            });
11821        }
11822
11823        // menu_anchor_test.dart 'RadioMenuButton has expected default mouse cursor on hover'.
11824        #[test]
11825        fn a_radio_menu_button_shows_the_basic_cursor_by_default() {
11826            test_widgets(|tester| {
11827                pump_material(tester, m3, |_app| {
11828                    RadioMenuButton::new(
11829                        1,
11830                        Some(0),
11831                        Some(Rc::new(|_app: &mut App, _value: Option<i32>| {})),
11832                        Some(Text::new("Radio")),
11833                    )
11834                    .into_widget()
11835                });
11836
11837                hover_from_outside(tester, center_of_first::<RadioMenuButton<i32>>);
11838
11839                assert!(shows_cursor(tester, SystemMouseCursors::BASIC));
11840            });
11841        }
11842
11843        /// Dart's `ButtonStyle(mouseCursor: WidgetStateProperty.all(SystemMouseCursors.cell))`.
11844        fn cell_cursor_style() -> ButtonStyle {
11845            ButtonStyle::new().mouse_cursor(Rc::new(MaterialStatePropertyAll::new(Some(
11846                MouseCursorRef::from(SystemMouseCursors::CELL),
11847            ))))
11848        }
11849
11850        /// Dart's mouse gesture added at `at`.
11851        fn add_mouse_at(tester: &mut WidgetTester, at: Offset) {
11852            let mut gesture = TestPointer::mouse(1, 0);
11853            tester.add_pointer(&mut gesture, at);
11854        }
11855
11856        // menu_anchor_test.dart 'MenuItemButton has expected mouse cursor when explicitly
11857        // configured'.
11858        #[test]
11859        fn a_menu_item_button_shows_the_cursor_of_its_style() {
11860            test_widgets(|tester| {
11861                pump_material(tester, m3, |_app| {
11862                    MenuItemButton::new()
11863                        .on_pressed(Listener::new(|_app| {}))
11864                        .style(cell_cursor_style())
11865                        .child(Text::new("Menu Item"))
11866                        .into_widget()
11867                });
11868
11869                let at = center_of_first::<MenuItemButton>(tester);
11870                add_mouse_at(tester, at);
11871
11872                assert!(shows_cursor(tester, SystemMouseCursors::CELL));
11873            });
11874        }
11875
11876        // menu_anchor_test.dart 'CheckboxMenuButton has expected mouse cursor when explicitly
11877        // configured'.
11878        #[test]
11879        fn a_checkbox_menu_button_shows_the_cursor_of_its_style() {
11880            test_widgets(|tester| {
11881                pump_material(tester, m3, |_app| {
11882                    CheckboxMenuButton::new(
11883                        Some(true),
11884                        Some(Rc::new(|_app: &mut App, _value: Option<bool>| {})),
11885                        Some(Text::new("Menu Item")),
11886                    )
11887                    .style(cell_cursor_style())
11888                    .into_widget()
11889                });
11890
11891                let at = center_of_first::<CheckboxMenuButton>(tester);
11892                add_mouse_at(tester, at);
11893
11894                assert!(shows_cursor(tester, SystemMouseCursors::CELL));
11895            });
11896        }
11897
11898        // menu_anchor_test.dart 'RadioMenuButton has expected mouse cursor when explicitly
11899        // configured'.
11900        #[test]
11901        fn a_radio_menu_button_shows_the_cursor_of_its_style() {
11902            test_widgets(|tester| {
11903                pump_material(tester, m3, |_app| {
11904                    RadioMenuButton::new(
11905                        false,
11906                        None,
11907                        Some(Rc::new(|_app: &mut App, _value: Option<bool>| {})),
11908                        Some(Text::new("Menu Item")),
11909                    )
11910                    .style(cell_cursor_style())
11911                    .into_widget()
11912                });
11913
11914                let at = center_of_first::<RadioMenuButton<bool>>(tester);
11915                add_mouse_at(tester, at);
11916
11917                assert!(shows_cursor(tester, SystemMouseCursors::CELL));
11918            });
11919        }
11920
11921        // menu_anchor_test.dart 'SubmenuButton has expected mouse cursor when explicitly
11922        // configured'.
11923        #[test]
11924        fn a_submenu_button_shows_the_cursor_of_its_style() {
11925            test_widgets(|tester| {
11926                pump_material(tester, m3, |_app| {
11927                    MenuBar::new(vec![
11928                        SubmenuButton::new(
11929                            vec![
11930                                MenuItemButton::new()
11931                                    .on_pressed(Listener::new(|_app| {}))
11932                                    .child(Text::new("Test menu item"))
11933                                    .into_widget(),
11934                            ],
11935                            Some(Text::new("File")),
11936                        )
11937                        .style(cell_cursor_style())
11938                        .into_widget(),
11939                    ])
11940                    .into_widget()
11941                });
11942
11943                let at = center_of_first::<SubmenuButton>(tester);
11944                add_mouse_at(tester, at);
11945
11946                assert!(shows_cursor(tester, SystemMouseCursors::CELL));
11947            });
11948        }
11949    }
11950
11951    /// menu_anchor_test.dart's 'Animations' group and the top-level cases after it.
11952    mod animations {
11953        use std::cell::Cell;
11954
11955        use waft_widgets::{Center, Column, SizedBox};
11956
11957        use super::*;
11958        use crate::dialog::{AlertDialog, ShowDialog};
11959        use crate::scaffold::Scaffold;
11960
11961        fn new_controller(tester: &WidgetTester) -> MenuControllerRef {
11962            MenuController::new(&mut tester.cell.borrow_mut()).into_erased()
11963        }
11964
11965        fn open(
11966            tester: &mut WidgetTester,
11967            controller: AnyMenuController,
11968            position: Option<Offset>,
11969        ) {
11970            controller.open(&mut tester.cell.borrow_mut(), position);
11971            tester.cell.checkpoint();
11972        }
11973
11974        fn close(tester: &mut WidgetTester, controller: AnyMenuController) {
11975            controller.close(&mut tester.cell.borrow_mut());
11976            tester.cell.checkpoint();
11977        }
11978
11979        fn pump_ms(tester: &mut WidgetTester, ms: u64) {
11980            tester.pump_by(Duration::from_millis(ms));
11981        }
11982
11983        fn new_focus_node(tester: &WidgetTester, label: Option<&str>) -> FocusNodeRef {
11984            let mut app = tester.cell.borrow_mut();
11985            let node = FocusNode::new(&mut app).into_erased::<AnyFocusNode>();
11986            if let Some(label) = label {
11987                node.set_debug_label(&mut app, Some(label.to_owned()));
11988            }
11989            node
11990        }
11991
11992        fn request_focus(tester: &mut WidgetTester, node: AnyFocusNode) {
11993            node.request_focus(&mut tester.cell.borrow_mut(), None);
11994            tester.cell.checkpoint();
11995        }
11996
11997        fn has_focus(tester: &WidgetTester, node: AnyFocusNode) -> bool {
11998            node.has_focus(&tester.cell.borrow_mut())
11999        }
12000
12001        fn has_primary_focus(tester: &WidgetTester, node: AnyFocusNode) -> bool {
12002            node.has_primary_focus(&tester.cell.borrow())
12003        }
12004
12005        /// Dart's `MenuItemButton(onPressed: () {}, child: Text(text))`.
12006        fn item(text: &str) -> WidgetRef {
12007            MenuItemButton::new()
12008                .on_pressed(Listener::new(|_app| {}))
12009                .child(Text::new(text))
12010                .into_widget()
12011        }
12012
12013        fn items(texts: &[&str]) -> Vec<WidgetRef> {
12014            texts.iter().map(|text| item(text)).collect()
12015        }
12016
12017        /// Dart's `hoverOver`, whose `tester.createGesture` gives each gesture a pointer and a
12018        /// device of its own.
12019        fn hover_with_new_mouse(tester: &mut WidgetTester, device: i64, at: Offset) {
12020            let mut mouse = TestPointer::mouse(device, 0);
12021            tester.add_pointer(&mut mouse, Offset::ZERO);
12022            tester.move_to(&mut mouse, at, false);
12023            tester.pump();
12024        }
12025
12026        /// The value of a `FadeTransition`'s opacity.
12027        fn opacity(tester: &WidgetTester, fade: AnyElement) -> f64 {
12028            let animation = tester.widget::<FadeTransition, _>(fade, |fade| fade.opacity.clone());
12029            animation.value(&tester.cell.borrow())
12030        }
12031
12032        /// The nearest of `of`'s ancestors whose widget is a `FadeTransition`.
12033        fn nearest_fade(tester: &WidgetTester, of: AnyElement) -> AnyElement {
12034            tester.ancestor_of_type::<FadeTransition>(of)
12035        }
12036
12037        /// Dart's `firstWidget<FadeTransition>(find.ancestor(of: find.widgetWithText(MenuItemButton,
12038        /// text), matching: find.byType(FadeTransition))).opacity.value`.
12039        fn item_opacity(tester: &WidgetTester, text: &str) -> f64 {
12040            let button = ancestors_of_type::<MenuItemButton>(tester, text)[0];
12041            opacity(tester, nearest_fade(tester, button))
12042        }
12043
12044        /// Dart's `firstWidget<FadeTransition>(find.widgetWithText(FadeTransition, text))
12045        /// .opacity.value`.
12046        fn text_fade_opacity(tester: &WidgetTester, text: &str) -> f64 {
12047            let fade = ancestors_of_type::<FadeTransition>(tester, text)[0];
12048            opacity(tester, fade)
12049        }
12050
12051        /// The opacity of the `FadeTransition` nearest above the menu panel.
12052        fn panel_opacity(tester: &WidgetTester) -> f64 {
12053            let panel = only(menu_panels(tester));
12054            opacity(tester, nearest_fade(tester, panel))
12055        }
12056
12057        /// Dart's `tester.getRect(find.descendant(of: find.byType(MenuAnchor), matching:
12058        /// find.byType(FocusScope)))`: the menu's `FocusScope`.
12059        fn panel_rect(tester: &WidgetTester) -> Rect {
12060            let anchor = tester.element(find::by_type::<MenuAnchor>());
12061            let scope = only(tester.descendants_of_type::<FocusScope>(anchor));
12062            rect_of_element(tester, scope)
12063        }
12064
12065        /// Dart's `MenuAnchor(controller: controller, animated: true, menuChildren: children)` as a
12066        /// `MaterialApp`'s `Material` home.
12067        fn pump_animated_anchor(
12068            tester: &mut WidgetTester,
12069            controller: MenuControllerRef,
12070            children: Vec<WidgetRef>,
12071        ) {
12072            pump_material(tester, m3, |_app| {
12073                MenuAnchor::new(children)
12074                    .controller(controller.clone())
12075                    .animated(true)
12076                    .into_widget()
12077            });
12078        }
12079
12080        /// Dart's `MenuStyle(padding: WidgetStatePropertyAll(EdgeInsets.zero))`.
12081        fn zero_padding() -> MenuStyle {
12082            MenuStyle::new().padding(Rc::new(waft_widgets::WidgetStatePropertyAll::new(Some(
12083                EdgeInsetsGeometry::ZERO,
12084            ))))
12085        }
12086
12087        /// A slot an `onAnimationStatusChanged` writes to.
12088        fn status_sink() -> (
12089            Rc<Cell<Option<AnimationStatus>>>,
12090            ValueChanged<AnimationStatus>,
12091        ) {
12092            let status = Rc::new(Cell::new(None));
12093            let sink = Rc::clone(&status);
12094            (
12095                status,
12096                Rc::new(move |_app: &mut App, value| sink.set(Some(value))),
12097            )
12098        }
12099
12100        /// Dart's `TextButton(onPressed: () => controller.isOpen ? close : open, child: Text(text))`
12101        /// builder of a `MenuAnchor`.
12102        fn toggle_button(
12103            text: &'static str,
12104        ) -> impl Fn(&mut App, BuildContext, AnyMenuController, Option<&WidgetRef>) -> WidgetRef + 'static
12105        {
12106            move |_app, _context, controller, _child| {
12107                TextButton::new(
12108                    Some(Listener::new(move |app| {
12109                        if controller.is_open(app) {
12110                            controller.close(app);
12111                        } else {
12112                            controller.open(app, None);
12113                        }
12114                    })),
12115                    Some(Text::new(text)),
12116                )
12117                .into_widget()
12118            }
12119        }
12120
12121        // menu_anchor_test.dart 'Animations can be disabled'.
12122        #[test]
12123        fn animations_can_be_disabled() {
12124            test_widgets(|tester| {
12125                let controller = new_controller(tester);
12126                pump_animated_anchor(tester, controller.clone(), items(&["Item 0"]));
12127
12128                // Open the menu and verify animations are enabled.
12129                open(tester, controller.handle(), None);
12130                pump(tester);
12131                pump_ms(tester, 50);
12132
12133                assert_more_or_less_equals_within(item_opacity(tester, "Item 0"), 0.2, 0.05);
12134
12135                pump_material(tester, m3, |_app| {
12136                    MenuAnchor::new(items(&["Item 0"]))
12137                        .controller(controller)
12138                        .into_widget()
12139                });
12140
12141                assert_eq!(item_opacity(tester, "Item 0"), 1.0);
12142            });
12143        }
12144
12145        // menu_anchor_test.dart 'MenuAnchor children can be changed'.
12146        #[test]
12147        fn the_children_of_an_animated_menu_anchor_can_be_changed() {
12148            test_widgets(|tester| {
12149                let controller = new_controller(tester);
12150                pump_animated_anchor(tester, controller.clone(), items(&["Item 0"]));
12151
12152                open(tester, controller.handle(), None);
12153                pump(tester);
12154                pump_ms(tester, 50);
12155
12156                assert_more_or_less_equals_within(item_opacity(tester, "Item 0"), 0.2, 0.05);
12157
12158                pump_animated_anchor(tester, controller.clone(), items(&["Item 1"]));
12159
12160                assert_more_or_less_equals_within(item_opacity(tester, "Item 1"), 0.2, 0.05);
12161            });
12162        }
12163
12164        // menu_anchor_test.dart 'Menu panel fades in'.
12165        #[test]
12166        fn the_menu_panel_fades_in_over_50_ms() {
12167            test_widgets(|tester| {
12168                let controller = new_controller(tester);
12169                pump_animated_anchor(
12170                    tester,
12171                    controller.clone(),
12172                    items(&["Item 0", "Item 1", "Item 2"]),
12173                );
12174
12175                open(tester, controller.handle(), None);
12176                pump(tester);
12177
12178                // Opacity values at different millisecond offsets during the 50 ms fade-in
12179                // animation.
12180                for (_ms, expected) in [
12181                    (0, 0.0),
12182                    (10, 0.2),
12183                    (20, 0.4),
12184                    (30, 0.6),
12185                    (40, 0.8),
12186                    (50, 1.0),
12187                ] {
12188                    assert_more_or_less_equals_within(panel_opacity(tester), expected, 0.05);
12189                    pump_ms(tester, 10);
12190                }
12191            });
12192        }
12193
12194        // menu_anchor_test.dart 'Menu panel fades out'.
12195        #[test]
12196        fn the_menu_panel_fades_out_over_the_last_50_ms_of_closing() {
12197            test_widgets(|tester| {
12198                let controller = new_controller(tester);
12199                pump_animated_anchor(
12200                    tester,
12201                    controller.clone(),
12202                    items(&["Item 0", "Item 1", "Item 2"]),
12203                );
12204
12205                open(tester, controller.handle(), None);
12206                pump(tester);
12207                tester.pump_and_settle();
12208                close(tester, controller.handle());
12209                pump(tester);
12210
12211                assert_more_or_less_equals_within(panel_opacity(tester), 1.0, 0.05);
12212
12213                pump_ms(tester, 100);
12214
12215                // Opacity values at different millisecond offsets during the 50 ms fade-out
12216                // animation.
12217                for (_ms, expected) in [(110, 1.0), (120, 0.8), (130, 0.6), (140, 0.4), (150, 0.2)]
12218                {
12219                    assert_more_or_less_equals_within(panel_opacity(tester), expected, 0.05);
12220                    pump_ms(tester, 10);
12221                }
12222            });
12223        }
12224
12225        /// Dart's padded-to-zero animated `MenuAnchor` of one 160 pixel tall child.
12226        fn pump_tall_anchor(tester: &mut WidgetTester, controller: MenuControllerRef) {
12227            pump_material(tester, m3, |_app| {
12228                MenuAnchor::new(vec![SizedBox::new().height(160.0).into_widget()])
12229                    .style(zero_padding())
12230                    .controller(controller.clone())
12231                    .animated(true)
12232                    .into_widget()
12233            });
12234        }
12235
12236        // menu_anchor_test.dart 'Menu panel height eases out while opening'.
12237        #[test]
12238        fn the_menu_panel_height_eases_out_while_opening() {
12239            test_widgets(|tester| {
12240                let controller = new_controller(tester);
12241                pump_tall_anchor(tester, controller.clone());
12242
12243                open(tester, controller.handle(), None);
12244                pump(tester);
12245
12246                for (_ms, expected) in [
12247                    (0, 0.0),
12248                    (100, 60.5),
12249                    (200, 125.5),
12250                    (300, 148.0),
12251                    (400, 157.5),
12252                    (500, 160.0),
12253                ] {
12254                    let height = panel_rect(tester).height();
12255                    assert_more_or_less_equals_within(height, expected, 1.0);
12256                    pump_ms(tester, 100);
12257                }
12258            });
12259        }
12260
12261        // menu_anchor_test.dart 'Menu panel height eases in while closing'.
12262        #[test]
12263        fn the_menu_panel_height_eases_in_while_closing() {
12264            test_widgets(|tester| {
12265                let controller = new_controller(tester);
12266                pump_tall_anchor(tester, controller.clone());
12267
12268                open(tester, controller.handle(), None);
12269                pump(tester);
12270                tester.pump_and_settle();
12271                close(tester, controller.handle());
12272                pump(tester);
12273
12274                assert_eq!(panel_rect(tester).height(), 160.0, "at t=0");
12275
12276                pump_ms(tester, 50);
12277
12278                assert_more_or_less_equals_within(panel_rect(tester).height(), 153.0, 2.0);
12279
12280                pump_ms(tester, 50);
12281
12282                for (_ms, expected) in [
12283                    (100, 129.0),
12284                    (110, 120.0),
12285                    (120, 110.0),
12286                    (130, 97.0),
12287                    (140, 80.0),
12288                    (150, 0.0),
12289                ] {
12290                    assert_more_or_less_equals_within(panel_rect(tester).height(), expected, 2.0);
12291                    pump_ms(tester, 10);
12292                }
12293            });
12294        }
12295
12296        // menu_anchor_test.dart 'Item fade-in animation staggers over 500 ms'.
12297        #[test]
12298        fn the_item_fade_in_staggers_over_500_ms() {
12299            test_widgets(|tester| {
12300                let controller = new_controller(tester);
12301                pump_animated_anchor(
12302                    tester,
12303                    controller.clone(),
12304                    items(&["Item 0", "Item 1", "Item 2", "Item 3"]),
12305                );
12306
12307                open(tester, controller.handle(), None);
12308                pump(tester);
12309
12310                // Opacity values at different millisecond offsets during the 500ms opening
12311                // animation.
12312                for (_time, expected) in [
12313                    (100, [0.400, 0.0667, 0.00, 0.00]),
12314                    (200, [0.800, 0.467, 0.133, 0.00]),
12315                    (300, [1.00, 0.867, 0.533, 0.200]),
12316                    (400, [1.00, 1.00, 0.933, 0.600]),
12317                    (500, [1.00, 1.00, 1.00, 1.00]),
12318                ] {
12319                    pump_ms(tester, 100);
12320                    for (i, expected) in expected.into_iter().enumerate() {
12321                        let opacity = item_opacity(tester, &format!("Item {i}"));
12322                        assert_more_or_less_equals_within(opacity, expected, 0.05);
12323                    }
12324                }
12325            });
12326        }
12327
12328        // menu_anchor_test.dart 'Item fade-out animation staggers over 150 ms with 50 ms delay'.
12329        #[test]
12330        fn the_item_fade_out_staggers_over_150_ms_after_a_50_ms_delay() {
12331            test_widgets(|tester| {
12332                let controller = new_controller(tester);
12333                pump_material(tester, m3, |_app| {
12334                    MenuAnchor::new(items(&["Item 0", "Item 1", "Item 2", "Item 3"]))
12335                        .builder(toggle_button("Open Menu"))
12336                        .controller(controller.clone())
12337                        .animated(true)
12338                        .into_widget()
12339                });
12340
12341                tester.tap(find::text("Open Menu"));
12342                pump(tester);
12343                pump_ms(tester, 501);
12344                close(tester, controller.handle());
12345                pump(tester);
12346
12347                // Opacity values at different millisecond offsets during the 150ms close animation.
12348                for (_time, expected) in [
12349                    (0, [1.00, 1.00, 1.00, 1.00]),
12350                    (25, [1.00, 1.00, 1.00, 1.00]),
12351                    (50, [1.00, 1.00, 1.00, 1.00]),
12352                    (75, [1.00, 1.00, 0.833, 0.500]),
12353                    (100, [1.00, 0.667, 0.333, 0.00]),
12354                    (125, [0.500, 0.167, 0.00, 0.00]),
12355                    (150, [0.00, 0.00, 0.00, 0.00]),
12356                ] {
12357                    for (i, expected) in expected.into_iter().enumerate() {
12358                        let opacity = text_fade_opacity(tester, &format!("Item {i}"));
12359                        assert_more_or_less_equals_within(opacity, expected, 0.05);
12360                    }
12361                    pump_ms(tester, 25);
12362                }
12363            });
12364        }
12365
12366        // menu_anchor_test.dart 'MenuAnchor calls onAnimationStatusChanged with correct values'.
12367        #[test]
12368        fn an_animated_menu_anchor_reports_each_animation_status() {
12369            test_widgets(|tester| {
12370                let controller = new_controller(tester);
12371                let (status, on_status) = status_sink();
12372                pump_material(tester, m3, |_app| {
12373                    MenuAnchor::new(items(&["Item 0"]))
12374                        .controller(controller.clone())
12375                        .animated(true)
12376                        .on_animation_status_changed(on_status)
12377                        .into_widget()
12378                });
12379
12380                // Open the menu
12381                open(tester, controller.handle(), None);
12382                pump(tester);
12383
12384                assert_eq!(status.get(), Some(AnimationStatus::Forward));
12385
12386                pump_ms(tester, 200);
12387
12388                assert_eq!(status.get(), Some(AnimationStatus::Forward));
12389
12390                close(tester, controller.handle());
12391                pump(tester);
12392
12393                assert_eq!(status.get(), Some(AnimationStatus::Reverse));
12394
12395                pump_ms(tester, 50);
12396
12397                assert_eq!(status.get(), Some(AnimationStatus::Reverse));
12398
12399                open(tester, controller.handle(), None);
12400                pump(tester);
12401
12402                assert_eq!(status.get(), Some(AnimationStatus::Forward));
12403
12404                tester.pump_and_settle();
12405
12406                assert_eq!(status.get(), Some(AnimationStatus::Completed));
12407
12408                close(tester, controller.handle());
12409
12410                tester.pump_and_settle();
12411
12412                assert_eq!(status.get(), Some(AnimationStatus::Dismissed));
12413            });
12414        }
12415
12416        // menu_anchor_test.dart 'MenuAnchor without animations calls onAnimationStatusChanged with
12417        // correct values'.
12418        #[test]
12419        fn a_menu_anchor_without_animations_reports_completed_and_dismissed() {
12420            test_widgets(|tester| {
12421                let controller = new_controller(tester);
12422                let (status, on_status) = status_sink();
12423                pump_material(tester, m3, |_app| {
12424                    MenuAnchor::new(items(&["Item 0"]))
12425                        .controller(controller.clone())
12426                        .on_animation_status_changed(on_status)
12427                        .into_widget()
12428                });
12429
12430                // Open the menu
12431                open(tester, controller.handle(), None);
12432                pump(tester);
12433
12434                assert_eq!(status.get(), Some(AnimationStatus::Completed));
12435
12436                close(tester, controller.handle());
12437                pump(tester);
12438
12439                assert_eq!(status.get(), Some(AnimationStatus::Dismissed));
12440
12441                open(tester, controller.handle(), None);
12442                pump(tester);
12443
12444                assert_eq!(status.get(), Some(AnimationStatus::Completed));
12445            });
12446        }
12447
12448        // menu_anchor_test.dart 'SubmenuButton onAnimationStatusChanged is invoked with correct
12449        // values'.
12450        #[test]
12451        fn an_animated_submenu_button_reports_each_animation_status() {
12452            test_widgets(|tester| {
12453                let controller = new_controller(tester);
12454                let submenu_controller = new_controller(tester);
12455                let (status, on_status) = status_sink();
12456                pump_material(tester, m3, |_app| {
12457                    MenuAnchor::new(vec![
12458                        SubmenuButton::new(items(&["Item 0"]), Some(Text::new("Submenu")))
12459                            .controller(submenu_controller.clone())
12460                            .animated(true)
12461                            .on_animation_status_changed(on_status)
12462                            .into_widget(),
12463                    ])
12464                    .controller(controller.clone())
12465                    .animated(true)
12466                    .into_widget()
12467                });
12468
12469                // Open the menu
12470                open(tester, controller.handle(), None);
12471                pump(tester);
12472                open(tester, submenu_controller.handle(), None);
12473                pump(tester);
12474
12475                assert_eq!(status.get(), Some(AnimationStatus::Forward));
12476
12477                pump_ms(tester, 200);
12478
12479                assert_eq!(status.get(), Some(AnimationStatus::Forward));
12480
12481                close(tester, submenu_controller.handle());
12482                pump(tester);
12483
12484                assert_eq!(status.get(), Some(AnimationStatus::Reverse));
12485
12486                pump_ms(tester, 50);
12487
12488                assert_eq!(status.get(), Some(AnimationStatus::Reverse));
12489
12490                open(tester, submenu_controller.handle(), None);
12491                pump(tester);
12492
12493                assert_eq!(status.get(), Some(AnimationStatus::Forward));
12494
12495                tester.pump_and_settle();
12496
12497                assert_eq!(status.get(), Some(AnimationStatus::Completed));
12498
12499                close(tester, submenu_controller.handle());
12500
12501                tester.pump_and_settle();
12502
12503                assert_eq!(status.get(), Some(AnimationStatus::Dismissed));
12504
12505                open(tester, submenu_controller.handle(), None);
12506                tester.pump_and_settle();
12507
12508                assert_eq!(status.get(), Some(AnimationStatus::Completed));
12509
12510                close(tester, controller.handle());
12511                pump(tester);
12512
12513                assert_eq!(status.get(), Some(AnimationStatus::Reverse));
12514
12515                pump_ms(tester, 50);
12516
12517                open(tester, submenu_controller.handle(), None);
12518                pump(tester);
12519                pump_ms(tester, 25);
12520
12521                // Reopen request should be ignored since the parent menu is closing.
12522                assert_eq!(status.get(), Some(AnimationStatus::Reverse));
12523
12524                pump(tester);
12525                tester.pump_and_settle();
12526
12527                assert_eq!(status.get(), Some(AnimationStatus::Dismissed));
12528            });
12529        }
12530
12531        // menu_anchor_test.dart 'Menu items can be pressed during opening animation'.
12532        #[test]
12533        fn menu_items_can_be_pressed_while_the_menu_opens() {
12534            test_widgets(|tester| {
12535                let controller = new_controller(tester);
12536                let press_count = Rc::new(Cell::new(0));
12537                let pressable = |text: &str| {
12538                    let press_count = Rc::clone(&press_count);
12539                    MenuItemButton::new()
12540                        .on_pressed(Listener::new(move |_app| {
12541                            press_count.set(press_count.get() + 1)
12542                        }))
12543                        .child(Text::new(text))
12544                        .into_widget()
12545                };
12546                let children = vec![pressable("Item 0"), pressable("Item 1")];
12547                pump_animated_anchor(tester, controller.clone(), children);
12548
12549                open(tester, controller.handle(), None);
12550                pump(tester);
12551                pump_ms(tester, 100);
12552
12553                tester.tap(find::text("Item 0"));
12554                pump(tester);
12555
12556                assert_eq!(press_count.get(), 1);
12557
12558                open(tester, controller.handle(), None);
12559                pump(tester);
12560                pump_ms(tester, 250);
12561                tester.tap(find::text("Item 1"));
12562                pump(tester);
12563
12564                assert_eq!(press_count.get(), 2);
12565            });
12566        }
12567
12568        // menu_anchor_test.dart 'Pointer is blocked while menu is closing'.
12569        #[test]
12570        fn a_closing_menu_does_not_take_taps() {
12571            test_widgets(|tester| {
12572                let controller = new_controller(tester);
12573                let item_pressed = Rc::new(Cell::new(false));
12574                let pressed = Rc::clone(&item_pressed);
12575                pump_animated_anchor(
12576                    tester,
12577                    controller.clone(),
12578                    vec![
12579                        MenuItemButton::new()
12580                            .on_pressed(Listener::new(move |_app| pressed.set(true)))
12581                            .child(Text::new("Item 0"))
12582                            .into_widget(),
12583                    ],
12584                );
12585
12586                // Open and wait for animation to complete
12587                open(tester, controller.handle(), None);
12588                tester.pump_and_settle();
12589
12590                assert!(shows(tester, "Item 0"));
12591
12592                // Start closing
12593                close(tester, controller.handle());
12594                pump(tester);
12595
12596                // Try to tap the item while closing
12597                tester.tap(find::text("Item 0"));
12598                pump(tester);
12599
12600                // Item should not have been pressed
12601                assert!(!item_pressed.get());
12602            });
12603        }
12604
12605        // menu_anchor_test.dart 'Menu items can be focused during opening animation'.
12606        #[test]
12607        fn menu_items_can_be_focused_while_the_menu_opens() {
12608            test_widgets(|tester| {
12609                let controller = new_controller(tester);
12610                let item0_focus_node = new_focus_node(tester, None);
12611                let item1_focus_node = new_focus_node(tester, None);
12612                pump_animated_anchor(
12613                    tester,
12614                    controller.clone(),
12615                    vec![
12616                        MenuItemButton::new()
12617                            .focus_node(item0_focus_node.clone())
12618                            .on_pressed(Listener::new(|_app| {}))
12619                            .child(Text::new("Item 0"))
12620                            .into_widget(),
12621                        MenuItemButton::new()
12622                            .focus_node(item1_focus_node.clone())
12623                            .on_pressed(Listener::new(|_app| {}))
12624                            .child(Text::new("Item 1"))
12625                            .into_widget(),
12626                    ],
12627                );
12628
12629                open(tester, controller.handle(), None);
12630                pump(tester);
12631
12632                request_focus(tester, item0_focus_node.handle());
12633                pump(tester);
12634
12635                assert!(has_focus(tester, item0_focus_node.handle()));
12636
12637                request_focus(tester, item1_focus_node.handle());
12638                pump(tester);
12639
12640                assert!(has_focus(tester, item1_focus_node.handle()));
12641            });
12642        }
12643
12644        // menu_anchor_test.dart 'Focus returns to parent scope during closing animation'.
12645        #[test]
12646        fn focus_returns_to_the_outside_button_as_soon_as_the_menu_starts_closing() {
12647            test_widgets(|tester| {
12648                let controller = new_controller(tester);
12649                let submenu_focus_node = new_focus_node(tester, None);
12650                let outside_focus_node = new_focus_node(tester, None);
12651                pump_material(tester, m3, |_app| {
12652                    ConstrainedBox::new(BoxConstraints::new().min_width(400.0).min_height(400.0))
12653                        .child(Column::new().children(vec![
12654                                TextButton::new(
12655                                    Some(Listener::new(|_app| {})),
12656                                    Some(Text::new("Outside")),
12657                                )
12658                                .focus_node(outside_focus_node.clone())
12659                                .into_widget(),
12660                                MenuAnchor::new(vec![
12661                                    MenuItemButton::new()
12662                                        .autofocus(true)
12663                                        .on_pressed(Listener::new(|_app| {}))
12664                                        .child(Text::new("Item 0"))
12665                                        .into_widget(),
12666                                    SubmenuButton::new(
12667                                        vec![
12668                                            MenuItemButton::new()
12669                                                .focus_node(submenu_focus_node.clone())
12670                                                .on_pressed(Listener::new(|_app| {}))
12671                                                .child(Text::new("Nested"))
12672                                                .into_widget(),
12673                                        ],
12674                                        Some(Text::new("Submenu")),
12675                                    )
12676                                    .animated(true)
12677                                    .into_widget(),
12678                                ])
12679                                .controller(controller.clone())
12680                                .animated(true)
12681                                .builder(|_app, _context, controller, _child| {
12682                                    TextButton::new(
12683                                        Some(Listener::new(move |app| {
12684                                            if controller.is_open(app) {
12685                                                controller.close(app);
12686                                            } else {
12687                                                controller.open(app, None);
12688                                            }
12689                                        })),
12690                                        Some(Text::new("Open Menu")),
12691                                    )
12692                                    .autofocus(true)
12693                                    .into_widget()
12694                                })
12695                                .into_widget(),
12696                            ]))
12697                        .into_widget()
12698                });
12699
12700                request_focus(tester, outside_focus_node.handle());
12701                pump(tester);
12702
12703                assert!(has_primary_focus(tester, outside_focus_node.handle()));
12704
12705                tester.tap(find::text("Open Menu"));
12706                pump(tester);
12707                pump_ms(tester, 500);
12708
12709                let submenu = tester.get_rect(find::text("Submenu")).center();
12710                hover_over(tester, submenu);
12711                pump(tester);
12712                pump_ms(tester, 500);
12713
12714                assert!(shows(tester, "Nested"));
12715
12716                request_focus(tester, submenu_focus_node.handle());
12717                pump(tester);
12718
12719                assert!(has_primary_focus(tester, submenu_focus_node.handle()));
12720
12721                close(tester, controller.handle());
12722                pump(tester);
12723
12724                assert!(has_primary_focus(tester, outside_focus_node.handle()));
12725
12726                pump_ms(tester, 50);
12727
12728                assert!(has_primary_focus(tester, outside_focus_node.handle()));
12729
12730                tester.pump_and_settle();
12731
12732                assert!(has_primary_focus(tester, outside_focus_node.handle()));
12733            });
12734        }
12735
12736        // menu_anchor_test.dart 'Submenu items can be traversed during opening animation'.
12737        #[test]
12738        fn submenu_items_can_be_traversed_while_the_menus_open() {
12739            test_widgets(|tester| {
12740                let controller = new_controller(tester);
12741                pump_material(tester, m3, |_app| {
12742                    MenuBar::new(vec![
12743                        SubmenuButton::new(
12744                            vec![
12745                                item("Item 0"),
12746                                SubmenuButton::new(
12747                                    items(&["Sub Item 0", "Sub Item 1"]),
12748                                    Some(Text::new("Submenu")),
12749                                )
12750                                .animated(true)
12751                                .into_widget(),
12752                            ],
12753                            Some(Text::new("Menu")),
12754                        )
12755                        .animated(true)
12756                        .into_widget(),
12757                    ])
12758                    .controller(controller)
12759                    .into_widget()
12760                });
12761
12762                tester.tap(find::text("Menu"));
12763                pump(tester);
12764                pump_ms(tester, 100);
12765
12766                assert_eq!(
12767                    focused_menu(tester),
12768                    Some(button_label("SubmenuButton", "Menu"))
12769                );
12770
12771                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
12772
12773                assert_eq!(
12774                    focused_menu(tester),
12775                    Some(button_label("MenuItemButton", "Item 0"))
12776                );
12777
12778                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
12779                pump(tester);
12780
12781                assert_eq!(
12782                    focused_menu(tester),
12783                    Some(button_label("SubmenuButton", "Submenu"))
12784                );
12785
12786                send_key(tester, LogicalKeyboardKey::ARROW_RIGHT);
12787                pump(tester);
12788
12789                assert_eq!(
12790                    focused_menu(tester),
12791                    Some(button_label("MenuItemButton", "Sub Item 0"))
12792                );
12793
12794                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
12795                pump(tester);
12796
12797                assert_eq!(
12798                    focused_menu(tester),
12799                    Some(button_label("MenuItemButton", "Sub Item 1"))
12800                );
12801
12802                send_key(tester, LogicalKeyboardKey::ARROW_LEFT);
12803                pump(tester);
12804
12805                assert_eq!(
12806                    focused_menu(tester),
12807                    Some(button_label("SubmenuButton", "Submenu"))
12808                );
12809
12810                send_key(tester, LogicalKeyboardKey::ARROW_RIGHT);
12811                pump(tester);
12812
12813                assert_eq!(
12814                    focused_menu(tester),
12815                    Some(button_label("MenuItemButton", "Sub Item 0"))
12816                );
12817
12818                send_key(tester, LogicalKeyboardKey::ARROW_LEFT);
12819                pump(tester);
12820
12821                send_key(tester, LogicalKeyboardKey::ARROW_UP);
12822                pump(tester);
12823
12824                assert_eq!(
12825                    focused_menu(tester),
12826                    Some(button_label("MenuItemButton", "Item 0"))
12827                );
12828            });
12829        }
12830
12831        // menu_anchor_test.dart 'Hover traversal works during opening animation'.
12832        #[test]
12833        fn hovering_moves_focus_while_the_menu_opens() {
12834            test_widgets(|tester| {
12835                let controller = new_controller(tester);
12836                pump_animated_anchor(
12837                    tester,
12838                    controller.clone(),
12839                    items(&["Item 0", "Item 1", "Item 2"]),
12840                );
12841
12842                open(tester, controller.handle(), None);
12843                pump(tester);
12844                pump_ms(tester, 100);
12845
12846                for (device, (wait, text)) in [
12847                    (0, "Item 0"),
12848                    (100, "Item 1"),
12849                    (100, "Item 2"),
12850                    (200, "Item 0"),
12851                ]
12852                .into_iter()
12853                .enumerate()
12854                {
12855                    if wait > 0 {
12856                        pump_ms(tester, wait);
12857                    }
12858                    let center = tester.get_rect(find::text(text)).center();
12859                    hover_with_new_mouse(tester, device as i64 + 1, center);
12860                    pump(tester);
12861
12862                    assert_eq!(
12863                        focused_menu(tester),
12864                        Some(button_label("MenuItemButton", text))
12865                    );
12866                }
12867            });
12868        }
12869
12870        // menu_anchor_test.dart 'MenuBar items can be traversed during submenu opening animation'.
12871        #[test]
12872        fn menu_bar_items_can_be_traversed_while_a_submenu_opens() {
12873            test_widgets(|tester| {
12874                let controller = new_controller(tester);
12875                pump_material(tester, m3, |_app| {
12876                    let submenu = |label: &str| {
12877                        SubmenuButton::new(
12878                            items(&[&format!("{label} Item")]),
12879                            Some(Text::new(label)),
12880                        )
12881                        .animated(true)
12882                        .into_widget()
12883                    };
12884                    MenuBar::new(vec![
12885                        submenu("Menu 0"),
12886                        submenu("Menu 1"),
12887                        submenu("Menu 2"),
12888                    ])
12889                    .controller(controller)
12890                    .into_widget()
12891                });
12892
12893                tester.tap(find::text("Menu 0"));
12894                pump(tester);
12895                pump_ms(tester, 20);
12896                send_key(tester, LogicalKeyboardKey::ARROW_RIGHT);
12897                pump(tester);
12898
12899                assert_eq!(
12900                    focused_menu(tester),
12901                    Some(button_label("SubmenuButton", "Menu 1"))
12902                );
12903
12904                send_key(tester, LogicalKeyboardKey::ARROW_RIGHT);
12905                pump(tester);
12906
12907                assert_eq!(
12908                    focused_menu(tester),
12909                    Some(button_label("SubmenuButton", "Menu 2"))
12910                );
12911
12912                pump_ms(tester, 20);
12913                send_key(tester, LogicalKeyboardKey::ARROW_LEFT);
12914                pump(tester);
12915
12916                assert_eq!(
12917                    focused_menu(tester),
12918                    Some(button_label("SubmenuButton", "Menu 1"))
12919                );
12920            });
12921        }
12922
12923        // menu_anchor_test.dart 'Focus state remains consistent throughout opening animation'.
12924        #[test]
12925        fn a_focused_item_keeps_focus_while_the_menu_opens() {
12926            test_widgets(|tester| {
12927                let controller = new_controller(tester);
12928                let item_focus_node = new_focus_node(tester, None);
12929                pump_material(tester, m3, |_app| {
12930                    Column::new()
12931                        .children(vec![
12932                            TextButton::new(
12933                                Some(Listener::new(|_app| {})),
12934                                Some(Text::new("Outside")),
12935                            )
12936                            .autofocus(true)
12937                            .into_widget(),
12938                            MenuAnchor::new(vec![
12939                                MenuItemButton::new()
12940                                    .focus_node(item_focus_node.clone())
12941                                    .on_pressed(Listener::new(|_app| {}))
12942                                    .child(Text::new("Item 0"))
12943                                    .into_widget(),
12944                                MenuItemButton::new()
12945                                    .autofocus(true)
12946                                    .on_pressed(Listener::new(|_app| {}))
12947                                    .child(Text::new("Item 1"))
12948                                    .into_widget(),
12949                            ])
12950                            .controller(controller.clone())
12951                            .animated(true)
12952                            .into_widget(),
12953                        ])
12954                        .into_widget()
12955                });
12956
12957                open(tester, controller.handle(), None);
12958                pump(tester);
12959
12960                request_focus(tester, item_focus_node.handle());
12961                pump(tester);
12962
12963                assert!(has_primary_focus(tester, item_focus_node.handle()));
12964
12965                pump_ms(tester, 200);
12966
12967                assert!(has_primary_focus(tester, item_focus_node.handle()));
12968
12969                tester.pump_and_settle();
12970
12971                assert!(has_primary_focus(tester, item_focus_node.handle()));
12972            });
12973        }
12974
12975        // menu_anchor_test.dart 'Scrollbar thumb is not shown while animated menu is opening'.
12976        #[test]
12977        fn the_scrollbar_thumb_shows_only_once_the_menu_has_opened() {
12978            test_widgets(|tester| {
12979                let controller = new_controller(tester);
12980                let texts: Vec<String> = (0..20).map(|i| format!("Item {i}")).collect();
12981                let texts: Vec<&str> = texts.iter().map(String::as_str).collect();
12982                pump_animated_anchor(tester, controller.clone(), items(&texts));
12983
12984                let thumb_visibility = |tester: &WidgetTester| {
12985                    let scrollbar = tester.element(find::by_type::<Scrollbar>());
12986                    tester.widget::<Scrollbar, _>(scrollbar, |scrollbar| scrollbar.thumb_visibility)
12987                };
12988
12989                open(tester, controller.handle(), None);
12990                pump(tester);
12991
12992                assert_eq!(thumb_visibility(tester), Some(false));
12993
12994                // Progress the animation to the middle.
12995                pump_ms(tester, 250);
12996
12997                assert_eq!(thumb_visibility(tester), Some(false));
12998
12999                tester.pump_and_settle();
13000
13001                assert_eq!(thumb_visibility(tester), Some(true));
13002            });
13003        }
13004
13005        // menu_anchor_test.dart 'Positioned menus always begin animating at the target position'.
13006        #[test]
13007        fn a_positioned_menu_begins_animating_at_its_position() {
13008            test_widgets(|tester| {
13009                let controller = new_controller(tester);
13010                let target_position = Offset::new(400.0, 400.0);
13011                pump_tall_anchor(tester, controller.clone());
13012
13013                open(tester, controller.handle(), Some(target_position));
13014
13015                pump(tester);
13016                pump_ms(tester, 2);
13017
13018                assert_eq!(panel_rect(tester).top_left(), target_position);
13019
13020                tester.pump_and_settle();
13021
13022                assert_eq!(panel_rect(tester).top_left(), target_position);
13023            });
13024        }
13025
13026        /// Dart's centred `MenuAnchor` of an 800 by 24 item, whose builder is as wide.
13027        fn pump_wide_anchor(
13028            tester: &mut WidgetTester,
13029            controller: MenuControllerRef,
13030            reserved_padding: Option<EdgeInsetsGeometry>,
13031        ) {
13032            pump_material(tester, m3, |_app| {
13033                let mut anchor = MenuAnchor::new(vec![
13034                    SizedBox::new().width(800.0).height(24.0).into_widget(),
13035                ])
13036                .controller(controller.clone())
13037                .builder(|_app, _context, _controller, _child| {
13038                    SizedBox::new().width(800.0).height(24.0).into_widget()
13039                });
13040                if let Some(reserved_padding) = reserved_padding {
13041                    anchor = anchor.reserved_padding(reserved_padding);
13042                }
13043                Center::new().child(anchor).into_widget()
13044            });
13045        }
13046
13047        fn menu_panel_rect(tester: &WidgetTester) -> Rect {
13048            rect_of_element(tester, only(menu_panels(tester)))
13049        }
13050
13051        // menu_anchor_test.dart 'Menu panel default reserved padding'.
13052        #[test]
13053        fn the_menu_panel_keeps_8_pixels_from_the_view_by_default() {
13054            test_widgets(|tester| {
13055                let controller = new_controller(tester);
13056                pump_wide_anchor(tester, controller.clone(), None);
13057
13058                open(tester, controller.handle(), None);
13059                pump(tester);
13060
13061                let default_reserved_padding = 8.0; // See K_MENU_VIEW_PADDING.
13062                assert_eq!(
13063                    menu_panel_rect(tester).width(),
13064                    800.0 - default_reserved_padding * 2.0
13065                );
13066            });
13067        }
13068
13069        // menu_anchor_test.dart 'Menu panel accepts custom reserved padding'.
13070        #[test]
13071        fn the_menu_panel_keeps_its_reserved_padding_from_the_view() {
13072            test_widgets(|tester| {
13073                let controller = new_controller(tester);
13074                let reserved_padding = EdgeInsetsGeometry::symmetric(0.0, 13.0);
13075                pump_wide_anchor(tester, controller.clone(), Some(reserved_padding));
13076
13077                open(tester, controller.handle(), None);
13078                pump(tester);
13079
13080                assert_eq!(
13081                    menu_panel_rect(tester).width(),
13082                    800.0 - reserved_padding.horizontal()
13083                );
13084            });
13085        }
13086
13087        /// `tester.pumpWidget(MaterialApp(home: home))`.
13088        fn pump_home(tester: &mut WidgetTester, home: impl FnOnce(&mut App) -> WidgetRef) {
13089            let root = {
13090                let mut app = tester.cell.borrow_mut();
13091                let theme = m3(&app);
13092                let home = home(&mut app);
13093                material_app(theme, home)
13094            };
13095            tester.pump_widget(root);
13096        }
13097
13098        /// Dart's `Center(child: SizedBox.shrink(child: child))` as a `MaterialApp`'s home.
13099        fn pump_shrunk(tester: &mut WidgetTester, child: WidgetRef) {
13100            pump_home(tester, |_app| {
13101                Center::new()
13102                    .child(SizedBox::shrink().child(child))
13103                    .into_widget()
13104            });
13105        }
13106
13107        fn size_of<W: 'static>(tester: &WidgetTester) -> Size {
13108            rect_of::<W>(tester).size()
13109        }
13110
13111        // menu_anchor_test.dart 'MenuAcceleratorLabel does not crash at zero area'.
13112        #[test]
13113        fn a_menu_accelerator_label_of_zero_area_does_not_panic() {
13114            test_widgets(|tester| {
13115                pump_shrunk(tester, MenuAcceleratorLabel::new("X").into_widget());
13116                assert_eq!(size_of::<MenuAcceleratorLabel>(tester), Size::ZERO);
13117            });
13118        }
13119
13120        // menu_anchor_test.dart 'Layout updates when reserved padding changes'.
13121        #[test]
13122        fn the_menu_lays_out_again_when_its_reserved_padding_changes() {
13123            test_widgets(|tester| {
13124                let controller = new_controller(tester);
13125                let reserved_padding = EdgeInsetsGeometry::symmetric(0.0, 13.0);
13126                let wide = || vec![SizedBox::new().width(800.0).height(24.0).into_widget()];
13127
13128                pump_home(tester, |_app| {
13129                    MenuAnchor::new(wide())
13130                        .controller(controller.clone())
13131                        .into_widget()
13132                });
13133
13134                open(tester, controller.handle(), Some(Offset::ZERO));
13135                pump(tester);
13136
13137                pump_home(tester, |_app| {
13138                    MenuAnchor::new(wide())
13139                        .controller(controller)
13140                        .reserved_padding(reserved_padding)
13141                        .into_widget()
13142                });
13143
13144                assert_eq!(
13145                    menu_panel_rect(tester).width(),
13146                    800.0 - reserved_padding.horizontal()
13147                );
13148            });
13149        }
13150
13151        // menu_anchor_test.dart 'SubmenuButton does not crash at zero area'.
13152        #[test]
13153        fn a_submenu_button_of_zero_area_does_not_panic() {
13154            test_widgets(|tester| {
13155                pump_shrunk(
13156                    tester,
13157                    SubmenuButton::new(Vec::new(), None::<WidgetRef>).into_widget(),
13158                );
13159                assert_eq!(size_of::<SubmenuButton>(tester), Size::ZERO);
13160            });
13161        }
13162
13163        // menu_anchor_test.dart 'MenuBar does not crash at zero area'.
13164        #[test]
13165        fn a_menu_bar_of_zero_area_does_not_panic() {
13166            test_widgets(|tester| {
13167                pump_shrunk(
13168                    tester,
13169                    MenuBar::new(vec![Text::new("X").into_widget()]).into_widget(),
13170                );
13171                assert_eq!(size_of::<MenuBar>(tester), Size::ZERO);
13172            });
13173        }
13174
13175        // menu_anchor_test.dart 'MenuItemButton does not crash at zero area'.
13176        #[test]
13177        fn a_menu_item_button_of_zero_area_does_not_panic() {
13178            test_widgets(|tester| {
13179                pump_shrunk(tester, MenuItemButton::new().into_widget());
13180                assert_eq!(size_of::<MenuItemButton>(tester), Size::ZERO);
13181            });
13182        }
13183
13184        // menu_anchor_test.dart 'RadioMenuButton does not crash at zero area'.
13185        #[test]
13186        fn a_radio_menu_button_of_zero_area_does_not_panic() {
13187            test_widgets(|tester| {
13188                pump_shrunk(
13189                    tester,
13190                    RadioMenuButton::new(
13191                        true,
13192                        Some(true),
13193                        Some(Rc::new(|_app: &mut App, _value: Option<bool>| {})),
13194                        None::<WidgetRef>,
13195                    )
13196                    .into_widget(),
13197                );
13198                assert_eq!(size_of::<RadioMenuButton<bool>>(tester), Size::ZERO);
13199            });
13200        }
13201
13202        // menu_anchor_test.dart 'CheckboxMenuButton does not crash at zero area'.
13203        #[test]
13204        fn a_checkbox_menu_button_of_zero_area_does_not_panic() {
13205            test_widgets(|tester| {
13206                pump_shrunk(
13207                    tester,
13208                    CheckboxMenuButton::new(
13209                        Some(true),
13210                        Some(Rc::new(|_app: &mut App, _value: Option<bool>| {})),
13211                        Some(Text::new("X")),
13212                    )
13213                    .into_widget(),
13214                );
13215                assert_eq!(size_of::<CheckboxMenuButton>(tester), Size::ZERO);
13216            });
13217        }
13218
13219        // menu_anchor_test.dart 'MenuAnchor does not crash at zero area'.
13220        #[test]
13221        fn a_menu_anchor_in_a_view_of_zero_area_does_not_panic() {
13222            test_widgets(|tester| {
13223                tester.view().set_physical_size(Size::ZERO);
13224                let menu_controller = new_controller(tester);
13225                pump_home(tester, |_app| {
13226                    Scaffold::new()
13227                        .body(
13228                            Center::new().child(
13229                                MenuAnchor::new(vec![Text::new("X").into_widget()])
13230                                    .controller(menu_controller.clone()),
13231                            ),
13232                        )
13233                        .into_widget()
13234                });
13235                assert_eq!(size_of::<MenuAnchor>(tester), Size::ZERO);
13236                open(tester, menu_controller.handle(), None);
13237                pump(tester);
13238                assert!(shows(tester, "X"));
13239            });
13240        }
13241
13242        // menu_anchor_test.dart 'Escape closes MenuAnchor opened by tap without childFocusNode'.
13243        #[test]
13244        fn escape_closes_a_menu_anchor_opened_by_a_tap_without_a_child_focus_node() {
13245            test_widgets(|tester| {
13246                let outside_focus_node = new_focus_node(tester, Some("Outside Focus"));
13247                pump_home(tester, |_app| {
13248                    Scaffold::new()
13249                        .body(Column::new().children(vec![
13250                                TextButton::new(
13251                                    Some(Listener::new(|_app| {})),
13252                                    Some(Text::new("Outside")),
13253                                )
13254                                .focus_node(outside_focus_node.clone())
13255                                .autofocus(true)
13256                                .into_widget(),
13257                                MenuAnchor::new(items(&["Item 1", "Item 2"]))
13258                                    .builder(toggle_button("Open menu"))
13259                                    .into_widget(),
13260                            ]))
13261                        .into_widget()
13262                });
13263
13264                pump(tester);
13265                assert!(has_primary_focus(tester, outside_focus_node.handle()));
13266
13267                tester.tap(find::text("Open menu"));
13268                tester.pump_and_settle();
13269                assert!(shows(tester, "Item 1"));
13270
13271                send_key(tester, LogicalKeyboardKey::ESCAPE);
13272                tester.pump_and_settle();
13273                assert!(!shows(tester, "Item 1"));
13274                assert!(has_primary_focus(tester, outside_focus_node.handle()));
13275
13276                // Reopen by tap, traverse with arrow key, and close with Escape.
13277                tester.tap(find::text("Open menu"));
13278                tester.pump_and_settle();
13279                assert!(shows(tester, "Item 1"));
13280
13281                send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
13282                pump(tester);
13283                assert_eq!(
13284                    focused_menu(tester),
13285                    Some(button_label("MenuItemButton", "Item 1"))
13286                );
13287
13288                send_key(tester, LogicalKeyboardKey::ESCAPE);
13289                tester.pump_and_settle();
13290                assert!(!shows(tester, "Item 1"));
13291                assert!(has_primary_focus(tester, outside_focus_node.handle()));
13292            });
13293        }
13294
13295        // menu_anchor_test.dart 'Escape closes MenuAnchor opened by tap inside a Dialog before
13296        // dismissing the Dialog'.
13297        #[test]
13298        fn escape_closes_a_menu_anchor_in_a_dialog_before_it_dismisses_the_dialog() {
13299            test_widgets(|tester| {
13300                pump_home(tester, |_app| {
13301                    Scaffold::new()
13302                        .body(Builder::new(|_app, context| {
13303                            TextButton::new(
13304                                Some(Listener::new(move |app| {
13305                                    let builder: waft_widgets::WidgetBuilder =
13306                                        Rc::new(|_app, _context| {
13307                                            AlertDialog::new()
13308                                                .title(Text::new("Dialog Title"))
13309                                                .content(
13310                                                    MenuAnchor::new(items(&["Menu Item 1"]))
13311                                                        .builder(
13312                                                            |_app, _context, controller, _child| {
13313                                                                TextButton::new(
13314                                                                    Some(Listener::new(
13315                                                                        move |app| {
13316                                                                            controller
13317                                                                                .open(app, None)
13318                                                                        },
13319                                                                    )),
13320                                                                    Some(Text::new("Open menu")),
13321                                                                )
13322                                                                .into_widget()
13323                                                            },
13324                                                        ),
13325                                                )
13326                                                .into_widget()
13327                                        });
13328                                    drop(ShowDialog::new(builder).show(app, context));
13329                                })),
13330                                Some(Text::new("Show Dialog")),
13331                            )
13332                            .into_widget()
13333                        }))
13334                        .into_widget()
13335                });
13336
13337                tester.tap(find::text("Show Dialog"));
13338                tester.pump_and_settle();
13339                assert!(shows(tester, "Dialog Title"));
13340
13341                tester.tap(find::text("Open menu"));
13342                tester.pump_and_settle();
13343                assert!(shows(tester, "Menu Item 1"));
13344
13345                // First Escape closes only the MenuAnchor menu, keeping the Dialog open.
13346                send_key(tester, LogicalKeyboardKey::ESCAPE);
13347                tester.pump_and_settle();
13348                assert!(!shows(tester, "Menu Item 1"));
13349                assert!(shows(tester, "Dialog Title"));
13350
13351                // Second Escape dismisses the Dialog.
13352                send_key(tester, LogicalKeyboardKey::ESCAPE);
13353                tester.pump_and_settle();
13354                assert!(!shows(tester, "Dialog Title"));
13355            });
13356        }
13357    }
13358    /// `menu_anchor_test.dart`, "MenuBar's MenuStyle is used": the menu bar describes its
13359    /// style and clip behavior.
13360    #[test]
13361    fn a_menu_bar_describes_its_style() {
13362        use std::rc::Rc;
13363
13364        use waft_embedder::Color;
13365        use waft_foundation::DiagnosticPropertiesBuilder;
13366        use waft_rendering::testing::ignoring_hash_codes;
13367        use waft_widgets::WidgetStatePropertyAll;
13368
13369        let red = Color::new(0xfff44336);
13370        let menu_bar = MenuBar::new(Vec::new()).style(
13371            MenuStyle::new()
13372                .background_color(Rc::new(WidgetStatePropertyAll::new(Some(red))))
13373                .elevation(Rc::new(WidgetStatePropertyAll::new(Some(10.0)))),
13374        );
13375        let cell = waft_foundation::AppCell::new();
13376        let app = cell.borrow();
13377        let description: Vec<String> = waft_widgets::testing::describe_properties(
13378            |properties: &mut DiagnosticPropertiesBuilder| {
13379                menu_bar.debug_fill_properties(&app, properties)
13380            },
13381        );
13382        assert_eq!(
13383            ignoring_hash_codes(&description.join("\n")),
13384            format!(
13385                "style: MenuStyle#00000(backgroundColor: WidgetStatePropertyAll({red}), elevation: WidgetStatePropertyAll(10.0))\nclipBehavior: Clip.none"
13386            )
13387        );
13388    }
13389
13390    /// `menu_anchor_test.dart`, "SubmenuButton's MenuStyle is used": the submenu button
13391    /// describes its focus node, menu style, offset and clip behavior.
13392    #[test]
13393    fn a_submenu_button_describes_its_menu_style() {
13394        use std::rc::Rc;
13395
13396        use waft_embedder::Color;
13397        use waft_foundation::DiagnosticPropertiesBuilder;
13398        use waft_painting::{BorderRadiusGeometry, BorderSide, RoundedRectangleBorder};
13399        use waft_rendering::testing::ignoring_hash_codes;
13400        use waft_widgets::WidgetStatePropertyAll;
13401
13402        let green = Color::new(0xff4caf50);
13403        let submenu = SubmenuButton::new(Vec::new(), Some(Text::new("Menu 0"))).menu_style(
13404            MenuStyle::new()
13405                .background_color(Rc::new(WidgetStatePropertyAll::new(Some(green))))
13406                .elevation(Rc::new(WidgetStatePropertyAll::new(Some(20.0))))
13407                .shape(Rc::new(WidgetStatePropertyAll::new(Some(
13408                    RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::ZERO)
13409                        .into(),
13410                )))),
13411        );
13412        let cell = waft_foundation::AppCell::new();
13413        let app = cell.borrow();
13414        let description: Vec<String> = waft_widgets::testing::describe_properties(
13415            |properties: &mut DiagnosticPropertiesBuilder| {
13416                submenu.debug_fill_properties(&app, properties)
13417            },
13418        );
13419        assert_eq!(
13420            ignoring_hash_codes(&description.join("\n")),
13421            format!(
13422                "focusNode: null\nmenuStyle: MenuStyle#00000(backgroundColor: WidgetStatePropertyAll({green}), elevation: WidgetStatePropertyAll(20.0), shape: WidgetStatePropertyAll(RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero)))\nalignmentOffset: null\nclipBehavior: hardEdge"
13423            )
13424        );
13425    }
13426}