Skip to main content

waft_material/
popup_menu.rs

1//! Flutter counterpart: material_ui's `popup_menu.dart`.
2//!
3//! A [`PopupMenuEntry`] is a widget that also answers its height and whether it represents a
4//! value; the menu holds them erased as [`PopupMenuEntryRef`]s. A route's result is erased
5//! (waft-widgets' navigator), so [`ShowMenu`] resolves to the `Rc<dyn Any>` an item popped
6//! with, which holds its `T`.
7
8use std::any::Any;
9use std::cell::{Cell, RefCell};
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12use std::time::Duration;
13
14use waft_animation::{
15    Animatable, Animation, AnimationRef, AnimationStyle, CurveTween, CurvedAnimation, Curves,
16    Interval,
17};
18use waft_embedder::{
19    Brightness, Clip, Color, Offset, Rect, SemanticsRole, Size, TargetPlatform, TextBaseline,
20    TextDirection,
21};
22use waft_foundation::{App, CompleterFuture, Handle, Listener, OptionRetained, Ref, ValueChanged};
23use waft_painting::{
24    AlignmentGeometry, BorderRadius, BorderRadiusGeometry, EdgeInsets, EdgeInsetsGeometry,
25    ShapeBorderRef, TextStyle,
26};
27use waft_rendering::{
28    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, BoxParentData,
29    PaintingContext, RelativeRect, RenderBox, RenderBoxData, RenderHandle, RenderObject,
30    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin, RenderShiftedBox,
31    SingleChildLayoutDelegate,
32};
33use waft_scheduler::{FrameCallback, SchedulerBinding};
34use waft_services::MouseCursorRef;
35use waft_widgets::{
36    Align, AnimatedBuilder, AnimatedDefaultTextStyle, BuildContext, CapturedThemes, ColoredBox,
37    ConstrainedBox, CustomSingleChildLayout, Directionality, FadeTransition, GlobalKey, Icon,
38    IconTheme, IconThemeData, IgnorePointer, InheritedTheme, IntoWidget, IntrinsicWidth, KeyRef,
39    LayoutBuilder, ListBody, LocalHistoryRoute, LocalHistoryRouteData, MediaQuery, MergeSemantics,
40    ModalRoute, ModalRouteData, NavigationMode, Navigator, OverlayRoute, OverlayRouteData, Padding,
41    PopupRoute, PredictiveBackRoute, RenderObjectWidget, Route, RouteData, RouteResult,
42    RouteSettingsRef, ScrollPositionAlignmentPolicy, Scrollable, Semantics,
43    SingleChildRenderObjectWidget, SingleChildScrollView, SingleTickerProviderStateMixin,
44    SingleTickerProviderStateMixinData, StandardComponentType, State, StateData, StatefulWidget,
45    TransitionRoute, TransitionRouteBase, TransitionRouteData, TraversalEdgeBehavior, WidgetRef,
46    WidgetState, WidgetStateMouseCursor, WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
47    downcast_widget,
48};
49
50use crate::button_style::ButtonStyle;
51use crate::constants::{K_MIN_INTERACTIVE_DIMENSION, K_THEME_CHANGE_DURATION};
52use crate::debug::debug_check_has_material_localizations;
53use crate::divider::Divider;
54use crate::generated::popup_menu_defaults_m3::{MENU_ITEM_PADDING, PopupMenuDefaultsM3};
55use crate::icon_button::IconButton;
56use crate::icons::Icons;
57use crate::ink_well::InkWell;
58use crate::list_tile::ListTile;
59use crate::list_tile_theme::ListTileTheme;
60use crate::material::{Material, MaterialType};
61use crate::material_localizations::MaterialLocalizations;
62use crate::popup_menu_theme::{
63    PopupMenuPosition, PopupMenuTheme, PopupMenuThemeData, PopupMenuThemeDataGetters,
64};
65use crate::theme::Theme;
66use crate::theme_data::MaterialTapTargetSize;
67use crate::theme_data_getters::DefaultsContext;
68use crate::tooltip::Tooltip;
69
70const K_MENU_DURATION: Duration = Duration::from_millis(300);
71const K_MENU_CLOSE_INTERVAL_END: f64 = 2.0 / 3.0;
72const K_MENU_DIVIDER_HEIGHT: f64 = 16.0;
73const K_MENU_MAX_WIDTH: f64 = 5.0 * K_MENU_WIDTH_STEP;
74const K_MENU_MIN_WIDTH: f64 = 2.0 * K_MENU_WIDTH_STEP;
75const K_MENU_WIDTH_STEP: f64 = 56.0;
76const K_MENU_SCREEN_PADDING: f64 = 8.0;
77
78// ---------------------------------------------------------------------------------------------
79// PopupMenuEntry
80
81/// A base class for entries in a Material Design popup menu.
82///
83/// The popup menu widget uses this interface to interact with the menu items. To show a popup
84/// menu, use the [`ShowMenu`] function. To create a button that shows a popup menu, consider
85/// using [`PopupMenuButton`].
86///
87/// The type `T` is the type of the value(s) the entry represents. All the entries in a given
88/// menu must represent values with consistent types.
89///
90/// A [`PopupMenuEntry`] may represent multiple values, for example a row with several icons,
91/// or a single entry, for example a menu item with an icon (see [`PopupMenuItem`]), or no value
92/// at all (for example, [`PopupMenuDivider`]).
93///
94/// A menu holds its entries as [`PopupMenuEntryRef`]s.
95///
96/// See also:
97///
98///  * [`PopupMenuItem`], a popup menu entry for a single value.
99///  * [`PopupMenuDivider`], a popup menu entry that is just a horizontal line.
100///  * [`CheckedPopupMenuItem`], a popup menu item with a checkmark.
101///  * [`ShowMenu`], a method to dynamically show a popup menu at a given location.
102///  * [`PopupMenuButton`], an [`IconButton`] that automatically shows a menu when it is tapped.
103pub trait PopupMenuEntry<T: 'static>: StatefulWidget {
104    /// The amount of vertical space occupied by this entry.
105    ///
106    /// This value is used at the time the [`ShowMenu`] method is called, if the
107    /// `initial_value` argument is provided, to determine the position of this entry when
108    /// aligning the selected entry over the given `position`. It is otherwise ignored.
109    fn height(&self) -> f64;
110
111    /// Whether this entry represents a particular value.
112    ///
113    /// This method is used by [`ShowMenu`], when it is called, to align the entry representing
114    /// the `initial_value`, if any, to the given `position`, and then later is called on each
115    /// entry to determine if it should be highlighted (if the method returns true, the entry
116    /// will have its background color set to the ambient `ThemeData::highlight_color`). If
117    /// `initial_value` is `None`, then this method is not called.
118    ///
119    /// If the [`PopupMenuEntry`] represents a single value, this should return true if the
120    /// argument matches that value. If it represents multiple values, it should return true if
121    /// the argument matches any of them.
122    fn represents(&self, value: Option<&T>) -> bool;
123}
124
125/// A [`PopupMenuEntry`] held as a value: the erased widget, whose height and values are still
126/// answered by the entry it holds. Dart types such a value `PopupMenuEntry<T>`.
127pub struct PopupMenuEntryRef<T: 'static> {
128    widget: WidgetRef,
129    height: fn(&WidgetRef) -> f64,
130    represents: fn(&WidgetRef, Option<&T>) -> bool,
131}
132
133impl<T: 'static> PopupMenuEntryRef<T> {
134    /// Erases `entry`.
135    #[cfg_attr(debug_assertions, track_caller)]
136    pub fn new<K, E: PopupMenuEntry<T> + IntoWidget<K>>(entry: E) -> PopupMenuEntryRef<T> {
137        PopupMenuEntryRef {
138            widget: entry.into_widget(),
139            height: |widget| {
140                downcast_widget::<E>(&**widget)
141                    .expect("an erased widget keeps its type")
142                    .height()
143            },
144            represents: |widget, value| {
145                downcast_widget::<E>(&**widget)
146                    .expect("an erased widget keeps its type")
147                    .represents(value)
148            },
149        }
150    }
151
152    /// See [`PopupMenuEntry::height`].
153    pub fn height(&self) -> f64 {
154        (self.height)(&self.widget)
155    }
156
157    /// See [`PopupMenuEntry::represents`].
158    pub fn represents(&self, value: Option<&T>) -> bool {
159        (self.represents)(&self.widget, value)
160    }
161
162    /// The widget itself.
163    pub fn widget(&self) -> &WidgetRef {
164        &self.widget
165    }
166}
167
168impl<T: 'static> Clone for PopupMenuEntryRef<T> {
169    fn clone(&self) -> PopupMenuEntryRef<T> {
170        PopupMenuEntryRef {
171            widget: self.widget.clone(),
172            height: self.height,
173            represents: self.represents,
174        }
175    }
176}
177
178impl<T: 'static> Debug for PopupMenuEntryRef<T> {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        Debug::fmt(&self.widget, f)
181    }
182}
183
184/// The kind tag of [`IntoWidget`] for a [`PopupMenuEntryRef`].
185pub struct PopupMenuEntryRefKind;
186
187impl<T: 'static> IntoWidget<PopupMenuEntryRefKind> for PopupMenuEntryRef<T> {
188    #[cfg_attr(debug_assertions, track_caller)]
189    fn into_widget(self) -> WidgetRef {
190        self.widget
191    }
192}
193
194// ---------------------------------------------------------------------------------------------
195// PopupMenuDivider
196
197/// A horizontal divider in a Material Design popup menu.
198///
199/// This widget adapts the [`Divider`] for use in popup menus.
200///
201/// It is a [`PopupMenuEntry`] of every `T`, as Dart's `PopupMenuEntry<Never>` is.
202///
203/// See also:
204///
205///  * [`PopupMenuItem`], for the kinds of items that this widget divides.
206///  * [`ShowMenu`], a method to dynamically show a popup menu at a given location.
207///  * [`PopupMenuButton`], an [`IconButton`] that automatically shows a menu when it is tapped.
208#[derive(Debug)]
209pub struct PopupMenuDivider {
210    pub key: Option<KeyRef>,
211
212    /// The height of the divider entry.
213    ///
214    /// Defaults to 16 pixels.
215    pub height: f64,
216
217    /// The thickness of the divider line.
218    ///
219    /// If this is `None`, then the `DividerThemeData::thickness` is used. If that is also
220    /// `None`, then this defaults to 1.0.
221    pub thickness: Option<f64>,
222
223    /// The amount of empty space to the leading edge of the divider line.
224    ///
225    /// If this is `None`, then the `DividerThemeData::indent` is used. If that is also `None`,
226    /// then this defaults to 0.0.
227    pub indent: Option<f64>,
228
229    /// The amount of empty space to the trailing edge of the divider line.
230    ///
231    /// If this is `None`, then the `DividerThemeData::end_indent` is used. If that is also
232    /// `None`, then this defaults to 0.0.
233    pub end_indent: Option<f64>,
234
235    /// The amount of radius for the border of the divider line.
236    ///
237    /// If this is `None`, then the default radius of [`Divider`] will be used.
238    pub radius: Option<BorderRadiusGeometry>,
239
240    /// The color of the divider line.
241    ///
242    /// If this is `None`, then the `DividerThemeData::color` is used. If that is also `None`,
243    /// then `ColorScheme::outline_variant` is used.
244    // TODO(framework): Add unit tests to this code snippet.
245    // https://github.com/flutter/flutter/issues/188530
246    pub color: Option<Color>,
247}
248
249impl PopupMenuDivider {
250    /// Creates a horizontal divider for a popup menu.
251    ///
252    /// By default, the divider has a height of 16 logical pixels.
253    pub fn new() -> PopupMenuDivider {
254        PopupMenuDivider {
255            key: None,
256            height: K_MENU_DIVIDER_HEIGHT,
257            thickness: None,
258            indent: None,
259            end_indent: None,
260            radius: None,
261            color: None,
262        }
263    }
264
265    /// Dart `PopupMenuDivider(key:)`.
266    pub fn key(mut self, key: KeyRef) -> PopupMenuDivider {
267        self.key = Some(key);
268        self
269    }
270
271    /// Dart `PopupMenuDivider(height:)`.
272    pub fn height(mut self, height: f64) -> PopupMenuDivider {
273        self.height = height;
274        self
275    }
276
277    /// Dart `PopupMenuDivider(thickness:)`.
278    pub fn thickness(mut self, thickness: f64) -> PopupMenuDivider {
279        self.thickness = Some(thickness);
280        self
281    }
282
283    /// Dart `PopupMenuDivider(indent:)`.
284    pub fn indent(mut self, indent: f64) -> PopupMenuDivider {
285        self.indent = Some(indent);
286        self
287    }
288
289    /// Dart `PopupMenuDivider(endIndent:)`.
290    pub fn end_indent(mut self, end_indent: f64) -> PopupMenuDivider {
291        self.end_indent = Some(end_indent);
292        self
293    }
294
295    /// Dart `PopupMenuDivider(radius:)`.
296    pub fn radius(mut self, radius: impl Into<BorderRadiusGeometry>) -> PopupMenuDivider {
297        self.radius = Some(radius.into());
298        self
299    }
300
301    /// Dart `PopupMenuDivider(color:)`.
302    pub fn color(mut self, color: Color) -> PopupMenuDivider {
303        self.color = Some(color);
304        self
305    }
306}
307
308impl Default for PopupMenuDivider {
309    fn default() -> PopupMenuDivider {
310        PopupMenuDivider::new()
311    }
312}
313
314impl<T: 'static> PopupMenuEntry<T> for PopupMenuDivider {
315    fn height(&self) -> f64 {
316        self.height
317    }
318
319    fn represents(&self, _value: Option<&T>) -> bool {
320        false
321    }
322}
323
324impl StatefulWidget for PopupMenuDivider {
325    type State = PopupMenuDividerState;
326
327    fn key(&self) -> Option<&KeyRef> {
328        self.key.as_ref()
329    }
330
331    fn create_state(&self) -> PopupMenuDividerState {
332        PopupMenuDividerState {
333            state: StateData::new(),
334        }
335    }
336}
337
338/// Dart's `_PopupMenuDividerState`.
339pub struct PopupMenuDividerState {
340    state: StateData<PopupMenuDivider>,
341}
342
343impl Debug for PopupMenuDividerState {
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        f.debug_struct("PopupMenuDividerState")
346            .finish_non_exhaustive()
347    }
348}
349
350impl State for PopupMenuDividerState {
351    type Widget = PopupMenuDivider;
352    waft_widgets::state_accessors!();
353
354    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
355        let widget = self.widget(app);
356        let mut divider = Divider::new().height(widget.height);
357        if let Some(thickness) = widget.thickness {
358            divider = divider.thickness(thickness);
359        }
360        if let Some(indent) = widget.indent {
361            divider = divider.indent(indent);
362        }
363        if let Some(color) = widget.color {
364            divider = divider.color(color);
365        }
366        if let Some(end_indent) = widget.end_indent {
367            divider = divider.end_indent(end_indent);
368        }
369        if let Some(radius) = widget.radius {
370            divider = divider.radius(radius);
371        }
372        divider.into_widget()
373    }
374}
375
376// ---------------------------------------------------------------------------------------------
377// _MenuItem
378
379// This widget only exists to enable _PopupMenuRoute to save the sizes of
380// each menu item. The sizes are used by _PopupMenuRouteLayout to compute the
381// y coordinate of the menu's origin so that the center of selected menu
382// item lines up with the center of its PopupMenuButton.
383/// Dart's `_MenuItem`.
384#[derive(Debug)]
385struct MenuItem {
386    on_layout: OnLayout,
387    child: Option<WidgetRef>,
388}
389
390/// Dart's `ValueChanged<Size> onLayout`, which `Debug` prints by name.
391#[derive(Clone)]
392struct OnLayout(ValueChanged<Size>);
393
394impl Debug for OnLayout {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        f.write_str("onLayout")
397    }
398}
399
400impl RenderObjectWidget for MenuItem {
401    type RenderObject = RenderMenuItem;
402
403    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
404        RenderMenuItem::new(app, self.on_layout.clone()).as_object()
405    }
406
407    fn update_render_object(
408        &self,
409        app: &mut App,
410        _context: BuildContext,
411        render_object: RenderHandle<RenderMenuItem>,
412    ) {
413        render_object.get_mut(app).on_layout = self.on_layout.clone();
414    }
415}
416
417impl SingleChildRenderObjectWidget for MenuItem {
418    fn child(&self) -> Option<&WidgetRef> {
419        self.child.as_ref()
420    }
421}
422
423/// Dart's `_RenderMenuItem`.
424struct RenderMenuItem {
425    render_object: RenderObjectData,
426    render_box: RenderBoxData,
427    child: RenderObjectWithChildData<AnyRenderBox>,
428    on_layout: OnLayout,
429}
430
431impl RenderMenuItem {
432    fn new(app: &mut App, on_layout: OnLayout) -> RenderHandle<RenderMenuItem> {
433        RenderHandle::new_box(
434            app,
435            RenderMenuItem {
436                render_object: RenderObjectData::new(),
437                render_box: RenderBoxData::new(),
438                child: RenderObjectWithChildData::new(),
439                on_layout,
440            },
441        )
442    }
443}
444
445impl RenderObjectWithChildMixin for RenderMenuItem {
446    type ChildType = AnyRenderBox;
447
448    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
449        &self.get(app).child
450    }
451
452    fn child_data_mut(
453        self: RenderHandle<Self>,
454        app: &mut App,
455    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
456        &mut self.get_mut(app).child
457    }
458}
459
460impl RenderShiftedBox for RenderMenuItem {}
461
462impl RenderObject for RenderMenuItem {
463    waft_rendering::render_object_accessors!();
464
465    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
466        let constraints = self.constraints(app);
467        match self.child(app) {
468            None => self.set_size(app, Size::ZERO),
469            Some(child) => {
470                child.layout(app, constraints, true);
471                let size = constraints.constrain(child.size(app));
472                self.set_size(app, size);
473                child.parent_data_of_mut::<BoxParentData>(app).offset = Offset::ZERO;
474            }
475        }
476        let size = self.size(app);
477        let on_layout = Rc::clone(&self.get(app).on_layout.0);
478        on_layout(app, size);
479    }
480
481    fn paint(
482        self: RenderHandle<Self>,
483        app: &mut App,
484        context: &mut PaintingContext,
485        offset: Offset,
486    ) {
487        RenderShiftedBox::paint(self, app, context, offset);
488    }
489
490    fn visit_children(
491        self: RenderHandle<Self>,
492        app: &App,
493        visitor: &mut dyn FnMut(AnyRenderObject),
494    ) {
495        if let Some(child) = self.child(app) {
496            visitor(child.as_object());
497        }
498    }
499}
500
501impl RenderBox for RenderMenuItem {
502    waft_rendering::render_box_accessors!();
503
504    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
505        RenderShiftedBox::compute_min_intrinsic_width(self, app, height)
506    }
507
508    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
509        RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
510    }
511
512    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
513        RenderShiftedBox::compute_min_intrinsic_height(self, app, width)
514    }
515
516    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
517        RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
518    }
519
520    fn compute_dry_layout(
521        self: RenderHandle<Self>,
522        app: &mut App,
523        constraints: BoxConstraints,
524    ) -> Size {
525        match self.child(app) {
526            Some(child) => child.get_dry_layout(app, constraints),
527            None => Size::ZERO,
528        }
529    }
530
531    fn compute_dry_baseline(
532        self: RenderHandle<Self>,
533        app: &mut App,
534        constraints: BoxConstraints,
535        baseline: TextBaseline,
536    ) -> Option<f64> {
537        self.child(app)
538            .and_then(|child| child.get_dry_baseline(app, constraints, baseline))
539    }
540
541    fn compute_distance_to_actual_baseline(
542        self: RenderHandle<Self>,
543        app: &mut App,
544        baseline: TextBaseline,
545    ) -> Option<f64> {
546        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
547    }
548
549    fn hit_test_children(
550        self: RenderHandle<Self>,
551        app: &mut App,
552        result: &mut BoxHitTestResult<'_>,
553        position: Offset,
554    ) -> bool {
555        RenderShiftedBox::hit_test_children(self, app, result, position)
556    }
557}
558
559// ---------------------------------------------------------------------------------------------
560// PopupMenuItem
561
562/// The fields of Dart's `PopupMenuItem<T>`, which [`PopupMenuItem`] and its subclasses, such
563/// as [`CheckedPopupMenuItem`], carry under the field `popup_menu_item`.
564pub struct PopupMenuItemData<T> {
565    pub key: Option<KeyRef>,
566
567    /// The value that will be returned by [`ShowMenu`] if this entry is selected.
568    pub value: Option<T>,
569
570    /// Called when the menu item is tapped.
571    pub on_tap: Option<Listener>,
572
573    /// Whether the user is permitted to select this item.
574    ///
575    /// Defaults to true. If this is false, then the item will not react to touches.
576    pub enabled: bool,
577
578    /// The minimum height of the menu item.
579    ///
580    /// Defaults to [`K_MIN_INTERACTIVE_DIMENSION`] pixels.
581    pub height: f64,
582
583    /// The padding of the menu item.
584    ///
585    /// The [`height`](Self::height) property may interact with the applied padding. For
586    /// example, If a [`height`](Self::height) greater than the height of the sum of the padding
587    /// and [`child`](Self::child) is provided, then the padding's effect will not be visible.
588    ///
589    /// If this is `None` and `ThemeData::use_material3` is true, the horizontal padding
590    /// defaults to 12.0 on both sides.
591    ///
592    /// If this is `None` and `ThemeData::use_material3` is false, the horizontal padding
593    /// defaults to 16.0 on both sides.
594    pub padding: Option<EdgeInsets>,
595
596    /// The text style of the popup menu item.
597    ///
598    /// If this property is `None`, then [`PopupMenuThemeData::text_style`] is used. If
599    /// [`PopupMenuThemeData::text_style`] is also `None`, then `TextTheme::title_medium` of
600    /// `ThemeData::text_theme` is used.
601    pub text_style: Option<TextStyle>,
602
603    /// The label style of the popup menu item.
604    ///
605    /// When `ThemeData::use_material3` is true, this styles the text of the popup menu item.
606    ///
607    /// If this property is `None`, then [`PopupMenuThemeData::label_text_style`] is used. If
608    /// [`PopupMenuThemeData::label_text_style`] is also `None`, then `TextTheme::label_large`
609    /// is used with the `ColorScheme::on_surface` color when popup menu item is enabled and the
610    /// `ColorScheme::on_surface` color with 0.38 opacity when the popup menu item is disabled.
611    pub label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
612
613    /// {@template material_ui.popupmenu.mouseCursor}
614    /// The cursor for a mouse pointer when it enters or is hovering over the widget.
615    ///
616    /// If [`mouse_cursor`](Self::mouse_cursor) is a [`WidgetStateMouseCursor`],
617    /// [`WidgetStateProperty::resolve`] is used for the following [`WidgetState`]s:
618    ///
619    ///  * [`WidgetState::Hovered`].
620    ///  * [`WidgetState::Focused`].
621    ///  * [`WidgetState::Disabled`].
622    ///
623    /// {@endtemplate}
624    ///
625    /// If `None`, then the value of [`PopupMenuThemeData::mouse_cursor`] is used. If that is
626    /// also `None`, then [`WidgetStateMouseCursor::adaptive_clickable`] is used.
627    pub mouse_cursor: Option<MouseCursorRef>,
628
629    /// The widget below this widget in the tree.
630    ///
631    /// Typically a single-line [`ListTile`] (for menus with icons) or a `Text`. An appropriate
632    /// `DefaultTextStyle` is put in scope for the child. In either case, the text should be
633    /// short enough that it won't wrap.
634    pub child: Option<WidgetRef>,
635}
636
637impl<T> PopupMenuItemData<T> {
638    /// The fields of an item showing `child`, with Dart's defaults.
639    pub fn new(child: Option<WidgetRef>) -> PopupMenuItemData<T> {
640        PopupMenuItemData {
641            key: None,
642            value: None,
643            on_tap: None,
644            enabled: true,
645            height: K_MIN_INTERACTIVE_DIMENSION,
646            padding: None,
647            text_style: None,
648            label_text_style: None,
649            mouse_cursor: None,
650            child,
651        }
652    }
653}
654
655impl<T: Debug> Debug for PopupMenuItemData<T> {
656    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657        f.debug_struct("PopupMenuItem")
658            .field("value", &self.value)
659            .field("enabled", &self.enabled)
660            .field("height", &self.height)
661            .field("padding", &self.padding)
662            .field("child", &self.child)
663            .finish_non_exhaustive()
664    }
665}
666
667/// The fluent setters of Dart's `PopupMenuItem` named arguments, defined on [`PopupMenuItem`]
668/// and on [`CheckedPopupMenuItem`], whose constructor passes them on as `super.` arguments.
669macro_rules! popup_menu_item_setters {
670    ($name:ident) => {
671        #[doc = concat!("Dart `", stringify!($name), "(key:)`.")]
672        pub fn key(mut self, key: KeyRef) -> $name<T> {
673            self.popup_menu_item.key = Some(key);
674            self
675        }
676
677        #[doc = concat!("Dart `", stringify!($name), "(value:)`.")]
678        pub fn value(mut self, value: T) -> $name<T> {
679            self.popup_menu_item.value = Some(value);
680            self
681        }
682
683        #[doc = concat!("Dart `", stringify!($name), "(onTap:)`.")]
684        pub fn on_tap(mut self, on_tap: Listener) -> $name<T> {
685            self.popup_menu_item.on_tap = Some(on_tap);
686            self
687        }
688
689        #[doc = concat!("Dart `", stringify!($name), "(enabled:)`.")]
690        pub fn enabled(mut self, enabled: bool) -> $name<T> {
691            self.popup_menu_item.enabled = enabled;
692            self
693        }
694
695        #[doc = concat!("Dart `", stringify!($name), "(height:)`.")]
696        pub fn height(mut self, height: f64) -> $name<T> {
697            self.popup_menu_item.height = height;
698            self
699        }
700
701        #[doc = concat!("Dart `", stringify!($name), "(padding:)`.")]
702        pub fn padding(mut self, padding: EdgeInsets) -> $name<T> {
703            self.popup_menu_item.padding = Some(padding);
704            self
705        }
706
707        #[doc = concat!("Dart `", stringify!($name), "(labelTextStyle:)`.")]
708        pub fn label_text_style(
709            mut self,
710            label_text_style: WidgetStatePropertyRef<Option<TextStyle>>,
711        ) -> $name<T> {
712            self.popup_menu_item.label_text_style = Some(label_text_style);
713            self
714        }
715
716        #[doc = concat!("Dart `", stringify!($name), "(mouseCursor:)`.")]
717        pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> $name<T> {
718            self.popup_menu_item.mouse_cursor = Some(mouse_cursor);
719            self
720        }
721    };
722}
723
724/// The trait every popup-menu-item widget implements: [`PopupMenuItem`] and its subclasses,
725/// such as [`CheckedPopupMenuItem`]. Dart's `W extends PopupMenuItem<T>`.
726///
727/// Its [`State`] is a [`PopupMenuItemStateLeaf`].
728pub trait PopupMenuItemLeaf: StatefulWidget {
729    /// Dart's `T` of `PopupMenuItem<T>`.
730    type Value: Clone + PartialEq + 'static;
731
732    /// The [`PopupMenuItemData`] bag, held under the field `popup_menu_item`.
733    fn popup_menu_item_data(&self) -> &PopupMenuItemData<Self::Value>;
734}
735
736/// An item in a Material Design popup menu.
737///
738/// To show a popup menu, use the [`ShowMenu`] function. To create a button that shows a popup
739/// menu, consider using [`PopupMenuButton`].
740///
741/// To show a checkmark next to a popup menu item, consider using [`CheckedPopupMenuItem`].
742///
743/// Typically the [`child`](PopupMenuItemData::child) of a [`PopupMenuItem`] is a `Text`
744/// widget. More elaborate menus with icons can use a [`ListTile`]. By default, a
745/// [`PopupMenuItem`] is [`K_MIN_INTERACTIVE_DIMENSION`] pixels high. If you use a widget with
746/// a different height, it must be specified in the [`height`](PopupMenuItemData::height)
747/// property.
748///
749/// See also:
750///
751///  * [`PopupMenuDivider`], which can be used to divide items from each other.
752///  * [`CheckedPopupMenuItem`], a variant of [`PopupMenuItem`] with a checkmark.
753///  * [`ShowMenu`], a method to dynamically show a popup menu at a given location.
754///  * [`PopupMenuButton`], an [`IconButton`] that automatically shows a menu when it is tapped.
755// TODO(framework): Add unit tests to this code snippet.
756// https://github.com/flutter/flutter/issues/188530
757pub struct PopupMenuItem<T: 'static> {
758    pub popup_menu_item: PopupMenuItemData<T>,
759}
760
761impl<T: Clone + PartialEq + 'static> PopupMenuItem<T> {
762    /// Creates an item for a popup menu.
763    ///
764    /// By default, the item is [`enabled`](PopupMenuItemData::enabled).
765    #[cfg_attr(debug_assertions, track_caller)]
766    pub fn new<K>(child: Option<impl IntoWidget<K>>) -> PopupMenuItem<T> {
767        PopupMenuItem {
768            popup_menu_item: PopupMenuItemData::new(match child {
769                Some(child) => Some(child.into_widget()),
770                None => None,
771            }),
772        }
773    }
774
775    popup_menu_item_setters!(PopupMenuItem);
776
777    /// Dart `PopupMenuItem(textStyle:)`.
778    pub fn text_style(mut self, text_style: TextStyle) -> PopupMenuItem<T> {
779        self.popup_menu_item.text_style = Some(text_style);
780        self
781    }
782}
783
784impl<T: 'static> Debug for PopupMenuItem<T> {
785    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786        f.debug_struct("PopupMenuItem")
787            .field("enabled", &self.popup_menu_item.enabled)
788            .field("height", &self.popup_menu_item.height)
789            .finish_non_exhaustive()
790    }
791}
792
793impl<T: Clone + PartialEq + 'static> PopupMenuItemLeaf for PopupMenuItem<T> {
794    type Value = T;
795
796    fn popup_menu_item_data(&self) -> &PopupMenuItemData<T> {
797        &self.popup_menu_item
798    }
799}
800
801impl<T: Clone + PartialEq + 'static> PopupMenuEntry<T> for PopupMenuItem<T> {
802    fn height(&self) -> f64 {
803        self.popup_menu_item.height
804    }
805
806    fn represents(&self, value: Option<&T>) -> bool {
807        value == self.popup_menu_item.value.as_ref()
808    }
809}
810
811impl<T: Clone + PartialEq + 'static> StatefulWidget for PopupMenuItem<T> {
812    type State = PopupMenuItemState<T>;
813
814    fn key(&self) -> Option<&KeyRef> {
815        self.popup_menu_item.key.as_ref()
816    }
817
818    fn create_state(&self) -> PopupMenuItemState<T> {
819        PopupMenuItemState {
820            state: StateData::new(),
821        }
822    }
823}
824
825/// The value type of a popup-menu-item state: its widget's `T`.
826pub type PopupMenuItemValue<S> = <<S as State>::Widget as PopupMenuItemLeaf>::Value;
827
828/// The trait every popup-menu-item state implements: [`PopupMenuItemState`] and its
829/// subclasses, such as [`CheckedPopupMenuItem`]'s state.
830///
831/// The virtuals a subclass overrides are the members here, each defaulting to the body of
832/// [`PopupMenuItemState`] of its name, which an override calls where Dart writes `super.…`;
833/// a leaf's own [`State::build`] runs [`PopupMenuItemState::build`].
834pub trait PopupMenuItemStateLeaf: State<Widget: PopupMenuItemLeaf> {
835    /// The menu item contents.
836    ///
837    /// Used by the [`State::build`] method.
838    ///
839    /// By default, this returns [`PopupMenuItemData::child`]. Override this to put something
840    /// else in the menu entry.
841    fn build_child(self: Handle<Self>, app: &mut App, context: BuildContext) -> Option<WidgetRef> {
842        PopupMenuItemState::<PopupMenuItemValue<Self>>::build_child(self, app, context)
843    }
844
845    /// The handler for when the user selects the menu item.
846    ///
847    /// Used by the `InkWell` inserted by the [`State::build`] method.
848    ///
849    /// By default, uses [`Navigator::pop`] to return the [`PopupMenuItemData::value`] from the
850    /// menu route.
851    fn handle_tap(self: Handle<Self>, app: &mut App) {
852        PopupMenuItemState::<PopupMenuItemValue<Self>>::handle_tap(self, app);
853    }
854
855    /// Builds the semantics for the menu item.
856    fn build_semantics(self: Handle<Self>, app: &mut App, child: WidgetRef) -> WidgetRef {
857        PopupMenuItemState::<PopupMenuItemValue<Self>>::build_semantics(self, app, child)
858    }
859}
860
861/// The [`State`] for [`PopupMenuItem`] subclasses.
862///
863/// By default this implements the basic styling and layout of Material Design popup menu
864/// items.
865///
866/// The [`PopupMenuItemStateLeaf::build_child`] method can be overridden to adjust exactly
867/// what gets placed in the menu. By default it returns [`PopupMenuItemData::child`].
868///
869/// The [`PopupMenuItemStateLeaf::handle_tap`] method can be overridden to adjust exactly what
870/// happens when the item is tapped. By default, it uses [`Navigator::pop`] to return the
871/// [`PopupMenuItemData::value`] from the menu route.
872///
873/// This struct is the state of [`PopupMenuItem`] itself, Dart's
874/// `PopupMenuItemState<T, PopupMenuItem<T>>`; its associated functions are the bodies Dart's
875/// `PopupMenuItemState` gives its subclasses.
876pub struct PopupMenuItemState<T: Clone + PartialEq + 'static> {
877    state: StateData<PopupMenuItem<T>>,
878}
879
880impl<T: Clone + PartialEq + 'static> Debug for PopupMenuItemState<T> {
881    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882        f.debug_struct("PopupMenuItemState").finish_non_exhaustive()
883    }
884}
885
886impl<T: Clone + PartialEq + 'static> PopupMenuItemState<T> {
887    /// See [`PopupMenuItemStateLeaf::build_child`].
888    pub fn build_child<S: PopupMenuItemStateLeaf<Widget: PopupMenuItemLeaf<Value = T>>>(
889        this: Handle<S>,
890        app: &mut App,
891        _context: BuildContext,
892    ) -> Option<WidgetRef> {
893        this.widget(app).popup_menu_item_data().child.clone()
894    }
895
896    /// See [`PopupMenuItemStateLeaf::handle_tap`].
897    pub fn handle_tap<S: PopupMenuItemStateLeaf<Widget: PopupMenuItemLeaf<Value = T>>>(
898        this: Handle<S>,
899        app: &mut App,
900    ) {
901        // Need to pop the navigator first in case onTap may push new route onto navigator.
902        let context = this.context(app);
903        let value = this.widget(app).popup_menu_item_data().value.clone();
904        Navigator::pop(
905            app,
906            context,
907            value.map(|value| Rc::new(value) as Rc<dyn Any>),
908        );
909
910        if let Some(on_tap) = this.widget(app).popup_menu_item_data().on_tap.clone() {
911            on_tap.call(app);
912        }
913    }
914
915    /// Dart's `PopupMenuItemState.build`, which a leaf's [`State::build`] runs.
916    pub fn build<S: PopupMenuItemStateLeaf<Widget: PopupMenuItemLeaf<Value = T>>>(
917        this: Handle<S>,
918        app: &mut App,
919        context: BuildContext,
920    ) -> WidgetRef {
921        let theme = Theme::of(app, context);
922        let popup_menu_theme = PopupMenuTheme::of(app, context);
923        let defaults: Box<dyn PopupMenuThemeDataGetters> = if theme.use_material3 {
924            Box::new(PopupMenuDefaultsM3::new(context))
925        } else {
926            Box::new(PopupMenuDefaultsM2::new(context))
927        };
928        let widget_ref = context.widget(app).clone();
929        let widget = waft_widgets::downcast_widget::<S::Widget>(&*widget_ref)
930            .expect("a popup menu item's state builds its item")
931            .popup_menu_item_data();
932        let enabled = widget.enabled;
933        let mut states = WidgetStates::new();
934        if !enabled {
935            states.insert(WidgetState::Disabled);
936        }
937
938        let mut style = if theme.use_material3 {
939            widget
940                .label_text_style
941                .as_ref()
942                .and_then(|label_text_style| label_text_style.resolve(&states))
943                .or_else(|| {
944                    popup_menu_theme
945                        .label_text_style
946                        .as_ref()
947                        .map(|label_text_style| {
948                            label_text_style
949                                .resolve(&states)
950                                .expect("PopupMenuThemeData.labelTextStyle resolves a style")
951                        })
952                })
953                .unwrap_or_else(|| {
954                    defaults
955                        .label_text_style(app)
956                        .as_ref()
957                        .expect("the defaults have a labelTextStyle")
958                        .resolve(&states)
959                        .expect("the defaults' labelTextStyle resolves a style")
960                })
961        } else {
962            widget
963                .text_style
964                .clone()
965                .or_else(|| popup_menu_theme.text_style.clone())
966                .or_else(|| defaults.text_style(app))
967                .expect("the defaults have a textStyle")
968        };
969
970        if !enabled && !theme.use_material3 {
971            style = style.copy_with().color(theme.disabled_color);
972        }
973        let padding: EdgeInsetsGeometry = widget
974            .padding
975            .unwrap_or(if theme.use_material3 {
976                MENU_ITEM_PADDING
977            } else {
978                POPUP_MENU_DEFAULTS_M2_MENU_ITEM_PADDING
979            })
980            .into();
981        let height = widget.height;
982        let mouse_cursor = widget.mouse_cursor.clone();
983
984        let mut align = Align::new().alignment(AlignmentGeometry::CENTER_START);
985        if let Some(child) = this.build_child(app, context) {
986            align = align.child(child);
987        }
988        let mut item = AnimatedDefaultTextStyle::new(
989            ConstrainedBox::new(BoxConstraints::new().min_height(height))
990                .child(Padding::new(padding).child(align)),
991            style.clone(),
992            K_THEME_CHANGE_DURATION,
993        )
994        .into_widget();
995
996        if !enabled {
997            let is_dark = theme.brightness() == Brightness::Dark;
998            item = IconTheme::merge(
999                None,
1000                IconThemeData::new().opacity(if is_dark { 0.5 } else { 0.38 }),
1001                item,
1002            );
1003        }
1004
1005        let mut ink_well = InkWell::new()
1006            .can_request_focus(enabled)
1007            .mouse_cursor(
1008                effective_mouse_cursor(mouse_cursor, popup_menu_theme.mouse_cursor.clone()).into(),
1009            )
1010            .child(
1011                ListTileTheme::merge(item)
1012                    .content_padding(EdgeInsetsGeometry::ZERO)
1013                    .title_text_style(style),
1014            );
1015        if enabled {
1016            ink_well = ink_well.on_tap(Listener::handle_method(this, S::handle_tap));
1017        }
1018        let semantics = this.build_semantics(app, ink_well.into_widget());
1019        MergeSemantics::new().child(semantics).into_widget()
1020    }
1021
1022    /// See [`PopupMenuItemStateLeaf::build_semantics`].
1023    pub fn build_semantics<S: PopupMenuItemStateLeaf<Widget: PopupMenuItemLeaf<Value = T>>>(
1024        this: Handle<S>,
1025        app: &mut App,
1026        child: WidgetRef,
1027    ) -> WidgetRef {
1028        Semantics::new()
1029            .role(SemanticsRole::MenuItem)
1030            .enabled(this.widget(app).popup_menu_item_data().enabled)
1031            .button(true)
1032            .child(child)
1033            .into_widget()
1034    }
1035}
1036
1037impl<T: Clone + PartialEq + 'static> PopupMenuItemStateLeaf for PopupMenuItemState<T> {}
1038
1039impl<T: Clone + PartialEq + 'static> State for PopupMenuItemState<T> {
1040    type Widget = PopupMenuItem<T>;
1041    waft_widgets::state_accessors!();
1042
1043    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1044        PopupMenuItemState::<T>::build(self, app, context)
1045    }
1046}
1047
1048// ---------------------------------------------------------------------------------------------
1049// CheckedPopupMenuItem
1050
1051/// An item with a checkmark in a Material Design popup menu.
1052///
1053/// To show a popup menu, use the [`ShowMenu`] function. To create a button that shows a popup
1054/// menu, consider using [`PopupMenuButton`].
1055///
1056/// A [`CheckedPopupMenuItem`] is [`K_MIN_INTERACTIVE_DIMENSION`] pixels high, which matches
1057/// the default minimum height of a [`PopupMenuItem`]. The horizontal layout uses [`ListTile`];
1058/// the checkmark is an `Icons::done` icon, shown in the `ListTile::leading` position.
1059///
1060/// See also:
1061///
1062///  * [`PopupMenuItem`], a popup menu entry for picking a command (as opposed to toggling a
1063///    value).
1064///  * [`PopupMenuDivider`], a popup menu entry that is just a horizontal line.
1065///  * [`ShowMenu`], a method to dynamically show a popup menu at a given location.
1066///  * [`PopupMenuButton`], an [`IconButton`] that automatically shows a menu when it is tapped.
1067// TODO(framework): Add unit tests to this code snippet.
1068// https://github.com/flutter/flutter/issues/188530
1069pub struct CheckedPopupMenuItem<T: 'static> {
1070    pub popup_menu_item: PopupMenuItemData<T>,
1071
1072    /// Whether to display a checkmark next to the menu item.
1073    ///
1074    /// Defaults to false.
1075    ///
1076    /// When true, an `Icons::done` checkmark is displayed.
1077    ///
1078    /// When this popup menu item is selected, the checkmark will fade in or out as appropriate
1079    /// to represent the implied new state.
1080    pub checked: bool,
1081}
1082
1083impl<T: Clone + PartialEq + 'static> CheckedPopupMenuItem<T> {
1084    /// Creates a popup menu item with a checkmark.
1085    ///
1086    /// By default, the menu item is [`enabled`](PopupMenuItemData::enabled) but unchecked. To
1087    /// mark the item as checked, set [`checked`](Self::checked) to true.
1088    pub fn new() -> CheckedPopupMenuItem<T> {
1089        CheckedPopupMenuItem {
1090            popup_menu_item: PopupMenuItemData::new(None),
1091            checked: false,
1092        }
1093    }
1094
1095    popup_menu_item_setters!(CheckedPopupMenuItem);
1096
1097    /// Dart `CheckedPopupMenuItem(checked:)`.
1098    pub fn checked(mut self, checked: bool) -> CheckedPopupMenuItem<T> {
1099        self.checked = checked;
1100        self
1101    }
1102
1103    /// Dart `CheckedPopupMenuItem(child:)`.
1104    ///
1105    /// The widget below this widget in the tree.
1106    ///
1107    /// Typically a `Text`. An appropriate `DefaultTextStyle` is put in scope for the child. The
1108    /// text should be short enough that it won't wrap.
1109    ///
1110    /// This widget is placed in the `ListTile::title` slot of a [`ListTile`] whose
1111    /// `ListTile::leading` slot is an `Icons::done` icon.
1112    #[cfg_attr(debug_assertions, track_caller)]
1113    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> CheckedPopupMenuItem<T> {
1114        self.popup_menu_item.child = Some(child.into_widget());
1115        self
1116    }
1117}
1118
1119impl<T: Clone + PartialEq + 'static> Default for CheckedPopupMenuItem<T> {
1120    fn default() -> CheckedPopupMenuItem<T> {
1121        CheckedPopupMenuItem::new()
1122    }
1123}
1124
1125impl<T: 'static> Debug for CheckedPopupMenuItem<T> {
1126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1127        f.debug_struct("CheckedPopupMenuItem")
1128            .field("checked", &self.checked)
1129            .field("enabled", &self.popup_menu_item.enabled)
1130            .finish_non_exhaustive()
1131    }
1132}
1133
1134impl<T: Clone + PartialEq + 'static> PopupMenuItemLeaf for CheckedPopupMenuItem<T> {
1135    type Value = T;
1136
1137    fn popup_menu_item_data(&self) -> &PopupMenuItemData<T> {
1138        &self.popup_menu_item
1139    }
1140}
1141
1142impl<T: Clone + PartialEq + 'static> PopupMenuEntry<T> for CheckedPopupMenuItem<T> {
1143    fn height(&self) -> f64 {
1144        self.popup_menu_item.height
1145    }
1146
1147    fn represents(&self, value: Option<&T>) -> bool {
1148        value == self.popup_menu_item.value.as_ref()
1149    }
1150}
1151
1152impl<T: Clone + PartialEq + 'static> StatefulWidget for CheckedPopupMenuItem<T> {
1153    type State = CheckedPopupMenuItemState<T>;
1154
1155    fn key(&self) -> Option<&KeyRef> {
1156        self.popup_menu_item.key.as_ref()
1157    }
1158
1159    fn create_state(&self) -> CheckedPopupMenuItemState<T> {
1160        CheckedPopupMenuItemState {
1161            state: StateData::new(),
1162            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
1163            controller: None,
1164        }
1165    }
1166}
1167
1168/// Dart's `_CheckedPopupMenuItemState`.
1169pub struct CheckedPopupMenuItemState<T: Clone + PartialEq + 'static> {
1170    state: StateData<CheckedPopupMenuItem<T>>,
1171    single_ticker_provider: SingleTickerProviderStateMixinData,
1172    /// Created in `init_state`, because a state is created without the [`App`].
1173    controller: Option<Ref<waft_animation::AnimationController>>,
1174}
1175
1176impl<T: Clone + PartialEq + 'static> CheckedPopupMenuItemState<T> {
1177    const FADE_DURATION: Duration = Duration::from_millis(150);
1178
1179    fn controller(self: Handle<Self>, app: &App) -> Handle<waft_animation::AnimationController> {
1180        app.get(self)
1181            .controller
1182            .handle()
1183            .expect("created in init_state")
1184    }
1185
1186    fn opacity(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
1187        app.get(self)
1188            .controller
1189            .as_ref()
1190            .expect("created in init_state")
1191            .erase()
1192    }
1193
1194    fn animation_changed(self: Handle<Self>, app: &mut App) {
1195        self.set_state(app, |_| {
1196            // animation changed
1197        });
1198    }
1199}
1200
1201impl<T: Clone + PartialEq + 'static> Debug for CheckedPopupMenuItemState<T> {
1202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1203        f.debug_struct("CheckedPopupMenuItemState")
1204            .field("controller", &self.controller)
1205            .finish_non_exhaustive()
1206    }
1207}
1208
1209impl<T: Clone + PartialEq + 'static> SingleTickerProviderStateMixin
1210    for CheckedPopupMenuItemState<T>
1211{
1212    fn single_ticker_provider_data(
1213        self: Handle<Self>,
1214        app: &App,
1215    ) -> &SingleTickerProviderStateMixinData {
1216        &app.get(self).single_ticker_provider
1217    }
1218
1219    fn single_ticker_provider_data_mut(
1220        self: Handle<Self>,
1221        app: &mut App,
1222    ) -> &mut SingleTickerProviderStateMixinData {
1223        &mut app.get_mut(self).single_ticker_provider
1224    }
1225}
1226
1227/// Dart's `vsync: this`.
1228impl<T: Clone + PartialEq + 'static> waft_scheduler::TickerProviderObject
1229    for CheckedPopupMenuItemState<T>
1230{
1231    fn create_ticker(
1232        self: Handle<Self>,
1233        app: &mut App,
1234        on_tick: waft_scheduler::TickerCallback,
1235    ) -> Ref<waft_scheduler::Ticker> {
1236        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1237    }
1238}
1239
1240impl<T: Clone + PartialEq + 'static> PopupMenuItemStateLeaf for CheckedPopupMenuItemState<T> {
1241    fn handle_tap(self: Handle<Self>, app: &mut App) {
1242        // This fades the checkmark in or out when tapped.
1243        let controller = self.controller(app);
1244        if self.widget(app).checked {
1245            controller.reverse(app, None);
1246        } else {
1247            controller.forward(app, None);
1248        }
1249        PopupMenuItemState::<T>::handle_tap(self, app);
1250    }
1251
1252    fn build_semantics(self: Handle<Self>, app: &mut App, child: WidgetRef) -> WidgetRef {
1253        let widget = self.widget(app);
1254        Semantics::new()
1255            .role(SemanticsRole::MenuItemCheckbox)
1256            .enabled(widget.popup_menu_item.enabled)
1257            .checked(widget.checked)
1258            .button(true)
1259            .child(child)
1260            .into_widget()
1261    }
1262
1263    fn build_child(self: Handle<Self>, app: &mut App, context: BuildContext) -> Option<WidgetRef> {
1264        let theme = Theme::of(app, context);
1265        let popup_menu_theme = PopupMenuTheme::of(app, context);
1266        let defaults: Box<dyn PopupMenuThemeDataGetters> = if theme.use_material3 {
1267            Box::new(PopupMenuDefaultsM3::new(context))
1268        } else {
1269            Box::new(PopupMenuDefaultsM2::new(context))
1270        };
1271        let widget_ref = context.widget(app).clone();
1272        let widget = waft_widgets::downcast_widget::<<Self as State>::Widget>(&*widget_ref)
1273            .expect("a checked popup menu item's state builds its item");
1274        let mut states = WidgetStates::new();
1275        if widget.checked {
1276            states.insert(WidgetState::Selected);
1277        }
1278        let effective_label_text_style = widget
1279            .popup_menu_item
1280            .label_text_style
1281            .clone()
1282            .or(popup_menu_theme.label_text_style)
1283            .or_else(|| defaults.label_text_style(app));
1284        let enabled = widget.popup_menu_item.enabled;
1285        let title = widget.popup_menu_item.child.clone();
1286        let controller = self.controller(app);
1287        let icon = if controller.status(app).is_dismissed() {
1288            None
1289        } else {
1290            Some(Icons::done())
1291        };
1292        let mut list_tile = ListTile::new()
1293            .enabled(enabled)
1294            .leading(FadeTransition::new(self.opacity(app)).child(Icon::new(icon)));
1295        if let Some(title_text_style) = effective_label_text_style
1296            .as_ref()
1297            .and_then(|label_text_style| label_text_style.resolve(&states))
1298        {
1299            list_tile = list_tile.title_text_style(title_text_style);
1300        }
1301        if let Some(title) = title {
1302            list_tile = list_tile.title(title);
1303        }
1304        Some(
1305            IgnorePointer::new()
1306                .child(ListTileTheme::merge(list_tile).content_padding(EdgeInsetsGeometry::ZERO))
1307                .into_widget(),
1308        )
1309    }
1310}
1311
1312impl<T: Clone + PartialEq + 'static> State for CheckedPopupMenuItemState<T> {
1313    type Widget = CheckedPopupMenuItem<T>;
1314    waft_widgets::state_accessors!();
1315
1316    fn init_state(self: Handle<Self>, app: &mut App) {
1317        let controller = waft_animation::AnimationController::new(
1318            app,
1319            None,
1320            Some(Self::FADE_DURATION),
1321            None,
1322            0.0,
1323            1.0,
1324            waft_animation::AnimationBehavior::Normal,
1325            self,
1326        );
1327        app.get_mut(self).controller = Some(controller.clone());
1328        let value = if self.widget(app).checked { 1.0 } else { 0.0 };
1329        controller.set_value(app, value);
1330        controller.add_listener(app, Listener::handle_method(self, Self::animation_changed));
1331    }
1332
1333    fn activate(self: Handle<Self>, app: &mut App) {
1334        SingleTickerProviderStateMixin::activate(self, app);
1335    }
1336
1337    fn dispose(self: Handle<Self>, app: &mut App) {
1338        let controller = self.controller(app);
1339        controller.dispose(app);
1340        SingleTickerProviderStateMixin::dispose(self, app);
1341    }
1342
1343    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1344        PopupMenuItemState::<T>::build(self, app, context)
1345    }
1346}
1347
1348/// Dart's `_EffectiveMouseCursor`: a [`WidgetStateMouseCursor`] passed along to the menu
1349/// item's `InkWell`, which resolves the property against [`WidgetState::Disabled`],
1350/// [`WidgetState::Hovered`] and [`WidgetState::Focused`].
1351fn effective_mouse_cursor(
1352    widget_cursor: Option<MouseCursorRef>,
1353    theme_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
1354) -> WidgetStateMouseCursor {
1355    WidgetStateMouseCursor::resolve_with(
1356        move |states| {
1357            <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&widget_cursor, states)
1358                .or_else(|| {
1359                    theme_cursor
1360                        .as_ref()
1361                        .and_then(|theme_cursor| theme_cursor.resolve(states))
1362                })
1363                .unwrap_or_else(|| WidgetStateMouseCursor::adaptive_clickable().resolve(states))
1364        },
1365        Some("WidgetStateMouseCursor(PopupMenuItemState)"),
1366    )
1367}
1368
1369/// Hand coded defaults based on Material Design 2.
1370///
1371/// Dart's `_PopupMenuDefaultsM2`.
1372struct PopupMenuDefaultsM2 {
1373    /// Dart's `super(..)` arguments.
1374    popup_menu_theme_data: PopupMenuThemeData,
1375    context: DefaultsContext,
1376}
1377
1378impl PopupMenuDefaultsM2 {
1379    fn new(context: BuildContext) -> PopupMenuDefaultsM2 {
1380        PopupMenuDefaultsM2 {
1381            popup_menu_theme_data: PopupMenuThemeData::new().elevation(8.0),
1382            context: DefaultsContext::new(context),
1383        }
1384    }
1385}
1386
1387impl PopupMenuThemeDataGetters for PopupMenuDefaultsM2 {
1388    fn popup_menu_theme_data(&self) -> &PopupMenuThemeData {
1389        &self.popup_menu_theme_data
1390    }
1391
1392    fn text_style(&self, app: &mut App) -> Option<TextStyle> {
1393        self.context.text_theme(app).title_medium.clone()
1394    }
1395
1396    fn menu_padding(&self, _app: &mut App) -> Option<EdgeInsetsGeometry> {
1397        Some(EdgeInsetsGeometry::symmetric(8.0, 0.0))
1398    }
1399}
1400
1401/// Dart's `_PopupMenuDefaultsM2.menuItemPadding`.
1402const POPUP_MENU_DEFAULTS_M2_MENU_ITEM_PADDING: EdgeInsets = EdgeInsets::symmetric(0.0, 16.0);
1403
1404// ---------------------------------------------------------------------------------------------
1405// _PopupMenu
1406
1407/// Dart's `_PopupMenu<T>`.
1408struct PopupMenu<T: Clone + PartialEq + 'static> {
1409    item_keys: Vec<GlobalKey>,
1410    route: Handle<PopupMenuRoute<T>>,
1411    semantic_label: Option<String>,
1412    constraints: Option<BoxConstraints>,
1413    clip_behavior: Clip,
1414}
1415
1416impl<T: Clone + PartialEq + 'static> Debug for PopupMenu<T> {
1417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1418        f.debug_struct("PopupMenu")
1419            .field("semantic_label", &self.semantic_label)
1420            .field("constraints", &self.constraints)
1421            .field("clip_behavior", &self.clip_behavior)
1422            .finish_non_exhaustive()
1423    }
1424}
1425
1426impl<T: Clone + PartialEq + 'static> StatefulWidget for PopupMenu<T> {
1427    type State = PopupMenuState<T>;
1428
1429    fn create_state(&self) -> PopupMenuState<T> {
1430        PopupMenuState {
1431            state: StateData::new(),
1432            opacities: Vec::new(),
1433        }
1434    }
1435}
1436
1437/// Dart's `_PopupMenuState<T>`.
1438struct PopupMenuState<T: Clone + PartialEq + 'static> {
1439    state: StateData<PopupMenu<T>>,
1440    opacities: Vec<Ref<CurvedAnimation>>,
1441}
1442
1443impl<T: Clone + PartialEq + 'static> Debug for PopupMenuState<T> {
1444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1445        f.debug_struct("PopupMenuState")
1446            .field("opacities", &self.opacities.len())
1447            .finish_non_exhaustive()
1448    }
1449}
1450
1451impl<T: Clone + PartialEq + 'static> PopupMenuState<T> {
1452    fn route_animation(app: &App, route: Handle<PopupMenuRoute<T>>) -> AnimationRef<f64> {
1453        ModalRoute::animation(route, app)
1454            .expect("an installed route has an animation")
1455            .keep(app)
1456    }
1457
1458    fn set_opacities(self: Handle<Self>, app: &mut App) {
1459        for opacity in std::mem::take(&mut app.get_mut(self).opacities) {
1460            opacity.dispose(app);
1461        }
1462        let route = self.widget(app).route;
1463        let count = app.get(route).items.len();
1464        let animation = Self::route_animation(app, route);
1465        let mut new_opacities = Vec::new();
1466        // 1.0 for the width and 0.5 for the last item's fade.
1467        let unit = 1.0 / (count as f64 + 1.5);
1468        for i in 0..count {
1469            let start = (i as f64 + 1.0) * unit;
1470            let end = (start + 1.5 * unit).clamp(0.0, 1.0);
1471            let opacity = CurvedAnimation::new(
1472                app,
1473                animation.clone(),
1474                Rc::new(Interval::new(start, end, Curves::linear())),
1475                None,
1476            );
1477            new_opacities.push(opacity);
1478        }
1479        app.get_mut(self).opacities = new_opacities;
1480    }
1481}
1482
1483impl<T: Clone + PartialEq + 'static> State for PopupMenuState<T> {
1484    type Widget = PopupMenu<T>;
1485    waft_widgets::state_accessors!();
1486
1487    fn init_state(self: Handle<Self>, app: &mut App) {
1488        self.set_opacities(app);
1489    }
1490
1491    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &PopupMenu<T>) {
1492        let route = self.widget(app).route;
1493        if app.get(old_widget.route).items.len() != app.get(route).items.len()
1494            || ModalRoute::animation(old_widget.route, app) != ModalRoute::animation(route, app)
1495        {
1496            self.set_opacities(app);
1497        }
1498    }
1499
1500    fn dispose(self: Handle<Self>, app: &mut App) {
1501        for opacity in std::mem::take(&mut app.get_mut(self).opacities) {
1502            opacity.dispose(app);
1503        }
1504    }
1505
1506    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1507        let route = self.widget(app).route;
1508        let count = app.get(route).items.len();
1509        // 1.0 for the width and 0.5 for the last item's fade.
1510        let unit = 1.0 / (count as f64 + 1.5);
1511        let mut children = Vec::new();
1512        let theme = Theme::of(app, context);
1513        let popup_menu_theme = PopupMenuTheme::of(app, context);
1514        let defaults: Box<dyn PopupMenuThemeDataGetters> = if theme.use_material3 {
1515            Box::new(PopupMenuDefaultsM3::new(context))
1516        } else {
1517            Box::new(PopupMenuDefaultsM2::new(context))
1518        };
1519
1520        for i in 0..count {
1521            let opacity = app.get(self).opacities[i].erase();
1522            let menu_route = app.get(route);
1523            let mut item = menu_route.items[i].widget().clone();
1524            if let Some(initial_value) = &menu_route.initial_value
1525                && menu_route.items[i].represents(Some(initial_value))
1526            {
1527                item = ColoredBox::new(Theme::of(app, context).highlight_color)
1528                    .child(item)
1529                    .into_widget();
1530            }
1531            let item_sizes = Rc::clone(&app.get(route).item_sizes);
1532            let item_key: KeyRef = self.widget(app).item_keys[i].clone().into();
1533            children.push(
1534                MenuItem {
1535                    on_layout: OnLayout(Rc::new(move |_app, size| {
1536                        item_sizes.borrow_mut()[i] = Some(size);
1537                    })),
1538                    child: Some(
1539                        FadeTransition::new(opacity)
1540                            .key(item_key)
1541                            .child(item)
1542                            .into_widget(),
1543                    ),
1544                }
1545                .into_widget(),
1546            );
1547        }
1548
1549        let animation = PopupMenuState::<T>::route_animation(app, route);
1550        let opacity = CurveTween::new(
1551            app,
1552            Rc::new(Interval::new(0.0, 1.0 / 3.0, Curves::linear())),
1553        );
1554        let width = CurveTween::new(app, Rc::new(Interval::new(0.0, unit, Curves::linear())));
1555        let height = CurveTween::new(
1556            app,
1557            Rc::new(Interval::new(0.0, unit * count as f64, Curves::linear())),
1558        );
1559
1560        let widget = self.widget(app);
1561        let (semantic_label, constraints, clip_behavior) = (
1562            widget.semantic_label.clone(),
1563            widget.constraints,
1564            widget.clip_behavior,
1565        );
1566        let menu_route = app.get(route);
1567        let (menu_padding, route_shape, route_color, route_elevation) = (
1568            menu_route.menu_padding,
1569            menu_route.shape.clone(),
1570            menu_route.color,
1571            menu_route.elevation,
1572        );
1573        let (route_shadow_color, route_surface_tint_color) =
1574            (menu_route.shadow_color, menu_route.surface_tint_color);
1575        let mut scroll_view =
1576            SingleChildScrollView::new().child(ListBody::new().children(children));
1577        if let Some(padding) = menu_padding
1578            .or(popup_menu_theme.menu_padding)
1579            .or_else(|| defaults.menu_padding(app))
1580        {
1581            scroll_view = scroll_view.padding(padding);
1582        }
1583        let mut semantics = Semantics::new()
1584            .role(SemanticsRole::Menu)
1585            .scopes_route(true)
1586            .names_route(true)
1587            .explicit_child_nodes(true);
1588        if let Some(semantic_label) = semantic_label {
1589            semantics = semantics.label(semantic_label);
1590        }
1591        let child = ConstrainedBox::new(
1592            constraints.unwrap_or(
1593                BoxConstraints::new()
1594                    .min_width(K_MENU_MIN_WIDTH)
1595                    .max_width(K_MENU_MAX_WIDTH),
1596            ),
1597        )
1598        .child(
1599            IntrinsicWidth::new()
1600                .step_width(K_MENU_WIDTH_STEP)
1601                .child(semantics.child(scroll_view)),
1602        )
1603        .into_widget();
1604
1605        let shape = route_shape
1606            .or(popup_menu_theme.shape)
1607            .or_else(|| defaults.shape(app));
1608        let color = route_color
1609            .or(popup_menu_theme.color)
1610            .or_else(|| defaults.color(app));
1611        let elevation = route_elevation
1612            .or(popup_menu_theme.elevation)
1613            .or_else(|| defaults.elevation(app))
1614            .expect("the defaults have an elevation");
1615        let shadow_color = route_shadow_color
1616            .or(popup_menu_theme.shadow_color)
1617            .or_else(|| defaults.shadow_color(app));
1618        let surface_tint_color = route_surface_tint_color
1619            .or(popup_menu_theme.surface_tint_color)
1620            .or_else(|| defaults.surface_tint_color(app));
1621        let opacity = opacity.animate(app, animation.clone());
1622        let animated = animation.clone();
1623        let animation = animation.handle();
1624
1625        AnimatedBuilder::new(Rc::new(animated), move |app, _context, child| {
1626            let mut material = Material::new()
1627                .clip_behavior(clip_behavior)
1628                .r#type(MaterialType::Card)
1629                .elevation(elevation);
1630            if let Some(shape) = &shape {
1631                material = material.shape(shape.clone());
1632            }
1633            if let Some(color) = color {
1634                material = material.color(color);
1635            }
1636            if let Some(shadow_color) = shadow_color {
1637                material = material.shadow_color(shadow_color);
1638            }
1639            if let Some(surface_tint_color) = surface_tint_color {
1640                material = material.surface_tint_color(surface_tint_color);
1641            }
1642            let mut align = Align::new()
1643                .alignment(AlignmentGeometry::TOP_END)
1644                .width_factor(width.evaluate(app, animation))
1645                .height_factor(height.evaluate(app, animation));
1646            if let Some(child) = child {
1647                align = align.child(child.clone());
1648            }
1649            FadeTransition::new(opacity.clone())
1650                .child(material.child(align))
1651                .into_widget()
1652        })
1653        .child(child)
1654        .into_widget()
1655    }
1656}
1657
1658// ---------------------------------------------------------------------------------------------
1659// _PopupMenuRouteLayout
1660
1661/// Positioning of the menu on the screen; Dart's `_PopupMenuRouteLayout`.
1662struct PopupMenuRouteLayout {
1663    /// Rectangle of underlying button, relative to the overlay's dimensions.
1664    position: RelativeRect,
1665
1666    /// The sizes of each item are computed when the menu is laid out, and before the route is
1667    /// laid out. The route's own list: Dart hands the delegate the route's `itemSizes`.
1668    item_sizes: Rc<RefCell<Vec<Option<Size>>>>,
1669
1670    /// The index of the selected item, or `None` if `PopupMenuButton::initial_value` was not
1671    /// specified.
1672    selected_item_index: Option<usize>,
1673
1674    /// Whether to prefer going to the left or to the right.
1675    text_direction: TextDirection,
1676
1677    /// The padding of unsafe area.
1678    padding: EdgeInsets,
1679}
1680
1681impl Debug for PopupMenuRouteLayout {
1682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1683        f.debug_struct("PopupMenuRouteLayout")
1684            .field("selected_item_index", &self.selected_item_index)
1685            .field("text_direction", &self.text_direction)
1686            .field("padding", &self.padding)
1687            .finish_non_exhaustive()
1688    }
1689}
1690
1691impl PopupMenuRouteLayout {
1692    fn closest_screen(screens: &[Rect], point: Offset) -> Rect {
1693        let mut closest = screens[0];
1694        for screen in screens {
1695            if (screen.center() - point).distance() < (closest.center() - point).distance() {
1696                closest = *screen;
1697            }
1698        }
1699        closest
1700    }
1701
1702    fn fit_inside_screen(&self, screen: Rect, child_size: Size, wanted_position: Offset) -> Offset {
1703        let padding = self.padding;
1704        let mut x = wanted_position.dx();
1705        let mut y = wanted_position.dy();
1706        // Avoid going outside an area defined as the rectangle 8.0 pixels from the
1707        // edge of the screen in every direction.
1708        if x < screen.left + K_MENU_SCREEN_PADDING + padding.left {
1709            x = screen.left + K_MENU_SCREEN_PADDING + padding.left;
1710        } else if x + child_size.width() > screen.right - K_MENU_SCREEN_PADDING - padding.right {
1711            x = screen.right - child_size.width() - K_MENU_SCREEN_PADDING - padding.right;
1712        }
1713        if y < screen.top + K_MENU_SCREEN_PADDING + padding.top {
1714            y = K_MENU_SCREEN_PADDING + padding.top;
1715        } else if y + child_size.height() > screen.bottom - K_MENU_SCREEN_PADDING - padding.bottom {
1716            y = screen.bottom - child_size.height() - K_MENU_SCREEN_PADDING - padding.bottom;
1717        }
1718
1719        Offset::new(x, y)
1720    }
1721}
1722
1723// We put the child wherever position specifies, so long as it will fit within
1724// the specified parent size padded (inset) by 8. If necessary, we adjust the
1725// child's position so that it fits.
1726impl SingleChildLayoutDelegate for PopupMenuRouteLayout {
1727    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
1728        // The menu can be at most the size of the overlay minus 8.0 pixels in each
1729        // direction.
1730        BoxConstraints::loose(constraints.biggest())
1731            .deflate((EdgeInsets::all(K_MENU_SCREEN_PADDING) + self.padding).into())
1732    }
1733
1734    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
1735        let position = self.position;
1736        let y = position.top;
1737
1738        // Find the ideal horizontal position.
1739        // size: The size of the overlay.
1740        // childSize: The size of the menu, when fully open, as determined by
1741        // getConstraintsForChild.
1742        let x = if position.left > position.right {
1743            // Menu button is closer to the right edge, so grow to the left, aligned to the right edge.
1744            size.width() - position.right - child_size.width()
1745        } else if position.left < position.right {
1746            // Menu button is closer to the left edge, so grow to the right, aligned to the left edge.
1747            position.left
1748        } else {
1749            // Menu button is equidistant from both edges, so grow in reading direction.
1750            match self.text_direction {
1751                TextDirection::Rtl => size.width() - position.right - child_size.width(),
1752                TextDirection::Ltr => position.left,
1753            }
1754        };
1755        let wanted_position = Offset::new(x, y);
1756        let origin_center = position.to_rect(Offset::ZERO & size).center();
1757        let sub_screens = [Offset::ZERO & size];
1758        let sub_screen = Self::closest_screen(&sub_screens, origin_center);
1759        self.fit_inside_screen(sub_screen, child_size, wanted_position)
1760    }
1761
1762    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
1763        let Some(old_delegate) = old_delegate.as_any().downcast_ref::<PopupMenuRouteLayout>()
1764        else {
1765            return true;
1766        };
1767        // If called when the old and new itemSizes have been initialized then
1768        // we expect them to have the same length because there's no practical
1769        // way to change length of the items list once the menu has been shown.
1770        debug_assert_eq!(
1771            self.item_sizes.borrow().len(),
1772            old_delegate.item_sizes.borrow().len()
1773        );
1774
1775        self.position != old_delegate.position
1776            || self.selected_item_index != old_delegate.selected_item_index
1777            || self.text_direction != old_delegate.text_direction
1778            || *self.item_sizes.borrow() != *old_delegate.item_sizes.borrow()
1779            || self.padding != old_delegate.padding
1780    }
1781
1782    fn as_any(&self) -> &dyn Any {
1783        self
1784    }
1785}
1786
1787// ---------------------------------------------------------------------------------------------
1788// _PopupMenuRoute
1789
1790/// Dart's `_PopupMenuRoute<T>`.
1791struct PopupMenuRoute<T: Clone + PartialEq + 'static> {
1792    route: RouteData,
1793    overlay_route: OverlayRouteData,
1794    transition_route: TransitionRouteData,
1795    local_history: LocalHistoryRouteData,
1796    modal_route: ModalRouteData,
1797    position: Option<RelativeRect>,
1798    position_builder: Option<PopupMenuPositionBuilder>,
1799    items: Vec<PopupMenuEntryRef<T>>,
1800    item_keys: Vec<GlobalKey>,
1801    item_sizes: Rc<RefCell<Vec<Option<Size>>>>,
1802    initial_value: Option<T>,
1803    elevation: Option<f64>,
1804    surface_tint_color: Option<Color>,
1805    shadow_color: Option<Color>,
1806    semantic_label: Option<String>,
1807    shape: Option<ShapeBorderRef>,
1808    menu_padding: Option<EdgeInsetsGeometry>,
1809    color: Option<Color>,
1810    captured_themes: Rc<CapturedThemes>,
1811    constraints: Option<BoxConstraints>,
1812    clip_behavior: Clip,
1813    pop_up_animation_style: Option<AnimationStyle>,
1814    barrier_label: String,
1815    animation: Option<Ref<CurvedAnimation>>,
1816}
1817
1818/// The arguments of Dart's `_PopupMenuRoute` constructor.
1819struct PopupMenuRouteArguments<T: 'static> {
1820    position: Option<RelativeRect>,
1821    position_builder: Option<PopupMenuPositionBuilder>,
1822    items: Vec<PopupMenuEntryRef<T>>,
1823    item_keys: Vec<GlobalKey>,
1824    initial_value: Option<T>,
1825    elevation: Option<f64>,
1826    surface_tint_color: Option<Color>,
1827    shadow_color: Option<Color>,
1828    barrier_label: String,
1829    semantic_label: Option<String>,
1830    shape: Option<ShapeBorderRef>,
1831    menu_padding: Option<EdgeInsetsGeometry>,
1832    color: Option<Color>,
1833    captured_themes: CapturedThemes,
1834    constraints: Option<BoxConstraints>,
1835    clip_behavior: Clip,
1836    settings: Option<RouteSettingsRef>,
1837    request_focus: Option<bool>,
1838    pop_up_animation_style: Option<AnimationStyle>,
1839}
1840
1841impl<T: Clone + PartialEq + 'static> PopupMenuRoute<T> {
1842    fn new(app: &mut App, arguments: PopupMenuRouteArguments<T>) -> Ref<PopupMenuRoute<T>> {
1843        debug_assert!(
1844            arguments.position.is_some() != arguments.position_builder.is_some(),
1845            "Either position or positionBuilder must be provided."
1846        );
1847        let route = RouteData::new(app, arguments.settings, arguments.request_focus);
1848        let transition_route = TransitionRouteData::new(app);
1849        let mut modal_route = ModalRouteData::new(app);
1850        // Menus always cycle focus through their items irrespective of the
1851        // focus traversal edge behavior set in the Navigator.
1852        modal_route.traversal_edge_behavior = Some(TraversalEdgeBehavior::ClosedLoop);
1853        let item_count = arguments.items.len();
1854        app.create(PopupMenuRoute {
1855            route,
1856            overlay_route: OverlayRouteData::new(),
1857            transition_route,
1858            local_history: LocalHistoryRouteData::new(),
1859            modal_route,
1860            position: arguments.position,
1861            position_builder: arguments.position_builder,
1862            items: arguments.items,
1863            item_keys: arguments.item_keys,
1864            item_sizes: Rc::new(RefCell::new(vec![None; item_count])),
1865            initial_value: arguments.initial_value,
1866            elevation: arguments.elevation,
1867            surface_tint_color: arguments.surface_tint_color,
1868            shadow_color: arguments.shadow_color,
1869            semantic_label: arguments.semantic_label,
1870            shape: arguments.shape,
1871            menu_padding: arguments.menu_padding,
1872            color: arguments.color,
1873            captured_themes: Rc::new(arguments.captured_themes),
1874            constraints: arguments.constraints,
1875            clip_behavior: arguments.clip_behavior,
1876            pop_up_animation_style: arguments.pop_up_animation_style,
1877            barrier_label: arguments.barrier_label,
1878            animation: None,
1879        })
1880    }
1881
1882    fn scroll_to(self: Handle<Self>, app: &mut App, selected_item_index: usize) {
1883        let item_key = app.get(self).item_keys[selected_item_index].clone();
1884        SchedulerBinding::add_post_frame_callback(
1885            app,
1886            FrameCallback::new(move |app, _duration| {
1887                if let Some(context) = item_key.current_context(app) {
1888                    drop(Scrollable::ensure_visible(
1889                        app,
1890                        context,
1891                        0.0,
1892                        Duration::ZERO,
1893                        Curves::ease(),
1894                        ScrollPositionAlignmentPolicy::Explicit,
1895                    ));
1896                }
1897            }),
1898            None,
1899        );
1900    }
1901}
1902
1903// Dart's `_PopupMenuRoute.dispose` disposes its curved animation and runs `super.dispose()`,
1904// so this impl writes out `modal_route_overrides!` with that `dispose`.
1905impl<T: Clone + PartialEq + 'static> Route for PopupMenuRoute<T> {
1906    waft_widgets::route_accessors!();
1907
1908    fn as_transition_route(self: Handle<Self>) -> Option<waft_widgets::AnyTransitionRoute> {
1909        Some(TransitionRoute::as_transition_route(self))
1910    }
1911
1912    fn as_modal_route(self: Handle<Self>) -> Option<waft_widgets::AnyModalRoute> {
1913        Some(ModalRoute::as_modal_route(self))
1914    }
1915
1916    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<waft_widgets::OverlayEntry>> {
1917        OverlayRoute::overlay_entries(self, app)
1918    }
1919
1920    fn install(self: Handle<Self>, app: &mut App) {
1921        ModalRoute::install(self, app)
1922    }
1923
1924    fn did_push(self: Handle<Self>, app: &mut App) -> waft_scheduler::TickerFuture {
1925        ModalRoute::did_push(self, app)
1926    }
1927
1928    fn did_add(self: Handle<Self>, app: &mut App) {
1929        ModalRoute::did_add(self, app)
1930    }
1931
1932    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<waft_widgets::AnyRoute>) {
1933        TransitionRoute::did_replace(self, app, old_route)
1934    }
1935
1936    fn will_pop(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
1937        LocalHistoryRoute::will_pop(self, app)
1938    }
1939
1940    fn pop_disposition(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
1941        ModalRoute::pop_disposition(self, app)
1942    }
1943
1944    fn on_pop_invoked_with_result(
1945        self: Handle<Self>,
1946        app: &mut App,
1947        did_pop: bool,
1948        result: RouteResult,
1949    ) {
1950        ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
1951    }
1952
1953    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
1954        LocalHistoryRoute::will_handle_pop_internally(self, app)
1955    }
1956
1957    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
1958        LocalHistoryRoute::did_pop(self, app, result)
1959    }
1960
1961    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: waft_widgets::AnyRoute) {
1962        ModalRoute::did_pop_next(self, app, next_route)
1963    }
1964
1965    fn did_change_next(
1966        self: Handle<Self>,
1967        app: &mut App,
1968        next_route: Option<waft_widgets::AnyRoute>,
1969    ) {
1970        ModalRoute::did_change_next(self, app, next_route)
1971    }
1972
1973    fn did_change_previous(
1974        self: Handle<Self>,
1975        app: &mut App,
1976        previous_route: Option<waft_widgets::AnyRoute>,
1977    ) {
1978        ModalRoute::did_change_previous(self, app, previous_route)
1979    }
1980
1981    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
1982        ModalRoute::changed_internal_state(self, app)
1983    }
1984
1985    fn changed_external_state(self: Handle<Self>, app: &mut App) {
1986        ModalRoute::changed_external_state(self, app)
1987    }
1988
1989    fn dispose(self: Handle<Self>, app: &mut App) {
1990        if let Some(animation) = app.get(self).animation.handle() {
1991            animation.dispose(app);
1992        }
1993        TransitionRoute::dispose(self, app)
1994    }
1995}
1996
1997impl<T: Clone + PartialEq + 'static> OverlayRoute for PopupMenuRoute<T> {
1998    waft_widgets::modal_overlay_route_overrides!();
1999}
2000
2001impl<T: Clone + PartialEq + 'static> PredictiveBackRoute for PopupMenuRoute<T> {
2002    waft_widgets::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
2003}
2004
2005impl<T: Clone + PartialEq + 'static> TransitionRoute for PopupMenuRoute<T> {
2006    waft_widgets::modal_transition_route_overrides!();
2007
2008    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
2009        app.get(self)
2010            .pop_up_animation_style
2011            .as_ref()
2012            .and_then(|style| style.duration)
2013            .unwrap_or(K_MENU_DURATION)
2014    }
2015
2016    fn opaque(self: Handle<Self>, app: &App) -> bool {
2017        PopupRoute::opaque(self, app)
2018    }
2019
2020    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
2021        PopupRoute::allow_snapshotting(self, app)
2022    }
2023
2024    fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
2025        let style = app.get(self).pop_up_animation_style.clone();
2026        if style.as_ref() != Some(&AnimationStyle::NO_ANIMATION) {
2027            if let Some(animation) = app.get(self).animation.as_ref() {
2028                return animation.erase();
2029            }
2030            let parent = TransitionRouteBase::create_animation(self, app);
2031            let curve = style
2032                .as_ref()
2033                .and_then(|style| style.curve.clone())
2034                .unwrap_or_else(Curves::linear);
2035            let reverse_curve = style
2036                .as_ref()
2037                .and_then(|style| style.reverse_curve.clone())
2038                .unwrap_or_else(|| {
2039                    Rc::new(Interval::new(
2040                        0.0,
2041                        K_MENU_CLOSE_INTERVAL_END,
2042                        Curves::linear(),
2043                    ))
2044                });
2045            let animation = CurvedAnimation::new(app, parent, curve, Some(reverse_curve));
2046            app.get_mut(self).animation = Some(animation.clone());
2047            return animation.into_erased();
2048        }
2049        TransitionRouteBase::create_animation(self, app)
2050    }
2051}
2052
2053impl<T: Clone + PartialEq + 'static> LocalHistoryRoute for PopupMenuRoute<T> {
2054    waft_widgets::local_history_route_accessors!();
2055}
2056
2057impl<T: Clone + PartialEq + 'static> ModalRoute for PopupMenuRoute<T> {
2058    waft_widgets::modal_route_accessors!();
2059
2060    fn barrier_dismissible(self: Handle<Self>, _app: &App) -> bool {
2061        true
2062    }
2063
2064    fn barrier_color(self: Handle<Self>, _app: &App) -> Option<Color> {
2065        None
2066    }
2067
2068    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
2069        Some(app.get(self).barrier_label.clone())
2070    }
2071
2072    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
2073        PopupRoute::maintain_state(self, app)
2074    }
2075
2076    fn build_page(
2077        self: Handle<Self>,
2078        app: &mut App,
2079        context: BuildContext,
2080        animation: AnimationRef<f64>,
2081        secondary_animation: AnimationRef<f64>,
2082    ) -> WidgetRef {
2083        let _ = (animation, secondary_animation);
2084        let mut selected_item_index = None;
2085        let route = app.get(self);
2086        if let Some(initial_value) = &route.initial_value {
2087            let mut index = 0;
2088            while selected_item_index.is_none() && index < route.items.len() {
2089                if route.items[index].represents(Some(initial_value)) {
2090                    selected_item_index = Some(index);
2091                }
2092                index += 1;
2093            }
2094        }
2095        if let Some(selected_item_index) = selected_item_index {
2096            self.scroll_to(app, selected_item_index);
2097        }
2098
2099        let route = app.get(self);
2100        let menu = PopupMenu {
2101            route: self,
2102            item_keys: route.item_keys.clone(),
2103            semantic_label: route.semantic_label.clone(),
2104            constraints: route.constraints,
2105            clip_behavior: route.clip_behavior,
2106        }
2107        .into_widget();
2108        let position_builder = route.position_builder.clone();
2109        let position = route.position;
2110        let item_sizes = Rc::clone(&route.item_sizes);
2111        let captured_themes = Rc::clone(&route.captured_themes);
2112        let media_query = MediaQuery::of(app, context);
2113        let padding = media_query.padding;
2114        MediaQuery::remove_padding(
2115            app,
2116            context,
2117            true,
2118            true,
2119            true,
2120            true,
2121            LayoutBuilder::new(move |app, context, constraints| {
2122                let position = match &position_builder {
2123                    Some(position_builder) => {
2124                        position_builder(app, context, constraints.constraints())
2125                    }
2126                    None => position.expect("Either position or positionBuilder"),
2127                };
2128                CustomSingleChildLayout::new(Rc::new(PopupMenuRouteLayout {
2129                    position,
2130                    item_sizes: Rc::clone(&item_sizes),
2131                    selected_item_index,
2132                    text_direction: Directionality::of(app, context),
2133                    padding,
2134                }))
2135                .child(captured_themes.wrap(menu.clone()))
2136                .into_widget()
2137            })
2138            .into_widget(),
2139        )
2140        .into_widget()
2141    }
2142}
2143
2144impl<T: Clone + PartialEq + 'static> PopupRoute for PopupMenuRoute<T> {}
2145
2146/// A callback that returns a [`RelativeRect`] that describes the position of the popup menu.
2147///
2148/// The `constraints` argument describes the constraints of the menu's overlay, as a
2149/// `LayoutBuilder`'s builder receives them.
2150pub type PopupMenuPositionBuilder =
2151    Rc<dyn Fn(&mut App, BuildContext, BoxConstraints) -> RelativeRect>;
2152
2153/// Show a popup menu that contains the `items` at `position`.
2154///
2155/// The `items` parameter must not be empty.
2156///
2157/// Only one of `position` or `position_builder` should be provided. Providing both throws an
2158/// assertion error. The `position_builder` is called whenever the menu's overlay is laid out,
2159/// with the overlay's constraints, and it should return the position of the menu.
2160///
2161/// If `initial_value` is specified then the first item with a matching value will be
2162/// highlighted and the value of `position` gives the rectangle whose vertical center will be
2163/// aligned with the vertical center of the highlighted item (when possible).
2164///
2165/// If `initial_value` is not specified then the top of the menu will be aligned with the top
2166/// of the `position` rectangle.
2167///
2168/// In both cases, the menu position will be adjusted if necessary to fit on the screen.
2169///
2170/// Horizontally, the menu is positioned so that it grows in the direction that has the most
2171/// room. For example, if the `position` describes a rectangle on the left edge of the screen,
2172/// then the left edge of the menu is aligned with the left edge of the `position`, and the
2173/// menu grows to the right. If both edges of the `position` are equidistant from the opposite
2174/// edge of the screen, then the ambient `Directionality` is used as a tie-breaker, preferring
2175/// to grow in the reading direction.
2176///
2177/// The positioning of the `initial_value` at the `position` is implemented by iterating over
2178/// the `items` to find the first whose [`PopupMenuEntry::represents`] method returns true for
2179/// `initial_value`, and then summing the values of [`PopupMenuEntry::height`] for all the
2180/// preceding widgets in the list.
2181///
2182/// The `elevation` argument specifies the z-coordinate at which to place the menu. The
2183/// elevation defaults to 8, the appropriate elevation for popup menus.
2184///
2185/// The `context` argument is used to look up the [`Navigator`] and [`Theme`] for the menu. It
2186/// is only used when the method is called. Its corresponding widget can be safely removed from
2187/// the tree before the popup menu is closed.
2188///
2189/// The `use_root_navigator` argument is used to determine whether to push the menu to the
2190/// [`Navigator`] furthest from or nearest to the given `context`. It is `false` by default.
2191///
2192/// The `semantic_label` argument is used by accessibility frameworks to announce screen
2193/// transitions when the menu is opened and closed. If this label is not provided, it will
2194/// default to `MaterialLocalizations::popup_menu_label`.
2195///
2196/// The `clip_behavior` argument is used to clip the shape of the menu. Defaults to
2197/// [`Clip::None`].
2198///
2199/// The `request_focus` argument specifies whether the menu should request focus when it
2200/// appears. If it is `None`, `Navigator::request_focus` is used instead.
2201///
2202/// The future resolves to the item's value the menu was popped with, erased as a route's
2203/// result is, or `None` if the menu was dismissed.
2204///
2205/// See also:
2206///
2207///  * [`PopupMenuItem`], a popup menu entry for a single value.
2208///  * [`PopupMenuDivider`], a popup menu entry that is just a horizontal line.
2209///  * [`CheckedPopupMenuItem`], a popup menu item with a checkmark.
2210///  * [`PopupMenuButton`], which provides an [`IconButton`] that shows a menu by calling this
2211///    method automatically.
2212///  * `SemanticsConfiguration::names_route`, for a description of edge triggered semantics.
2213pub struct ShowMenu<T: Clone + PartialEq + 'static> {
2214    position: Option<RelativeRect>,
2215    position_builder: Option<PopupMenuPositionBuilder>,
2216    items: Vec<PopupMenuEntryRef<T>>,
2217    initial_value: Option<T>,
2218    elevation: Option<f64>,
2219    shadow_color: Option<Color>,
2220    surface_tint_color: Option<Color>,
2221    semantic_label: Option<String>,
2222    shape: Option<ShapeBorderRef>,
2223    menu_padding: Option<EdgeInsetsGeometry>,
2224    color: Option<Color>,
2225    use_root_navigator: bool,
2226    constraints: Option<BoxConstraints>,
2227    clip_behavior: Clip,
2228    route_settings: Option<RouteSettingsRef>,
2229    pop_up_animation_style: Option<AnimationStyle>,
2230    request_focus: Option<bool>,
2231}
2232
2233impl<T: Clone + PartialEq + 'static> ShowMenu<T> {
2234    /// Creates a builder for a popup menu; Dart's `showMenu` required argument is the items,
2235    /// and every other argument is a setter.
2236    pub fn new(items: Vec<PopupMenuEntryRef<T>>) -> ShowMenu<T> {
2237        ShowMenu {
2238            position: None,
2239            position_builder: None,
2240            items,
2241            initial_value: None,
2242            elevation: None,
2243            shadow_color: None,
2244            surface_tint_color: None,
2245            semantic_label: None,
2246            shape: None,
2247            menu_padding: None,
2248            color: None,
2249            use_root_navigator: false,
2250            constraints: None,
2251            clip_behavior: Clip::None,
2252            route_settings: None,
2253            pop_up_animation_style: None,
2254            request_focus: None,
2255        }
2256    }
2257
2258    /// The rectangle the menu is positioned against.
2259    pub fn position(mut self, position: RelativeRect) -> ShowMenu<T> {
2260        self.position = Some(position);
2261        self
2262    }
2263
2264    /// A builder of the rectangle the menu is positioned against.
2265    pub fn position_builder(mut self, position_builder: PopupMenuPositionBuilder) -> ShowMenu<T> {
2266        self.position_builder = Some(position_builder);
2267        self
2268    }
2269
2270    /// The value the menu opens with.
2271    pub fn initial_value(mut self, initial_value: T) -> ShowMenu<T> {
2272        self.initial_value = Some(initial_value);
2273        self
2274    }
2275
2276    /// The z-coordinate of the menu.
2277    pub fn elevation(mut self, elevation: f64) -> ShowMenu<T> {
2278        self.elevation = Some(elevation);
2279        self
2280    }
2281
2282    /// The color of the menu's shadow.
2283    pub fn shadow_color(mut self, shadow_color: Color) -> ShowMenu<T> {
2284        self.shadow_color = Some(shadow_color);
2285        self
2286    }
2287
2288    /// The color of the menu's surface tint.
2289    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> ShowMenu<T> {
2290        self.surface_tint_color = Some(surface_tint_color);
2291        self
2292    }
2293
2294    /// The semantic label announced when the menu opens and closes.
2295    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> ShowMenu<T> {
2296        self.semantic_label = Some(semantic_label.into());
2297        self
2298    }
2299
2300    /// The shape of the menu.
2301    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> ShowMenu<T> {
2302        self.shape = Some(shape.into());
2303        self
2304    }
2305
2306    /// The padding inside the menu.
2307    pub fn menu_padding(mut self, menu_padding: impl Into<EdgeInsetsGeometry>) -> ShowMenu<T> {
2308        let menu_padding = menu_padding.into();
2309        self.menu_padding = Some(menu_padding);
2310        self
2311    }
2312
2313    /// The menu's background color.
2314    pub fn color(mut self, color: Color) -> ShowMenu<T> {
2315        self.color = Some(color);
2316        self
2317    }
2318
2319    /// Whether to push the menu to the root navigator. Defaults to `false`.
2320    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowMenu<T> {
2321        self.use_root_navigator = use_root_navigator;
2322        self
2323    }
2324
2325    /// The size constraints on the menu.
2326    pub fn constraints(mut self, constraints: BoxConstraints) -> ShowMenu<T> {
2327        self.constraints = Some(constraints);
2328        self
2329    }
2330
2331    /// The clip behavior of the menu. Defaults to `Clip::None`.
2332    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ShowMenu<T> {
2333        self.clip_behavior = clip_behavior;
2334        self
2335    }
2336
2337    /// The route settings passed to the menu's route.
2338    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowMenu<T> {
2339        self.route_settings = Some(route_settings);
2340        self
2341    }
2342
2343    /// An animation style that overrides the menu's animation.
2344    pub fn pop_up_animation_style(mut self, pop_up_animation_style: AnimationStyle) -> ShowMenu<T> {
2345        self.pop_up_animation_style = Some(pop_up_animation_style);
2346        self
2347    }
2348
2349    /// Whether the menu's route requests focus when it appears.
2350    pub fn request_focus(mut self, request_focus: bool) -> ShowMenu<T> {
2351        self.request_focus = Some(request_focus);
2352        self
2353    }
2354
2355    /// Shows the menu and returns the value the menu was popped with.
2356    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
2357        let ShowMenu {
2358            position,
2359            position_builder,
2360            items,
2361            initial_value,
2362            elevation,
2363            shadow_color,
2364            surface_tint_color,
2365            semantic_label,
2366            shape,
2367            menu_padding,
2368            color,
2369            use_root_navigator,
2370            constraints,
2371            clip_behavior,
2372            route_settings,
2373            pop_up_animation_style,
2374            request_focus,
2375        } = self;
2376
2377        debug_assert!(!items.is_empty());
2378        debug_assert!(debug_check_has_material_localizations(app, context));
2379        debug_assert!(
2380            position.is_some() != position_builder.is_some(),
2381            "Either position or positionBuilder must be provided."
2382        );
2383
2384        let mut semantic_label = semantic_label;
2385        match app.platform().target_platform() {
2386            TargetPlatform::IOS | TargetPlatform::MacOS => {}
2387            TargetPlatform::Android
2388            | TargetPlatform::Fuchsia
2389            | TargetPlatform::Linux
2390            | TargetPlatform::Windows => {
2391                if semantic_label.is_none() {
2392                    semantic_label =
2393                        Some(<dyn MaterialLocalizations>::of(app, context).popup_menu_label());
2394                }
2395            }
2396        }
2397
2398        let menu_item_keys: Vec<GlobalKey> = (0..items.len()).map(|_| GlobalKey::new()).collect();
2399        let navigator = Navigator::of(app, context, use_root_navigator);
2400        let barrier_label = <dyn MaterialLocalizations>::of(app, context).menu_dismiss_label();
2401        let navigator_context = navigator.context(app);
2402        let captured_themes = <dyn InheritedTheme>::capture(app, context, Some(navigator_context));
2403        let route = PopupMenuRoute::new(
2404            app,
2405            PopupMenuRouteArguments {
2406                position,
2407                position_builder,
2408                items,
2409                item_keys: menu_item_keys,
2410                initial_value,
2411                elevation,
2412                shadow_color,
2413                surface_tint_color,
2414                semantic_label,
2415                barrier_label,
2416                shape,
2417                menu_padding,
2418                color,
2419                captured_themes,
2420                constraints,
2421                clip_behavior,
2422                settings: route_settings,
2423                pop_up_animation_style,
2424                request_focus,
2425            },
2426        );
2427        navigator.push(app, route.into_erased())
2428    }
2429}
2430
2431/// Signature for the callback invoked when a menu item is selected. The argument is the value
2432/// of the [`PopupMenuItem`] that caused its menu to be dismissed.
2433///
2434/// Used by [`PopupMenuButton::on_selected`].
2435pub type PopupMenuItemSelected<T> = Rc<dyn Fn(&mut App, T)>;
2436
2437/// Signature for the callback invoked when a [`PopupMenuButton`] is dismissed without
2438/// selecting an item.
2439///
2440/// Used by [`PopupMenuButton::on_canceled`].
2441pub type PopupMenuCanceled = Listener;
2442
2443/// Signature used by [`PopupMenuButton`] to lazily construct the items shown when the button
2444/// is pressed.
2445///
2446/// Used by [`PopupMenuButton::item_builder`].
2447pub type PopupMenuItemBuilder<T> = Rc<dyn Fn(&mut App, BuildContext) -> Vec<PopupMenuEntryRef<T>>>;
2448
2449// ---------------------------------------------------------------------------------------------
2450// PopupMenuButton
2451
2452/// Displays a menu when pressed and calls [`on_selected`](Self::on_selected) when the menu is
2453/// dismissed because an item was selected. The value passed to
2454/// [`on_selected`](Self::on_selected) is the value of the selected menu item.
2455///
2456/// One of [`child`](Self::child) or [`icon`](Self::icon) may be provided, but not both. If
2457/// [`icon`](Self::icon) is provided, then [`PopupMenuButton`] behaves like an [`IconButton`].
2458///
2459/// If both are `None`, then a standard overflow icon is created (depending on the platform).
2460///
2461/// ## Updating to `MenuAnchor`
2462///
2463/// There is a Material 3 component, `MenuAnchor` that is preferred for applications that are
2464/// configured for Material 3 (see `ThemeData::use_material3`). The `MenuAnchor` widget's
2465/// visuals are a little bit different, see the Material 3 spec at
2466/// <https://m3.material.io/components/menus/guidelines> for more details.
2467///
2468/// The `MenuAnchor` widget's API is also slightly different. `MenuAnchor` can be used to wrap
2469/// any widget that should have a menu associated with it, and it uses `MenuItemButton` for the
2470/// items it shows.
2471///
2472/// See also:
2473///
2474///  * [`PopupMenuItem`], a popup menu entry for a single value.
2475///  * [`PopupMenuDivider`], a popup menu entry that is just a horizontal line.
2476///  * [`CheckedPopupMenuItem`], a popup menu item with a checkmark.
2477///  * [`ShowMenu`], a method to dynamically show a popup menu at a given location.
2478pub struct PopupMenuButton<T: 'static> {
2479    pub key: Option<KeyRef>,
2480
2481    /// Called when the button is pressed to create the items to show in the menu.
2482    pub item_builder: PopupMenuItemBuilder<T>,
2483
2484    /// The value of the menu item, if any, that should be highlighted when the menu opens.
2485    pub initial_value: Option<T>,
2486
2487    /// Called when the popup menu is shown.
2488    pub on_opened: Option<Listener>,
2489
2490    /// Called when the user selects a value from the popup menu created by this button.
2491    ///
2492    /// If the popup menu is dismissed without selecting a value,
2493    /// [`on_canceled`](Self::on_canceled) is called instead.
2494    pub on_selected: Option<PopupMenuItemSelected<T>>,
2495
2496    /// Called when the user dismisses the popup menu without selecting an item.
2497    ///
2498    /// If the user selects a value, [`on_selected`](Self::on_selected) is called instead.
2499    pub on_canceled: Option<PopupMenuCanceled>,
2500
2501    /// Text that describes the action that will occur when the button is pressed.
2502    ///
2503    /// This text is displayed when the user long-presses on the button and is used for
2504    /// accessibility.
2505    pub tooltip: Option<String>,
2506
2507    /// The z-coordinate at which to place the menu when open. This controls the size of the
2508    /// shadow below the menu.
2509    ///
2510    /// Defaults to 8, the appropriate elevation for popup menus.
2511    pub elevation: Option<f64>,
2512
2513    /// The color used to paint the shadow below the menu.
2514    ///
2515    /// If `None` then the ambient [`PopupMenuThemeData::shadow_color`] is used. If that is
2516    /// `None` too, then the overall theme's `ThemeData::shadow_color` (default black) is used.
2517    pub shadow_color: Option<Color>,
2518
2519    /// The color used as an overlay on [`color`](Self::color) to indicate elevation.
2520    ///
2521    /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
2522    /// introduced a set of tone-based surfaces and surface containers in its `ColorScheme`,
2523    /// which provide more flexibility. The intention is to eventually remove surface tint color
2524    /// from the framework.
2525    ///
2526    /// If `None`, [`PopupMenuThemeData::surface_tint_color`] is used. If that is also `None`,
2527    /// the default value is `Colors::TRANSPARENT`.
2528    ///
2529    /// See `Material::surface_tint_color` for more details on how this overlay is applied.
2530    pub surface_tint_color: Option<Color>,
2531
2532    /// Matches IconButton's 8 dps padding by default. In some cases, notably where this button
2533    /// appears as the trailing element of a list item, it's useful to be able to set the
2534    /// padding to zero.
2535    pub padding: EdgeInsetsGeometry,
2536
2537    /// If provided, menu padding is used for empty space around the outside of the popup menu.
2538    ///
2539    /// If this property is `None`, then [`PopupMenuThemeData::menu_padding`] is used. If
2540    /// [`PopupMenuThemeData::menu_padding`] is also `None`, then vertical padding of 8 pixels
2541    /// is used.
2542    pub menu_padding: Option<EdgeInsetsGeometry>,
2543
2544    /// The splash radius.
2545    ///
2546    /// If `None`, default splash radius of [`InkWell`] or [`IconButton`] is used.
2547    pub splash_radius: Option<f64>,
2548
2549    /// If provided, [`child`](Self::child) is the widget used for this button and the button
2550    /// will utilize an [`InkWell`] for taps.
2551    pub child: Option<WidgetRef>,
2552
2553    /// The border radius for the [`InkWell`] that wraps the [`child`](Self::child).
2554    ///
2555    /// Defaults to `None`, which indicates no border radius should be applied.
2556    pub border_radius: Option<BorderRadius>,
2557
2558    /// If provided, the [`icon`](Self::icon) is used for this button and the button will
2559    /// behave like an [`IconButton`].
2560    pub icon: Option<WidgetRef>,
2561
2562    /// The offset is applied relative to the initial position set by the
2563    /// [`position`](Self::position).
2564    ///
2565    /// When not set, the offset defaults to [`Offset::ZERO`].
2566    pub offset: Offset,
2567
2568    /// Whether this popup menu button is interactive.
2569    ///
2570    /// Defaults to true.
2571    ///
2572    /// If true, the button will respond to presses by displaying the menu.
2573    ///
2574    /// If false, the button is styled with the disabled color from the current [`Theme`] and
2575    /// will not respond to presses or show the popup menu and
2576    /// [`on_selected`](Self::on_selected), [`on_canceled`](Self::on_canceled) and
2577    /// [`item_builder`](Self::item_builder) will not be called.
2578    ///
2579    /// This can be useful in situations where the app needs to show the button, but doesn't
2580    /// currently have anything to show in the menu.
2581    pub enabled: bool,
2582
2583    /// If provided, the shape used for the menu.
2584    ///
2585    /// If this property is `None`, then [`PopupMenuThemeData::shape`] is used. If
2586    /// [`PopupMenuThemeData::shape`] is also `None`, then the default shape for
2587    /// [`MaterialType::Card`] is used. This default shape is a rectangle with rounded edges of
2588    /// `BorderRadius::circular(2.0)`.
2589    pub shape: Option<ShapeBorderRef>,
2590
2591    /// If provided, the background color used for the menu.
2592    ///
2593    /// If this property is `None`, then [`PopupMenuThemeData::color`] is used. If
2594    /// [`PopupMenuThemeData::color`] is also `None`, then `ThemeData::card_color` is used in
2595    /// Material 2. In Material3, defaults to `ColorScheme::surface_container`.
2596    pub color: Option<Color>,
2597
2598    /// If provided, this color is used for the button icon.
2599    ///
2600    /// If this property is `None`, then [`PopupMenuThemeData::icon_color`] is used. If
2601    /// [`PopupMenuThemeData::icon_color`] is also `None` then defaults to
2602    /// `IconThemeData::color`.
2603    pub icon_color: Option<Color>,
2604
2605    /// Whether detected gestures should provide acoustic and/or haptic feedback.
2606    ///
2607    /// For example, on Android a tap will produce a clicking sound and a long-press will
2608    /// produce a short vibration, when feedback is enabled.
2609    ///
2610    /// See also:
2611    ///
2612    ///  * `Feedback` for providing platform-specific feedback to certain actions.
2613    pub enable_feedback: Option<bool>,
2614
2615    /// If provided, the size of the [`Icon`].
2616    ///
2617    /// If this property is `None`, then `IconThemeData::size` is used. If
2618    /// `IconThemeData::size` is also `None`, then default size is 24.0 pixels.
2619    pub icon_size: Option<f64>,
2620
2621    /// Optional size constraints for the menu.
2622    ///
2623    /// When unspecified, defaults to:
2624    ///
2625    /// ```text
2626    /// BoxConstraints::new().min_width(2.0 * 56.0).max_width(5.0 * 56.0)
2627    /// ```
2628    ///
2629    /// The default constraints ensure that the menu width matches maximum width recommended by
2630    /// the Material Design guidelines. Specifying this parameter enables creation of menu wider
2631    /// than the default maximum width.
2632    pub constraints: Option<BoxConstraints>,
2633
2634    /// Whether the popup menu is positioned over or under the popup menu button.
2635    ///
2636    /// [`offset`](Self::offset) is used to change the position of the popup menu relative to
2637    /// the position set by this parameter.
2638    ///
2639    /// If this property is `None`, then [`PopupMenuThemeData::position`] is used. If
2640    /// [`PopupMenuThemeData::position`] is also `None`, then the position defaults to
2641    /// [`PopupMenuPosition::Over`] which makes the popup menu appear directly over the button
2642    /// that was used to create it.
2643    pub position: Option<PopupMenuPosition>,
2644
2645    /// {@macro cupertino_ui.Material.clipBehavior}
2646    ///
2647    /// The [`clip_behavior`](Self::clip_behavior) argument is used the clip shape of the menu.
2648    ///
2649    /// Defaults to [`Clip::None`].
2650    pub clip_behavior: Clip,
2651
2652    /// Used to determine whether to push the menu to the [`Navigator`] furthest from or nearest
2653    /// to the given `context`.
2654    ///
2655    /// Defaults to false.
2656    pub use_root_navigator: bool,
2657
2658    /// Used to override the default animation curves and durations of the popup menu's open
2659    /// and close transitions.
2660    ///
2661    /// If `AnimationStyle::curve` is provided, it will be used to override the default popup
2662    /// animation curve. Otherwise, defaults to `Curves::linear`.
2663    ///
2664    /// If `AnimationStyle::reverse_curve` is provided, it will be used to override the default
2665    /// popup animation reverse curve. Otherwise, defaults to `Interval(0.0, 2.0 / 3.0)`.
2666    ///
2667    /// If `AnimationStyle::duration` is provided, it will be used to override the default popup
2668    /// animation duration. Otherwise, defaults to 300ms.
2669    ///
2670    /// To disable the theme animation, use [`AnimationStyle::NO_ANIMATION`].
2671    ///
2672    /// If this is `None`, then the default animation will be used.
2673    pub pop_up_animation_style: Option<AnimationStyle>,
2674
2675    /// Optional route settings for the menu.
2676    ///
2677    /// See `RouteSettings` for details.
2678    pub route_settings: Option<RouteSettingsRef>,
2679
2680    /// Customizes this icon button's appearance.
2681    ///
2682    /// The [`style`](Self::style) is only used for Material 3 [`IconButton`]s. If
2683    /// `ThemeData::use_material3` is set to true, [`style`](Self::style) is preferred for icon
2684    /// button customization, and any parameters defined in [`style`](Self::style) will
2685    /// override the same parameters in [`IconButton`].
2686    ///
2687    /// `None` by default.
2688    pub style: Option<ButtonStyle>,
2689
2690    /// Whether to request focus when the menu appears.
2691    ///
2692    /// If `None`, `Navigator::request_focus` will be used instead.
2693    pub request_focus: Option<bool>,
2694}
2695
2696macro_rules! popup_menu_button_setters {
2697    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
2698        $(
2699            #[doc = concat!("Dart `PopupMenuButton(", $dart, ":)`.")]
2700            pub fn $field(mut self, $field: $ty) -> PopupMenuButton<T> {
2701                self.$field = Some($field);
2702                self
2703            }
2704        )*
2705    };
2706}
2707
2708impl<T: Clone + PartialEq + 'static> PopupMenuButton<T> {
2709    /// Creates a button that shows a popup menu.
2710    pub fn new(
2711        item_builder: impl Fn(&mut App, BuildContext) -> Vec<PopupMenuEntryRef<T>> + 'static,
2712    ) -> PopupMenuButton<T> {
2713        PopupMenuButton {
2714            key: None,
2715            item_builder: Rc::new(item_builder),
2716            initial_value: None,
2717            on_opened: None,
2718            on_selected: None,
2719            on_canceled: None,
2720            tooltip: None,
2721            elevation: None,
2722            shadow_color: None,
2723            surface_tint_color: None,
2724            padding: EdgeInsetsGeometry::all(8.0),
2725            menu_padding: None,
2726            child: None,
2727            border_radius: None,
2728            splash_radius: None,
2729            icon: None,
2730            icon_size: None,
2731            offset: Offset::ZERO,
2732            enabled: true,
2733            shape: None,
2734            color: None,
2735            icon_color: None,
2736            enable_feedback: None,
2737            constraints: None,
2738            position: None,
2739            clip_behavior: Clip::None,
2740            use_root_navigator: false,
2741            pop_up_animation_style: None,
2742            route_settings: None,
2743            style: None,
2744            request_focus: None,
2745        }
2746    }
2747
2748    popup_menu_button_setters!(
2749        key: KeyRef => "key",
2750        initial_value: T => "initialValue",
2751        on_opened: Listener => "onOpened",
2752        on_canceled: PopupMenuCanceled => "onCanceled",
2753        elevation: f64 => "elevation",
2754        shadow_color: Color => "shadowColor",
2755        surface_tint_color: Color => "surfaceTintColor",
2756        menu_padding: EdgeInsetsGeometry => "menuPadding",
2757        border_radius: BorderRadius => "borderRadius",
2758        splash_radius: f64 => "splashRadius",
2759        icon_size: f64 => "iconSize",
2760        color: Color => "color",
2761        icon_color: Color => "iconColor",
2762        enable_feedback: bool => "enableFeedback",
2763        constraints: BoxConstraints => "constraints",
2764        position: PopupMenuPosition => "position",
2765        pop_up_animation_style: AnimationStyle => "popUpAnimationStyle",
2766        route_settings: RouteSettingsRef => "routeSettings",
2767        style: ButtonStyle => "style",
2768        request_focus: bool => "requestFocus",
2769    );
2770
2771    /// Dart `PopupMenuButton(onSelected:)`.
2772    pub fn on_selected(
2773        mut self,
2774        on_selected: impl Fn(&mut App, T) + 'static,
2775    ) -> PopupMenuButton<T> {
2776        self.on_selected = Some(Rc::new(on_selected));
2777        self
2778    }
2779
2780    /// Dart `PopupMenuButton(tooltip:)`.
2781    pub fn tooltip(mut self, tooltip: impl Into<String>) -> PopupMenuButton<T> {
2782        self.tooltip = Some(tooltip.into());
2783        self
2784    }
2785
2786    /// Dart `PopupMenuButton(padding:)`.
2787    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> PopupMenuButton<T> {
2788        let padding = padding.into();
2789        self.padding = padding;
2790        self
2791    }
2792
2793    /// Dart `PopupMenuButton(child:)`.
2794    #[cfg_attr(debug_assertions, track_caller)]
2795    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> PopupMenuButton<T> {
2796        self.child = Some(child.into_widget());
2797        self
2798    }
2799
2800    /// Dart `PopupMenuButton(icon:)`.
2801    #[cfg_attr(debug_assertions, track_caller)]
2802    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> PopupMenuButton<T> {
2803        self.icon = Some(icon.into_widget());
2804        self
2805    }
2806
2807    /// Dart `PopupMenuButton(offset:)`.
2808    pub fn offset(mut self, offset: Offset) -> PopupMenuButton<T> {
2809        self.offset = offset;
2810        self
2811    }
2812
2813    /// Dart `PopupMenuButton(enabled:)`.
2814    pub fn enabled(mut self, enabled: bool) -> PopupMenuButton<T> {
2815        self.enabled = enabled;
2816        self
2817    }
2818
2819    /// Dart `PopupMenuButton(shape:)`.
2820    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> PopupMenuButton<T> {
2821        self.shape = Some(shape.into());
2822        self
2823    }
2824
2825    /// Dart `PopupMenuButton(clipBehavior:)`.
2826    pub fn clip_behavior(mut self, clip_behavior: Clip) -> PopupMenuButton<T> {
2827        self.clip_behavior = clip_behavior;
2828        self
2829    }
2830
2831    /// Dart `PopupMenuButton(useRootNavigator:)`.
2832    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> PopupMenuButton<T> {
2833        self.use_root_navigator = use_root_navigator;
2834        self
2835    }
2836}
2837
2838impl<T: 'static> Debug for PopupMenuButton<T> {
2839    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2840        f.debug_struct("PopupMenuButton")
2841            .field("tooltip", &self.tooltip)
2842            .field("enabled", &self.enabled)
2843            .field("position", &self.position)
2844            .finish_non_exhaustive()
2845    }
2846}
2847
2848impl<T: Clone + PartialEq + 'static> StatefulWidget for PopupMenuButton<T> {
2849    type State = PopupMenuButtonState<T>;
2850
2851    fn key(&self) -> Option<&KeyRef> {
2852        self.key.as_ref()
2853    }
2854
2855    fn debug_check_constructor(&self) {
2856        debug_assert!(
2857            !(self.child.is_some() && self.icon.is_some()),
2858            "You can only pass [child] or [icon], not both."
2859        );
2860    }
2861
2862    fn create_state(&self) -> PopupMenuButtonState<T> {
2863        PopupMenuButtonState {
2864            state: StateData::new(),
2865            is_menu_expanded: false,
2866            last_position: Rc::default(),
2867            popup_menu_theme: None,
2868            cached_button_render_box: None,
2869            cached_overlay_render_box: None,
2870        }
2871    }
2872}
2873
2874/// The [`State`] for a [`PopupMenuButton`].
2875///
2876/// See [`show_button_menu`](Self::show_button_menu) for a way to programmatically open the
2877/// popup menu of your button state.
2878pub struct PopupMenuButtonState<T: Clone + PartialEq + 'static> {
2879    state: StateData<PopupMenuButton<T>>,
2880    is_menu_expanded: bool,
2881    /// Dart's `_lastPosition`, shared with the position builder of the menu this button
2882    /// shows, which reads it after the state is disposed, as Dart's menu keeps the state
2883    /// alive.
2884    last_position: Rc<Cell<Option<RelativeRect>>>,
2885    /// Dart's `late PopupMenuThemeData _popupMenuTheme`.
2886    popup_menu_theme: Option<PopupMenuThemeData>,
2887    cached_button_render_box: Option<AnyRenderBox>,
2888    cached_overlay_render_box: Option<AnyRenderBox>,
2889}
2890
2891impl<T: Clone + PartialEq + 'static> Debug for PopupMenuButtonState<T> {
2892    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2893        f.debug_struct("PopupMenuButtonState")
2894            .field("is_menu_expanded", &self.is_menu_expanded)
2895            .finish_non_exhaustive()
2896    }
2897}
2898
2899impl<T: Clone + PartialEq + 'static> PopupMenuButtonState<T> {
2900    fn update_cached_objects(self: Handle<Self>, app: &mut App) {
2901        if self.mounted(app) {
2902            let context = self.context(app);
2903            let popup_menu_theme = PopupMenuTheme::of(app, context);
2904            app.get_mut(self).popup_menu_theme = Some(popup_menu_theme);
2905
2906            let button_render_object = context.find_render_object(app);
2907            if let Some(button) = button_render_object.and_then(|object| object.as_box()) {
2908                app.get_mut(self).cached_button_render_box = Some(button);
2909            }
2910            let use_root_navigator = self.widget(app).use_root_navigator;
2911            match Navigator::maybe_of(app, context, use_root_navigator) {
2912                Some(navigator) => {
2913                    let overlay_render_object = navigator
2914                        .overlay(app)
2915                        .and_then(|overlay| overlay.context(app).find_render_object(app));
2916                    if let Some(overlay) = overlay_render_object.and_then(|object| object.as_box())
2917                    {
2918                        app.get_mut(self).cached_overlay_render_box = Some(overlay);
2919                    }
2920                }
2921                None => {
2922                    let state = app.get_mut(self);
2923                    state.cached_button_render_box = None;
2924                    state.cached_overlay_render_box = None;
2925                }
2926            }
2927        }
2928    }
2929
2930    fn get_default_position(
2931        last_position: &Cell<Option<RelativeRect>>,
2932        constraints: BoxConstraints,
2933    ) -> RelativeRect {
2934        last_position
2935            .get()
2936            .unwrap_or_else(|| RelativeRect::from_size(Rect::ZERO, constraints.biggest()))
2937    }
2938
2939    /// Dart's `_positionBuilder`; `last_position` is the state's `last_position`, which it
2940    /// reads after the state is gone.
2941    fn position_builder(
2942        self: Handle<Self>,
2943        last_position: &Cell<Option<RelativeRect>>,
2944        app: &mut App,
2945        _context: BuildContext,
2946        constraints: BoxConstraints,
2947    ) -> RelativeRect {
2948        if !self.mounted(app) {
2949            // When the route is displayed, the `_positionBuilder` closure is stored.
2950            // Even after the button has been unmounted and the context becomes invalid,
2951            // the route might keep displaying, and `_positionBuilder` must continue to
2952            // work in that case.
2953            return Self::get_default_position(last_position, constraints);
2954        }
2955
2956        let popup_menu_theme = app
2957            .get(self)
2958            .popup_menu_theme
2959            .clone()
2960            .expect("set in did_change_dependencies");
2961
2962        // Use cached render objects if available.
2963        let button = app.get(self).cached_button_render_box;
2964        let overlay = app.get(self).cached_overlay_render_box;
2965
2966        // Check if cached render objects are available and still attached.
2967        let (Some(button), Some(overlay)) = (button, overlay) else {
2968            // Render objects are not available or detached, return cached position or default.
2969            return Self::get_default_position(last_position, constraints);
2970        };
2971        if !button.as_object().attached(app) || !overlay.as_object().attached(app) {
2972            return Self::get_default_position(last_position, constraints);
2973        }
2974        let widget = self.widget(app);
2975        let popup_menu_position = widget
2976            .position
2977            .or(popup_menu_theme.position)
2978            .unwrap_or(PopupMenuPosition::Over);
2979        let offset = match popup_menu_position {
2980            PopupMenuPosition::Over => widget.offset,
2981            PopupMenuPosition::Under => {
2982                let mut offset = Offset::new(0.0, button.size(app).height()) + widget.offset;
2983                if widget.child.is_none() {
2984                    // Remove the padding of the icon button.
2985                    offset = offset - Offset::new(0.0, widget.padding.vertical() / 2.0);
2986                }
2987                offset
2988            }
2989        };
2990        let button_size = button.size(app);
2991        let position = RelativeRect::from_rect(
2992            Rect::from_points(
2993                button.local_to_global(app, offset, Some(overlay.as_object())),
2994                button.local_to_global(
2995                    app,
2996                    button_size.bottom_right(Offset::ZERO) + offset,
2997                    Some(overlay.as_object()),
2998                ),
2999            ),
3000            Offset::ZERO & overlay.size(app),
3001        );
3002
3003        last_position.set(Some(position));
3004        position
3005    }
3006
3007    /// A method to show a popup menu with the items supplied to
3008    /// [`PopupMenuButton::item_builder`] at the position of your [`PopupMenuButton`].
3009    ///
3010    /// By default, it is called when the user taps the button and
3011    /// [`PopupMenuButton::enabled`] is set to `true`. Moreover, you can open the button by
3012    /// calling the method manually.
3013    ///
3014    /// You would access your [`PopupMenuButtonState`] using a `GlobalKey` and show the menu of
3015    /// the button with `global_key.current_state::<PopupMenuButtonState<T>>(app)
3016    /// .unwrap().show_button_menu(app)`.
3017    pub fn show_button_menu(self: Handle<Self>, app: &mut App) {
3018        // Ensure cached render objects are initialized
3019        self.update_cached_objects(app);
3020        let context = self.context(app);
3021        let item_builder = Rc::clone(&self.widget(app).item_builder);
3022        let items = item_builder(app, context);
3023        // Only show the menu if there is something to show
3024        if !items.is_empty() {
3025            if let Some(on_opened) = self.widget(app).on_opened.clone() {
3026                on_opened.call(app);
3027            }
3028            self.set_state(app, |state| {
3029                state.is_menu_expanded = true;
3030            });
3031            let widget = self.widget(app);
3032            let initial_value = widget.initial_value.clone();
3033            let elevation = widget.elevation;
3034            let shadow_color = widget.shadow_color;
3035            let surface_tint_color = widget.surface_tint_color;
3036            let shape = widget.shape.clone();
3037            let menu_padding = widget.menu_padding;
3038            let color = widget.color;
3039            let constraints = widget.constraints;
3040            let clip_behavior = widget.clip_behavior;
3041            let use_root_navigator = widget.use_root_navigator;
3042            let pop_up_animation_style = widget.pop_up_animation_style.clone();
3043            let route_settings = widget.route_settings.clone();
3044            let request_focus = widget.request_focus;
3045            let last_position = Rc::clone(&app.get(self).last_position);
3046            let mut show = ShowMenu::new(items)
3047                .position_builder(Rc::new(move |app, context, constraints| {
3048                    self.position_builder(&last_position, app, context, constraints)
3049                }))
3050                .use_root_navigator(use_root_navigator)
3051                .clip_behavior(clip_behavior);
3052            if let Some(initial_value) = initial_value {
3053                show = show.initial_value(initial_value);
3054            }
3055            if let Some(elevation) = elevation {
3056                show = show.elevation(elevation);
3057            }
3058            if let Some(shadow_color) = shadow_color {
3059                show = show.shadow_color(shadow_color);
3060            }
3061            if let Some(surface_tint_color) = surface_tint_color {
3062                show = show.surface_tint_color(surface_tint_color);
3063            }
3064            if let Some(shape) = shape {
3065                show = show.shape(shape);
3066            }
3067            if let Some(menu_padding) = menu_padding {
3068                show = show.menu_padding(menu_padding);
3069            }
3070            if let Some(color) = color {
3071                show = show.color(color);
3072            }
3073            if let Some(constraints) = constraints {
3074                show = show.constraints(constraints);
3075            }
3076            if let Some(route_settings) = route_settings {
3077                show = show.route_settings(route_settings);
3078            }
3079            if let Some(pop_up_animation_style) = pop_up_animation_style {
3080                show = show.pop_up_animation_style(pop_up_animation_style);
3081            }
3082            if let Some(request_focus) = request_focus {
3083                show = show.request_focus(request_focus);
3084            }
3085            let popped = show.show(app, context);
3086            drop(app.spawn(async move |cx| {
3087                let new_value = popped.await;
3088                cx.update(|app| {
3089                    if !self.mounted(app) {
3090                        return;
3091                    }
3092                    self.set_state(app, |state| {
3093                        state.is_menu_expanded = false;
3094                    });
3095                    let new_value =
3096                        new_value.and_then(|new_value| new_value.downcast_ref::<T>().cloned());
3097                    let Some(new_value) = new_value else {
3098                        if let Some(on_canceled) = self.widget(app).on_canceled.clone() {
3099                            on_canceled.call(app);
3100                        }
3101                        return;
3102                    };
3103                    if let Some(on_selected) = self.widget(app).on_selected.clone() {
3104                        on_selected(app, new_value);
3105                    }
3106                });
3107            }));
3108        }
3109    }
3110
3111    fn can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
3112        let context = self.context(app);
3113        let mode = MediaQuery::maybe_navigation_mode_of(app, context)
3114            .unwrap_or(NavigationMode::Traditional);
3115        match mode {
3116            NavigationMode::Traditional => self.widget(app).enabled,
3117            NavigationMode::Directional => true,
3118        }
3119    }
3120}
3121
3122impl<T: Clone + PartialEq + 'static> State for PopupMenuButtonState<T> {
3123    type Widget = PopupMenuButton<T>;
3124    waft_widgets::state_accessors!();
3125
3126    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3127        self.update_cached_objects(app);
3128    }
3129
3130    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3131        let icon_theme = IconTheme::of(app, context);
3132        let popup_menu_theme = PopupMenuTheme::of(app, context);
3133        let enable_feedback = self
3134            .widget(app)
3135            .enable_feedback
3136            .or(PopupMenuTheme::of(app, context).enable_feedback)
3137            .unwrap_or(true);
3138
3139        debug_assert!(debug_check_has_material_localizations(app, context));
3140        let localizations = <dyn MaterialLocalizations>::of(app, context);
3141        let can_request_focus = self.can_request_focus(app);
3142        let is_menu_expanded = app.get(self).is_menu_expanded;
3143        let widget = self.widget(app);
3144        let tooltip = widget
3145            .tooltip
3146            .clone()
3147            .unwrap_or_else(|| localizations.show_menu_tooltip());
3148        let on_pressed = widget
3149            .enabled
3150            .then(|| Listener::handle_method(self, Self::show_button_menu));
3151
3152        if let Some(child) = &widget.child {
3153            let mut ink_well = InkWell::new()
3154                .can_request_focus(can_request_focus)
3155                .enable_feedback(enable_feedback)
3156                .child(child.clone());
3157            if let Some(border_radius) = widget.border_radius {
3158                ink_well = ink_well.border_radius(border_radius);
3159            }
3160            if let Some(on_pressed) = on_pressed {
3161                ink_well = ink_well.on_tap(on_pressed);
3162            }
3163            if let Some(splash_radius) = widget.splash_radius {
3164                ink_well = ink_well.radius(splash_radius);
3165            }
3166            let child = Tooltip::new()
3167                .message(tooltip)
3168                .child(ink_well)
3169                .into_widget();
3170            let tap_target_size = widget
3171                .style
3172                .as_ref()
3173                .and_then(|style| style.tap_target_size)
3174                .unwrap_or(MaterialTapTargetSize::ShrinkWrap);
3175            let result = if tap_target_size == MaterialTapTargetSize::Padded {
3176                ConstrainedBox::new(
3177                    BoxConstraints::new()
3178                        .min_width(K_MIN_INTERACTIVE_DIMENSION)
3179                        .min_height(K_MIN_INTERACTIVE_DIMENSION),
3180                )
3181                .child(child)
3182                .into_widget()
3183            } else {
3184                child
3185            };
3186            // The button semantics are added here rather than by the [InkWell] so
3187            // that assistive technologies describe the popup menu button the same way
3188            // regardless of whether it is built from [child] or from [icon], in which
3189            // case the semantics come from the [IconButton].
3190            return Semantics::new()
3191                .button(true)
3192                .enabled(widget.enabled)
3193                .expanded(is_menu_expanded)
3194                .child(result)
3195                .into_widget();
3196        }
3197
3198        let icon = widget
3199            .icon
3200            .clone()
3201            .unwrap_or_else(|| Icon::new(Some(Icons::adaptive().more(app))).into_widget());
3202        let mut icon_button = IconButton::new(
3203            on_pressed,
3204            Semantics::new().expanded(is_menu_expanded).child(icon),
3205        )
3206        .key(StandardComponentType::MoreButton.key())
3207        .padding(widget.padding)
3208        .tooltip(tooltip)
3209        .enable_feedback(enable_feedback);
3210        if let Some(splash_radius) = widget.splash_radius {
3211            icon_button = icon_button.splash_radius(splash_radius);
3212        }
3213        if let Some(icon_size) = widget
3214            .icon_size
3215            .or(popup_menu_theme.icon_size)
3216            .or(icon_theme.size)
3217        {
3218            icon_button = icon_button.icon_size(icon_size);
3219        }
3220        if let Some(color) = widget
3221            .icon_color
3222            .or(popup_menu_theme.icon_color)
3223            .or(icon_theme.color.as_deref().copied())
3224        {
3225            icon_button = icon_button.color(color);
3226        }
3227        if let Some(style) = widget.style.clone() {
3228            icon_button = icon_button.style(style);
3229        }
3230        Semantics::new().child(icon_button).into_widget()
3231    }
3232}
3233
3234#[cfg(test)]
3235mod tests {
3236    //! Ported from `test/popup_menu_test.dart`; the semantics-tree cases wait for the semantics
3237    //! tree, the goldens are not ported, and the display-feature case waits for
3238    //! `DisplayFeatureSubScreen`.
3239
3240    use std::cell::{Cell, RefCell};
3241
3242    use waft_embedder::Locale;
3243    use waft_widgets::{
3244        AnyElement, Builder, Center, Column, Container, DefaultWidgetsLocalizations, Localizations,
3245        MediaQueryData, RouteSettings, SizedBox, Text,
3246    };
3247
3248    use waft_widgets::testing::{
3249        TargetPlatformVariant, TestPointer, WidgetTester, assert_f32_equals, expect, find,
3250        finds_one_widget, test_widgets, test_widgets_variant,
3251    };
3252
3253    use super::*;
3254    use crate::material_localizations::DefaultMaterialLocalizations;
3255    use crate::page::MaterialPageRoute;
3256    use crate::theme_data::ThemeData;
3257    use crate::tooltip::tests::{m2, m3, pump_app};
3258
3259    /// Dart's `PopupMenuItem<T>(value: value, child: Text(text))`.
3260    fn item<T: Clone + PartialEq + 'static>(value: T, text: &str) -> PopupMenuEntryRef<T> {
3261        PopupMenuEntryRef::new(PopupMenuItem::new(Some(Text::new(text))).value(value))
3262    }
3263
3264    /// Dart's `find.text(text)` with `findsOneWidget` or `findsNothing`.
3265    fn shows(tester: &WidgetTester, text: &str) -> bool {
3266        !find::text(text).evaluate(tester).is_empty()
3267    }
3268
3269    /// Dart's `tester.tap(find.byKey(key))`.
3270    fn tap_key(tester: &mut WidgetTester, key: &GlobalKey) {
3271        let center = tester.get_center(key);
3272        tester.tap_at(center, 1);
3273    }
3274
3275    /// Dart's `tester.getRect(find.byType(T))` of the only one.
3276    fn rect_of<W: 'static>(tester: &WidgetTester) -> Rect {
3277        tester.get_rect(tester.render_box_of(tester.element(find::by_type::<W>())))
3278    }
3279
3280    /// Dart's `tester.getRect(find.byKey(key))`.
3281    fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
3282        tester.get_rect(tester.render_object(key).as_box().expect("a render box"))
3283    }
3284
3285    fn context_of(tester: &WidgetTester, key: &GlobalKey) -> BuildContext {
3286        key.current_context(&tester.cell.borrow())
3287            .expect("the keyed widget is mounted")
3288    }
3289
3290    /// Dart's `Navigator.of(context).pop()`.
3291    fn pop(tester: &mut WidgetTester, context: BuildContext) {
3292        let mut app = tester.cell.borrow_mut();
3293        Navigator::of(&mut app, context, false).pop(&mut app, None);
3294        drop(app);
3295        tester.cell.checkpoint();
3296    }
3297
3298    /// A counter a callback bumps: Dart's `var opens = 0; () => opens++`.
3299    fn counter() -> (Rc<Cell<u32>>, Listener) {
3300        let count = Rc::new(Cell::new(0));
3301        let bump = Rc::clone(&count);
3302        (count, Listener::new(move |_app| bump.set(bump.get() + 1)))
3303    }
3304
3305    /// Dart's `TestApp(textDirection: text_direction, child: child)`: a navigator whose one
3306    /// page is `Material(child: child)`, under the view's media query.
3307    fn test_app(
3308        text_direction: TextDirection,
3309        child: impl Fn() -> WidgetRef + 'static,
3310    ) -> WidgetRef {
3311        let child = Rc::new(child);
3312        Localizations::new(
3313            Locale::new("en").country_code("US"),
3314            vec![
3315                DefaultWidgetsLocalizations::delegate(),
3316                DefaultMaterialLocalizations::delegate(),
3317            ],
3318        )
3319        .child(Builder::new(move |app, context| {
3320            let view = waft_widgets::View::of(app, context);
3321            let data = MediaQueryData::from_view(app, &*view, None);
3322            let child = Rc::clone(&child);
3323            MediaQuery::new(
3324                data,
3325                Directionality::new(
3326                    text_direction,
3327                    Navigator::new().on_generate_route(move |app, settings| {
3328                        let child = Rc::clone(&child);
3329                        let route = MaterialPageRoute::new(
3330                            app,
3331                            Rc::new(move |_app, _context| {
3332                                Material::new().child(child()).into_widget()
3333                            }),
3334                        );
3335                        route
3336                            .clone()
3337                            .settings(app, RouteSettingsRef::Settings(settings.clone()));
3338                        Some(route.erase())
3339                    }),
3340                ),
3341            )
3342            .into_widget()
3343        }))
3344        .into_widget()
3345    }
3346
3347    #[test]
3348    fn navigator_push_works_within_a_popup_menu_button() {
3349        test_widgets(|tester| {
3350            let target_key = GlobalKey::new();
3351            let key = target_key.clone();
3352            let root = {
3353                let app = tester.cell.borrow();
3354                crate::app::MaterialApp::new()
3355                    .theme(m3(&app))
3356                    .routes([(
3357                        "/next".to_owned(),
3358                        Rc::new(|_app: &mut App, _context: BuildContext| {
3359                            Text::new("Next").into_widget()
3360                        }) as waft_widgets::WidgetBuilder,
3361                    )])
3362                    .home(
3363                        Material::new()
3364                            .child(
3365                                Center::new().child(
3366                                    Builder::new(move |_app, context| {
3367                                        PopupMenuButton::new(|_app, _context| vec![item(1, "One")])
3368                                            .on_selected(move |app, _value: i32| {
3369                                                drop(Navigator::push_named(
3370                                                    app, context, "/next", None,
3371                                                ));
3372                                            })
3373                                            .into_widget()
3374                                    })
3375                                    .key(key.clone().into()),
3376                                ),
3377                            )
3378                            .into_widget(),
3379                    )
3380                    .into_widget()
3381            };
3382            tester.pump_widget(root);
3383
3384            tap_key(tester, &target_key);
3385            tester.pump();
3386            tester.pump_by(Duration::from_secs(1)); // finish the menu animation
3387
3388            assert!(shows(tester, "One"));
3389            assert!(!shows(tester, "Next"));
3390
3391            tester.tap(find::text("One"));
3392            tester.pump(); // return the future
3393            tester.pump(); // start the navigation
3394            tester.pump_by(Duration::from_secs(1)); // end the navigation
3395
3396            assert!(!shows(tester, "One"));
3397            assert!(shows(tester, "Next"));
3398        });
3399    }
3400
3401    #[test]
3402    fn popup_menu_button_calls_on_opened_callback_when_the_menu_is_opened() {
3403        test_widgets(|tester| {
3404            let (opens, on_opened) = counter();
3405            let popup_context = Rc::new(Cell::new(None));
3406            let no_items_key = GlobalKey::new();
3407            let no_callback_key = GlobalKey::new();
3408            let with_callback_key = GlobalKey::new();
3409            let (a, b, c) = (
3410                no_items_key.clone(),
3411                no_callback_key.clone(),
3412                with_callback_key.clone(),
3413            );
3414            let saved = Rc::clone(&popup_context);
3415            pump_app(tester, m3, move |_app| {
3416                Material::new()
3417                    .child(Column::new().children(vec![
3418                        PopupMenuButton::<i32>::new(|_app, _context| Vec::new())
3419                            .key(a.into())
3420                            .on_opened(on_opened.clone())
3421                            .into_widget(),
3422                        PopupMenuButton::new(move |_app, context| {
3423                            saved.set(Some(context));
3424                            vec![item(1, "Tap me please!")]
3425                        })
3426                        .key(b.into())
3427                        .into_widget(),
3428                        PopupMenuButton::new(|_app, _context| vec![item(1, "Tap me, too!")])
3429                            .key(c.into())
3430                            .on_opened(on_opened)
3431                            .into_widget(),
3432                    ]))
3433                    .into_widget()
3434            });
3435
3436            // Make sure callback is not called when the menu is not shown
3437            tap_key(tester, &no_items_key);
3438            tester.pump();
3439            assert_eq!(opens.get(), 0);
3440
3441            // Make sure everything works if no callback is provided
3442            tap_key(tester, &no_callback_key);
3443            tester.pump();
3444            assert_eq!(opens.get(), 0);
3445
3446            // Close the opened menu
3447            pop(tester, popup_context.get().expect("the item builder ran"));
3448            tester.pump();
3449
3450            // Make sure callback is called when the button is tapped
3451            tap_key(tester, &with_callback_key);
3452            tester.pump();
3453            assert_eq!(opens.get(), 1);
3454        });
3455    }
3456
3457    #[test]
3458    fn popup_menu_button_calls_on_canceled_callback_when_an_item_is_not_selected() {
3459        test_widgets(|tester| {
3460            let (cancels, on_canceled) = counter();
3461            let popup_context = Rc::new(Cell::new(None));
3462            let no_callback_key = GlobalKey::new();
3463            let with_callback_key = GlobalKey::new();
3464            let (a, b) = (no_callback_key.clone(), with_callback_key.clone());
3465            let saved = Rc::clone(&popup_context);
3466            pump_app(tester, m3, move |_app| {
3467                Material::new()
3468                    .child(Column::new().children(vec![
3469                        PopupMenuButton::new(|_app, _context| vec![item(1, "Tap me please!")])
3470                            .key(a.into())
3471                            .into_widget(),
3472                        PopupMenuButton::new(move |_app, context| {
3473                            saved.set(Some(context));
3474                            vec![item(1, "Tap me, too!")]
3475                        })
3476                        .key(b.into())
3477                        .on_canceled(on_canceled)
3478                        .into_widget(),
3479                    ]))
3480                    .into_widget()
3481            });
3482
3483            // Make sure everything works if no callback is provided
3484            tap_key(tester, &no_callback_key);
3485            tester.pump();
3486            tester.pump_by(Duration::from_secs(1));
3487            tester.tap_at(Offset::ZERO, 1);
3488            tester.pump();
3489            assert_eq!(cancels.get(), 0);
3490
3491            // Make sure callback is called when a non-selection tap occurs
3492            tap_key(tester, &with_callback_key);
3493            tester.pump();
3494            tester.pump_by(Duration::from_secs(1));
3495            tester.tap_at(Offset::ZERO, 1);
3496            tester.pump();
3497            assert_eq!(cancels.get(), 1);
3498
3499            // Make sure callback is called when back navigation occurs
3500            tap_key(tester, &with_callback_key);
3501            tester.pump();
3502            tester.pump_by(Duration::from_secs(1));
3503            pop(tester, popup_context.get().expect("the item builder ran"));
3504            tester.pump();
3505            assert_eq!(cancels.get(), 2);
3506        });
3507    }
3508
3509    /// Dart's `find.widgetWithText(W, text)`: the `W` nearest above the `Text` showing `text`.
3510    fn widget_with_text<W: 'static>(tester: &WidgetTester, text: &str) -> AnyElement {
3511        tester.ancestor_of_type::<W>(tester.element(find::text(text)))
3512    }
3513
3514    /// Dart's `tester.getRect(find.widgetWithText(W, text))`.
3515    fn rect_with_text<W: 'static>(tester: &WidgetTester, text: &str) -> Rect {
3516        tester.get_rect(tester.render_box_of(widget_with_text::<W>(tester, text)))
3517    }
3518
3519    fn near(actual: f64, expected: f64) -> bool {
3520        (actual - expected).abs() <= f64::from(f32::EPSILON) * expected.abs().max(1.0)
3521    }
3522
3523    /// Dart's `MaterialApp(home: Scaffold(body: Center(child: button)))`.
3524    fn centered_in_scaffold(
3525        tester: &mut WidgetTester,
3526        theme: impl FnOnce(&App) -> ThemeData,
3527        button: impl FnOnce() -> WidgetRef,
3528    ) {
3529        let body = Center::new().child(button()).into_widget();
3530        pump_app(tester, theme, move |_app| {
3531            crate::scaffold::Scaffold::new().body(body).into_widget()
3532        });
3533    }
3534
3535    fn has_scheduled_frame(tester: &WidgetTester) -> bool {
3536        SchedulerBinding::has_scheduled_frame(&mut tester.cell.borrow_mut())
3537    }
3538
3539    #[test]
3540    fn disabled_popup_menu_button_will_not_call_item_builder_on_opened_on_selected_or_on_canceled()
3541    {
3542        test_widgets(|tester| {
3543            let popup_button_key = GlobalKey::new();
3544            let item_builder_called = Rc::new(Cell::new(false));
3545            let on_opened_called = Rc::new(Cell::new(false));
3546            let on_selected_called = Rc::new(Cell::new(false));
3547            let on_canceled_called = Rc::new(Cell::new(false));
3548
3549            let build_app = |tester: &mut WidgetTester| {
3550                let key = popup_button_key.clone();
3551                let (builder_called, opened, selected, canceled) = (
3552                    Rc::clone(&item_builder_called),
3553                    Rc::clone(&on_opened_called),
3554                    Rc::clone(&on_selected_called),
3555                    Rc::clone(&on_canceled_called),
3556                );
3557                pump_app(tester, m3, move |_app| {
3558                    Builder::new(move |app, context| {
3559                        let (builder_called, opened, selected, canceled) = (
3560                            Rc::clone(&builder_called),
3561                            Rc::clone(&opened),
3562                            Rc::clone(&selected),
3563                            Rc::clone(&canceled),
3564                        );
3565                        MediaQuery::new(
3566                            MediaQuery::of(app, context)
3567                                .copy_with()
3568                                .navigation_mode(NavigationMode::Directional),
3569                            Material::new().child(Column::new().children(vec![
3570                                PopupMenuButton::new(move |_app, _context| {
3571                                    builder_called.set(true);
3572                                    vec![item(1, "Tap me please!")]
3573                                })
3574                                .enabled(false)
3575                                .child(Text::new("Tap Me").key(key.clone().into()))
3576                                .on_opened(Listener::new(move |_app| opened.set(true)))
3577                                .on_selected(move |_app, _selected: i32| selected.set(true))
3578                                .on_canceled(Listener::new(move |_app| canceled.set(true)))
3579                                .into_widget(),
3580                            ])),
3581                        )
3582                        .into_widget()
3583                    })
3584                    .into_widget()
3585                });
3586            };
3587
3588            build_app(tester);
3589
3590            for directional in [false, true] {
3591                if directional {
3592                    // Test again, with directional navigation mode and after focusing the
3593                    // button.
3594                    build_app(tester);
3595                    let context = context_of(tester, &popup_button_key);
3596                    let mut app = tester.cell.borrow_mut();
3597                    let node = waft_widgets::Focus::of(&mut app, context, false, false);
3598                    node.request_focus(&mut app, None);
3599                    drop(app);
3600                    tester.pump_and_settle();
3601                }
3602
3603                // Try to bring up the popup menu and select the first item from it
3604                tap_key(tester, &popup_button_key);
3605                tester.pump_and_settle();
3606                tap_key(tester, &popup_button_key);
3607                tester.pump_and_settle();
3608                assert!(!item_builder_called.get());
3609                assert!(!on_opened_called.get());
3610                assert!(!on_selected_called.get());
3611
3612                // Try to bring up the popup menu and tap outside it to cancel the menu
3613                tap_key(tester, &popup_button_key);
3614                tester.pump_and_settle();
3615                tester.tap_at(Offset::ZERO, 1);
3616                tester.pump_and_settle();
3617                assert!(!item_builder_called.get());
3618                assert!(!on_opened_called.get());
3619                assert!(!on_canceled_called.get());
3620            }
3621        });
3622    }
3623
3624    /// Dart's 'disabled PopupMenuButton is not focusable' and 'Disabled PopupMenuButton is
3625    /// focusable with directional navigation'.
3626    fn disabled_button_takes_focus(
3627        tester: &mut WidgetTester,
3628        navigation_mode: Option<NavigationMode>,
3629    ) -> bool {
3630        let child_key = GlobalKey::new();
3631        let key = child_key.clone();
3632        pump_app(tester, m3, move |_app| {
3633            Builder::new(move |app, context| {
3634                let button = Material::new().child(Column::new().children(vec![
3635                    PopupMenuButton::new(|_app, _context| vec![item(1, "Tap me please!")])
3636                        .enabled(false)
3637                        .child(Container::new().key(key.clone().into()))
3638                        .on_selected(|_app, _selected: i32| {})
3639                        .into_widget(),
3640                ]));
3641                match navigation_mode {
3642                    Some(navigation_mode) => MediaQuery::new(
3643                        MediaQuery::of(app, context)
3644                            .copy_with()
3645                            .navigation_mode(navigation_mode),
3646                        button,
3647                    )
3648                    .into_widget(),
3649                    None => button.into_widget(),
3650                }
3651            })
3652            .into_widget()
3653        });
3654        let context = context_of(tester, &child_key);
3655        let node = {
3656            let mut app = tester.cell.borrow_mut();
3657            let node = waft_widgets::Focus::of(&mut app, context, false, false);
3658            node.request_focus(&mut app, None);
3659            node
3660        };
3661        tester.pump();
3662        node.has_primary_focus(&tester.cell.borrow())
3663    }
3664
3665    #[test]
3666    fn disabled_popup_menu_button_is_not_focusable() {
3667        test_widgets(|tester| assert!(!disabled_button_takes_focus(tester, None)));
3668    }
3669
3670    #[test]
3671    fn disabled_popup_menu_button_is_focusable_with_directional_navigation() {
3672        test_widgets(|tester| {
3673            assert!(disabled_button_takes_focus(
3674                tester,
3675                Some(NavigationMode::Directional)
3676            ));
3677        });
3678    }
3679
3680    #[test]
3681    fn popup_menu_item_on_tap_callback_is_called_when_defined() {
3682        test_widgets(|tester| {
3683            let counters = Rc::new(RefCell::new([0, 0]));
3684            let taps = Rc::clone(&counters);
3685            tester.pump_widget(test_app(TextDirection::Ltr, move || {
3686                let taps = Rc::clone(&taps);
3687                Material::new()
3688                    .child(
3689                        PopupMenuButton::<()>::new(move |_app, _context| {
3690                            let (first, second) = (Rc::clone(&taps), Rc::clone(&taps));
3691                            vec![
3692                                PopupMenuEntryRef::new(
3693                                    PopupMenuItem::new(Some(Text::new("First option"))).on_tap(
3694                                        Listener::new(move |_app| first.borrow_mut()[0] += 1),
3695                                    ),
3696                                ),
3697                                PopupMenuEntryRef::new(
3698                                    PopupMenuItem::new(Some(Text::new("Second option"))).on_tap(
3699                                        Listener::new(move |_app| second.borrow_mut()[1] += 1),
3700                                    ),
3701                                ),
3702                                PopupMenuEntryRef::new(PopupMenuItem::new(Some(Text::new(
3703                                    "Option without onTap",
3704                                )))),
3705                            ]
3706                        })
3707                        .child(Text::new("Actions")),
3708                    )
3709                    .into_widget()
3710            }));
3711
3712            for (option, expected) in [
3713                ("First option", [1, 0]),
3714                ("First option", [2, 0]),
3715                ("Second option", [2, 1]),
3716                ("Option without onTap", [2, 1]),
3717            ] {
3718                tester.tap(find::text("Actions"));
3719                tester.pump_and_settle();
3720                tester.tap(find::text(option));
3721                tester.pump_and_settle();
3722                assert_eq!(*counters.borrow(), expected);
3723            }
3724        });
3725    }
3726
3727    #[test]
3728    fn popup_menu_item_can_have_both_on_tap_and_value() {
3729        test_widgets(|tester| {
3730            let counters = Rc::new(RefCell::new([0, 0]));
3731            let selected: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
3732            let (taps, chosen) = (Rc::clone(&counters), Rc::clone(&selected));
3733            tester.pump_widget(test_app(TextDirection::Ltr, move || {
3734                let (taps, chosen) = (Rc::clone(&taps), Rc::clone(&chosen));
3735                Material::new()
3736                    .child(
3737                        PopupMenuButton::new(move |_app, _context| {
3738                            let (first, second) = (Rc::clone(&taps), Rc::clone(&taps));
3739                            vec![
3740                                PopupMenuEntryRef::new(
3741                                    PopupMenuItem::new(Some(Text::new("First option")))
3742                                        .value("first".to_owned())
3743                                        .on_tap(Listener::new(move |_app| {
3744                                            first.borrow_mut()[0] += 1
3745                                        })),
3746                                ),
3747                                PopupMenuEntryRef::new(
3748                                    PopupMenuItem::new(Some(Text::new("Second option")))
3749                                        .value("second".to_owned())
3750                                        .on_tap(Listener::new(move |_app| {
3751                                            second.borrow_mut()[1] += 1
3752                                        })),
3753                                ),
3754                                item("third".to_owned(), "Option without onTap"),
3755                            ]
3756                        })
3757                        .on_selected(move |_app, value: String| *chosen.borrow_mut() = Some(value))
3758                        .child(Text::new("Actions")),
3759                    )
3760                    .into_widget()
3761            }));
3762
3763            for (option, expected, value) in [
3764                ("First option", [1, 0], "first"),
3765                ("First option", [2, 0], "first"),
3766                ("Second option", [2, 1], "second"),
3767                ("Option without onTap", [2, 1], "third"),
3768            ] {
3769                tester.tap(find::text("Actions"));
3770                tester.pump_and_settle();
3771                tester.tap(find::text(option));
3772                tester.pump_and_settle();
3773                assert_eq!(*counters.borrow(), expected);
3774                assert_eq!(selected.borrow().as_deref(), Some(value));
3775            }
3776        });
3777    }
3778
3779    #[test]
3780    fn popup_menu_item_is_only_focusable_when_enabled() {
3781        test_widgets(|tester| {
3782            let popup_button_key = GlobalKey::new();
3783            let child_key = GlobalKey::new();
3784            let item_builder_called = Rc::new(Cell::new(false));
3785            let build = |tester: &mut WidgetTester, enabled: bool| {
3786                let (key, child_key, called) = (
3787                    popup_button_key.clone(),
3788                    child_key.clone(),
3789                    Rc::clone(&item_builder_called),
3790                );
3791                pump_app(tester, m3, move |_app| {
3792                    Material::new()
3793                        .child(Column::new().children(vec![
3794                            PopupMenuButton::new(move |_app, _context| {
3795                                called.set(true);
3796                                vec![PopupMenuEntryRef::new(
3797                                    PopupMenuItem::new(Some(
3798                                        Text::new("Tap me please!").key(child_key.clone().into()),
3799                                    ))
3800                                    .enabled(enabled)
3801                                    .value(1),
3802                                )]
3803                            })
3804                            .key(key.into())
3805                            .into_widget(),
3806                        ]))
3807                        .into_widget()
3808                });
3809            };
3810            let child_node = |tester: &WidgetTester| {
3811                let context = context_of(tester, &child_key);
3812                waft_widgets::Focus::of(&mut tester.cell.borrow_mut(), context, false, false)
3813            };
3814
3815            build(tester, true);
3816            // Open the popup to build and show the menu contents.
3817            tap_key(tester, &popup_button_key);
3818            tester.pump_and_settle();
3819            let node = child_node(tester);
3820            // Now that the contents are shown, request focus on the child text.
3821            node.request_focus(&mut tester.cell.borrow_mut(), None);
3822            tester.pump_and_settle();
3823            assert!(item_builder_called.get());
3824
3825            // Make sure that the focus went where we expected it to.
3826            assert!(node.has_primary_focus(&tester.cell.borrow()));
3827            item_builder_called.set(false);
3828
3829            // Close the popup.
3830            tap_key(tester, &popup_button_key);
3831            tester.pump_and_settle();
3832
3833            build(tester, false);
3834            tester.pump_and_settle();
3835            // Open the popup again to rebuild the contents with enabled == false.
3836            tap_key(tester, &popup_button_key);
3837            tester.pump_and_settle();
3838
3839            assert!(item_builder_called.get());
3840            let node = child_node(tester);
3841            assert!(!node.has_primary_focus(&tester.cell.borrow()));
3842        });
3843    }
3844
3845    /// Dart's `testPositioningDown` and `testPositioningDownThenUp` of 'PopupMenu
3846    /// positioning'.
3847    fn test_positioning(
3848        tester: &mut WidgetTester,
3849        text_direction: TextDirection,
3850        alignment: AlignmentGeometry,
3851        growth_direction: TextDirection,
3852        start_rect: Rect,
3853        then_up: bool,
3854    ) {
3855        // reset in case we had a menu up already
3856        tester.pump_widget(Container::new().into_widget());
3857        tester.pump_widget(test_app(text_direction, move || {
3858            Align::new()
3859                .alignment(alignment)
3860                .child(
3861                    PopupMenuButton::new(|_app, _context| {
3862                        vec![item(1, "AAA"), item(2, "BBB"), item(3, "CCC")]
3863                    })
3864                    .child(
3865                        SizedBox::new()
3866                            .height(100.0)
3867                            .width(100.0)
3868                            .child(Text::new("XXX")),
3869                    ),
3870                )
3871                .into_widget()
3872        }));
3873        tester.tap(find::text("XXX"));
3874        tester.pump();
3875
3876        let mut rect = rect_of::<PopupMenu<i32>>(tester);
3877        assert_f32_equals(rect, start_rect);
3878        let mut done_vertically = false;
3879        let mut vertical_stage = 0; // 0=down, 1=up, 2=done
3880        let mut done_horizontally = false;
3881        loop {
3882            tester.pump_by(Duration::from_millis(20));
3883            let new_rect = rect_of::<PopupMenu<i32>>(tester);
3884            if then_up {
3885                match vertical_stage {
3886                    0 if new_rect.top < rect.top => {
3887                        vertical_stage = 1;
3888                        assert!(new_rect.bottom >= rect.bottom);
3889                    }
3890                    0 => {
3891                        assert_f32_equals(new_rect.top, rect.top);
3892                        assert!(new_rect.bottom > rect.bottom);
3893                    }
3894                    1 if near(new_rect.top, rect.top) => {
3895                        vertical_stage = 2;
3896                        assert_f32_equals(new_rect.bottom, rect.bottom);
3897                    }
3898                    1 => {
3899                        assert!(new_rect.top < rect.top);
3900                        assert_f32_equals(new_rect.bottom, rect.bottom);
3901                    }
3902                    _ => {
3903                        assert_f32_equals(new_rect.bottom, rect.bottom);
3904                        assert_f32_equals(new_rect.top, rect.top);
3905                    }
3906                }
3907            } else {
3908                assert_f32_equals(new_rect.top, rect.top);
3909                if done_vertically {
3910                    assert_f32_equals(new_rect.bottom, rect.bottom);
3911                } else if near(new_rect.bottom, rect.bottom) {
3912                    done_vertically = true;
3913                } else {
3914                    assert!(new_rect.bottom > rect.bottom);
3915                }
3916            }
3917            match growth_direction {
3918                TextDirection::Rtl => {
3919                    assert_f32_equals(new_rect.right, rect.right);
3920                    if done_horizontally {
3921                        assert_f32_equals(new_rect.left, rect.left);
3922                    } else if near(new_rect.left, rect.left) {
3923                        done_horizontally = true;
3924                    } else {
3925                        assert!(new_rect.left < rect.left);
3926                    }
3927                }
3928                TextDirection::Ltr => {
3929                    assert_f32_equals(new_rect.left, rect.left);
3930                    if done_horizontally {
3931                        assert_f32_equals(new_rect.right, rect.right);
3932                    } else if near(new_rect.right, rect.right) {
3933                        done_horizontally = true;
3934                    } else {
3935                        assert!(new_rect.right > rect.right);
3936                    }
3937                }
3938            }
3939            rect = new_rect;
3940            if !has_scheduled_frame(tester) {
3941                break;
3942            }
3943        }
3944    }
3945
3946    #[test]
3947    fn popup_menu_positioning() {
3948        use TextDirection::{Ltr, Rtl};
3949        test_widgets(|tester| {
3950            let cases = [
3951                (Ltr, AlignmentGeometry::TOP_RIGHT, Rtl, 792.0, 8.0, false),
3952                (Rtl, AlignmentGeometry::TOP_RIGHT, Rtl, 792.0, 8.0, false),
3953                (Ltr, AlignmentGeometry::TOP_LEFT, Ltr, 8.0, 8.0, false),
3954                (Rtl, AlignmentGeometry::TOP_LEFT, Ltr, 8.0, 8.0, false),
3955                (Ltr, AlignmentGeometry::TOP_CENTER, Ltr, 350.0, 8.0, false),
3956                (Rtl, AlignmentGeometry::TOP_CENTER, Rtl, 450.0, 8.0, false),
3957                (
3958                    Ltr,
3959                    AlignmentGeometry::CENTER_RIGHT,
3960                    Rtl,
3961                    792.0,
3962                    250.0,
3963                    false,
3964                ),
3965                (
3966                    Rtl,
3967                    AlignmentGeometry::CENTER_RIGHT,
3968                    Rtl,
3969                    792.0,
3970                    250.0,
3971                    false,
3972                ),
3973                (Ltr, AlignmentGeometry::CENTER_LEFT, Ltr, 8.0, 250.0, false),
3974                (Rtl, AlignmentGeometry::CENTER_LEFT, Ltr, 8.0, 250.0, false),
3975                (Ltr, AlignmentGeometry::CENTER, Ltr, 350.0, 250.0, false),
3976                (Rtl, AlignmentGeometry::CENTER, Rtl, 450.0, 250.0, false),
3977                (
3978                    Ltr,
3979                    AlignmentGeometry::BOTTOM_RIGHT,
3980                    Rtl,
3981                    792.0,
3982                    500.0,
3983                    true,
3984                ),
3985                (
3986                    Rtl,
3987                    AlignmentGeometry::BOTTOM_RIGHT,
3988                    Rtl,
3989                    792.0,
3990                    500.0,
3991                    true,
3992                ),
3993                (Ltr, AlignmentGeometry::BOTTOM_LEFT, Ltr, 8.0, 500.0, true),
3994                (Rtl, AlignmentGeometry::BOTTOM_LEFT, Ltr, 8.0, 500.0, true),
3995                (
3996                    Ltr,
3997                    AlignmentGeometry::BOTTOM_CENTER,
3998                    Ltr,
3999                    350.0,
4000                    500.0,
4001                    true,
4002                ),
4003                (
4004                    Rtl,
4005                    AlignmentGeometry::BOTTOM_CENTER,
4006                    Rtl,
4007                    450.0,
4008                    500.0,
4009                    true,
4010                ),
4011            ];
4012            for (text_direction, alignment, growth_direction, x, y, then_up) in cases {
4013                test_positioning(
4014                    tester,
4015                    text_direction,
4016                    alignment,
4017                    growth_direction,
4018                    Rect::from_ltwh(x, y, 0.0, 0.0),
4019                    then_up,
4020                );
4021            }
4022        });
4023    }
4024
4025    #[test]
4026    fn popup_menu_offset_test() {
4027        test_widgets(|tester| {
4028            let build_menu_button = |offset: Offset| {
4029                Material::new()
4030                    .child(
4031                        PopupMenuButton::new(|_app, _context| {
4032                            vec![PopupMenuEntryRef::new(
4033                                PopupMenuItem::new(Some(Builder::new(|_app, _context| {
4034                                    Text::new("AAA").into_widget()
4035                                })))
4036                                .value(1),
4037                            )]
4038                        })
4039                        .offset(offset),
4040                    )
4041                    .into_widget()
4042            };
4043            let in_scaffold = |tester: &mut WidgetTester, body: WidgetRef| {
4044                pump_app(tester, m3, move |_app| {
4045                    crate::scaffold::Scaffold::new().body(body).into_widget()
4046                });
4047            };
4048            let icon_button_center = |tester: &WidgetTester| {
4049                tester
4050                    .get_rect(tester.render_box_of(tester.element(find::by_type::<IconButton>())))
4051                    .center()
4052            };
4053
4054            // Popup a menu without any offset.
4055            in_scaffold(tester, build_menu_button(Offset::ZERO));
4056
4057            // Popup the menu.
4058            let center = icon_button_center(tester);
4059            tester.tap_at(center, 1);
4060            tester.pump_and_settle();
4061
4062            // Initial state, the menu start at Offset(8.0, 8.0), the 8 pixels is edge padding
4063            // when offset.dx < 8.0.
4064            assert_f32_equals(
4065                rect_of::<PopupMenu<i32>>(tester).top_left(),
4066                Offset::new(8.0, 8.0),
4067            );
4068
4069            // Collapse the menu.
4070            tester.tap_at(center, 1);
4071            tester.pump_and_settle();
4072
4073            // Popup a new menu with Offset(50.0, 50.0).
4074            in_scaffold(tester, build_menu_button(Offset::new(50.0, 50.0)));
4075
4076            tester.tap_at(center, 1);
4077            tester.pump_and_settle();
4078
4079            // This time the menu should start at Offset(50.0, 50.0), the padding only added
4080            // when offset.dx < 8.0.
4081            assert_f32_equals(
4082                rect_of::<PopupMenu<i32>>(tester).top_left(),
4083                Offset::new(50.0, 50.0),
4084            );
4085        });
4086    }
4087
4088    #[test]
4089    fn popup_menu_button_popup_menu_divider() {
4090        // Regression test for https://github.com/flutter/flutter/issues/27072
4091        test_widgets(|tester| {
4092            let selected_value: Rc<RefCell<String>> = Rc::default();
4093            let chosen = Rc::clone(&selected_value);
4094            centered_in_scaffold(tester, m3, move || {
4095                PopupMenuButton::new(|_app, _context| {
4096                    vec![
4097                        item("1".to_owned(), "1"),
4098                        PopupMenuEntryRef::new(PopupMenuDivider::new()),
4099                        item("2".to_owned(), "2"),
4100                    ]
4101                })
4102                .on_selected(move |_app, result: String| *chosen.borrow_mut() = result)
4103                .initial_value("1".to_owned())
4104                .child(Text::new("Menu Button"))
4105                .into_widget()
4106            });
4107
4108            for value in ["1", "2"] {
4109                tester.tap(find::text("Menu Button"));
4110                tester.pump_and_settle();
4111                assert!(shows(tester, "1"));
4112                expect(
4113                    tester,
4114                    &find::by_type::<PopupMenuDivider>(),
4115                    finds_one_widget(),
4116                );
4117                assert!(shows(tester, "2"));
4118
4119                tester.tap(find::text(value));
4120                tester.pump_and_settle();
4121                assert_eq!(*selected_value.borrow(), value);
4122            }
4123        });
4124    }
4125
4126    #[test]
4127    fn popup_menu_item_child_height_is_a_minimum_child_is_vertically_centered() {
4128        test_widgets(|tester| {
4129            let popup_menu_button_key = GlobalKey::new();
4130            let key = popup_menu_button_key.clone();
4131            centered_in_scaffold(tester, m3, move || {
4132                PopupMenuButton::new(|_app, _context| {
4133                    vec![
4134                        // This menu item's height will be 48 because the default minimum height
4135                        // is 48 and the height of the text is less than 48.
4136                        item("0".to_owned(), "Item 0"),
4137                        // This menu item's height parameter specifies its minimum height. The
4138                        // overall height of the menu item will be 50 because the child's
4139                        // height 40, is less than 50.
4140                        PopupMenuEntryRef::new(
4141                            PopupMenuItem::new(Some(
4142                                SizedBox::new().height(40.0).child(Text::new("Item 1")),
4143                            ))
4144                            .height(50.0)
4145                            .value("1".to_owned()),
4146                        ),
4147                        // This menu item's height parameter specifies its minimum height, so
4148                        // the overall height of the menu item will be 75.
4149                        PopupMenuEntryRef::new(
4150                            PopupMenuItem::new(Some(SizedBox::new().child(Text::new("Item 2"))))
4151                                .height(75.0)
4152                                .value("2".to_owned()),
4153                        ),
4154                        // This menu item's height will be 100.
4155                        PopupMenuEntryRef::new(
4156                            PopupMenuItem::new(Some(
4157                                SizedBox::new().height(100.0).child(Text::new("Item 3")),
4158                            ))
4159                            .value("3".to_owned()),
4160                        ),
4161                    ]
4162                })
4163                .key(key.into())
4164                .child(Text::new("button"))
4165                .on_selected(|_app, _result: String| {})
4166                .into_widget()
4167            });
4168
4169            // Show the menu
4170            tap_key(tester, &popup_menu_button_key);
4171            tester.pump_and_settle();
4172
4173            // The menu items and their InkWells should have the expected vertical size
4174            for (text, height) in [
4175                ("Item 0", 48.0),
4176                ("Item 1", 50.0),
4177                ("Item 2", 75.0),
4178                ("Item 3", 100.0),
4179            ] {
4180                assert_eq!(
4181                    rect_with_text::<PopupMenuItem<String>>(tester, text).height(),
4182                    height
4183                );
4184                assert_eq!(rect_with_text::<InkWell>(tester, text).height(), height);
4185            }
4186
4187            // Menu item children which whose height is less than the PopupMenuItem
4188            // are vertically centered.
4189            for text in ["Item 0", "Item 2"] {
4190                assert_f32_equals(
4191                    rect_with_text::<PopupMenuItem<String>>(tester, text)
4192                        .center()
4193                        .dy(),
4194                    tester.get_rect(find::text(text)).center().dy(),
4195                );
4196            }
4197        });
4198    }
4199
4200    /// A button showing `items` in the scaffold's centre, keyed `key`, with a `Text('button')`
4201    /// child: the tree of Dart's padding and height cases.
4202    fn keyed_text_button(
4203        tester: &mut WidgetTester,
4204        theme: impl FnOnce(&App) -> ThemeData,
4205        key: &GlobalKey,
4206        items: impl Fn() -> Vec<PopupMenuEntryRef<String>> + 'static,
4207    ) {
4208        let key = key.clone();
4209        centered_in_scaffold(tester, theme, move || {
4210            PopupMenuButton::new(move |_app, _context| items())
4211                .key(key.into())
4212                .child(Text::new("button"))
4213                .on_selected(|_app, _result: String| {})
4214                .into_widget()
4215        });
4216    }
4217
4218    fn disabled_and_enabled_items() -> Vec<PopupMenuEntryRef<String>> {
4219        vec![
4220            PopupMenuEntryRef::new(
4221                PopupMenuItem::new(Some(Text::new("Item 0")))
4222                    .value("0".to_owned())
4223                    .enabled(false),
4224            ),
4225            item("1".to_owned(), "Item 1"),
4226        ]
4227    }
4228
4229    /// Dart's `tester.widget<Padding>(find.widgetWithText(Padding, text).first).padding`: the
4230    /// `Padding` nearest above the text, as Dart's ancestor finder lists the nearest first.
4231    fn nearest_padding_of(tester: &WidgetTester, text: &str) -> EdgeInsetsGeometry {
4232        let padding = widget_with_text::<Padding>(tester, text);
4233        tester.widget(padding, |padding: &Padding| padding.padding)
4234    }
4235
4236    /// Dart's padding of the `ConstrainedBox` whose child is a `Padding`, above `text`.
4237    fn item_padding_of<W: 'static>(tester: &WidgetTester, text: &str) -> EdgeInsetsGeometry {
4238        let text_element = tester.element(find::text(text));
4239        let item = tester.ancestor_of_type::<W>(text_element);
4240        let constrained = tester
4241            .descendants_of_type::<ConstrainedBox>(item)
4242            .into_iter()
4243            .find(|constrained| {
4244                let app = tester.cell.borrow();
4245                let widget =
4246                    waft_widgets::downcast_widget::<ConstrainedBox>(&**constrained.widget(&app))
4247                        .expect("found by type");
4248                widget.child.as_ref().is_some_and(|child| {
4249                    waft_widgets::downcast_widget::<Padding>(&**child).is_some()
4250                })
4251            })
4252            .expect("a ConstrainedBox around the item's Padding");
4253        let app = tester.cell.borrow();
4254        let widget = waft_widgets::downcast_widget::<ConstrainedBox>(&**constrained.widget(&app))
4255            .expect("found");
4256        waft_widgets::downcast_widget::<Padding>(&**widget.child.as_ref().expect("a child"))
4257            .expect("a Padding")
4258            .padding
4259    }
4260
4261    /// Dart's `tester.widget<SingleChildScrollView>(find.byType(SingleChildScrollView)).padding`.
4262    fn menu_padding(tester: &WidgetTester) -> Option<EdgeInsetsGeometry> {
4263        let scroll_view = tester.element(find::by_type::<SingleChildScrollView>());
4264        tester.widget(scroll_view, |scroll_view: &SingleChildScrollView| {
4265            scroll_view.padding
4266        })
4267    }
4268
4269    #[test]
4270    fn material3_popup_menu_item_default_padding() {
4271        test_widgets(|tester| {
4272            let key = GlobalKey::new();
4273            keyed_text_button(tester, m3, &key, disabled_and_enabled_items);
4274
4275            // Show the menu.
4276            tap_key(tester, &key);
4277            tester.pump_and_settle();
4278
4279            // Dart's `paddingFor` reads 'Item 0' for both.
4280            assert_eq!(
4281                nearest_padding_of(tester, "Item 0"),
4282                EdgeInsetsGeometry::symmetric(0.0, 12.0)
4283            );
4284            assert_eq!(
4285                nearest_padding_of(tester, "Item 0"),
4286                EdgeInsetsGeometry::symmetric(0.0, 12.0)
4287            );
4288        });
4289    }
4290
4291    #[test]
4292    fn material2_popup_menu_item_default_padding() {
4293        test_widgets(|tester| {
4294            let key = GlobalKey::new();
4295            keyed_text_button(tester, m2, &key, disabled_and_enabled_items);
4296
4297            // Show the menu.
4298            tap_key(tester, &key);
4299            tester.pump_and_settle();
4300
4301            assert_eq!(
4302                nearest_padding_of(tester, "Item 0"),
4303                EdgeInsetsGeometry::symmetric(0.0, 16.0)
4304            );
4305            assert_eq!(
4306                nearest_padding_of(tester, "Item 0"),
4307                EdgeInsetsGeometry::symmetric(0.0, 16.0)
4308            );
4309        });
4310    }
4311
4312    /// Dart's 'PopupMenu default padding' and the second 'Material2 - PopupMenuItem default
4313    /// padding'.
4314    fn default_menu_padding(tester: &mut WidgetTester, theme: fn(&App) -> ThemeData) {
4315        let key = GlobalKey::new();
4316        keyed_text_button(tester, theme, &key, disabled_and_enabled_items);
4317
4318        // Show the menu.
4319        tap_key(tester, &key);
4320        tester.pump_by(Duration::from_millis(300));
4321
4322        // Check popup menu padding.
4323        assert_eq!(
4324            menu_padding(tester),
4325            Some(EdgeInsetsGeometry::symmetric(8.0, 0.0))
4326        );
4327    }
4328
4329    #[test]
4330    fn popup_menu_default_padding() {
4331        test_widgets(|tester| default_menu_padding(tester, m3));
4332    }
4333
4334    #[test]
4335    fn material2_popup_menu_default_padding() {
4336        test_widgets(|tester| default_menu_padding(tester, m2));
4337    }
4338
4339    #[test]
4340    fn popup_menu_item_custom_padding() {
4341        test_widgets(|tester| {
4342            let key = GlobalKey::new();
4343            keyed_text_button(tester, m2, &key, || {
4344                let custom = |text: &str, padding: EdgeInsets, height: Option<f64>| {
4345                    let item = PopupMenuItem::new(Some(Text::new(text)))
4346                        .padding(padding)
4347                        .value("0".to_owned());
4348                    PopupMenuEntryRef::new(match height {
4349                        Some(height) => item.height(height),
4350                        None => item,
4351                    })
4352                };
4353                vec![
4354                    custom("Item 0", EdgeInsets::ZERO, None),
4355                    custom("Item 1", EdgeInsets::ZERO, Some(0.0)),
4356                    custom("Item 2", EdgeInsets::all(20.0), None),
4357                    custom("Item 3", EdgeInsets::all(20.0), Some(100.0)),
4358                ]
4359            });
4360
4361            // Show the menu
4362            tap_key(tester, &key);
4363            tester.pump_and_settle();
4364
4365            // The menu items and their InkWells should have the expected vertical size
4366            // given the interactions between heights and padding.
4367            for (text, height) in [
4368                ("Item 0", 48.0),  // Minimum interactive height (48)
4369                ("Item 1", 16.0),  // Height of text (16)
4370                ("Item 2", 56.0),  // Padding (20.0 + 20.0) + Height of text (16) = 56
4371                ("Item 3", 100.0), // Height value of 100, since child (16) + padding (40) < 100
4372            ] {
4373                assert_eq!(
4374                    rect_with_text::<PopupMenuItem<String>>(tester, text).height(),
4375                    height,
4376                    "{text}"
4377                );
4378            }
4379
4380            for (text, padding) in [
4381                ("Item 0", EdgeInsetsGeometry::ZERO),
4382                ("Item 1", EdgeInsetsGeometry::ZERO),
4383                ("Item 2", EdgeInsetsGeometry::all(20.0)),
4384                ("Item 3", EdgeInsetsGeometry::all(20.0)),
4385            ] {
4386                assert_eq!(
4387                    item_padding_of::<PopupMenuItem<String>>(tester, text),
4388                    padding
4389                );
4390            }
4391        });
4392    }
4393
4394    #[test]
4395    fn checked_popup_menu_item_child_height_is_a_minimum_child_is_vertically_centered() {
4396        test_widgets(|tester| {
4397            let key = GlobalKey::new();
4398            keyed_text_button(tester, m3, &key, || {
4399                let checked = |text: &str, value: &str, height: Option<f64>, child: SizedBox| {
4400                    let item = CheckedPopupMenuItem::new()
4401                        .checked(true)
4402                        .value(value.to_owned())
4403                        .child(child.child(Text::new(text)));
4404                    PopupMenuEntryRef::new(match height {
4405                        Some(height) => item.height(height),
4406                        None => item,
4407                    })
4408                };
4409                vec![
4410                    // This menu item's height will be 56.0 because the default minimum height
4411                    // is 48, but the contents of PopupMenuItem are 56.0 tall.
4412                    PopupMenuEntryRef::new(
4413                        CheckedPopupMenuItem::new()
4414                            .checked(true)
4415                            .value("0".to_owned())
4416                            .child(Text::new("Item 0")),
4417                    ),
4418                    // This menu item's height parameter specifies its minimum height. The
4419                    // overall height of the menu item will be 60 because the child's
4420                    // height 56, is less than 60.
4421                    checked("Item 1", "1", Some(60.0), SizedBox::new().height(40.0)),
4422                    // This menu item's height parameter specifies its minimum height, so the
4423                    // overall height of the menu item will be 75.
4424                    checked("Item 2", "2", Some(75.0), SizedBox::new()),
4425                    // This menu item's height will be 100.
4426                    checked("Item 3", "3", Some(100.0), SizedBox::new()),
4427                ]
4428            });
4429
4430            // Show the menu
4431            tap_key(tester, &key);
4432            tester.pump_and_settle();
4433
4434            // The menu items and their InkWells should have the expected vertical size
4435            for (text, height) in [
4436                ("Item 0", 56.0),
4437                ("Item 1", 60.0),
4438                ("Item 2", 75.0),
4439                ("Item 3", 100.0),
4440            ] {
4441                assert_eq!(
4442                    rect_with_text::<CheckedPopupMenuItem<String>>(tester, text).height(),
4443                    height,
4444                    "{text}"
4445                );
4446                // We evaluate the InkWell at the first index because that is the ListTile's
4447                // InkWell, which wins in the gesture arena over the child's InkWell and
4448                // is the one of interest.
4449                let ink_wells: Vec<AnyElement> = tester
4450                    .ancestors(tester.element(find::text(text)))
4451                    .into_iter()
4452                    .filter(|ancestor| {
4453                        waft_widgets::downcast_widget::<InkWell>(
4454                            &**ancestor.widget(&tester.cell.borrow()),
4455                        )
4456                        .is_some()
4457                    })
4458                    .collect();
4459                assert_eq!(ink_wells.len(), 2);
4460                let outer = ink_wells[1];
4461                assert_eq!(
4462                    tester.get_rect(tester.render_box_of(outer)).height(),
4463                    height,
4464                    "{text}"
4465                );
4466            }
4467
4468            // Menu item children which whose height is less than the PopupMenuItem
4469            // are vertically centered.
4470            for text in ["Item 0", "Item 2"] {
4471                assert_f32_equals(
4472                    rect_with_text::<CheckedPopupMenuItem<String>>(tester, text)
4473                        .center()
4474                        .dy(),
4475                    tester.get_rect(find::text(text)).center().dy(),
4476                );
4477            }
4478        });
4479    }
4480
4481    #[test]
4482    fn checked_popup_menu_item_custom_padding() {
4483        test_widgets(|tester| {
4484            let key = GlobalKey::new();
4485            keyed_text_button(tester, m3, &key, || {
4486                let custom = |text: &str, padding: EdgeInsets, height: Option<f64>| {
4487                    let item = CheckedPopupMenuItem::new()
4488                        .padding(padding)
4489                        .value("0".to_owned())
4490                        .child(Text::new(text));
4491                    PopupMenuEntryRef::new(match height {
4492                        Some(height) => item.height(height),
4493                        None => item,
4494                    })
4495                };
4496                vec![
4497                    custom("Item 0", EdgeInsets::ZERO, None),
4498                    custom("Item 1", EdgeInsets::ZERO, Some(0.0)),
4499                    custom("Item 2", EdgeInsets::all(20.0), None),
4500                    custom("Item 3", EdgeInsets::all(20.0), Some(100.0)),
4501                ]
4502            });
4503
4504            // Show the menu
4505            tap_key(tester, &key);
4506            tester.pump_and_settle();
4507
4508            // The menu items and their InkWells should have the expected vertical size
4509            // given the interactions between heights and padding.
4510            for (text, height) in [
4511                ("Item 0", 56.0),  // Minimum ListTile height (56)
4512                ("Item 1", 56.0),  // Minimum ListTile height (56)
4513                ("Item 2", 96.0),  // Padding (20.0 + 20.0) + Height of ListTile (56) = 96
4514                ("Item 3", 100.0), // Height value of 100, since child (56) + padding (40) < 100
4515            ] {
4516                assert_eq!(
4517                    rect_with_text::<CheckedPopupMenuItem<String>>(tester, text).height(),
4518                    height,
4519                    "{text}"
4520                );
4521            }
4522
4523            for (text, padding) in [
4524                ("Item 0", EdgeInsetsGeometry::ZERO),
4525                ("Item 1", EdgeInsetsGeometry::ZERO),
4526                ("Item 2", EdgeInsetsGeometry::all(20.0)),
4527                ("Item 3", EdgeInsetsGeometry::all(20.0)),
4528            ] {
4529                assert_eq!(
4530                    item_padding_of::<CheckedPopupMenuItem<String>>(tester, text),
4531                    padding
4532                );
4533            }
4534        });
4535    }
4536
4537    #[test]
4538    fn update_popup_menu_item_layout_while_the_menu_is_visible() {
4539        test_widgets(|tester| {
4540            let key = GlobalKey::new();
4541            let build_frame =
4542                |tester: &mut WidgetTester, text_direction: TextDirection, font_size: f64| {
4543                    let key = key.clone();
4544                    let root = {
4545                        let app = tester.cell.borrow();
4546                        crate::app::MaterialApp::new()
4547                            .theme(m2(&app))
4548                            .builder(move |app, context, child| {
4549                                let title_medium = Theme::of(app, context)
4550                                    .text_theme
4551                                    .title_medium
4552                                    .clone()
4553                                    .expect("titleMedium");
4554                                Directionality::new(
4555                                    text_direction,
4556                                    PopupMenuTheme::new(
4557                                        PopupMenuTheme::of(app, context).copy_with().text_style(
4558                                            title_medium.copy_with().font_size(font_size),
4559                                        ),
4560                                        child.expect("a navigator").clone(),
4561                                    ),
4562                                )
4563                                .into_widget()
4564                            })
4565                            .home(
4566                                crate::scaffold::Scaffold::new()
4567                                    .body(
4568                                        PopupMenuButton::new(|_app, _context| {
4569                                            vec![
4570                                                item("0".to_owned(), "Item 0"),
4571                                                item("1".to_owned(), "Item 1"),
4572                                            ]
4573                                        })
4574                                        .key(key.into())
4575                                        .child(Text::new("button"))
4576                                        .on_selected(|_app, _result: String| {}),
4577                                    )
4578                                    .into_widget(),
4579                            )
4580                            .into_widget()
4581                    };
4582                    tester.pump_widget(root);
4583                };
4584
4585            // Show the menu
4586            build_frame(tester, TextDirection::Ltr, 24.0);
4587            tap_key(tester, &key);
4588            tester.pump_and_settle();
4589
4590            // The menu items should have their default heights and horizontal alignment.
4591            for text in ["Item 0", "Item 1"] {
4592                assert_eq!(
4593                    rect_with_text::<PopupMenuItem<String>>(tester, text).height(),
4594                    48.0
4595                );
4596                assert_f32_equals(tester.get_rect(find::text(text)).left, 24.0);
4597            }
4598
4599            // While the menu is up, change its font size to 64 (default is 16).
4600            build_frame(tester, TextDirection::Ltr, 64.0);
4601            tester.pump_and_settle(); // Theme changes are animated.
4602            for text in ["Item 0", "Item 1"] {
4603                assert_eq!(
4604                    rect_with_text::<PopupMenuItem<String>>(tester, text).height(),
4605                    128.0
4606                );
4607                assert_eq!(tester.get_rect(find::text(text)).height(), 128.0);
4608                assert_f32_equals(tester.get_rect(find::text(text)).left, 24.0);
4609            }
4610
4611            // While the menu is up, change the textDirection to rtl. Now menu items
4612            // will be aligned right.
4613            build_frame(tester, TextDirection::Rtl, 24.0);
4614            tester.pump_and_settle(); // Theme changes are animated.
4615            for text in ["Item 0", "Item 1"] {
4616                assert_eq!(
4617                    rect_with_text::<PopupMenuItem<String>>(tester, text).height(),
4618                    48.0
4619                );
4620                assert_f32_equals(tester.get_rect(find::text(text)).left, 72.0);
4621            }
4622        });
4623    }
4624
4625    #[test]
4626    #[should_panic(expected = "You can only pass [child] or [icon], not both.")]
4627    fn popup_menu_buttons_child_and_icon_properties_cannot_be_simultaneously_defined() {
4628        PopupMenuButton::<i32>::new(|_app, _context| Vec::new())
4629            .icon(Icon::new(Some(Icons::error())))
4630            .child(Container::new())
4631            .into_widget();
4632    }
4633
4634    /// Dart's 'PopupMenuButton default tooltip' and 'custom tooltip'.
4635    fn three_buttons_tooltips(
4636        tester: &mut WidgetTester,
4637        tooltip: Option<&'static str>,
4638    ) -> Vec<Option<String>> {
4639        pump_app(tester, m3, move |_app| {
4640            let with_tooltip = |button: PopupMenuButton<i32>| match tooltip {
4641                Some(tooltip) => button.tooltip(tooltip),
4642                None => button,
4643            };
4644            let items = |_app: &mut App, _context: BuildContext| vec![item(1, "Tap me please!")];
4645            Material::new()
4646                .child(Column::new().children(vec![
4647                    // Tooltip should be present when [PopupMenuButton.icon]
4648                    // and [PopupMenuButton.child] are undefined.
4649                    with_tooltip(PopupMenuButton::new(items)).into_widget(),
4650                    // Tooltip should be present when [PopupMenuButton.child] is defined.
4651                    with_tooltip(PopupMenuButton::new(items))
4652                        .child(Text::new("Test text"))
4653                        .into_widget(),
4654                    // Tooltip should be present when [PopupMenuButton.icon] is defined.
4655                    with_tooltip(PopupMenuButton::new(items))
4656                        .icon(Icon::new(Some(Icons::check())))
4657                        .into_widget(),
4658                ]))
4659                .into_widget()
4660        });
4661        find::by_type::<Tooltip>()
4662            .evaluate(tester)
4663            .into_iter()
4664            .map(|tooltip| tester.widget(tooltip, |tooltip: &Tooltip| tooltip.message.clone()))
4665            .collect()
4666    }
4667
4668    #[test]
4669    fn popup_menu_button_default_tooltip() {
4670        test_widgets(|tester| {
4671            // The default tooltip is defined as [MaterialLocalizations.showMenuTooltip]
4672            // and it is used when no tooltip is provided.
4673            let expected = DefaultMaterialLocalizations.show_menu_tooltip();
4674            assert_eq!(
4675                three_buttons_tooltips(tester, None),
4676                vec![Some(expected); 3]
4677            );
4678        });
4679    }
4680
4681    #[test]
4682    fn popup_menu_button_custom_tooltip() {
4683        test_widgets(|tester| {
4684            assert_eq!(
4685                three_buttons_tooltips(tester, Some("Test tooltip")),
4686                vec![Some("Test tooltip".to_owned()); 3]
4687            );
4688        });
4689    }
4690
4691    #[test]
4692    fn allow_widget_for_popup_menu_button_icon() {
4693        test_widgets(|tester| {
4694            pump_app(tester, m3, |_app| {
4695                Material::new()
4696                    .child(
4697                        PopupMenuButton::new(|_app, _context| vec![item(1, "Tap me please!")])
4698                            .tooltip("Test tooltip")
4699                            .icon(Text::new("PopupMenuButton icon")),
4700                    )
4701                    .into_widget()
4702            });
4703
4704            expect(
4705                tester,
4706                &find::text("PopupMenuButton icon"),
4707                finds_one_widget(),
4708            );
4709        });
4710    }
4711
4712    /// Dart's 'showMenu uses nested navigator by default' and 'uses root navigator if
4713    /// useRootNavigator is true': whether the menu's route is the nested navigator's, which
4714    /// Dart's `MenuObserver`s count.
4715    fn menu_is_in_nested_navigator(tester: &mut WidgetTester, use_root_navigator: bool) -> bool {
4716        let nested_key = GlobalKey::new();
4717        let button_key = GlobalKey::new();
4718        let (nested, button) = (nested_key.clone(), button_key.clone());
4719        pump_app(tester, m3, move |_app| {
4720            Navigator::new()
4721                .key(nested.into())
4722                .on_generate_route(move |app, _settings| {
4723                    let button = button.clone();
4724                    let route = MaterialPageRoute::new(
4725                        app,
4726                        Rc::new(move |_app, context| {
4727                            crate::elevated_button::ElevatedButton::new(
4728                                Some(Listener::new(move |app| {
4729                                    drop(
4730                                        ShowMenu::new(vec![item(1, "1")])
4731                                            .position(RelativeRect::FILL)
4732                                            .use_root_navigator(use_root_navigator)
4733                                            .show(app, context),
4734                                    );
4735                                })),
4736                                Some(Text::new("Show Menu")),
4737                            )
4738                            .key(button.clone().into())
4739                            .into_widget()
4740                        }),
4741                    );
4742                    Some(route.erase())
4743                })
4744                .into_widget()
4745        });
4746
4747        // Open the dialog.
4748        tap_key(tester, &button_key);
4749        tester.pump();
4750
4751        let menu = tester.element(find::by_type::<PopupMenu<i32>>());
4752        let nested = nested_key
4753            .current_context(&tester.cell.borrow())
4754            .expect("the nested navigator is mounted");
4755        tester.ancestors(menu).contains(&nested)
4756    }
4757
4758    #[test]
4759    fn show_menu_uses_nested_navigator_by_default() {
4760        test_widgets(|tester| assert!(menu_is_in_nested_navigator(tester, false)));
4761    }
4762
4763    #[test]
4764    fn show_menu_uses_root_navigator_if_use_root_navigator_is_true() {
4765        test_widgets(|tester| assert!(!menu_is_in_nested_navigator(tester, true)));
4766    }
4767
4768    #[test]
4769    fn popup_menu_button_calling_show_button_menu_manually() {
4770        test_widgets(|tester| {
4771            let global_key = GlobalKey::new();
4772            let key = global_key.clone();
4773            pump_app(tester, m3, move |_app| {
4774                Material::new()
4775                    .child(Column::new().children(vec![
4776                        PopupMenuButton::new(|_app, _context| vec![item(1, "Tap me please!")])
4777                            .key(key.into())
4778                            .into_widget(),
4779                    ]))
4780                    .into_widget()
4781            });
4782
4783            assert!(!shows(tester, "Tap me please!"));
4784
4785            let state = global_key
4786                .current_state::<PopupMenuButtonState<i32>>(&tester.cell.borrow())
4787                .expect("the button is mounted");
4788            state.show_button_menu(&mut tester.cell.borrow_mut());
4789            // The PopupMenuItem will appear after an animation, hence,
4790            // we have to first wait for the tester to settle.
4791            tester.pump_and_settle();
4792
4793            assert!(shows(tester, "Tap me please!"));
4794        });
4795    }
4796
4797    /// Dart's `MaterialApp(builder: (context, child) => MediaQuery(data: data, child: child!),
4798    /// theme: theme, home: home)`.
4799    fn app_under_media_query(
4800        tester: &mut WidgetTester,
4801        theme: impl FnOnce(&App) -> ThemeData,
4802        data: MediaQueryData,
4803        home: WidgetRef,
4804    ) {
4805        let root = {
4806            let app = tester.cell.borrow();
4807            crate::app::MaterialApp::new()
4808                .theme(theme(&app))
4809                .builder(move |_app, _context, child| {
4810                    MediaQuery::new(data.clone(), child.expect("a navigator").clone()).into_widget()
4811                })
4812                .home(home)
4813                .into_widget()
4814        };
4815        tester.pump_widget(root);
4816    }
4817
4818    /// Dart's `tester.getRect(find.byType(SingleChildScrollView))`.
4819    fn scroll_view_rect(tester: &WidgetTester) -> Rect {
4820        rect_of::<SingleChildScrollView>(tester)
4821    }
4822
4823    #[test]
4824    fn popup_menu_button_has_expected_default_mouse_cursor_on_hover() {
4825        test_widgets(|tester| {
4826            let key = GlobalKey::new();
4827            let button_key = key.clone();
4828            centered_in_scaffold(tester, m3, move || {
4829                PopupMenuButton::new(|_app, _context| {
4830                    vec![item("a".to_owned(), "A"), item("b".to_owned(), "B")]
4831                })
4832                .key(button_key.into())
4833                .into_widget()
4834            });
4835
4836            let mut gesture = TestPointer::mouse(1, 0);
4837            let center = tester.get_center(&key);
4838            tester.add_pointer(&mut gesture, center);
4839            tester.pump();
4840
4841            let basic: MouseCursorRef = waft_services::SystemMouseCursors::BASIC.into();
4842            assert!(*tester.active_cursor(1) == *basic);
4843        });
4844    }
4845
4846    /// Dart's tree for 'PopupMenuItem changes mouse cursor when hovered' and its checked
4847    /// twin: `item` at the top left of a scaffold, under a `MouseRegion` that would show the
4848    /// forbidden cursor.
4849    fn item_under_forbidden_cursor(tester: &mut WidgetTester, item: WidgetRef) {
4850        pump_app(tester, m3, move |_app| {
4851            crate::scaffold::Scaffold::new()
4852                .body(
4853                    Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
4854                        Material::new().child(
4855                            waft_widgets::MouseRegion::new()
4856                                .cursor(waft_services::SystemMouseCursors::FORBIDDEN.into())
4857                                .child(
4858                                    // The [SemanticsRole.menu] is added here to make sure the
4859                                    // item's parent role is menu.
4860                                    Semantics::new().role(SemanticsRole::Menu).child(item),
4861                                ),
4862                        ),
4863                    ),
4864                )
4865                .into_widget()
4866        });
4867    }
4868
4869    /// Dart's 'PopupMenuItem changes mouse cursor when hovered' and 'CheckedPopupMenuItem
4870    /// changes mouse cursor when hovered': the cursor of an item with a text cursor, of one
4871    /// with none, and of a disabled one.
4872    fn item_cursors(
4873        tester: &mut WidgetTester,
4874        item: impl Fn(&GlobalKey, Option<MouseCursorRef>, bool) -> WidgetRef,
4875    ) {
4876        let key = GlobalKey::new();
4877        let cursor = |name: waft_services::SystemMouseCursor| -> MouseCursorRef { name.into() };
4878        item_under_forbidden_cursor(
4879            tester,
4880            item(
4881                &key,
4882                Some(cursor(waft_services::SystemMouseCursors::TEXT)),
4883                true,
4884            ),
4885        );
4886
4887        let mut gesture = TestPointer::mouse(1, 0);
4888        let center = tester.get_center(&key);
4889        tester.add_pointer(&mut gesture, center);
4890        tester.pump();
4891
4892        assert!(*tester.active_cursor(1) == *cursor(waft_services::SystemMouseCursors::TEXT));
4893
4894        // Test default cursor
4895        item_under_forbidden_cursor(tester, item(&key, None, true));
4896        assert!(*tester.active_cursor(1) == *cursor(waft_services::SystemMouseCursors::BASIC));
4897
4898        // Test default cursor when disabled
4899        item_under_forbidden_cursor(tester, item(&key, None, false));
4900        assert!(*tester.active_cursor(1) == *cursor(waft_services::SystemMouseCursors::BASIC));
4901    }
4902
4903    #[test]
4904    fn popup_menu_item_changes_mouse_cursor_when_hovered() {
4905        test_widgets(|tester| {
4906            item_cursors(tester, |key, mouse_cursor, enabled| {
4907                let item = PopupMenuItem::new(Some(Container::new()))
4908                    .key(key.clone().into())
4909                    .value(1)
4910                    .enabled(enabled);
4911                match mouse_cursor {
4912                    Some(mouse_cursor) => item.mouse_cursor(mouse_cursor),
4913                    None => item,
4914                }
4915                .into_widget()
4916            });
4917        });
4918    }
4919
4920    #[test]
4921    fn checked_popup_menu_item_changes_mouse_cursor_when_hovered() {
4922        test_widgets(|tester| {
4923            item_cursors(tester, |key, mouse_cursor, enabled| {
4924                let item = CheckedPopupMenuItem::new()
4925                    .key(key.clone().into())
4926                    .value(1)
4927                    .enabled(enabled)
4928                    .child(Container::new());
4929                match mouse_cursor {
4930                    Some(mouse_cursor) => item.mouse_cursor(mouse_cursor),
4931                    None => item,
4932                }
4933                .into_widget()
4934            });
4935        });
4936    }
4937
4938    #[test]
4939    fn popup_menu_in_app_bar_does_not_overlap_with_the_status_bar() {
4940        test_widgets(|tester| {
4941            let status_bar_height = 24.0;
4942            let first_item_key = GlobalKey::new();
4943            let selected_value = Rc::new(Cell::new(1));
4944            let first_key = first_item_key.clone();
4945            let home = waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
4946                let selected = Rc::clone(&selected_value);
4947                let first_key = first_key.clone();
4948                crate::scaffold::Scaffold::new()
4949                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
4950                        crate::app_bar::AppBar::new()
4951                            .title(Text::new("PopupMenu Test"))
4952                            .actions(vec![
4953                                PopupMenuButton::new(move |_app, _context| {
4954                                    vec![
4955                                        PopupMenuEntryRef::new(
4956                                            PopupMenuItem::new(Some(Text::new("Item 1")))
4957                                                .key(first_key.clone().into())
4958                                                .value(1),
4959                                        ),
4960                                        item(2, "Item 2"),
4961                                        item(3, "Item 3"),
4962                                    ]
4963                                })
4964                                .on_selected({
4965                                    let selected = Rc::clone(&selected);
4966                                    let set_state = Rc::clone(&set_state);
4967                                    move |app, result: i32| {
4968                                        let selected = Rc::clone(&selected);
4969                                        set_state(app, &mut |_app| selected.set(result));
4970                                    }
4971                                })
4972                                .initial_value(selected.get())
4973                                .into_widget(),
4974                            ]),
4975                    ))
4976                    .into_widget()
4977            })
4978            .into_widget();
4979            app_under_media_query(
4980                tester,
4981                m3,
4982                MediaQueryData::new().padding(EdgeInsets::only(0.0, status_bar_height, 0.0, 0.0)),
4983                home,
4984            );
4985
4986            let more_vert = || {
4987                let icon = Icons::more_vert();
4988                let element = tester.element(find::by_icon(&icon).first());
4989                tester.get_rect(tester.render_box_of(element)).center()
4990            };
4991            let center = more_vert();
4992            tester.tap_at(center, 1);
4993            tester.pump_and_settle();
4994
4995            // Tap third item.
4996            tester.tap(find::text("Item 3"));
4997            tester.pump_and_settle();
4998
4999            // Open popupMenu again.
5000            tester.tap_at(center, 1);
5001            tester.pump_and_settle();
5002
5003            // Check whether the first item is not overlapping with status bar.
5004            assert!(rect_of_key(tester, &first_item_key).top > status_bar_height);
5005        });
5006    }
5007
5008    #[test]
5009    fn vertically_long_popup_menu_does_not_overlap_with_the_status_bar_and_bottom_notch() {
5010        test_widgets(|tester| {
5011            let window_padding_top = 44.0;
5012            let window_padding_bottom = 34.0;
5013            let home = crate::scaffold::Scaffold::new()
5014                .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
5015                    crate::app_bar::AppBar::new().title(Text::new("PopupMenu Test")),
5016                ))
5017                .body(
5018                    PopupMenuButton::new(|_app, _context| {
5019                        (0..20).map(|i| item(i, &format!("Item {i}"))).collect()
5020                    })
5021                    .child(Text::new("Show Menu")),
5022                )
5023                .into_widget();
5024            app_under_media_query(
5025                tester,
5026                m3,
5027                MediaQueryData::new().padding(EdgeInsets::only(
5028                    0.0,
5029                    window_padding_top,
5030                    0.0,
5031                    window_padding_bottom,
5032                )),
5033                home,
5034            );
5035
5036            tester.tap(find::text("Show Menu"));
5037            tester.pump_and_settle();
5038
5039            let menu = scroll_view_rect(tester);
5040            assert_f32_equals(menu.top, window_padding_top + 8.0);
5041            // Screen height is 600.
5042            assert_f32_equals(menu.bottom, 600.0 - window_padding_bottom - 8.0);
5043        });
5044    }
5045
5046    /// Dart's `buildFrame` of the two 'PopupMenu position test when have unsafe area' cases:
5047    /// a pink 20x20 button among the app bar's actions, under a media query of `padding`.
5048    fn unsafe_area_frame(
5049        tester: &mut WidgetTester,
5050        padding: EdgeInsets,
5051        button_key: &GlobalKey,
5052        items: impl Fn() -> Vec<PopupMenuEntryRef<i32>> + 'static,
5053    ) {
5054        let home = crate::scaffold::Scaffold::new()
5055            .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
5056                crate::app_bar::AppBar::new()
5057                    .title(Text::new("PopupMenu Test"))
5058                    .actions(vec![
5059                        PopupMenuButton::new(move |_app, _context| items())
5060                            .child(
5061                                SizedBox::new()
5062                                    .key(button_key.clone().into())
5063                                    .height(20.0)
5064                                    .width(20.0)
5065                                    .child(ColoredBox::new(crate::colors::Colors::PINK.primary())),
5066                            )
5067                            .into_widget(),
5068                    ]),
5069            ))
5070            .body(SizedBox::shrink())
5071            .into_widget();
5072        app_under_media_query(tester, m2, MediaQueryData::new().padding(padding), home);
5073    }
5074
5075    #[test]
5076    fn popup_menu_position_test_when_have_unsafe_area() {
5077        test_widgets(|tester| {
5078            let button_key = GlobalKey::new();
5079            unsafe_area_frame(
5080                tester,
5081                EdgeInsets::only(0.0, 32.0, 0.0, 32.0),
5082                &button_key,
5083                || vec![item(1, "-1-"), item(2, "-2-")],
5084            );
5085
5086            tap_key(tester, &button_key);
5087            tester.pump_and_settle();
5088
5089            let button = rect_of_key(tester, &button_key).top_right();
5090            assert_f32_equals(button, Offset::new(800.0, 32.0)); // The topPadding is 32.0.
5091
5092            let popup_menu = scroll_view_rect(tester).top_right();
5093
5094            // The menu should be positioned directly next to the top of the button.
5095            // The 8.0 pixels is [_kMenuScreenPadding].
5096            assert_f32_equals(
5097                popup_menu,
5098                Offset::new(button.dx() - 8.0, button.dy() + 8.0),
5099            );
5100        });
5101    }
5102
5103    // Regression test for https://github.com/flutter/flutter/issues/82874
5104    #[test]
5105    fn popup_menu_position_test_when_have_unsafe_area_left_right_padding() {
5106        test_widgets(|tester| {
5107            let button_key = GlobalKey::new();
5108            let padding = EdgeInsets::only(300.0, 32.0, 310.0, 64.0);
5109            let media_query_padding: Rc<Cell<Option<EdgeInsets>>> = Rc::default();
5110            let seen = Rc::clone(&media_query_padding);
5111            unsafe_area_frame(tester, padding, &button_key, move || {
5112                let seen = Rc::clone(&seen);
5113                vec![
5114                    PopupMenuEntryRef::new(
5115                        PopupMenuItem::new(Some(Builder::new(move |app, context| {
5116                            seen.set(Some(MediaQuery::padding_of(app, context)));
5117                            // A long long text string.
5118                            Text::new("-1-".repeat(500)).into_widget()
5119                        })))
5120                        .value(1),
5121                    ),
5122                    item(2, "-2-"),
5123                ]
5124            });
5125
5126            tap_key(tester, &button_key);
5127            tester.pump_and_settle();
5128
5129            let button = rect_of_key(tester, &button_key).top_right();
5130            // The topPadding is 32.0.
5131            assert_f32_equals(button, Offset::new(800.0 - padding.right, padding.top));
5132
5133            let menu = scroll_view_rect(tester);
5134
5135            // The menu should be positioned directly next to the top of the button.
5136            // The 8.0 pixels is [_kMenuScreenPadding].
5137            assert_f32_equals(
5138                menu.top_right(),
5139                Offset::new(800.0 - padding.right - 8.0, padding.top + 8.0),
5140            );
5141            assert_f32_equals(
5142                menu.top_left(),
5143                Offset::new(padding.left + 8.0, padding.top + 8.0),
5144            );
5145            // Dart's next expectation, that the menu's bottom left is at
5146            // `Offset(padding.left + 8.0, 600.0 - padding.bottom - 8.0)`, waits on Valo: its
5147            // paragraph breaks a line only where UAX #14 allows one, where SkParagraph breaks
5148            // a word wider than the line, so the long text stays one line and the menu short.
5149
5150            // The `MediaQueryData.padding` should be removed.
5151            assert_eq!(media_query_padding.get(), Some(EdgeInsets::ZERO));
5152        });
5153    }
5154
5155    // Regression test for https://github.com/flutter/flutter/issues/163477
5156    #[test]
5157    fn popup_menus_overlay_can_be_rebuilt_even_when_the_button_is_unmounted() {
5158        test_widgets(|tester| {
5159            let button_key = GlobalKey::new();
5160            let set_state: Rc<RefCell<Option<waft_widgets::StateSetter>>> = Rc::default();
5161            let show_button = Rc::new(Cell::new(true));
5162
5163            let widget = |view_size: Size| {
5164                let (button_key, set_state, show_button) = (
5165                    button_key.clone(),
5166                    Rc::clone(&set_state),
5167                    Rc::clone(&show_button),
5168                );
5169                let app = crate::app::MaterialApp::new().home(
5170                    Material::new()
5171                        .child(waft_widgets::StatefulBuilder::new(
5172                            move |_app, _context, inner_set_state| {
5173                                *set_state.borrow_mut() = Some(inner_set_state);
5174                                if show_button.get() {
5175                                    PopupMenuButton::new(|_app, _context| {
5176                                        vec![PopupMenuEntryRef::new(
5177                                            PopupMenuItem::new(Some(Text::new("ACTION")))
5178                                                .value(1)
5179                                                .on_tap(Listener::new(|_app| {})),
5180                                        )]
5181                                    })
5182                                    .key(button_key.clone().into())
5183                                    .pop_up_animation_style(AnimationStyle::new(
5184                                        None,
5185                                        None,
5186                                        None,
5187                                        Some(Duration::from_millis(400)),
5188                                    ))
5189                                    .into_widget()
5190                                } else {
5191                                    Container::new().into_widget()
5192                                }
5193                            },
5194                        ))
5195                        .into_widget(),
5196                );
5197                Center::new()
5198                    .child(
5199                        SizedBox::new()
5200                            .width(view_size.width())
5201                            .height(view_size.height())
5202                            .child(app),
5203                    )
5204                    .into_widget()
5205            };
5206
5207            // Pump a button
5208            tester.pump_widget(widget(Size::new(500.0, 500.0)));
5209
5210            // Tap the button to show the menu
5211            tap_key(tester, &button_key);
5212            tester.pump_and_settle();
5213            expect(tester, &find::text("ACTION"), finds_one_widget());
5214            assert!(context_of_maybe(tester, &button_key).is_some());
5215
5216            // Hide the button. The menu still shows since it's placed on a separate route.
5217            let setter = set_state.borrow().clone().expect("built");
5218            let flag = Rc::clone(&show_button);
5219            setter(&mut tester.cell.borrow_mut(), &mut |_app| flag.set(false));
5220            tester.pump();
5221            expect(tester, &find::text("ACTION"), finds_one_widget());
5222            assert!(context_of_maybe(tester, &button_key).is_none());
5223
5224            // Resize the view, causing the menu to rebuild. Before the fix, this
5225            // rebuild would lead to a crash, because it relies on context of the button,
5226            // which has been unmounted.
5227            tester.pump_widget(widget(Size::new(300.0, 300.0)));
5228        });
5229    }
5230
5231    fn context_of_maybe(tester: &WidgetTester, key: &GlobalKey) -> Option<BuildContext> {
5232        key.current_context(&tester.cell.borrow())
5233    }
5234
5235    /// Dart's `show_menu(context: context, position: RelativeRect.fill, items: items,
5236    /// routeSettings: route_settings)` with the other arguments' defaults.
5237    fn show_menu_at_fill<T: Clone + PartialEq + 'static>(
5238        app: &mut App,
5239        context: BuildContext,
5240        items: Vec<PopupMenuEntryRef<T>>,
5241        route_settings: Option<RouteSettingsRef>,
5242    ) -> CompleterFuture<RouteResult> {
5243        let mut show = ShowMenu::new(items).position(RelativeRect::FILL);
5244        if let Some(route_settings) = route_settings {
5245            show = show.route_settings(route_settings);
5246        }
5247        show.show(app, context)
5248    }
5249
5250    /// Dart's `feedback` group, 'PopupMenuButton enableFeedback works properly': the click
5251    /// sound waits with `SystemSound`, so what decides it is checked instead, the
5252    /// `enableFeedback` the button's `InkWell` is built with, and no haptic is asked for.
5253    #[test]
5254    fn popup_menu_button_enable_feedback_works_properly() {
5255        #[derive(Default)]
5256        struct FeedbackTester {
5257            haptics: RefCell<Vec<waft_embedder::HapticFeedbackType>>,
5258        }
5259
5260        impl waft_embedder::Haptics for FeedbackTester {
5261            fn feedback(&self, kind: waft_embedder::HapticFeedbackType) {
5262                self.haptics.borrow_mut().push(kind);
5263            }
5264        }
5265
5266        test_widgets(|_| {
5267            let feedback = Rc::new(FeedbackTester::default());
5268            let platform = waft_test::TestPlatform::new()
5269                .on(waft_embedder::TargetPlatform::Android)
5270                .with_haptics(Rc::clone(&feedback) as Rc<dyn waft_embedder::Haptics>);
5271            let mut tester = WidgetTester::with_platform(platform);
5272            let tester = &mut tester;
5273            for (widget_enable_feedback, theme_enable_feedback, expected) in [
5274                // PopupMenuButton with enabled feedback.
5275                (Some(true), None, true),
5276                // PopupMenuButton with disabled feedback.
5277                (Some(false), None, false),
5278                // PopupMenuButton with enabled feedback by default.
5279                (None, None, true),
5280                // PopupMenu with disabled feedback using PopupMenuButtonTheme.
5281                (None, Some(false), false),
5282                // PopupMenu enableFeedback property overrides PopupMenuButtonTheme.
5283                (Some(false), Some(true), false),
5284            ] {
5285                pump_app(tester, m3, move |_app| {
5286                    let mut theme = PopupMenuThemeData::new();
5287                    theme.enable_feedback = theme_enable_feedback;
5288                    let mut button = PopupMenuButton::new(|_app, _context| vec![item(1, "One")])
5289                        .child(Text::new("Show Menu"));
5290                    button.enable_feedback = widget_enable_feedback;
5291                    crate::scaffold::Scaffold::new()
5292                        .body(PopupMenuTheme::new(theme, button))
5293                        .into_widget()
5294                });
5295                let ink_well = tester.element(find::by_type::<InkWell>());
5296                assert_eq!(
5297                    tester.widget(ink_well, |ink_well: &InkWell| ink_well
5298                        .ink_response
5299                        .enable_feedback),
5300                    expected
5301                );
5302                tester.tap(find::text("Show Menu"));
5303                tester.pump_and_settle();
5304                assert!(shows(tester, "One"));
5305                assert!(feedback.haptics.borrow().is_empty());
5306                tester.pump_widget(Container::new().into_widget());
5307            }
5308        });
5309    }
5310
5311    #[test]
5312    fn can_customize_popup_menu_button_icon() {
5313        test_widgets(|tester| {
5314            let icon_color = Color::new(0xffffff00);
5315            let icon_size = 29.5;
5316            centered_in_scaffold(tester, m3, move || {
5317                PopupMenuButton::new(|_app, _context| vec![item("value".to_owned(), "child")])
5318                    .icon_color(icon_color)
5319                    .icon_size(icon_size)
5320                    .into_widget()
5321            });
5322
5323            let more = Icons::adaptive().more(&tester.cell.borrow());
5324            let icon = tester.element(find::by_icon(&more).first());
5325            assert_eq!(
5326                tester.glyph_style(icon).color.as_deref().copied(),
5327                Some(icon_color)
5328            );
5329            assert_eq!(
5330                tester.get_rect(tester.render_box_of(icon)).size(),
5331                Size::new(icon_size, icon_size)
5332            );
5333        });
5334    }
5335
5336    #[test]
5337    fn does_not_crash_in_small_overlay() {
5338        test_widgets(|tester| {
5339            let navigator = GlobalKey::new();
5340            let key = navigator.clone();
5341            pump_app(tester, m3, move |_app| {
5342                let navigator = key.clone();
5343                crate::scaffold::Scaffold::new()
5344                    .body(Column::new().children(vec![
5345                        crate::outlined_button::OutlinedButton::new(
5346                            Some(Listener::new(move |app| {
5347                                let context = navigator
5348                                    .current_context(app)
5349                                    .expect("the navigator is mounted");
5350                                drop(show_menu_at_fill::<()>(
5351                                    app,
5352                                    context,
5353                                    vec![PopupMenuEntryRef::new(PopupMenuItem::new(Some(
5354                                        Text::new("foo"),
5355                                    )))],
5356                                    None,
5357                                ));
5358                            })),
5359                            Some(Text::new("press")),
5360                        )
5361                        .into_widget(),
5362                        SizedBox::square(Some(10.0))
5363                            .child(Navigator::new().key(key.into()).on_generate_route(
5364                                |app, _settings| {
5365                                    let route = MaterialPageRoute::new(
5366                                        app,
5367                                        Rc::new(|_app, _context| {
5368                                            Container::new()
5369                                                .color(crate::colors::Colors::RED.primary())
5370                                                .into_widget()
5371                                        }),
5372                                    );
5373                                    Some(route.erase())
5374                                },
5375                            ))
5376                            .into_widget(),
5377                    ]))
5378                    .into_widget()
5379            });
5380
5381            tester.tap(find::text("press"));
5382            tester.pump_and_settle();
5383            expect(tester, &find::text("foo"), finds_one_widget());
5384        });
5385    }
5386
5387    // Regression test for https://github.com/flutter/flutter/issues/80869
5388    #[test]
5389    fn the_menu_position_test_in_the_scrollable_widget() {
5390        test_widgets(|tester| {
5391            let button_key = GlobalKey::new();
5392            let key = button_key.clone();
5393            pump_app(tester, m3, move |_app| {
5394                crate::scaffold::Scaffold::new()
5395                    .body(
5396                        SingleChildScrollView::new().child(Column::new().children(vec![
5397                        SizedBox::new().height(100.0).into_widget(),
5398                        PopupMenuButton::new(|_app, _context| vec![item(1, "-1-"), item(2, "-2-")])
5399                            .child(
5400                                SizedBox::new()
5401                                    .key(key.into())
5402                                    .height(10.0)
5403                                    .width(10.0)
5404                                    .child(ColoredBox::new(crate::colors::Colors::PINK.primary())),
5405                            )
5406                            .into_widget(),
5407                        SizedBox::new().height(600.0).into_widget(),
5408                    ])),
5409                    )
5410                    .into_widget()
5411            });
5412            let menu_top_left = |tester: &WidgetTester| {
5413                let scroll_views = find::by_type::<SingleChildScrollView>().evaluate(tester);
5414                let last = *scroll_views.last().expect("the menu's scroll view");
5415                tester.get_rect(tester.render_box_of(last)).top_left()
5416            };
5417
5418            // Open the menu.
5419            tap_key(tester, &button_key);
5420            tester.pump_and_settle();
5421
5422            let button = rect_of_key(tester, &button_key).top_left();
5423            assert_f32_equals(button, Offset::new(0.0, 100.0));
5424
5425            // The menu should be positioned directly next to the top of the button.
5426            // The 8.0 pixels is [_kMenuScreenPadding].
5427            assert_f32_equals(menu_top_left(tester), Offset::new(8.0, 100.0));
5428
5429            // Close the menu.
5430            tap_key(tester, &button_key);
5431            tester.pump_and_settle();
5432
5433            // Scroll a little bit.
5434            let scroll_view = tester.element(find::by_type::<SingleChildScrollView>());
5435            let start = tester.get_rect(tester.render_box_of(scroll_view)).center();
5436            tester.drag_from(start, Offset::new(0.0, -50.0), 1);
5437
5438            let button = rect_of_key(tester, &button_key).top_left();
5439            assert_f32_equals(button, Offset::new(0.0, 50.0));
5440
5441            // Open the menu again.
5442            tap_key(tester, &button_key);
5443            tester.pump_and_settle();
5444
5445            // The menu should be positioned directly next to the top of the button.
5446            // The 8.0 pixels is [_kMenuScreenPadding].
5447            assert_f32_equals(menu_top_left(tester), Offset::new(8.0, 50.0));
5448        });
5449    }
5450
5451    #[test]
5452    fn popup_menu_button_custom_splash_radius() {
5453        test_widgets(|tester| {
5454            let build_frame_without_child =
5455                |tester: &mut WidgetTester, splash_radius: Option<f64>| {
5456                    centered_in_scaffold(tester, m2, move || {
5457                        let mut button = PopupMenuButton::new(|_app, _context| {
5458                            vec![item("value".to_owned(), "child")]
5459                        });
5460                        button.splash_radius = splash_radius;
5461                        button.into_widget()
5462                    });
5463                };
5464            let build_frame_with_child = |tester: &mut WidgetTester, splash_radius: Option<f64>| {
5465                centered_in_scaffold(tester, m3, move || {
5466                    let mut button = PopupMenuButton::<String>::new(|_app, _context| {
5467                        vec![PopupMenuEntryRef::new(PopupMenuDivider::new())]
5468                    })
5469                    .child(Text::new("An item"));
5470                    button.splash_radius = splash_radius;
5471                    button.into_widget()
5472                });
5473            };
5474            let ink_response_radius = |tester: &WidgetTester| {
5475                let ink_response = tester.element(find::by_type::<crate::ink_well::InkResponse>());
5476                tester.widget(
5477                    ink_response,
5478                    |ink_response: &crate::ink_well::InkResponse| ink_response.radius,
5479                )
5480            };
5481            let ink_well_radius = |tester: &WidgetTester| {
5482                let ink_well = tester.element(find::by_type::<InkWell>());
5483                tester.widget(ink_well, |ink_well: &InkWell| ink_well.ink_response.radius)
5484            };
5485
5486            build_frame_without_child(tester, None);
5487            assert_eq!(
5488                ink_response_radius(tester),
5489                Some(Material::DEFAULT_SPLASH_RADIUS)
5490            );
5491            build_frame_with_child(tester, None);
5492            assert_eq!(ink_well_radius(tester), None);
5493
5494            let test_splash_radius = 50.0;
5495
5496            build_frame_without_child(tester, Some(test_splash_radius));
5497            assert_eq!(ink_response_radius(tester), Some(test_splash_radius));
5498            build_frame_with_child(tester, Some(test_splash_radius));
5499            assert_eq!(ink_well_radius(tester), Some(test_splash_radius));
5500        });
5501    }
5502
5503    #[test]
5504    fn can_override_menu_size_constraints() {
5505        test_widgets(|tester| {
5506            let key = GlobalKey::new();
5507            let button_key = key.clone();
5508            centered_in_scaffold(tester, m3, move || {
5509                PopupMenuButton::new(|_app, _context| vec![item("value".to_owned(), "Item 0")])
5510                    .key(button_key.into())
5511                    .constraints(BoxConstraints::new().min_width(500.0))
5512                    .into_widget()
5513            });
5514
5515            // Show the menu
5516            tap_key(tester, &key);
5517            tester.pump_and_settle();
5518
5519            let item = rect_with_text::<PopupMenuItem<String>>(tester, "Item 0");
5520            assert_eq!(item.height(), 48.0);
5521            assert_eq!(item.width(), 500.0);
5522        });
5523    }
5524
5525    #[test]
5526    fn can_change_menu_position_and_offset() {
5527        test_widgets(|tester| {
5528            let build_menu_button = |position: Option<PopupMenuPosition>, offset: Offset| {
5529                let button = PopupMenuButton::new(|_app, _context| {
5530                    vec![PopupMenuEntryRef::new(
5531                        PopupMenuItem::new(Some(Builder::new(|_app, _context| {
5532                            Text::new("AAA").into_widget()
5533                        })))
5534                        .value(1),
5535                    )]
5536                })
5537                .offset(offset);
5538                match position {
5539                    Some(position) => button.position(position),
5540                    None => button,
5541                }
5542            };
5543            for (position, offset, expected) in [
5544                // Popup menu with `MenuPosition.over (default) with default offset`.
5545                (
5546                    Some(PopupMenuPosition::Over),
5547                    Offset::ZERO,
5548                    Offset::new(8.0, 8.0),
5549                ),
5550                // Popup menu with `MenuPosition.under`(custom) with default offset`.
5551                (
5552                    Some(PopupMenuPosition::Under),
5553                    Offset::ZERO,
5554                    Offset::new(8.0, 40.0),
5555                ),
5556                // Popup menu with `MenuPosition.over (default) with custom offset`.
5557                (None, Offset::new(0.0, 50.0), Offset::new(8.0, 50.0)),
5558                // Popup menu with `MenuPosition.under (custom) with custom offset`.
5559                (
5560                    Some(PopupMenuPosition::Under),
5561                    Offset::new(0.0, 50.0),
5562                    Offset::new(8.0, 90.0),
5563                ),
5564            ] {
5565                let button = build_menu_button(position, offset);
5566                pump_app(tester, m3, move |_app| {
5567                    crate::scaffold::Scaffold::new()
5568                        .body(Material::new().child(button))
5569                        .into_widget()
5570                });
5571
5572                // Open the popup menu.
5573                let icon_button = tester.element(find::by_type::<IconButton>());
5574                let center = tester.get_rect(tester.render_box_of(icon_button)).center();
5575                tester.tap_at(center, 1);
5576                tester.pump_and_settle();
5577
5578                assert_f32_equals(rect_of::<PopupMenu<i32>>(tester).top_left(), expected);
5579
5580                // Close the popup menu.
5581                tester.tap_at(Offset::ZERO, 1);
5582                tester.pump();
5583            }
5584        });
5585    }
5586
5587    #[test]
5588    fn popup_menu_button_icon_inherits_icon_themes_size() {
5589        test_widgets(|tester| {
5590            let build_popup_menu = |tester: &mut WidgetTester,
5591                                    theme_icon_size: Option<f64>,
5592                                    icon_size: Option<f64>| {
5593                centered_in_scaffold(
5594                    tester,
5595                    move |app| {
5596                        let mut icon_theme = waft_widgets::IconThemeData::new();
5597                        icon_theme.size = theme_icon_size;
5598                        ThemeData::builder().icon_theme(icon_theme).build(app)
5599                    },
5600                    move || {
5601                        let mut button = PopupMenuButton::new(|_app, _context| {
5602                            vec![item("value".to_owned(), "Item 0")]
5603                        });
5604                        button.icon_size = icon_size;
5605                        button.into_widget()
5606                    },
5607                );
5608            };
5609            let icon_size = |tester: &WidgetTester| {
5610                let icon = tester.element(find::by_icon(&Icons::more_vert()).first());
5611                tester.get_rect(tester.render_box_of(icon)).size()
5612            };
5613
5614            // Popup menu with default icon size.
5615            build_popup_menu(tester, None, None);
5616            // Default PopupMenuButton icon size is 24.0.
5617            assert_eq!(icon_size(tester), Size::new(24.0, 24.0));
5618
5619            // Popup menu with custom theme icon size.
5620            build_popup_menu(tester, Some(30.0), None);
5621            tester.pump_and_settle();
5622            // PopupMenuButton icon inherits IconTheme's size.
5623            assert_eq!(icon_size(tester), Size::new(30.0, 30.0));
5624
5625            // Popup menu with custom icon size.
5626            build_popup_menu(tester, Some(30.0), Some(50.0));
5627            tester.pump_and_settle();
5628            // PopupMenuButton icon size overrides IconTheme's size.
5629            assert_eq!(icon_size(tester), Size::new(50.0, 50.0));
5630        });
5631    }
5632
5633    #[test]
5634    fn popup_menu_clip_behavior() {
5635        // Regression test for https://github.com/flutter/flutter/issues/107215
5636        test_widgets(|tester| {
5637            let popup_button_key = GlobalKey::new();
5638            let radius = 20.0;
5639            for clip_behavior in [Clip::None, Clip::HardEdge] {
5640                let key = popup_button_key.clone();
5641                centered_in_scaffold(tester, m3, move || {
5642                    PopupMenuButton::new(|_app, _context| vec![item("value".to_owned(), "Item 0")])
5643                        .key(key.into())
5644                        .shape(waft_painting::RoundedRectangleBorder::new(
5645                            waft_painting::BorderSide::NONE,
5646                            BorderRadiusGeometry::circular(radius),
5647                        ))
5648                        .clip_behavior(clip_behavior)
5649                        .into_widget()
5650                });
5651
5652                // Open the popup to build and show the menu contents.
5653                tap_key(tester, &popup_button_key);
5654                tester.pump_and_settle();
5655
5656                let materials = find::by_type::<Material>().evaluate(tester);
5657                let material = *materials.last().expect("the menu's Material");
5658                assert_eq!(
5659                    tester.widget(material, |material: &Material| material.clip_behavior),
5660                    clip_behavior
5661                );
5662
5663                // Close the popup menu.
5664                tester.tap_at(Offset::ZERO, 1);
5665                tester.pump_and_settle();
5666            }
5667        });
5668    }
5669
5670    #[test]
5671    fn popup_menu_scrollbar_inherits_scrollbar_theme() {
5672        use crate::scrollbar::Scrollbar;
5673        use crate::scrollbar::tests::painted;
5674        use crate::scrollbar_theme::{ScrollbarTheme, ScrollbarThemeData};
5675        use waft_rendering::testing::{PaintCall, assert_paints};
5676
5677        fn menu_button(key: &GlobalKey) -> PopupMenuButton<()> {
5678            PopupMenuButton::new(|_app, _context| {
5679                vec![PopupMenuEntryRef::new(
5680                    PopupMenuItem::<()>::new(Some(Text::new("Example"))).height(1000.0),
5681                )]
5682            })
5683            .key(key.clone().into())
5684        }
5685
5686        /// Dart's `expect(find.byType(Scrollbar), findsOneWidget)` and
5687        /// `expect(find.byType(Scrollbar), paints..rrect(color: thumb))`.
5688        fn expect_one_scrollbar_painting(tester: &WidgetTester, thumb: u32) {
5689            tester.element(find::by_type::<Scrollbar>());
5690            assert_paints(
5691                &painted(tester),
5692                &[PaintCall::rrect(Some(Color::new(thumb)))],
5693            );
5694        }
5695
5696        for platform in [
5697            TargetPlatform::Linux,
5698            TargetPlatform::MacOS,
5699            TargetPlatform::Windows,
5700        ] {
5701            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
5702                let popup_button_key = GlobalKey::new();
5703                let scrollbar_theme = ScrollbarThemeData::new()
5704                    .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
5705                        Color::new(0xffff0000),
5706                    )))
5707                    .thumb_visibility(<dyn WidgetStateProperty<Option<bool>>>::all(Some(true)));
5708                let theme = |scrollbar_theme: ScrollbarThemeData| {
5709                    move |app: &App| {
5710                        ThemeData::builder()
5711                            .scrollbar_theme(scrollbar_theme)
5712                            .build(app)
5713                    }
5714                };
5715
5716                let key = popup_button_key.clone();
5717                pump_app(tester, theme(scrollbar_theme.clone()), move |_app| {
5718                    Material::new()
5719                        .child(Column::new().children([menu_button(&key).into_widget()]))
5720                        .into_widget()
5721                });
5722
5723                tap_key(tester, &popup_button_key);
5724                tester.pump_and_settle();
5725
5726                // Test Scrollbar thumb color.
5727                expect_one_scrollbar_painting(tester, 0xffff0000);
5728
5729                // Close the menu.
5730                tester.tap_at(Offset::new(20.0, 20.0), 1);
5731                tester.pump_and_settle();
5732
5733                // Test local ScrollbarTheme overrides global ScrollbarTheme.
5734                let key = popup_button_key.clone();
5735                let local_theme = scrollbar_theme.copy_with().thumb_color(
5736                    <dyn WidgetStateProperty<Option<Color>>>::all(Some(Color::new(0xff0000ff))),
5737                );
5738                pump_app(tester, theme(scrollbar_theme), move |_app| {
5739                    Material::new()
5740                        .child(Column::new().children([
5741                            ScrollbarTheme::new(local_theme, menu_button(&key)).into_widget(),
5742                        ]))
5743                        .into_widget()
5744                });
5745                tap_key(tester, &popup_button_key);
5746                tester.pump_and_settle();
5747
5748                // Scrollbar thumb color should be updated.
5749                expect_one_scrollbar_painting(tester, 0xff0000ff);
5750            });
5751        }
5752    }
5753
5754    #[test]
5755    fn uses_closed_loop_focus_traversal() {
5756        test_widgets(|tester| {
5757            let popup_button_key = GlobalKey::new();
5758            let key = popup_button_key.clone();
5759            centered_in_scaffold(tester, m3, move || {
5760                PopupMenuButton::new(|_app, _context| {
5761                    vec![item("a".to_owned(), "A"), item("b".to_owned(), "B")]
5762                })
5763                .key(key.into())
5764                .into_widget()
5765            });
5766
5767            // Open the popup to build and show the menu contents.
5768            tap_key(tester, &popup_button_key);
5769            tester.pump_and_settle();
5770
5771            let node = |tester: &WidgetTester, text: &str| {
5772                let element = tester.element(find::text(text));
5773                waft_widgets::Focus::of(&mut tester.cell.borrow_mut(), element, false, false)
5774            };
5775            let invoke = |tester: &mut WidgetTester, intent: &dyn waft_widgets::Intent| {
5776                let result = {
5777                    let mut app = tester.cell.borrow_mut();
5778                    let context = waft_widgets::primary_focus(&mut app)
5779                        .and_then(|focus| focus.context(&app))
5780                        .expect("a focused node with a context");
5781                    waft_widgets::Actions::invoke(&mut app, context, intent)
5782                };
5783                tester.pump();
5784                result
5785                    .and_then(|result| result.downcast_ref::<bool>().copied())
5786                    .expect("the focus actions answer whether focus moved")
5787            };
5788            let has_focus = |tester: &WidgetTester, text: &str| {
5789                node(tester, text).has_focus(&tester.cell.borrow_mut())
5790            };
5791
5792            // Start at A
5793            let a = node(tester, "A");
5794            a.request_focus(&mut tester.cell.borrow_mut(), None);
5795            tester.pump();
5796            assert!(has_focus(tester, "A"));
5797            assert!(!has_focus(tester, "B"));
5798
5799            for (intent, a_focused) in [
5800                // A -> B
5801                (
5802                    &waft_widgets::NextFocusIntent as &dyn waft_widgets::Intent,
5803                    false,
5804                ),
5805                // B -> A (wrap around)
5806                (&waft_widgets::NextFocusIntent, true),
5807                // B <- A
5808                (&waft_widgets::PreviousFocusIntent, false),
5809                // A <- B (wrap around)
5810                (&waft_widgets::PreviousFocusIntent, true),
5811            ] {
5812                assert!(invoke(tester, intent));
5813                assert_eq!(has_focus(tester, "A"), a_focused);
5814                assert_eq!(has_focus(tester, "B"), !a_focused);
5815            }
5816        });
5817    }
5818
5819    #[test]
5820    fn popup_menu_with_route_settings() {
5821        test_widgets(|tester| {
5822            pump_app(tester, m3, |_app| {
5823                Material::new()
5824                    .child(
5825                        Center::new().child(crate::elevated_button::ElevatedButton::new(
5826                            None,
5827                            Some(Text::new("Go")),
5828                        )),
5829                    )
5830                    .into_widget()
5831            });
5832
5833            let context = tester.element(find::text("Go"));
5834            let example_setting = RouteSettings::default().name("simple");
5835
5836            drop(show_menu_at_fill::<()>(
5837                &mut tester.cell.borrow_mut(),
5838                context,
5839                vec![PopupMenuEntryRef::new(PopupMenuItem::new(Some(Text::new(
5840                    "foo",
5841                ))))],
5842                Some(RouteSettingsRef::Settings(example_setting)),
5843            ));
5844
5845            // Dart's `_ClosureNavigatorObserver` records the settings of the route on top; the
5846            // settings of the route the item is in say the same.
5847            tester.pump_and_settle();
5848            expect(tester, &find::text("foo"), finds_one_widget());
5849            let foo = tester.element(find::text("foo"));
5850            let settings =
5851                waft_widgets::AnyModalRoute::settings_of(&mut tester.cell.borrow_mut(), foo);
5852            assert_eq!(
5853                settings.as_ref().and_then(|settings| settings.name()),
5854                Some("simple")
5855            );
5856
5857            tester.tap(find::text("foo"));
5858            tester.pump_and_settle();
5859            let settings =
5860                waft_widgets::AnyModalRoute::settings_of(&mut tester.cell.borrow_mut(), context);
5861            assert_eq!(
5862                settings.as_ref().and_then(|settings| settings.name()),
5863                Some("/")
5864            );
5865        });
5866    }
5867
5868    #[test]
5869    fn popup_menu_is_positioned_under_the_child() {
5870        test_widgets(|tester| {
5871            let popup_button_key = GlobalKey::new();
5872            let child_key = GlobalKey::new();
5873            let (key, child) = (popup_button_key.clone(), child_key.clone());
5874            pump_app(tester, m3, move |_app| {
5875                Material::new()
5876                    .child(Column::new().children(vec![
5877                        PopupMenuButton::<()>::new(|_app, _context| {
5878                            vec![PopupMenuEntryRef::new(PopupMenuItem::new(Some(Text::new(
5879                                "Example",
5880                            ))))]
5881                        })
5882                        .key(key.into())
5883                        .position(PopupMenuPosition::Under)
5884                        .child(SizedBox::new().key(child.into()).height(50.0).width(50.0))
5885                        .into_widget(),
5886                    ]))
5887                    .into_widget()
5888            });
5889
5890            tap_key(tester, &popup_button_key);
5891            tester.pump_and_settle();
5892
5893            let child_bottom_left = rect_of_key(tester, &child_key).bottom_left();
5894            // Dart's `find.bySemanticsLabel('Popup menu')`: the menu's `Semantics` node, the
5895            // `_PopupMenu`'s box.
5896            let menu_top_left = rect_of::<PopupMenu<()>>(tester).top_left();
5897            assert_f32_equals(child_bottom_left, menu_top_left);
5898        });
5899    }
5900
5901    #[test]
5902    fn popup_menu_item_on_tap_should_be_calling_after_navigator_pop() {
5903        test_widgets(|tester| {
5904            pump_app(tester, m3, |_app| {
5905                crate::scaffold::Scaffold::new()
5906                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
5907                        crate::app_bar::AppBar::new().actions(vec![
5908                            PopupMenuButton::new(|_app, context| {
5909                                vec![PopupMenuEntryRef::new(
5910                                    PopupMenuItem::new(Some(Text::new("ACTION")))
5911                                        .on_tap(Listener::new(move |app| {
5912                                            drop(
5913                                                crate::bottom_sheet::ShowModalBottomSheet::new(
5914                                                    Rc::new(|_app, _context| {
5915                                                        SizedBox::new()
5916                                                            .height(200.0)
5917                                                            .child(Center::new().child(Text::new(
5918                                                                "ModalBottomSheet",
5919                                                            )))
5920                                                            .into_widget()
5921                                                    }),
5922                                                )
5923                                                .show(app, context),
5924                                            );
5925                                        }))
5926                                        .value(10),
5927                                )]
5928                            })
5929                            .into_widget(),
5930                        ]),
5931                    ))
5932                    .into_widget()
5933            });
5934
5935            let button = tester.element(find::by_type::<PopupMenuButton<i32>>());
5936            let center = tester.get_rect(tester.render_box_of(button)).center();
5937            tester.tap_at(center, 1);
5938            tester.pump_and_settle();
5939
5940            tester.tap(find::text("ACTION"));
5941            tester.pump_and_settle();
5942
5943            // Verify that the ModalBottomSheet is displayed
5944            expect(tester, &find::text("ModalBottomSheet"), finds_one_widget());
5945        });
5946    }
5947
5948    /// Dart's `_labelStyle(tester, label)`: the style of the `RichText` below the text.
5949    fn label_style(tester: &WidgetTester, label: &str) -> TextStyle {
5950        tester.glyph_style(tester.element(find::text(label)))
5951    }
5952
5953    /// The menu's `Material`, the last one: Dart's `find.byType(Material).last`.
5954    fn last_material_size(tester: &WidgetTester) -> Size {
5955        let materials = find::by_type::<Material>().evaluate(tester);
5956        let material = *materials.last().expect("a Material");
5957        tester.get_rect(tester.render_box_of(material)).size()
5958    }
5959
5960    /// An app bar whose action is a button keyed `key` showing `items`.
5961    fn app_bar_button<T: Clone + PartialEq + 'static>(
5962        tester: &mut WidgetTester,
5963        theme: impl FnOnce(&App) -> ThemeData,
5964        key: &GlobalKey,
5965        items: impl Fn() -> Vec<PopupMenuEntryRef<T>> + 'static,
5966    ) {
5967        let key = key.clone();
5968        pump_app(tester, theme, move |_app| {
5969            crate::scaffold::Scaffold::new()
5970                .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
5971                    crate::app_bar::AppBar::new().actions(vec![
5972                        PopupMenuButton::new(move |_app, _context| items())
5973                            .key(key.into())
5974                            .into_widget(),
5975                    ]),
5976                ))
5977                .into_widget()
5978        });
5979    }
5980
5981    fn custom_text_style() -> TextStyle {
5982        TextStyle::new()
5983            .font_size(20.0)
5984            .font_weight(waft_embedder::FontWeight::BOLD)
5985            .font_style(waft_embedder::FontStyle::Italic)
5986    }
5987
5988    /// Dart's `const CheckedPopupMenuItem<void>(child: Text('Item 1'))` and its checked
5989    /// twin; Dart's second is a `CheckedPopupMenuItem<int>` in a list of `void` items, which
5990    /// a Rust list of one item type cannot hold.
5991    fn checked_items(
5992        label_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
5993    ) -> Vec<PopupMenuEntryRef<()>> {
5994        let with_style = |item: CheckedPopupMenuItem<()>| match &label_text_style {
5995            Some(label_text_style) => item.label_text_style(Rc::clone(label_text_style)),
5996            None => item,
5997        };
5998        vec![
5999            PopupMenuEntryRef::new(with_style(
6000                CheckedPopupMenuItem::new().child(Text::new("Item 1")),
6001            )),
6002            PopupMenuEntryRef::new(with_style(
6003                CheckedPopupMenuItem::new()
6004                    .checked(true)
6005                    .child(Text::new("Item 2")),
6006            )),
6007        ]
6008    }
6009
6010    #[test]
6011    fn material3_checked_popup_menu_item_label_text_style_uses_correct_text_style() {
6012        test_widgets(|tester| {
6013            let key = GlobalKey::new();
6014            app_bar_button(tester, m3, &key, || checked_items(None));
6015
6016            // Show the menu
6017            tap_key(tester, &key);
6018            tester.pump_and_settle();
6019
6020            // Test default text style.
6021            let on_surface = m3(&tester.cell.borrow()).color_scheme.on_surface();
6022            assert_eq!(label_style(tester, "Item 1").font_size, Some(14.0));
6023            assert_eq!(
6024                label_style(tester, "Item 1").color.as_deref().copied(),
6025                Some(on_surface)
6026            );
6027
6028            // Close the menu.
6029            tester.tap_at(Offset::new(20.0, 20.0), 1);
6030            tester.pump_and_settle();
6031
6032            // Test custom text theme.
6033            app_bar_button(
6034                tester,
6035                |app| {
6036                    m3(app)
6037                        .copy_with()
6038                        .text_theme(
6039                            crate::text_theme::TextTheme::new().label_large(custom_text_style()),
6040                        )
6041                        .build()
6042                },
6043                &key,
6044                || checked_items(None),
6045            );
6046
6047            // Show the menu.
6048            tap_key(tester, &key);
6049            tester.pump_and_settle();
6050
6051            // Test custom text theme.
6052            let style = label_style(tester, "Item 1");
6053            assert_eq!(style.font_size, custom_text_style().font_size);
6054            assert_eq!(style.font_weight, custom_text_style().font_weight);
6055            assert_eq!(style.font_style, custom_text_style().font_style);
6056        });
6057    }
6058
6059    #[test]
6060    fn checked_popup_menu_item_label_text_style_resolve_material_states() {
6061        test_widgets(|tester| {
6062            let key = GlobalKey::new();
6063            let label_text_style =
6064                <dyn WidgetStateProperty<Option<TextStyle>>>::resolve_with(|states| {
6065                    if states.contains(&WidgetState::Selected) {
6066                        return Some(
6067                            TextStyle::new()
6068                                .color(crate::colors::Colors::RED.primary())
6069                                .font_size(24.0),
6070                        );
6071                    }
6072                    Some(
6073                        TextStyle::new()
6074                            .color(crate::colors::Colors::AMBER.primary())
6075                            .font_size(20.0),
6076                    )
6077                });
6078            let style = Rc::clone(&label_text_style);
6079            app_bar_button(tester, m3, &key, move || {
6080                checked_items(Some(Rc::clone(&style)))
6081            });
6082
6083            // Show the menu.
6084            tap_key(tester, &key);
6085            tester.pump_and_settle();
6086
6087            let mut selected = WidgetStates::new();
6088            selected.insert(WidgetState::Selected);
6089            let merged = |tester: &WidgetTester, label: &str| {
6090                let style = label_style(tester, label);
6091                (style.color.as_deref().copied(), style.font_size)
6092            };
6093            let expected = |states: &WidgetStates| {
6094                let style = label_text_style.resolve(states).expect("a style");
6095                (style.color.as_deref().copied(), style.font_size)
6096            };
6097            assert_eq!(merged(tester, "Item 1"), expected(&WidgetStates::new()));
6098            assert_eq!(merged(tester, "Item 2"), expected(&selected));
6099        });
6100    }
6101
6102    /// Dart's `getItemSafeArea(label).minimum` of the two 'overrides redundant
6103    /// ListTile.contentPadding' cases: the `ListTile`'s `SafeArea` above the label.
6104    fn item_safe_area_minimum(tester: &WidgetTester, label: &str) -> EdgeInsets {
6105        let safe_area = widget_with_text::<waft_widgets::SafeArea>(tester, label);
6106        tester.widget(safe_area, |safe_area: &waft_widgets::SafeArea| {
6107            safe_area.minimum
6108        })
6109    }
6110
6111    #[test]
6112    fn checked_popup_menu_item_overrides_redundant_list_tile_content_padding() {
6113        test_widgets(|tester| {
6114            let key = GlobalKey::new();
6115            keyed_text_button(tester, m2, &key, || {
6116                vec![
6117                    PopupMenuEntryRef::new(
6118                        CheckedPopupMenuItem::new()
6119                            .value("0".to_owned())
6120                            .child(Text::new("Item 0")),
6121                    ),
6122                    PopupMenuEntryRef::new(
6123                        CheckedPopupMenuItem::new()
6124                            .value("1".to_owned())
6125                            .checked(true)
6126                            .child(Text::new("Item 1")),
6127                    ),
6128                ]
6129            });
6130
6131            // Show the menu.
6132            tap_key(tester, &key);
6133            tester.pump_and_settle();
6134
6135            assert_eq!(item_safe_area_minimum(tester, "Item 0"), EdgeInsets::ZERO);
6136            assert_eq!(item_safe_area_minimum(tester, "Item 1"), EdgeInsets::ZERO);
6137        });
6138    }
6139
6140    #[test]
6141    fn popup_menu_item_overrides_redundant_list_tile_content_padding() {
6142        test_widgets(|tester| {
6143            let key = GlobalKey::new();
6144            keyed_text_button(tester, m2, &key, || {
6145                vec![
6146                    PopupMenuEntryRef::new(
6147                        PopupMenuItem::new(Some(ListTile::new().title(Text::new("Item 0"))))
6148                            .value("0".to_owned())
6149                            .enabled(false),
6150                    ),
6151                    PopupMenuEntryRef::new(
6152                        PopupMenuItem::new(Some(ListTile::new().title(Text::new("Item 1"))))
6153                            .value("1".to_owned()),
6154                    ),
6155                ]
6156            });
6157
6158            // Show the menu.
6159            tap_key(tester, &key);
6160            tester.pump_and_settle();
6161
6162            assert_eq!(item_safe_area_minimum(tester, "Item 0"), EdgeInsets::ZERO);
6163            assert_eq!(item_safe_area_minimum(tester, "Item 1"), EdgeInsets::ZERO);
6164        });
6165    }
6166
6167    fn text_and_list_tile_items() -> Vec<PopupMenuEntryRef<String>> {
6168        vec![
6169            // Popup menu item with a Text widget.
6170            item("0".to_owned(), "Item 0"),
6171            // Popup menu item with a ListTile widget.
6172            PopupMenuEntryRef::new(
6173                PopupMenuItem::new(Some(ListTile::new().title(Text::new("Item 1"))))
6174                    .value("1".to_owned()),
6175            ),
6176        ]
6177    }
6178
6179    /// Dart's 'Material3 - PopupMenuItem overrides ListTile.titleTextStyle' and its
6180    /// Material 2 twin: the default font size and colour, then the text theme's style that
6181    /// `custom` puts in its place.
6182    fn item_overrides_title_text_style(
6183        tester: &mut WidgetTester,
6184        theme: fn(&App) -> ThemeData,
6185        default_font_size: f64,
6186        default_color: impl Fn(&ThemeData) -> Option<Color>,
6187        custom: fn(crate::text_theme::TextTheme, TextStyle) -> crate::text_theme::TextTheme,
6188    ) {
6189        let key = GlobalKey::new();
6190        keyed_text_button(tester, theme, &key, text_and_list_tile_items);
6191
6192        // Show the menu.
6193        tap_key(tester, &key);
6194        tester.pump_and_settle();
6195
6196        let expected_color = default_color(&theme(&tester.cell.borrow()));
6197        for label in ["Item 0", "Item 1"] {
6198            let style = label_style(tester, label);
6199            assert_eq!(style.font_size, Some(default_font_size), "{label}");
6200            assert_eq!(style.color.as_deref().copied(), expected_color, "{label}");
6201        }
6202
6203        // Close the menu.
6204        tester.tap_at(Offset::new(20.0, 20.0), 1);
6205        tester.pump_and_settle();
6206
6207        // Test custom text theme.
6208        keyed_text_button(
6209            tester,
6210            move |app| {
6211                theme(app)
6212                    .copy_with()
6213                    .text_theme(custom(
6214                        crate::text_theme::TextTheme::new(),
6215                        custom_text_style(),
6216                    ))
6217                    .build()
6218            },
6219            &key,
6220            text_and_list_tile_items,
6221        );
6222
6223        // Show the menu.
6224        tap_key(tester, &key);
6225        tester.pump_and_settle();
6226
6227        for label in ["Item 0", "Item 1"] {
6228            let style = label_style(tester, label);
6229            assert_eq!(style.font_size, custom_text_style().font_size, "{label}");
6230            assert_eq!(
6231                style.font_weight,
6232                custom_text_style().font_weight,
6233                "{label}"
6234            );
6235            assert_eq!(style.font_style, custom_text_style().font_style, "{label}");
6236        }
6237    }
6238
6239    #[test]
6240    fn material3_popup_menu_item_overrides_list_tile_title_text_style() {
6241        test_widgets(|tester| {
6242            item_overrides_title_text_style(
6243                tester,
6244                m3,
6245                14.0,
6246                |theme| Some(theme.color_scheme.on_surface()),
6247                crate::text_theme::TextTheme::label_large,
6248            );
6249        });
6250    }
6251
6252    #[test]
6253    fn material2_popup_menu_item_overrides_list_tile_title_text_style() {
6254        test_widgets(|tester| {
6255            item_overrides_title_text_style(
6256                tester,
6257                m2,
6258                16.0,
6259                |theme| {
6260                    theme
6261                        .text_theme
6262                        .title_medium
6263                        .as_ref()
6264                        .and_then(|style| style.color.as_deref().copied())
6265                },
6266                crate::text_theme::TextTheme::title_medium,
6267            );
6268        });
6269    }
6270
6271    #[test]
6272    fn checked_popup_menu_item_on_tap_callback_is_called_when_defined() {
6273        test_widgets(|tester| {
6274            let (count, on_tap) = counter();
6275            tester.pump_widget(test_app(TextDirection::Ltr, move || {
6276                let on_tap = on_tap.clone();
6277                Material::new()
6278                    .child(
6279                        PopupMenuButton::new(move |_app, _context| {
6280                            vec![
6281                                PopupMenuEntryRef::new(
6282                                    CheckedPopupMenuItem::new()
6283                                        .on_tap(on_tap.clone())
6284                                        .value("item1".to_owned())
6285                                        .child(Text::new("Item with onTap")),
6286                                ),
6287                                PopupMenuEntryRef::new(
6288                                    CheckedPopupMenuItem::new()
6289                                        .value("item2".to_owned())
6290                                        .child(Text::new("Item without onTap")),
6291                                ),
6292                            ]
6293                        })
6294                        .child(Text::new("button")),
6295                    )
6296                    .into_widget()
6297            }));
6298
6299            for (label, expected) in [("Item with onTap", 1), ("Item without onTap", 1)] {
6300                tester.tap(find::text("button"));
6301                tester.pump_and_settle();
6302                let center = rect_with_text::<CheckedPopupMenuItem<String>>(tester, label).center();
6303                tester.tap_at(center, 1);
6304                tester.pump_and_settle();
6305                assert_eq!(count.get(), expected);
6306            }
6307        });
6308    }
6309
6310    /// Dart's 'PopupMenuButton uses root navigator if useRootNavigator is true' and 'does not
6311    /// use root navigator if useRootNavigator is false': whether the menu's route is the
6312    /// nested navigator's, which Dart's `MenuObserver`s count.
6313    fn button_menu_is_in_nested_navigator(
6314        tester: &mut WidgetTester,
6315        use_root_navigator: bool,
6316    ) -> bool {
6317        let nested_key = GlobalKey::new();
6318        let nested = nested_key.clone();
6319        pump_app(tester, m3, move |_app| {
6320            Navigator::new()
6321                .key(nested.into())
6322                .on_generate_route(move |app, _settings| {
6323                    let route = MaterialPageRoute::new(
6324                        app,
6325                        Rc::new(move |_app, _context| {
6326                            Material::new()
6327                                .child(
6328                                    PopupMenuButton::new(|_app, _context| {
6329                                        vec![
6330                                            PopupMenuEntryRef::new(
6331                                                CheckedPopupMenuItem::new()
6332                                                    .value("item1".to_owned())
6333                                                    .child(Text::new("item 1")),
6334                                            ),
6335                                            PopupMenuEntryRef::new(
6336                                                CheckedPopupMenuItem::new()
6337                                                    .value("item2".to_owned())
6338                                                    .child(Text::new("item 2")),
6339                                            ),
6340                                        ]
6341                                    })
6342                                    .use_root_navigator(use_root_navigator)
6343                                    .child(Text::new("button")),
6344                                )
6345                                .into_widget()
6346                        }),
6347                    );
6348                    Some(route.erase())
6349                })
6350                .into_widget()
6351        });
6352
6353        // Open the dialog.
6354        tester.tap(find::text("button"));
6355        tester.pump();
6356
6357        let menu = tester.element(find::by_type::<PopupMenu<String>>());
6358        let nested = nested_key
6359            .current_context(&tester.cell.borrow())
6360            .expect("the nested navigator is mounted");
6361        tester.ancestors(menu).contains(&nested)
6362    }
6363
6364    #[test]
6365    fn popup_menu_button_uses_root_navigator_if_use_root_navigator_is_true() {
6366        test_widgets(|tester| assert!(!button_menu_is_in_nested_navigator(tester, true)));
6367    }
6368
6369    #[test]
6370    fn popup_menu_button_does_not_use_root_navigator_if_use_root_navigator_is_false() {
6371        test_widgets(|tester| assert!(button_menu_is_in_nested_navigator(tester, false)));
6372    }
6373
6374    #[test]
6375    fn override_popup_menu_animation_using_animation_style() {
6376        test_widgets(|tester| {
6377            let target_key = GlobalKey::new();
6378            let build_popup_menu =
6379                |tester: &mut WidgetTester, animation_style: Option<AnimationStyle>| {
6380                    let key = target_key.clone();
6381                    pump_app(tester, m3, move |_app| {
6382                        let mut button = PopupMenuButton::new(|_app, _context| {
6383                            vec![item(1, "One"), item(2, "Two"), item(3, "Three")]
6384                        })
6385                        .key(key.into());
6386                        button.pop_up_animation_style = animation_style.clone();
6387                        Material::new()
6388                            .child(Center::new().child(button))
6389                            .into_widget()
6390                    });
6391                };
6392            let assert_size_within = |tester: &WidgetTester, expected: Size| {
6393                let size = last_material_size(tester);
6394                assert!(
6395                    (size - expected).distance() <= 0.1,
6396                    "{size:?} is not within 0.1 of {expected:?}"
6397                );
6398            };
6399
6400            // Test default animation.
6401            build_popup_menu(tester, None);
6402
6403            tap_key(tester, &target_key);
6404            tester.pump();
6405            // Advance the animation by 1/3 of its duration.
6406            tester.pump_by(Duration::from_millis(100));
6407            assert_size_within(tester, Size::new(112.0, 80.0));
6408
6409            // Advance the animation by 2/3 of its duration.
6410            tester.pump_by(Duration::from_millis(100));
6411            assert_size_within(tester, Size::new(112.0, 160.0));
6412
6413            // Advance the animation to the end.
6414            tester.pump_and_settle();
6415            assert_size_within(tester, Size::new(112.0, 160.0));
6416
6417            // Tap outside to dismiss the menu.
6418            tester.tap_at(Offset::new(20.0, 20.0), 1);
6419            tester.pump_and_settle();
6420
6421            // Override the animation duration.
6422            build_popup_menu(
6423                tester,
6424                Some(AnimationStyle::new(None, Some(Duration::ZERO), None, None)),
6425            );
6426
6427            tap_key(tester, &target_key);
6428            tester.pump();
6429            // Advance the animation by 1 millisecond.
6430            tester.pump_by(Duration::from_millis(1));
6431            assert_size_within(tester, Size::new(112.0, 160.0));
6432
6433            // Tap outside to dismiss the menu.
6434            tester.tap_at(Offset::new(20.0, 20.0), 1);
6435            tester.pump_and_settle();
6436
6437            // Override the animation curve.
6438            build_popup_menu(
6439                tester,
6440                Some(AnimationStyle::new(
6441                    Some(crate::motion::Easing::emphasized_accelerate()),
6442                    None,
6443                    None,
6444                    None,
6445                )),
6446            );
6447
6448            tap_key(tester, &target_key);
6449            tester.pump();
6450            // Advance the animation by 1/3 of its duration.
6451            tester.pump_by(Duration::from_millis(100));
6452            assert_size_within(tester, Size::new(32.4, 15.4));
6453
6454            // Advance the animation by 2/3 of its duration.
6455            tester.pump_by(Duration::from_millis(100));
6456            assert_size_within(tester, Size::new(112.0, 72.2));
6457
6458            // Advance the animation to the end.
6459            tester.pump_and_settle();
6460            assert_size_within(tester, Size::new(112.0, 160.0));
6461        });
6462    }
6463
6464    /// Dart's `tester.scrollUntilVisible(finder, delta)` on the menu's scroll view: drags it
6465    /// a step at a time until `text` is inside the view.
6466    fn scroll_menu_until_visible(tester: &mut WidgetTester, text: &str, delta: f64) {
6467        for _ in 0..50 {
6468            let viewport = scroll_view_rect(tester);
6469            let target = tester.get_rect(find::text(text));
6470            if target.top >= viewport.top && target.bottom <= viewport.bottom {
6471                return;
6472            }
6473            let step = if target.top < viewport.top {
6474                delta
6475            } else {
6476                -delta
6477            };
6478            let start = viewport.center();
6479            tester.drag_from(
6480                start,
6481                Offset::new(
6482                    0.0,
6483                    step.clamp(-viewport.height() / 2.0, viewport.height() / 2.0),
6484                ),
6485                1,
6486            );
6487            tester.pump();
6488        }
6489        panic!("{text} did not come into view");
6490    }
6491
6492    #[test]
6493    fn popup_menu_button_scrolls_initial_value_selected_value_to_visible() {
6494        test_widgets(|tester| {
6495            let length = 50;
6496            let selected_value = length - 1;
6497            pump_app(tester, m3, move |_app| {
6498                crate::scaffold::Scaffold::new()
6499                    .body(
6500                        Align::new()
6501                            .alignment(AlignmentGeometry::BOTTOM_CENTER)
6502                            .child(
6503                                PopupMenuButton::new(move |_app, _context| {
6504                                    (0..length)
6505                                        .map(|index| item(index, &format!("item #{index}")))
6506                                        .collect()
6507                                })
6508                                .pop_up_animation_style(AnimationStyle::NO_ANIMATION)
6509                                .initial_value(selected_value)
6510                                .child(Text::new("click here")),
6511                            ),
6512                    )
6513                    .into_widget()
6514            });
6515            tester.tap(find::text("click here"));
6516            tester.pump();
6517
6518            // Set up finder and verify basic widget structure.
6519            expect(tester, &find::text("item #49"), finds_one_widget());
6520
6521            // The initially selected menu item should be positioned on screen.
6522            let window_height = WidgetTester::SIZE.height();
6523            assert!(tester.get_rect(find::text("item #49")).bottom <= window_height);
6524
6525            // Select item 20.
6526            scroll_menu_until_visible(tester, "item #20", 500.0);
6527            expect(tester, &find::text("item #20"), finds_one_widget());
6528            tester.tap(find::text("item #20"));
6529            tester.pump();
6530
6531            // Open menu again.
6532            tester.tap(find::text("click here"));
6533            tester.pump();
6534            expect(tester, &find::text("item #20"), finds_one_widget());
6535
6536            // The selected menu item should be positioned on screen.
6537            assert!(tester.get_rect(find::text("item #20")).bottom <= window_height);
6538        });
6539    }
6540
6541    #[test]
6542    fn popup_menu_button_properly_positions_a_constrained_size_popup() {
6543        test_widgets(|tester| {
6544            let window_size = WidgetTester::SIZE;
6545            let length = 50;
6546            pump_app(tester, m3, move |_app| {
6547                crate::scaffold::Scaffold::new()
6548                    .body(
6549                        Padding::new(EdgeInsetsGeometry::all(50.0)).child(
6550                            Align::new()
6551                                .alignment(AlignmentGeometry::BOTTOM_CENTER)
6552                                .child(
6553                                    PopupMenuButton::new(move |_app, _context| {
6554                                        (0..length)
6555                                            .map(|index| item(index, &format!("item #{index}")))
6556                                            .collect()
6557                                    })
6558                                    .constraints(
6559                                        BoxConstraints::new()
6560                                            .max_height(window_size.height() / 3.0),
6561                                    )
6562                                    .pop_up_animation_style(AnimationStyle::NO_ANIMATION)
6563                                    .initial_value(length - 1)
6564                                    .child(Text::new("click here")),
6565                                ),
6566                        ),
6567                    )
6568                    .into_widget()
6569            });
6570            tester.tap(find::text("click here"));
6571            tester.pump();
6572
6573            // Set up finders and verify basic widget structure
6574            let button = tester.element(find::by_type::<PopupMenuButton<i32>>());
6575            expect(tester, &find::text("item #49"), finds_one_widget());
6576            let list_body = tester.element(find::by_type::<ListBody>());
6577            let list_viewport = tester.ancestor_of_type::<SingleChildScrollView>(list_body);
6578
6579            // The button and the list viewport should overlap
6580            let button_bounds = tester.get_rect(button);
6581            let list_viewport_bounds = tester.get_rect(list_viewport);
6582            assert!(list_viewport_bounds.top <= window_size.height());
6583            assert!(list_viewport_bounds.bottom <= window_size.height());
6584            assert!(list_viewport_bounds.overlaps(button_bounds));
6585        });
6586    }
6587
6588    #[test]
6589    fn popup_menu_button_honors_style() {
6590        test_widgets(|tester| {
6591            pump_app(tester, m3, |_app| {
6592                crate::scaffold::Scaffold::new()
6593                    .body(
6594                        PopupMenuButton::new(|_app, _context| vec![item(1, "One")]).style(
6595                            crate::button_style::ButtonStyle::new().icon_color(
6596                                <dyn WidgetStateProperty<Option<Color>>>::all(Some(
6597                                    crate::colors::Colors::RED.primary(),
6598                                )),
6599                            ),
6600                        ),
6601                    )
6602                    .into_widget()
6603            });
6604            let button = tester.element(find::by_type::<PopupMenuButton<i32>>());
6605            let rich_text = *tester
6606                .descendants_of_type::<waft_widgets::RichText>(button)
6607                .first()
6608                .expect("the icon's RichText");
6609            let color = tester.widget(rich_text, |rich_text: &waft_widgets::RichText| {
6610                rich_text
6611                    .text
6612                    .style()
6613                    .and_then(|style| style.color.as_deref().copied())
6614            });
6615            assert_eq!(color, Some(crate::colors::Colors::RED.primary()));
6616        });
6617    }
6618
6619    #[test]
6620    fn popup_menu_childs_ink_well_border_radius() {
6621        test_widgets(|tester| {
6622            let border_radius = BorderRadius::all(waft_embedder::Radius::circular(20.0));
6623            for radius in [None, Some(border_radius)] {
6624                centered_in_scaffold(tester, m3, move || {
6625                    let mut button = PopupMenuButton::new(|_app, _context| {
6626                        vec![item("value".to_owned(), "Item 0")]
6627                    })
6628                    .child(
6629                        waft_widgets::Row::new()
6630                            .main_axis_size(waft_rendering::MainAxisSize::Min)
6631                            .children(vec![
6632                                Text::new("Pop up menu").into_widget(),
6633                                Icon::new(Some(Icons::arrow_drop_down())).into_widget(),
6634                            ]),
6635                    );
6636                    button.border_radius = radius;
6637                    button.into_widget()
6638                });
6639                tester.pump_and_settle();
6640
6641                let ink_well = tester.element(find::by_type::<InkWell>());
6642                assert_eq!(
6643                    tester.widget(ink_well, |ink_well: &InkWell| ink_well
6644                        .ink_response
6645                        .border_radius),
6646                    radius
6647                );
6648            }
6649        });
6650    }
6651
6652    #[test]
6653    fn popup_menu_button_respects_material_tap_target_size() {
6654        test_widgets(|tester| {
6655            let button_size = 10.0;
6656            for (tap_target_size, expected) in [
6657                (MaterialTapTargetSize::Padded, Size::new(48.0, 48.0)),
6658                (
6659                    MaterialTapTargetSize::ShrinkWrap,
6660                    Size::new(button_size, button_size),
6661                ),
6662            ] {
6663                centered_in_scaffold(tester, m3, move || {
6664                    PopupMenuButton::new(|_app, _context| vec![item("value".to_owned(), "Item 0")])
6665                        .style(
6666                            crate::button_style::ButtonStyle::new()
6667                                .tap_target_size(tap_target_size),
6668                        )
6669                        .child(SizedBox::new().height(button_size).width(button_size))
6670                        .into_widget()
6671                });
6672                tester.pump_and_settle();
6673
6674                assert_eq!(rect_of::<InkWell>(tester).size(), expected);
6675            }
6676        });
6677    }
6678
6679    #[test]
6680    fn if_request_focus_is_false_the_original_focus_should_be_preserved_upon_menu_appearance() {
6681        test_widgets(|tester| {
6682            let field_focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut());
6683            pump_app(tester, m3, {
6684                let field_focus_node = field_focus_node.clone();
6685                move |_app| {
6686                    crate::scaffold::Scaffold::new()
6687                        .body(Column::new().children(vec![
6688                        crate::text_field::TextField::new()
6689                            .focus_node(field_focus_node.erase())
6690                            .autofocus(true)
6691                            .into_widget(),
6692                        PopupMenuButton::new(|_app, _context| vec![item(1, "One")])
6693                            .style(crate::button_style::ButtonStyle::new().icon_color(
6694                                <dyn WidgetStateProperty<Option<Color>>>::all(Some(
6695                                    crate::colors::Colors::RED.primary(),
6696                                )),
6697                            ))
6698                            .request_focus(false)
6699                            .child(Text::new("click here"))
6700                            .into_widget(),
6701                    ]))
6702                        .into_widget()
6703                }
6704            });
6705            tester.pump();
6706            assert!(waft_widgets::FocusNodeLeaf::has_focus(
6707                field_focus_node.handle(),
6708                &mut tester.cell.borrow_mut()
6709            ));
6710            tester.tap(find::text("click here"));
6711            tester.pump();
6712            assert!(waft_widgets::FocusNodeLeaf::has_focus(
6713                field_focus_node.handle(),
6714                &mut tester.cell.borrow_mut()
6715            ));
6716        });
6717    }
6718
6719    /// How many `Icon`s show `icon`: Dart's `find.byIcon(icon)` with `findsOneWidget` or
6720    /// `findsNothing`.
6721    fn icon_count(tester: &WidgetTester, icon: &waft_widgets::IconData) -> usize {
6722        find::by_type::<Icon>()
6723            .evaluate(tester)
6724            .into_iter()
6725            .filter(|element| {
6726                tester.widget(*element, |widget: &Icon| widget.icon.as_ref() == Some(icon))
6727            })
6728            .count()
6729    }
6730
6731    #[test]
6732    fn popup_menu_button_is_horizontal_on_ios() {
6733        test_widgets(|tester| {
6734            let build = |tester: &mut WidgetTester, target: waft_embedder::TargetPlatform| {
6735                tester.platform().set_target(target);
6736                pump_app(tester, m3, |_app| {
6737                    crate::scaffold::Scaffold::new()
6738                        .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
6739                            crate::app_bar::AppBar::new().actions(vec![
6740                                PopupMenuButton::new(|_app, _context| vec![item(1, "One")])
6741                                    .into_widget(),
6742                            ]),
6743                        ))
6744                        .into_widget()
6745                });
6746            };
6747
6748            build(tester, waft_embedder::TargetPlatform::Android);
6749
6750            assert_eq!(icon_count(tester, &Icons::more_vert()), 1);
6751            assert_eq!(icon_count(tester, &Icons::more_horiz()), 0);
6752
6753            for target in [
6754                waft_embedder::TargetPlatform::IOS,
6755                waft_embedder::TargetPlatform::MacOS,
6756            ] {
6757                build(tester, target);
6758                tester.pump_and_settle(); // Run theme change animation.
6759
6760                assert_eq!(icon_count(tester, &Icons::more_vert()), 0);
6761                assert_eq!(icon_count(tester, &Icons::more_horiz()), 1);
6762            }
6763        });
6764    }
6765
6766    #[test]
6767    #[should_panic(expected = "You can only pass [child] or [icon], not both.")]
6768    fn popup_menu_button_fails_when_given_both_child_and_icon() {
6769        PopupMenuButton::new(|_app, _context| vec![item(1, "1")])
6770            .icon(Icon::new(Some(Icons::view_carousel())))
6771            .child(Text::new("heyo"))
6772            .into_widget();
6773    }
6774
6775    #[test]
6776    fn popup_menu_button_creates_icon_button_when_given_an_icon() {
6777        test_widgets(|tester| {
6778            pump_app(tester, m3, |_app| {
6779                crate::scaffold::Scaffold::new()
6780                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
6781                        crate::app_bar::AppBar::new().actions(vec![
6782                            PopupMenuButton::new(|_app, _context| vec![item(1, "1")])
6783                                .icon(Icon::new(Some(Icons::view_carousel())))
6784                                .into_widget(),
6785                        ]),
6786                    ))
6787                    .into_widget()
6788            });
6789
6790            expect(tester, &find::by_type::<IconButton>(), finds_one_widget());
6791            assert_eq!(icon_count(tester, &Icons::view_carousel()), 1);
6792        });
6793    }
6794
6795    /// Dart's three 'PopupMenu positioning inside nested Overlay/Navigator' cases: the menu's
6796    /// top left, `find.bySemanticsLabel('Popup menu')` (the `_PopupMenu`'s box), is the
6797    /// button's.
6798    fn menu_top_left_is_the_buttons(tester: &mut WidgetTester, button_key: &GlobalKey) {
6799        tap_key(tester, button_key);
6800        tester.pump_and_settle();
6801
6802        let button_top_left = rect_of_key(tester, button_key).top_left();
6803        assert_f32_equals(
6804            rect_of::<PopupMenu<i32>>(tester).top_left(),
6805            button_top_left,
6806        );
6807    }
6808
6809    fn show_menu_button(key: &GlobalKey, use_root_navigator: bool) -> WidgetRef {
6810        PopupMenuButton::new(|_app, _context| vec![item(1, "Item 1"), item(2, "Item 2")])
6811            .key(key.clone().into())
6812            .use_root_navigator(use_root_navigator)
6813            .child(Text::new("Show Menu"))
6814            .into_widget()
6815    }
6816
6817    #[test]
6818    fn popup_menu_positioning_inside_nested_overlay() {
6819        test_widgets(|tester| {
6820            let button_key = GlobalKey::new();
6821            let key = button_key.clone();
6822            pump_app(tester, m3, move |app| {
6823                let body = crate::tooltip::tests::overlay(
6824                    app,
6825                    Center::new()
6826                        .child(show_menu_button(&key, false))
6827                        .into_widget(),
6828                );
6829                crate::scaffold::Scaffold::new()
6830                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
6831                        crate::app_bar::AppBar::new().title(Text::new("Example")),
6832                    ))
6833                    .body(Padding::new(EdgeInsetsGeometry::all(8.0)).child(body))
6834                    .into_widget()
6835            });
6836            menu_top_left_is_the_buttons(tester, &button_key);
6837        });
6838    }
6839
6840    fn nested_navigator_case(tester: &mut WidgetTester, use_root_navigator: bool) {
6841        let button_key = GlobalKey::new();
6842        let key = button_key.clone();
6843        pump_app(tester, m3, move |_app| {
6844            let key = key.clone();
6845            crate::scaffold::Scaffold::new()
6846                .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
6847                    crate::app_bar::AppBar::new().title(Text::new("Example")),
6848                ))
6849                .body(Padding::new(EdgeInsetsGeometry::all(8.0)).child(
6850                    Navigator::new().on_generate_route(move |app, _settings| {
6851                        let key = key.clone();
6852                        let route = MaterialPageRoute::new(
6853                            app,
6854                            Rc::new(move |_app, _context| {
6855                                Padding::new(EdgeInsetsGeometry::all(8.0))
6856                                    .child(
6857                                        Center::new()
6858                                            .child(show_menu_button(&key, use_root_navigator)),
6859                                    )
6860                                    .into_widget()
6861                            }),
6862                        );
6863                        Some(route.erase())
6864                    }),
6865                ))
6866                .into_widget()
6867        });
6868        menu_top_left_is_the_buttons(tester, &button_key);
6869    }
6870
6871    #[test]
6872    fn popup_menu_positioning_inside_nested_navigator() {
6873        test_widgets(|tester| nested_navigator_case(tester, false));
6874    }
6875
6876    #[test]
6877    fn popup_menu_positioning_inside_nested_navigator_when_use_root_navigator() {
6878        test_widgets(|tester| nested_navigator_case(tester, true));
6879    }
6880
6881    #[test]
6882    fn popup_menu_button_with_route_settings() {
6883        test_widgets(|tester| {
6884            let button_key = GlobalKey::new();
6885            let key = button_key.clone();
6886            pump_app(tester, m3, move |_app| {
6887                crate::scaffold::Scaffold::new()
6888                    .body(
6889                        PopupMenuButton::new(|_app, _context| {
6890                            vec![item(1, "Item 1"), item(2, "Item 2")]
6891                        })
6892                        .key(key.into())
6893                        .route_settings(RouteSettingsRef::Settings(
6894                            RouteSettings::default().name("/popup"),
6895                        ))
6896                        .child(Text::new("Show Menu")),
6897                    )
6898                    .into_widget()
6899            });
6900
6901            tap_key(tester, &button_key);
6902            tester.pump_and_settle();
6903
6904            // Dart's `_ClosureNavigatorObserver` records the settings of the route on top: the
6905            // menu's, which its items are in.
6906            let item = tester.element(find::text("Item 1"));
6907            let settings =
6908                waft_widgets::AnyModalRoute::settings_of(&mut tester.cell.borrow_mut(), item);
6909            assert_eq!(
6910                settings.as_ref().and_then(|settings| settings.name()),
6911                Some("/popup")
6912            );
6913        });
6914    }
6915
6916    #[test]
6917    fn popup_menu_removes_media_query_padding() {
6918        test_widgets(|tester| {
6919            let popup_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
6920            let saved = Rc::clone(&popup_context);
6921            pump_app(tester, m3, move |_app| {
6922                MediaQuery::new(
6923                    MediaQueryData::new().padding(EdgeInsets::all(50.0)),
6924                    Material::new().child(
6925                        PopupMenuButton::new(move |_app, context| {
6926                            saved.set(Some(context));
6927                            let saved = Rc::clone(&saved);
6928                            vec![PopupMenuEntryRef::new(
6929                                PopupMenuItem::new(Some(Builder::new(move |_app, context| {
6930                                    saved.set(Some(context));
6931                                    Text::new("AAA").into_widget()
6932                                })))
6933                                .value(1),
6934                            )]
6935                        })
6936                        .child(
6937                            SizedBox::new()
6938                                .height(100.0)
6939                                .width(100.0)
6940                                .child(Text::new("XXX")),
6941                        ),
6942                    ),
6943                )
6944                .into_widget()
6945            });
6946
6947            tester.tap(find::text("XXX"));
6948
6949            tester.pump();
6950
6951            let context = popup_context.get().expect("the menu built");
6952            assert_eq!(
6953                MediaQuery::of(&mut tester.cell.borrow_mut(), context).padding,
6954                EdgeInsets::ZERO
6955            );
6956        });
6957    }
6958
6959    /// Dart's `tester.widget<Container>(find.byType(Container))` of the open menu's divider.
6960    fn divider_container(
6961        tester: &mut WidgetTester,
6962        divider: PopupMenuDivider,
6963    ) -> (Option<EdgeInsetsGeometry>, waft_painting::BoxDecoration) {
6964        let divider = Rc::new(RefCell::new(Some(divider)));
6965        centered_in_scaffold(tester, m3, move || {
6966            let divider = Rc::clone(&divider);
6967            PopupMenuButton::<String>::new(move |_app, _context| {
6968                let divider = divider.borrow_mut().take().unwrap_or_default();
6969                vec![PopupMenuEntryRef::new(divider)]
6970            })
6971            .on_selected(|_app, _result: String| {})
6972            .child(Text::new("Menu Button"))
6973            .into_widget()
6974        });
6975
6976        let button = tester.element(find::by_type::<PopupMenuButton<String>>());
6977        let center = tester.get_rect(tester.render_box_of(button)).center();
6978        tester.tap_at(center, 1);
6979        tester.pump();
6980        let container = tester.element(find::by_type::<Container>());
6981        tester.widget(container, |container: &Container| {
6982            (
6983                container.margin,
6984                container
6985                    .decoration
6986                    .as_ref()
6987                    .and_then(|decoration| {
6988                        decoration
6989                            .as_any()
6990                            .downcast_ref::<waft_painting::BoxDecoration>()
6991                    })
6992                    .expect("a BoxDecoration")
6993                    .clone(),
6994            )
6995        })
6996    }
6997
6998    fn bottom_side(decoration: &waft_painting::BoxDecoration) -> waft_painting::BorderSide {
6999        decoration.border.as_ref().expect("a border").bottom()
7000    }
7001
7002    #[test]
7003    fn popup_menu_divider_custom_thickness() {
7004        test_widgets(|tester| {
7005            let (_, decoration) = divider_container(tester, PopupMenuDivider::new().thickness(5.0));
7006            assert_eq!(bottom_side(&decoration).width, 5.0);
7007        });
7008    }
7009
7010    #[test]
7011    fn popup_menu_divider_custom_indent() {
7012        test_widgets(|tester| {
7013            let (margin, _) = divider_container(tester, PopupMenuDivider::new().indent(5.0));
7014            match margin {
7015                Some(EdgeInsetsGeometry::Directional(margin)) => assert_eq!(margin.start, 5.0),
7016                other => panic!("an EdgeInsetsDirectional margin, not {other:?}"),
7017            }
7018        });
7019    }
7020
7021    #[test]
7022    fn popup_menu_divider_custom_color() {
7023        test_widgets(|tester| {
7024            let deep_orange = crate::colors::Colors::DEEP_ORANGE.primary();
7025            let (_, decoration) =
7026                divider_container(tester, PopupMenuDivider::new().color(deep_orange));
7027            assert_eq!(bottom_side(&decoration).color, deep_orange);
7028        });
7029    }
7030
7031    #[test]
7032    fn popup_menu_divider_custom_end_indent() {
7033        test_widgets(|tester| {
7034            let (margin, _) = divider_container(tester, PopupMenuDivider::new().end_indent(5.0));
7035            match margin {
7036                Some(EdgeInsetsGeometry::Directional(margin)) => assert_eq!(margin.end, 5.0),
7037                other => panic!("an EdgeInsetsDirectional margin, not {other:?}"),
7038            }
7039        });
7040    }
7041
7042    #[test]
7043    fn popup_menu_divider_custom_radius() {
7044        test_widgets(|tester| {
7045            let (_, decoration) = divider_container(
7046                tester,
7047                PopupMenuDivider::new()
7048                    .radius(BorderRadius::all(waft_embedder::Radius::circular(5.0))),
7049            );
7050            assert_eq!(
7051                decoration.border_radius,
7052                Some(BorderRadiusGeometry::from(BorderRadius::all(
7053                    waft_embedder::Radius::circular(5.0)
7054                )))
7055            );
7056        });
7057    }
7058
7059    // Regression test for https://github.com/flutter/flutter/issues/171422.
7060    #[test]
7061    fn popup_menu_button_should_not_crash_when_being_hidden_immediately() {
7062        test_widgets(|tester| {
7063            let show_popup_menu = Rc::new(Cell::new(true));
7064            let build_widget = |tester: &mut WidgetTester| {
7065                let show = Rc::clone(&show_popup_menu);
7066                pump_app(tester, m3, move |_app| {
7067                    let mut actions = Vec::new();
7068                    if show.get() {
7069                        let hide = Rc::clone(&show);
7070                        actions.push(
7071                            PopupMenuButton::new(|_app, _context| {
7072                                vec![
7073                                    item("add".to_owned(), "Add"),
7074                                    item("hide".to_owned(), "Hide"),
7075                                    item("delete".to_owned(), "Delete"),
7076                                ]
7077                            })
7078                            .on_selected(move |_app, value: String| {
7079                                if value == "hide" {
7080                                    hide.set(false);
7081                                }
7082                            })
7083                            .into_widget(),
7084                        );
7085                    }
7086                    let shown = if show.get() {
7087                        "PopupMenu is showing"
7088                    } else {
7089                        "PopupMenu is hidden"
7090                    };
7091                    crate::scaffold::Scaffold::new()
7092                        .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
7093                            crate::app_bar::AppBar::new().actions(actions),
7094                        ))
7095                        .body(Text::new(format!("PopupMenuButton:{shown}")))
7096                        .into_widget()
7097                });
7098            };
7099
7100            build_widget(tester);
7101
7102            // Find the PopupMenuButton.
7103            let button = tester.element(find::by_type::<PopupMenuButton<String>>());
7104
7105            // Tap on PopupMenuButton.
7106            let center = tester.get_rect(tester.render_box_of(button)).center();
7107            tester.tap_at(center, 1);
7108            tester.pump_and_settle();
7109
7110            // Tap on "Hide" menu item.
7111            tester.tap(find::text("Hide"));
7112
7113            // Rebuild the widget tree with the PopupMenuButton removed to trigger the bug.
7114            build_widget(tester);
7115        });
7116    }
7117
7118    // Regression test for https://github.com/flutter/flutter/issues/43824.
7119    #[test]
7120    fn popup_menu_updates_when_popup_menu_theme_in_theme_changes() {
7121        test_widgets(|tester| {
7122            let theme = |elevation: f64, color: Color, shadow: Color, tint: Color, radius: f64| {
7123                PopupMenuThemeData::new()
7124                    .elevation(elevation)
7125                    .color(color)
7126                    .shadow_color(shadow)
7127                    .surface_tint_color(tint)
7128                    .shape(waft_painting::RoundedRectangleBorder::new(
7129                        waft_painting::BorderSide::NONE,
7130                        BorderRadiusGeometry::circular(radius),
7131                    ))
7132                    .menu_padding(EdgeInsetsGeometry::all(radius))
7133            };
7134            let colors = crate::colors::Colors::RED.primary();
7135            let popup_menu_theme1 = theme(
7136                10.0,
7137                colors,
7138                crate::colors::Colors::BLACK,
7139                crate::colors::Colors::WHITE,
7140                10.0,
7141            );
7142            let popup_menu_theme2 = theme(
7143                20.0,
7144                crate::colors::Colors::BLUE.primary(),
7145                crate::colors::Colors::WHITE,
7146                crate::colors::Colors::BLACK,
7147                20.0,
7148            );
7149            let build_app = |tester: &mut WidgetTester, popup_menu_theme: PopupMenuThemeData| {
7150                pump_app(
7151                    tester,
7152                    move |app| {
7153                        ThemeData::builder()
7154                            .popup_menu_theme(popup_menu_theme)
7155                            .build(app)
7156                    },
7157                    |_app| {
7158                        crate::scaffold::Scaffold::new()
7159                            .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
7160                                crate::app_bar::AppBar::new().actions(vec![
7161                                    PopupMenuButton::new(|_app, _context| {
7162                                        vec![
7163                                            item("0".to_owned(), "Item 0"),
7164                                            item("1".to_owned(), "Item 1"),
7165                                        ]
7166                                    })
7167                                    .into_widget(),
7168                                ]),
7169                            ))
7170                            .into_widget()
7171                    },
7172                );
7173            };
7174            let check_popup_menu =
7175                |tester: &WidgetTester, popup_menu_theme: &PopupMenuThemeData| {
7176                    let materials = find::by_type::<Material>().evaluate(tester);
7177                    let material = *materials.last().expect("the menu's Material");
7178                    tester.widget(material, |material: &Material| {
7179                        assert_eq!(Some(material.elevation), popup_menu_theme.elevation);
7180                        assert_eq!(material.color, popup_menu_theme.color);
7181                        assert_eq!(material.shadow_color, popup_menu_theme.shadow_color);
7182                        assert_eq!(
7183                            material.surface_tint_color,
7184                            popup_menu_theme.surface_tint_color
7185                        );
7186                        assert_eq!(material.shape, popup_menu_theme.shape);
7187                    });
7188                    assert_eq!(menu_padding(tester), popup_menu_theme.menu_padding);
7189                };
7190
7191            // Show the menu with the first theme.
7192            build_app(tester, popup_menu_theme1.clone());
7193            let button = tester.element(find::by_type::<PopupMenuButton<String>>());
7194            let center = tester.get_rect(tester.render_box_of(button)).center();
7195            tester.tap_at(center, 1);
7196            tester.pump_and_settle();
7197
7198            check_popup_menu(tester, &popup_menu_theme1);
7199
7200            // Rebuild with the second theme.
7201            build_app(tester, popup_menu_theme2.clone());
7202            tester.pump_and_settle();
7203
7204            check_popup_menu(tester, &popup_menu_theme2);
7205        });
7206    }
7207
7208    #[test]
7209    fn checked_popup_menu_item_does_not_crash_at_zero_area() {
7210        test_widgets(|tester| {
7211            centered_in_scaffold(tester, m3, || {
7212                SizedBox::shrink()
7213                    .child(CheckedPopupMenuItem::<String>::new().child(Text::new("X")))
7214                    .into_widget()
7215            });
7216            assert_eq!(
7217                rect_of::<CheckedPopupMenuItem<String>>(tester).size(),
7218                Size::ZERO
7219            );
7220        });
7221    }
7222
7223    #[test]
7224    fn popup_menu_item_does_not_crash_at_zero_area() {
7225        test_widgets(|tester| {
7226            centered_in_scaffold(tester, m3, || {
7227                SizedBox::shrink()
7228                    .child(PopupMenuItem::<String>::new(Some(Text::new("X"))))
7229                    .into_widget()
7230            });
7231            assert_eq!(rect_of::<PopupMenuItem<String>>(tester).size(), Size::ZERO);
7232        });
7233    }
7234
7235    #[test]
7236    fn popup_menu_button_does_not_crash_at_zero_area() {
7237        // This test case only verifies the layout of the button itself, not the
7238        // overlay, because there doesn't seem to be a way to open the menu at zero
7239        // area. Though, this should be sufficient since the overlay has been verified
7240        // by similar tests for MenuAnchor and PopupMenuItem.
7241        test_widgets(|tester| {
7242            tester.view().set_physical_size(Size::ZERO);
7243            pump_app(tester, m3, |_app| {
7244                Center::new()
7245                    .child(
7246                        SizedBox::shrink().child(PopupMenuButton::new(|_app, _context| {
7247                            vec![item("X".to_owned(), "X")]
7248                        })),
7249                    )
7250                    .into_widget()
7251            });
7252            assert_eq!(
7253                rect_of::<PopupMenuButton<String>>(tester).size(),
7254                Size::ZERO
7255            );
7256        });
7257    }
7258
7259    #[test]
7260    fn popup_menu_divider_does_not_crash_at_zero_area() {
7261        test_widgets(|tester| {
7262            pump_app(tester, m3, |_app| {
7263                Center::new()
7264                    .child(SizedBox::shrink().child(PopupMenuDivider::new()))
7265                    .into_widget()
7266            });
7267            assert_eq!(rect_of::<PopupMenuDivider>(tester).size(), Size::ZERO);
7268        });
7269    }
7270
7271    // Regression test for https://github.com/flutter/flutter/issues/177003
7272    /// Dart's `find.bySemanticsLabel(popupMenuLabel)`: the label the menu's `Semantics` is
7273    /// built with, per host platform and theme platform.
7274    #[test]
7275    fn popup_menu_semantics_for_mismatched_platforms() {
7276        use waft_embedder::TargetPlatform;
7277        test_widgets(|_| {
7278            for target in [
7279                TargetPlatform::Android,
7280                TargetPlatform::Fuchsia,
7281                TargetPlatform::IOS,
7282                TargetPlatform::Linux,
7283                TargetPlatform::MacOS,
7284                TargetPlatform::Windows,
7285            ] {
7286                let mut tester = WidgetTester::on(target);
7287                let tester = &mut tester;
7288                for theme_platform in [TargetPlatform::Android, TargetPlatform::IOS] {
7289                    pump_app(
7290                        tester,
7291                        move |app| ThemeData::builder().platform(theme_platform).build(app),
7292                        |_app| {
7293                            crate::scaffold::Scaffold::new()
7294                                .body(Builder::new(|_app, context| {
7295                                    crate::outlined_button::OutlinedButton::new(
7296                                        Some(Listener::new(move |app| {
7297                                            drop(show_menu_at_fill::<()>(
7298                                                app,
7299                                                context,
7300                                                vec![PopupMenuEntryRef::new(PopupMenuItem::new(
7301                                                    Some(Text::new("foo")),
7302                                                ))],
7303                                                None,
7304                                            ));
7305                                        })),
7306                                        Some(Text::new("open")),
7307                                    )
7308                                    .into_widget()
7309                                }))
7310                                .into_widget()
7311                        },
7312                    );
7313
7314                    tester.tap(find::text("open"));
7315                    tester.pump_and_settle();
7316
7317                    let menu = tester.element(find::by_type::<PopupMenu<()>>());
7318                    let label =
7319                        tester.widget(menu, |menu: &PopupMenu<()>| menu.semantic_label.clone());
7320                    match target {
7321                        // Apple platforms don't show label.
7322                        TargetPlatform::IOS | TargetPlatform::MacOS => assert_eq!(label, None),
7323                        // Non-Apple platforms show label.
7324                        _ => {
7325                            assert_eq!(label, Some(DefaultMaterialLocalizations.popup_menu_label()))
7326                        }
7327                    }
7328
7329                    // Dismiss the popup.
7330                    let foo = tester.element(find::text("foo"));
7331                    pop(tester, foo);
7332                    tester.pump_and_settle();
7333                }
7334            }
7335        });
7336    }
7337
7338    /// Dart's collector frees the item fades `_PopupMenuState` makes once the menu closes;
7339    /// here they are freed with the state's references to them.
7340    #[test]
7341    fn a_closed_menu_frees_the_item_fades_its_state_made() {
7342        test_widgets(|tester| {
7343            let key = GlobalKey::new();
7344            let button_key = key.clone();
7345            pump_app(tester, m3, move |_app| {
7346                Material::new()
7347                    .child(
7348                        PopupMenuButton::new(|_app, _context| vec![item(1, "One"), item(2, "Two")])
7349                            .key(button_key.into()),
7350                    )
7351                    .into_widget()
7352            });
7353            tap_key(tester, &key);
7354            tester.pump_and_settle();
7355            let opacities = {
7356                let menu = tester.element(find::by_type::<PopupMenu<i32>>());
7357                let app = tester.cell.borrow();
7358                let state = menu
7359                    .state_handle::<PopupMenuState<i32>>(&app)
7360                    .expect("the menu is stateful");
7361                app.get(state)
7362                    .opacities
7363                    .iter()
7364                    .map(|opacity| opacity.handle())
7365                    .collect::<Vec<_>>()
7366            };
7367            assert_eq!(opacities.len(), 2);
7368
7369            tester.tap_at(Offset::ZERO, 1);
7370            tester.pump_and_settle();
7371            tester.cell.checkpoint();
7372            let app = tester.cell.borrow();
7373            assert!(opacities.iter().all(|opacity| !app.contains(*opacity)));
7374        });
7375    }
7376}