From e1e029d26d54728bff49620340fb11ebf974cd4e Mon Sep 17 00:00:00 2001 From: davidhicks980 <59215665+davidhicks980@users.noreply.github.com> Date: Wed, 28 Jan 2026 19:56:42 -0500 Subject: [PATCH] [material/menu_anchor.dart] Add animations to MenuAnchor. (#176494) * Adds MD3 animations to MenuAnchor. * Adds a "hoverOpenDelay" parameter on `SubmenuButton` * Moves the layout algorithm from SingleChildLayoutDelegate to a custom render object. This was done because I needed to access the dry layout of the menu panel for the best effect. I'll demonstrate below. Turns out using dry layout significantly limits what children you can use with a widget. As a result, I'm calculating the final height using the inverse height factor. Fixes https://github.com/flutter/flutter/issues/135025 I don't have access to the internal Google documentation, so I did my best to deduce the spec from https://github.com/material-components/material-web/blob/main/menu/internal/menu.ts. This change is currently opt-in via an `animated` parameter on `MenuAnchor` and `SubmenuButton`. As a result, this is not a breaking change. Because the PR is already quite large, I chose to not add animation customization to this PR. I also didn't change any theming files or `DropdownMenu`. The only other API addition is a `hoverOpenDelay` parameter on `SubmenuButton`. This parameter delays the start of a submenu opening by the specified duration. It is independent of the `animated` parameter. When `animated == false`, the menu runs its forward and reverse animations with a duration of 0. I originally disposed of all animation assets when `animated` was false, but found that the code/testing complexity to be unwieldy. Blocked by https://github.com/flutter/flutter/pull/176503 ## Examples * Basic example adapted from material-web https://github.com/user-attachments/assets/e6d02fab-e11c-4dce-ab82-2fb39c1111e0 * Example showing scrollbar https://github.com/user-attachments/assets/847054ba-7218-4e73-9835-019bfa7b5521 * MenuBar usage https://github.com/user-attachments/assets/8231b1cd-c40c-4f18-af87-1b77b43ecb7b Thanks to @QuncCccccc and @dkwingsmt for [their work on this issue.](https://github.com/flutter/flutter/pull/143416) Sorry for throwing a wrench into the original PR by introducing `RawMenuAnchor`... ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --- .../material/menu_anchor/menu_anchor.0.dart | 11 +- .../material/menu_anchor/menu_anchor.1.dart | 2 + .../lib/material/menu_anchor/menu_bar.0.dart | 10 +- .../menu_anchor/menu_anchor.0_test.dart | 40 +- .../flutter/lib/src/material/menu_anchor.dart | 622 +++++++- .../test/material/menu_anchor_test.dart | 1372 ++++++++++++++++- 6 files changed, 1982 insertions(+), 75 deletions(-) diff --git a/examples/api/lib/material/menu_anchor/menu_anchor.0.dart b/examples/api/lib/material/menu_anchor/menu_anchor.0.dart index b5f2b5506fd..c1fd7a90790 100644 --- a/examples/api/lib/material/menu_anchor/menu_anchor.0.dart +++ b/examples/api/lib/material/menu_anchor/menu_anchor.0.dart @@ -55,6 +55,7 @@ class _MyCascadingMenuState extends State { MenuEntry? _lastSelection; final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button'); ShortcutRegistryEntry? _shortcutsEntry; + AnimationStatus _animationStatus = AnimationStatus.dismissed; Color get backgroundColor => _backgroundColor; Color _backgroundColor = Colors.red; @@ -109,6 +110,13 @@ class _MyCascadingMenuState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ MenuAnchor( + animated: true, + onAnimationStatusChanged: (AnimationStatus status) { + // Store the animation status so that it can be used to determine + // whether the menu is opening or closing when the button is + // pressed. + _animationStatus = status; + }, childFocusNode: _buttonFocusNode, menuChildren: [ MenuItemButton( @@ -128,6 +136,7 @@ class _MyCascadingMenuState extends State { child: Text(MenuEntry.showMessage.label), ), SubmenuButton( + animated: true, menuChildren: [ MenuItemButton( onPressed: () => _activate(MenuEntry.colorRed), @@ -153,7 +162,7 @@ class _MyCascadingMenuState extends State { return TextButton( focusNode: _buttonFocusNode, onPressed: () { - if (controller.isOpen) { + if (_animationStatus.isForwardOrCompleted) { controller.close(); } else { controller.open(); diff --git a/examples/api/lib/material/menu_anchor/menu_anchor.1.dart b/examples/api/lib/material/menu_anchor/menu_anchor.1.dart index e68b4e2b1fe..876059d1a84 100644 --- a/examples/api/lib/material/menu_anchor/menu_anchor.1.dart +++ b/examples/api/lib/material/menu_anchor/menu_anchor.1.dart @@ -142,6 +142,7 @@ class _MyContextMenuState extends State { onTapDown: _handleTapDown, onSecondaryTapDown: _handleSecondaryTapDown, child: MenuAnchor( + animated: true, controller: _menuController, menuChildren: [ MenuItemButton( @@ -161,6 +162,7 @@ class _MyContextMenuState extends State { child: Text(MenuEntry.showMessage.label), ), SubmenuButton( + animated: true, menuChildren: [ MenuItemButton( onPressed: () => _activate(MenuEntry.colorRed), diff --git a/examples/api/lib/material/menu_anchor/menu_bar.0.dart b/examples/api/lib/material/menu_anchor/menu_bar.0.dart index 4a02fc369eb..25959c26ec0 100644 --- a/examples/api/lib/material/menu_anchor/menu_bar.0.dart +++ b/examples/api/lib/material/menu_anchor/menu_bar.0.dart @@ -29,11 +29,17 @@ class MenuEntry { final VoidCallback? onPressed; final List? menuChildren; - static List build(List selections) { + static List build( + List selections, [ + Duration hoverOpenDelay = Duration.zero, + ]) { Widget buildSelection(MenuEntry selection) { if (selection.menuChildren != null) { return SubmenuButton( - menuChildren: MenuEntry.build(selection.menuChildren!), + menuChildren: MenuEntry.build( + selection.menuChildren!, + const Duration(milliseconds: 150), + ), child: Text(selection.label), ); } diff --git a/examples/api/test/material/menu_anchor/menu_anchor.0_test.dart b/examples/api/test/material/menu_anchor/menu_anchor.0_test.dart index 20636f4a528..186412e0e57 100644 --- a/examples/api/test/material/menu_anchor/menu_anchor.0_test.dart +++ b/examples/api/test/material/menu_anchor/menu_anchor.0_test.dart @@ -27,7 +27,7 @@ void main() { await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); expect(find.text('Background Color'), findsOneWidget); expect(find.text(example.MenuEntry.colorRed.label), findsOneWidget); @@ -35,7 +35,7 @@ void main() { expect(find.text(example.MenuEntry.colorBlue.label), findsOneWidget); await tester.tap(find.text('Background Color')); - await tester.pump(); + await tester.pump(const Duration(milliseconds: 150)); expect(find.text(example.MenuEntry.colorRed.label), findsNothing); expect(find.text(example.MenuEntry.colorGreen.label), findsNothing); @@ -135,4 +135,40 @@ void main() { const Offset(0.0, safeAreaPadding), ); }); + + testWidgets('MenuAnchor can toggle between opening and closing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(const example.MenuApp()); + + await tester.tap(find.text('OPEN MENU')); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + Finder panel = find + .descendant( + of: find.byType(MenuAnchor), + matching: find.byType(FadeTransition), + ) + .first; + + final double panelHeight = tester.getSize(panel).height; + // Height differs based on platform, so use a large range. + expect(panelHeight, closeTo(135, 20)); + + await tester.tap(find.text('OPEN MENU')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final double panelHeightAfterClose = tester.getSize(panel).height; + expect(panelHeightAfterClose, closeTo(90, 20)); + + await tester.tap(find.text('OPEN MENU')); + await tester.pump(); + await tester.pumpAndSettle(); + + final double panelHeightAfterReopen = tester.getSize(panel).height; + expect(panelHeightAfterReopen, closeTo(140, 20)); + }); } diff --git a/packages/flutter/lib/src/material/menu_anchor.dart b/packages/flutter/lib/src/material/menu_anchor.dart index e8b7d023a94..8f15b29743d 100644 --- a/packages/flutter/lib/src/material/menu_anchor.dart +++ b/packages/flutter/lib/src/material/menu_anchor.dart @@ -10,7 +10,9 @@ /// @docImport 'radio_theme.dart'; library; +import 'dart:async'; import 'dart:math' as math; +import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -33,6 +35,7 @@ import 'menu_bar_theme.dart'; import 'menu_button_theme.dart'; import 'menu_style.dart'; import 'menu_theme.dart'; +import 'motion.dart'; import 'radio.dart'; import 'scrollbar.dart'; import 'text_button.dart'; @@ -46,6 +49,7 @@ import 'theme_data.dart'; // enum SingingCharacter { lafayette } // late SingingCharacter? _character; // late StateSetter setState; +// AnimationStatus animationStatus = AnimationStatus.dismissed; // Enable if you want verbose logging about menu changes. const bool _kDebugMenus = false; @@ -84,6 +88,50 @@ const double _kMenuViewPadding = 8; // The minimum horizontal spacing on the outside of the top level menu. const double _kTopLevelMenuHorizontalMinPadding = 4; +// The default opening animation duration for menus. +const Duration _kMenuOpeningDuration = Duration(milliseconds: 500); + +// The default closing animation duration for menus. +const Duration _kMenuClosingDuration = Duration(milliseconds: 150); + +/// The default curve used to animate the height of the menu panel while the +/// menu is opening. +/// +/// **NOTE**: This animation curve follows the material web implementation of +/// [Easing.emphasized](https://github.com/material-components/material-web/blob/516cbc02bf770b7c3c5c6b546f1e5d81939b9f23/internal/motion/animation.ts#L18) +/// instead of the curve recommended by the Material 3 specification, +/// [Curves.easeInOutCubicEmphasized](https://m3.material.io/styles/motion/easing-and-duration/tokens-specs). +/// This change was made because the web curve [was more consistent with the +/// timing of the menu item fade-in +/// animations](https://github.com/flutter/flutter/pull/176494#discussion_r2545178254). +const Curve _kMenuPanelHeightForwardCurve = Cubic(.3, 0, 0, 1); + +// The default curve used to animate the height of the menu panel while the menu +// is closing. +const Curve _kMenuPanelHeightReverseCurve = _TweenCurve( + 0.35, + 1, + curve: FlippedCurve(Easing.emphasizedAccelerate), +); + +// The default curve used to animate the opacity of the menu panel when opening. +const Curve _kMenuPanelOpacityForwardCurve = Interval(0, 50 / 500); + +// The default curve used to animate the opacity of the menu panel when closing. +const Curve _kMenuPanelOpacityReverseCurve = FlippedCurve(Interval(100 / 150, 150 / 150)); + +// The default fade-in duration of each menu item as a fraction of the opening +// duration. +const double _kMenuItemRelativeFadeInDuration = 1 / 2; + +// The default fade-out duration of each menu item as a fraction of the closing +// duration. +const double _kMenuItemRelativeFadeOutDuration = 1 / 3; + +// The default delay between the start of each menu item's fade-out as a +// fraction of the closing duration. +const double _kMenuItemRelativeFadeOutDelay = 1 / 3; + /// The type of builder function used by [MenuAnchor.builder] to build the /// widget that the [MenuAnchor] surrounds. /// @@ -99,17 +147,54 @@ typedef MenuAnchorChildBuilder = Widget Function(BuildContext context, MenuController controller, Widget? child); class _MenuAnchorScope extends InheritedWidget { - const _MenuAnchorScope({required this.state, required super.child}); + const _MenuAnchorScope({ + required this.state, + required this.animationStatus, + required super.child, + }); final _MenuAnchorState state; + final AnimationStatus animationStatus; @override bool updateShouldNotify(_MenuAnchorScope oldWidget) { assert(oldWidget.state == state, 'The state of a MenuAnchor should not change.'); - return false; + return oldWidget.animationStatus != animationStatus; } } +// A curve that linearly interpolates between two values over a given curve. +// +// For example, `_TweenCurve(0.2, 0.8, curve: Curves.easeIn)` will produce a +// curve that starts at 0.2, ends at 0.8, and follows the easeIn curve between +// those two values. The curve is applied first, and then the result is linearly +// interpolated between begin and end. +// +// This differs from an `Interval` in that an Interval changes the duration over +// which the curve is applied, whereas `_TweenCurve` changes the output range of +// the curve. +class _TweenCurve extends Curve { + const _TweenCurve(this.begin, this.end, {required this.curve}) + : assert(begin >= 0.0), + assert(begin <= 1.0), + assert(end >= 0.0), + assert(end <= 1.0), + assert(end >= begin); + + final double begin; + final double end; + final Curve curve; + + @override + double transformInternal(double t) { + t = curve.transform(t); + return ui.lerpDouble(begin, end, t)!; + } + + @override + String toString() => '_TweenCurve($begin, $end, $curve)'; +} + /// A widget used to mark the "anchor" for a set of submenus, defining the /// rectangle used to position the menu, which can be done either with an /// explicit location, or with an alignment. @@ -128,7 +213,8 @@ class _MenuAnchorScope extends InheritedWidget { /// /// {@tool dartpad} /// This example shows how to use a [MenuAnchor] to wrap a button and open a -/// cascading menu from the button. +/// cascading menu from the button. This example also shows how to use +/// [onAnimationStatusChanged] to track animation status and toggle the menu. /// /// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.0.dart ** /// {@end-tool} @@ -174,6 +260,8 @@ class MenuAnchor extends StatefulWidget { this.onClose, this.crossAxisUnconstrained = true, this.useRootOverlay = false, + this.animated = false, + this.onAnimationStatusChanged, required this.menuChildren, this.builder, this.child, @@ -293,6 +381,55 @@ class MenuAnchor extends StatefulWidget { /// Defaults to false. final bool useRootOverlay; + /// Whether this widget should open or close a submenu with an animation. + /// + /// Defaults to false. + final bool animated; + + /// An optional callback that is invoked when the [AnimationStatus] of the + /// menu changes during open and close animations. + /// + /// If [animated] is false, this callback will only be invoked with + /// [AnimationStatus.completed] when the menu is opened, and + /// [AnimationStatus.dismissed] when the menu is closed. + /// + /// This callback provides a way to determine when the menu is opening or + /// closing. This is necessary because the [MenuController.isOpen] property + /// remains true throughout the opening, opened, and closing phases, and + /// therefore cannot be used on its own to determine the current animation + /// direction. + /// + /// {@tool snippet} + /// This example shows how to use the [onAnimationStatusChanged] callback to + /// create a [MenuAnchor] that will toggle between opening and closing. + /// + /// ```dart + /// MenuAnchor( + /// animated: true, + /// onAnimationStatusChanged: (AnimationStatus status) { + /// // Typically, animationStatus would be stored in a State object. + /// animationStatus = status; + /// }, + /// menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Menu Item'))], + /// builder: (BuildContext context, MenuController controller, Widget? child) { + /// return IconButton( + /// onPressed: () { + /// if (animationStatus.isForwardOrCompleted) { + /// controller.close(); + /// } else { + /// controller.open(); + /// } + /// }, + /// icon: const Icon(Icons.more_vert), + /// ); + /// }, + /// ); + /// ``` + /// {@end-tool} + /// + /// Defaults to null. + final ValueChanged? onAnimationStatusChanged; + /// A list of children containing the menu items that are the contents of the /// menu surrounded by this [MenuAnchor]. /// @@ -345,16 +482,42 @@ class MenuAnchor extends StatefulWidget { } } -class _MenuAnchorState extends State { +class _MenuAnchorState extends State with SingleTickerProviderStateMixin { Axis get _orientation => Axis.vertical; MenuController get _menuController => widget.controller ?? _internalMenuController!; MenuController? _internalMenuController; final FocusScopeNode _menuScopeNode = FocusScopeNode(); - _MenuAnchorState? get _parent => _MenuAnchorState._maybeOf(context); + late final AnimationController _animationController = AnimationController(vsync: this); + late final CurvedAnimation heightAnimation = CurvedAnimation( + parent: _animationController, + curve: _kMenuPanelHeightForwardCurve, + reverseCurve: _kMenuPanelHeightReverseCurve, + ); + late final CurvedAnimation opacityAnimation = CurvedAnimation( + parent: _animationController, + curve: _kMenuPanelOpacityForwardCurve, + reverseCurve: _kMenuPanelOpacityReverseCurve, + ); + List _menuChildren = []; + List _cachedAnimations = []; + _MenuAnchorState? get _parent => _maybeOf(context); + bool get isSubmenu => MenuController.maybeOf(context) != null; + bool get isClosingOrClosed => switch (_animationController.status) { + AnimationStatus.dismissed || AnimationStatus.reverse => true, + AnimationStatus.forward || AnimationStatus.completed => false, + }; + bool get isClosing => switch (_animationController.status) { + AnimationStatus.reverse => true, + AnimationStatus.dismissed || AnimationStatus.forward || AnimationStatus.completed => false, + }; @override void initState() { super.initState(); + _resolveAnimationController(); + _resolveMenuItems(); + _animationController.addStatusListener(_handleAnimationStatusChanged); + if (widget.controller == null) { _internalMenuController = MenuController(); } @@ -370,21 +533,141 @@ class _MenuAnchorState extends State { _internalMenuController = null; } } + + if (oldWidget.animated != widget.animated || widget.menuChildren != oldWidget.menuChildren) { + _resolveMenuItems(); + } + + if (oldWidget.animated != widget.animated) { + _resolveAnimationController(); + } } @override void dispose() { assert(_debugMenuInfo('Disposing of $this')); + _menuChildren.clear(); + for (final CurvedAnimation animation in _cachedAnimations) { + animation.dispose(); + } _internalMenuController = null; _menuScopeNode.dispose(); + heightAnimation.dispose(); + opacityAnimation.dispose(); + _animationController.stop(); + _animationController.dispose(); super.dispose(); } + void _resolveAnimationController() { + if (widget.animated) { + _animationController.duration = _kMenuOpeningDuration; + _animationController.reverseDuration = _kMenuClosingDuration; + } else { + _animationController.duration = Duration.zero; + _animationController.reverseDuration = Duration.zero; + } + } + + void _resolveMenuItems() { + _menuChildren = []; + for (final CurvedAnimation animation in _cachedAnimations) { + animation.dispose(); + } + _cachedAnimations = []; + + final int itemCount = widget.menuChildren.length; + if (itemCount == 0) { + return; + } + + if (!widget.animated) { + _menuChildren.addAll(widget.menuChildren); + return; + } + + const double forwardFinalItemOffset = 1 - _kMenuItemRelativeFadeInDuration; + const double reverseFinalItemOffset = + 1 - _kMenuItemRelativeFadeOutDuration - _kMenuItemRelativeFadeOutDelay; + + double forwardProgress = 0; + double reverseProgress = 0; + double itemFadeInGap = 0; + double itemFadeOutGap = 0; + if (itemCount > 1) { + // Spread every item evenly across the remaining time after accounting for + // the fade in/out durations. + itemFadeInGap = forwardFinalItemOffset / (itemCount - 1); + itemFadeOutGap = reverseFinalItemOffset / (itemCount - 1); + } + + for (final Widget child in widget.menuChildren) { + final forwardCurve = Interval( + forwardProgress, + forwardProgress + _kMenuItemRelativeFadeInDuration, + ); + + final reverseCurve = Interval( + reverseProgress, + reverseProgress + _kMenuItemRelativeFadeOutDuration, + ); + + final animation = CurvedAnimation( + parent: _animationController, + curve: forwardCurve, + reverseCurve: reverseCurve, + ); + + _cachedAnimations.add(animation); + _menuChildren.add( + FadeTransition(opacity: animation, alwaysIncludeSemantics: true, child: child), + ); + forwardProgress += itemFadeInGap; + reverseProgress += itemFadeOutGap; + } + } + + void _handleAnimationStatusChanged(AnimationStatus status) { + setState(() { + // Rebuild to update isClosedOrClosing and notify dependents of AnimationStatus changes. + }); + widget.onAnimationStatusChanged?.call(status); + } + + void _handleMenuOpenRequest(Offset? position, VoidCallback showOverlay) { + // If this menu's parent is closing, submenus should not open. This prevents + // a submenu calling MenuController.open() after a parent menu has started + // closing. + if (_parent?.isClosing ?? false) { + return; + } + + showOverlay(); + + if (_animationController.isForwardOrCompleted) { + return; + } + + _animationController.forward(); + } + + void _handleMenuCloseRequest(VoidCallback hideOverlay) { + if (!_animationController.isForwardOrCompleted) { + return; + } + + _menuController.closeChildren(); + _animationController.reverse().whenComplete(hideOverlay); + } + @override Widget build(BuildContext context) { final Widget child = _MenuAnchorScope( state: this, + animationStatus: _animationController.status, child: RawMenuAnchor( + onOpenRequested: _handleMenuOpenRequest, + onCloseRequested: _handleMenuCloseRequest, useRootOverlay: widget.useRootOverlay, onOpen: widget.onOpen, onClose: widget.onClose, @@ -405,18 +688,35 @@ class _MenuAnchorState extends State { } Widget _buildOverlay(BuildContext context, RawMenuOverlayInfo position) { - return _Submenu( - layerLink: widget.layerLink, - consumeOutsideTaps: widget.consumeOutsideTap, - menuScopeNode: _menuScopeNode, - menuStyle: widget.style, - clipBehavior: widget.clipBehavior, - menuChildren: widget.menuChildren, - crossAxisUnconstrained: widget.crossAxisUnconstrained, - menuPosition: position, - anchor: this, - alignmentOffset: widget.alignmentOffset ?? Offset.zero, - reservedPadding: widget.reservedPadding ?? const EdgeInsets.all(_kMenuViewPadding), + // ExcludeSemantics, ExcludeFocus, and IgnorePointer are used to effectively + // disable all interactions with the menu while it is closing. + // + // An animated menu should behave the same as a menu without animations. + // Focus should be able to move to a menu as soon as it starts to open, and + // a menu should not be interactive as soon as it starts to close. + return ExcludeSemantics( + excluding: isClosingOrClosed, + child: IgnorePointer( + ignoring: isClosingOrClosed, + child: ExcludeFocus( + excluding: isClosingOrClosed, + child: _Submenu( + fadeAnimation: opacityAnimation, + heightAnimation: heightAnimation, + layerLink: widget.layerLink, + consumeOutsideTaps: widget.consumeOutsideTap, + menuScopeNode: _menuScopeNode, + menuStyle: widget.style, + clipBehavior: widget.clipBehavior, + menuChildren: _menuChildren, + crossAxisUnconstrained: widget.crossAxisUnconstrained, + menuPosition: position, + anchor: this, + alignmentOffset: widget.alignmentOffset ?? Offset.zero, + reservedPadding: widget.reservedPadding ?? const EdgeInsets.all(_kMenuViewPadding), + ), + ), + ), ); } @@ -462,6 +762,10 @@ class _MenuAnchorState extends State { return context.getInheritedWidgetOfExactType<_MenuAnchorScope>()?.state; } + static AnimationStatus? _maybeAnimationStatusOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType<_MenuAnchorScope>()?.animationStatus; + } + @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.debug}) { return describeIdentity(this); @@ -1458,6 +1762,9 @@ class SubmenuButton extends StatefulWidget { this.trailingIcon, this.submenuIcon, this.useRootOverlay = false, + this.hoverOpenDelay = Duration.zero, + this.animated = false, + this.onAnimationStatusChanged, required this.menuChildren, required this.child, }); @@ -1542,6 +1849,21 @@ class SubmenuButton extends StatefulWidget { /// Defaults to false. final bool useRootOverlay; + /// An optional callback that is invoked when the [AnimationStatus] of the + /// menu changes during open and close animations. + /// + /// If [animated] is false, this callback will only be invoked with + /// [AnimationStatus.completed] when the menu is opened, and + /// [AnimationStatus.dismissed] when the menu is closed. + /// + /// Because the [MenuController.isOpen] property is true while the menu is + /// opening, opened, and closing, it cannot be used to determine whether the + /// menu is in the process of closing or opening. As such, this callback + /// provides a way to determine when the menu is opening or closing. + /// + /// Defaults to null. + final ValueChanged? onAnimationStatusChanged; + /// The list of widgets that appear in the menu when it is opened. /// /// These can be any widget, but are typically either [MenuItemButton] or @@ -1551,6 +1873,23 @@ class SubmenuButton extends StatefulWidget { /// disabled. final List menuChildren; + /// The duration to wait before opening the menu when the button is hovered. + /// + /// Because [MenuBar] children can only be opened by hover if a sibling + /// [SubmenuButton] is already open, providing a [hoverOpenDelay] to direct + /// children of a [MenuBar] will throw an assertion error. This is to avoid + /// the case where the [hoverOpenDelay] for a [SubmenuButton] is longer than + /// the duration of a sibling's closing animation, which leads to that menu + /// never opening. + /// + /// Defaults to [Duration.zero]. + final Duration hoverOpenDelay; + + /// Whether the menu should open and close with an animation. + /// + /// Defaults to false. + final bool animated; + /// The widget displayed in the middle portion of this button. /// /// Typically this is the button's label, using a [Text] widget. @@ -1704,6 +2043,8 @@ class _SubmenuButtonState extends State { FocusNode get _buttonFocusNode => widget.focusNode ?? _internalFocusNode!; bool get _enabled => widget.menuChildren.isNotEmpty; bool _isHovered = false; + AnimationStatus _animationStatus = AnimationStatus.dismissed; + Timer? _hoverOpenTimer; @override void initState() { @@ -1721,8 +2062,15 @@ class _SubmenuButtonState extends State { _buttonFocusNode.addListener(_handleFocusChange); } + @override + void didChangeDependencies() { + super.didChangeDependencies(); + assert(_debugValidateHoverOpenDelay()); + } + @override void dispose() { + _clearHoverOpenTimer(); _buttonFocusNode.removeListener(_handleFocusChange); _internalFocusNode?.dispose(); _internalFocusNode = null; @@ -1732,6 +2080,7 @@ class _SubmenuButtonState extends State { @override void didUpdateWidget(SubmenuButton oldWidget) { super.didUpdateWidget(oldWidget); + assert(_debugValidateHoverOpenDelay()); if (widget.focusNode != oldWidget.focusNode) { if (oldWidget.focusNode == null) { _internalFocusNode?.removeListener(_handleFocusChange); @@ -1759,6 +2108,7 @@ class _SubmenuButtonState extends State { Offset menuPaddingOffset = widget.alignmentOffset ?? Offset.zero; final EdgeInsets menuPadding = _computeMenuPadding(context); final Axis orientation = _parent?._orientation ?? Axis.vertical; + // Move the submenu over by the size of the menu padding, so that // the first menu item aligns with the submenu button that opens it. menuPaddingOffset += switch ((orientation, Directionality.of(context))) { @@ -1784,14 +2134,16 @@ class _SubmenuButtonState extends State { actions: actions, child: MenuAnchor( key: _anchorKey, + onAnimationStatusChanged: _handleAnimationStatusChanged, controller: _menuController, childFocusNode: _buttonFocusNode, alignmentOffset: menuPaddingOffset, clipBehavior: widget.clipBehavior, - onClose: _onClose, - onOpen: _onOpen, + onClose: _handleClose, + onOpen: _handleOpen, style: widget.menuStyle, useRootOverlay: widget.useRootOverlay, + animated: widget.animated, builder: (BuildContext context, MenuController controller, Widget? child) { // Since we don't want to use the theme style or default style from the // TextButton, we merge the styles, merging them in the right order when @@ -1806,7 +2158,7 @@ class _SubmenuButtonState extends State { if (!mounted) { return; } - if (controller.isOpen) { + if (_animationStatus.isForwardOrCompleted) { controller.close(); } else { controller.open(); @@ -1817,6 +2169,7 @@ class _SubmenuButtonState extends State { if (_isHovered) { widget.onHover?.call(false); _isHovered = false; + _clearHoverOpenTimer(); } } @@ -1829,22 +2182,26 @@ class _SubmenuButtonState extends State { _isHovered = true; widget.onHover?.call(true); final _MenuAnchorState root = _MenuAnchorState._maybeOf(context)!._root; - // Don't open the root menu bar menus on hover unless something else + // Don't open the root menu bar menus on hover unless a sibling menu // is already open. This means that the user has to first click to // open a menu on the menu bar before hovering allows them to traverse // it. - if (root._orientation == Axis.horizontal && !root._menuController.isOpen) { + if (_parent?._orientation == Axis.horizontal && !root._menuController.isOpen) { return; } - controller.open(); - _buttonFocusNode.requestFocus(); + if (_buttonFocusNode.hasPrimaryFocus) { + _clearHoverOpenTimer(); + _maybeOpenMenuOnHoverOrFocus(); + } else { + _buttonFocusNode.requestFocus(); + } } } child = MergeSemantics( child: Semantics( - expanded: _enabled && controller.isOpen, + expanded: _enabled && _animationStatus.isForwardOrCompleted, child: TextButton( style: mergedStyle, focusNode: _buttonFocusNode, @@ -1885,7 +2242,14 @@ class _SubmenuButtonState extends State { ); } - void _onClose() { + void _handleAnimationStatusChanged(AnimationStatus status) { + setState(() { + _animationStatus = status; + }); + widget.onAnimationStatusChanged?.call(status); + } + + void _handleClose() { // After closing the children of this submenu, this submenu button will // regain focus. Because submenu buttons open on focus, this submenu will // immediately reopen. To prevent this from happening, we prevent focus on @@ -1901,7 +2265,7 @@ class _SubmenuButtonState extends State { widget.onClose?.call(); } - void _onOpen() { + void _handleOpen() { if (!_waitingToFocusMenu) { SchedulerBinding.instance.addPostFrameCallback((_) { if (mounted) { @@ -1928,15 +2292,70 @@ class _SubmenuButtonState extends State { } void _handleFocusChange() { - if (_buttonFocusNode.hasPrimaryFocus) { - if (!_menuController.isOpen && _isOpenOnFocusEnabled) { - _menuController.open(); - } - } else { - if (!_anchorState!._menuScopeNode.hasFocus && _menuController.isOpen) { + _clearHoverOpenTimer(); + if (!_buttonFocusNode.hasPrimaryFocus) { + if (!_anchorState!._menuScopeNode.hasFocus && _animationStatus.isForwardOrCompleted) { _menuController.close(); } + return; } + + _maybeOpenMenuOnHoverOrFocus(); + } + + void _maybeOpenMenuOnHoverOrFocus() { + if (!_isOpenOnFocusEnabled) { + return; + } + + if (_menuController.isOpen) { + if (_animationStatus != AnimationStatus.reverse) { + // If the menu isn't closing, there's no reason to reopen it. + return; + } + + if (_isHovered) { + // If the button is hovered, avoid reopening the menu that the user deliberately + // closed. + return; + } + + if (_parent?._orientation == Axis.horizontal) { + // Top-level (horizontal) buttons in a menubar will try to reopen when + // closed, since focus returns to their button. + return; + } + } + + if (widget.hoverOpenDelay == Duration.zero) { + _menuController.open(); + return; + } + + _hoverOpenTimer = Timer(widget.hoverOpenDelay, () { + // The menu controller could change, so we can't use a tearoff. + _menuController.open(); + }); + } + + void _clearHoverOpenTimer() { + _hoverOpenTimer?.cancel(); + _hoverOpenTimer = null; + } + + bool _debugValidateHoverOpenDelay() { + if (_parent?._orientation == Axis.horizontal && widget.hoverOpenDelay > Duration.zero) { + throw FlutterError.fromParts([ + ErrorSummary( + 'A non-zero hoverOpenDelay was used in a top-level SubmenuButton situated in a MenuBar.', + ), + ErrorDescription( + 'MenuBar children can only be opened by hover if a sibling SubmenuButton is already open. When the hoverOpenDelay for a SubmenuButton is longer than the closing animation of a sibling SubmenuButton, that sibling will close before this SubmenuButton begins opening, leading to this SubmenuButton never opening.', + ), + context.describeElement('The affected SubmenuButton is'), + ]); + } + return true; } } @@ -2342,6 +2761,7 @@ class _MenuBarAnchorState extends _MenuAnchorState { ); return _MenuAnchorScope( state: this, + animationStatus: _animationController.status, child: RawMenuAnchorGroup( controller: _menuController, child: Builder( @@ -2932,6 +3352,7 @@ class _MenuLayout extends SingleChildLayoutDelegate { required this.orientation, required this.parentOrientation, required this.reservedPadding, + required this.heightFactor, }); // Rectangle of underlying button, relative to the overlay's dimensions. @@ -2966,6 +3387,9 @@ class _MenuLayout extends SingleChildLayoutDelegate { // How close to the edge of the safe area the menu will be placed. final EdgeInsetsGeometry reservedPadding; + // The factor by which the height of the menu is scaled. + final double heightFactor; + @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) { // The menu can be at most the size of the overlay minus the view padding @@ -2979,6 +3403,23 @@ class _MenuLayout extends SingleChildLayoutDelegate { // childSize: The size of the menu, when fully open, as determined by // getConstraintsForChild. final Rect overlayRect = Offset.zero & size; + final double unconstrainedHeight = heightFactor > 0.01 ? childSize.height / heightFactor : 0; + final double childHeightEstimate = math.min(unconstrainedHeight, size.height); + final childSizeEstimate = Size(childSize.width, childHeightEstimate); + final ui.Offset finalPosition = _positionChild(childSizeEstimate, overlayRect); + // If the menu sits above the anchor when fully open, grow upward. + // Keep the bottom (attachment) fixed by shifting the top-left during animation. + final bool growsUp = finalPosition.dy + childSizeEstimate.height <= anchorRect.center.dy; + if (growsUp) { + final double dy = childHeightEstimate - childSize.height; + return Offset(finalPosition.dx, finalPosition.dy + dy); + } + + final initialPosition = Offset(finalPosition.dx, anchorRect.bottom); + return Offset.lerp(initialPosition, finalPosition, heightFactor)!; + } + + ui.Offset _positionChild(ui.Size childSize, ui.Rect overlayRect) { double x; double y; if (menuPosition == null) { @@ -3090,6 +3531,7 @@ class _MenuLayout extends SingleChildLayoutDelegate { orientation != oldDelegate.orientation || parentOrientation != oldDelegate.parentOrientation || reservedPadding != oldDelegate.reservedPadding || + heightFactor != oldDelegate.heightFactor || !setEquals(avoidBounds, oldDelegate.avoidBounds); } @@ -3114,6 +3556,7 @@ class _MenuPanel extends StatefulWidget { this.clipBehavior = Clip.none, required this.orientation, this.crossAxisUnconstrained = true, + this.heightAnimation, required this.children, }); @@ -3135,6 +3578,9 @@ class _MenuPanel extends StatefulWidget { /// The layout orientation of this panel. final Axis orientation; + /// The animation that controls the height of the menu panel. + final Animation? heightAnimation; + /// The list of widgets to use as children of this menu panel. /// /// These are the top level [SubmenuButton]s. @@ -3231,7 +3677,51 @@ class _MenuPanelState extends State<_MenuPanel> { }).toList(); } - Widget menuPanel = _intrinsicCrossSize( + final bool displayScrollbar = switch (_MenuAnchorState._maybeAnimationStatusOf(context)) { + AnimationStatus.completed => true, + AnimationStatus.forward || + AnimationStatus.reverse || + AnimationStatus.dismissed || + null => false, + }; + + Widget menuPanel = Padding( + padding: resolvedPadding, + child: ScrollConfiguration( + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false, overscroll: false, physics: const ClampingScrollPhysics()), + child: PrimaryScrollController( + controller: scrollController, + child: Scrollbar( + thumbVisibility: displayScrollbar, + child: SingleChildScrollView( + controller: scrollController, + scrollDirection: widget.orientation, + child: Flex( + crossAxisAlignment: CrossAxisAlignment.start, + textDirection: Directionality.of(context), + direction: widget.orientation, + mainAxisSize: MainAxisSize.min, + children: children, + ), + ), + ), + ), + ), + ); + + if (widget.heightAnimation != null) { + // An AnimatedBuilder is used instead of SizeTransition because Material + // already introduces its own ClipRRect for the shape. + menuPanel = AnimatedBuilder( + animation: widget.heightAnimation!, + builder: _buildAnimatedHeight, + child: menuPanel, + ); + } + + menuPanel = _intrinsicCrossSize( child: Material( elevation: elevation, shape: shape, @@ -3240,33 +3730,7 @@ class _MenuPanelState extends State<_MenuPanel> { surfaceTintColor: surfaceTintColor, type: backgroundColor == null ? MaterialType.transparency : MaterialType.canvas, clipBehavior: widget.clipBehavior, - child: Padding( - padding: resolvedPadding, - child: ScrollConfiguration( - behavior: ScrollConfiguration.of(context).copyWith( - scrollbars: false, - overscroll: false, - physics: const ClampingScrollPhysics(), - ), - child: PrimaryScrollController( - controller: scrollController, - child: Scrollbar( - thumbVisibility: true, - child: SingleChildScrollView( - controller: scrollController, - scrollDirection: widget.orientation, - child: Flex( - crossAxisAlignment: CrossAxisAlignment.start, - textDirection: Directionality.of(context), - direction: widget.orientation, - mainAxisSize: MainAxisSize.min, - children: children, - ), - ), - ), - ), - ), - ), + child: menuPanel, ), ); @@ -3288,6 +3752,15 @@ class _MenuPanelState extends State<_MenuPanel> { Axis.vertical => IntrinsicWidth(child: child), }; } + + Widget _buildAnimatedHeight(BuildContext context, Widget? child) { + return Align( + alignment: AlignmentDirectional.topStart, + heightFactor: widget.heightAnimation!.value, + widthFactor: 1, + child: child, + ); + } } // A widget that defines the menu drawn in the overlay. @@ -3303,6 +3776,8 @@ class _Submenu extends StatelessWidget { this.crossAxisUnconstrained = true, required this.menuChildren, required this.menuScopeNode, + required this.fadeAnimation, + required this.heightAnimation, required this.reservedPadding, }); @@ -3316,6 +3791,8 @@ class _Submenu extends StatelessWidget { final Clip clipBehavior; final bool crossAxisUnconstrained; final List menuChildren; + final Animation fadeAnimation; + final Animation heightAnimation; final EdgeInsetsGeometry reservedPadding; @override @@ -3384,12 +3861,17 @@ class _Submenu extends StatelessWidget { }, child: Shortcuts( shortcuts: _kMenuTraversalShortcuts, - child: _MenuPanel( - menuStyle: menuStyle, - clipBehavior: clipBehavior, - orientation: anchor._orientation, - crossAxisUnconstrained: crossAxisUnconstrained, - children: menuChildren, + child: FadeTransition( + opacity: fadeAnimation, + alwaysIncludeSemantics: true, + child: _MenuPanel( + menuStyle: menuStyle, + clipBehavior: clipBehavior, + orientation: anchor._orientation, + crossAxisUnconstrained: crossAxisUnconstrained, + heightAnimation: heightAnimation, + children: menuChildren, + ), ), ), ), @@ -3401,8 +3883,9 @@ class _Submenu extends StatelessWidget { data: Theme.of(context).copyWith(visualDensity: visualDensity), child: ConstrainedBox( constraints: BoxConstraints.loose(menuPosition.overlaySize), - child: Builder( - builder: (BuildContext context) { + child: AnimatedBuilder( + animation: heightAnimation, + builder: (BuildContext context, Widget? child) { final MediaQueryData mediaQuery = MediaQuery.of(context); return CustomSingleChildLayout( delegate: _MenuLayout( @@ -3416,6 +3899,7 @@ class _Submenu extends StatelessWidget { orientation: anchor._orientation, parentOrientation: anchor._parent?._orientation ?? Axis.horizontal, reservedPadding: reservedPadding, + heightFactor: heightAnimation.value, ), child: menuPanel, ); diff --git a/packages/flutter/test/material/menu_anchor_test.dart b/packages/flutter/test/material/menu_anchor_test.dart index 82d25510d6a..2ed71edbac7 100644 --- a/packages/flutter/test/material/menu_anchor_test.dart +++ b/packages/flutter/test/material/menu_anchor_test.dart @@ -9,6 +9,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker/leak_tracker.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../widgets/semantics_tester.dart'; @@ -170,7 +171,7 @@ void main() { Future hoverOver(WidgetTester tester, Finder finder) async { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(tester.getCenter(finder)); - await tester.pumpAndSettle(); + await tester.pump(); return gesture; } @@ -2079,6 +2080,137 @@ void main() { expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 12"))')); }); + testWidgets('hoverOpenDelay delays when a SubmenuButton opens', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: SubmenuButton( + hoverOpenDelay: const Duration(milliseconds: 500), + menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Item 0'))], + child: const Text('Submenu'), + ), + ), + ), + ); + + // Hover over the submenu button + await hoverOver(tester, find.text('Submenu')); + await tester.pump(const Duration(milliseconds: 499)); + + expect(find.text('Item 0'), findsNothing); + + await tester.pump(const Duration(milliseconds: 1)); + + // Menu should now be open + expect(find.text('Item 0'), findsOneWidget); + }); + + testWidgets('hoverOpenDelay can be cancelled', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: [ + const Text('Outside'), + SubmenuButton( + hoverOpenDelay: const Duration(milliseconds: 500), + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + ], + child: const Text('Submenu'), + ), + ], + ), + ), + ), + ); + + // Hover over the submenu button + await hoverOver(tester, find.text('Submenu')); + await tester.pump(const Duration(milliseconds: 499)); + + expect(find.text('Item 0'), findsNothing); + + // Move hover away before the delay completes + await hoverOver(tester, find.text('Outside')); + await tester.pump(const Duration(milliseconds: 1)); + + expect(find.text('Item 0'), findsNothing); + }); + + testWidgets('hoverOpenDelay restarts after cancellation', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: [ + const Text('Outside'), + SubmenuButton( + hoverOpenDelay: const Duration(milliseconds: 500), + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + ], + child: const Text('Submenu'), + ), + ], + ), + ), + ), + ); + + await hoverOver(tester, find.text('Submenu')); + await tester.pump(const Duration(milliseconds: 499)); + + expect(find.text('Item 0'), findsNothing); + + await hoverOver(tester, find.text('Outside')); + await tester.pump(const Duration(milliseconds: 1)); + + expect(find.text('Item 0'), findsNothing); + + await hoverOver(tester, find.text('Submenu')); + await tester.pump(const Duration(milliseconds: 500)); + + expect(find.text('Item 0'), findsOneWidget); + }); + + testWidgets( + 'Throws if non-zero hoverOpenDelay is applied to MenuBar items', + experimentalLeakTesting: LeakTesting.settings + .withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuBar( + children: [ + SubmenuButton( + hoverOpenDelay: const Duration(milliseconds: 1), + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + ], + child: const Text('Submenu'), + ), + ], + ), + ), + ), + ); + + // Should throw because MenuBar items cannot have a hoverOpenDelay + expect( + tester.takeException(), + isA().having( + (FlutterError e) => e.message, + 'message', + contains( + 'A non-zero hoverOpenDelay was used in a top-level SubmenuButton situated in a MenuBar', + ), + ), + ); + }, + ); + testWidgets('scrolling does not trigger hover traversal', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/150911. final GlobalKey scrolledMenuItemKey = GlobalKey(); @@ -4554,6 +4686,171 @@ void main() { semantics.dispose(); }); + + testWidgets('Animated SubmenuButton expanded/collapsed state', (WidgetTester tester) async { + final semantics = SemanticsTester(tester); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SubmenuButton( + animated: true, + style: SubmenuButton.styleFrom(fixedSize: const Size(88.0, 36.0)), + menuChildren: [ + MenuItemButton( + style: MenuItemButton.styleFrom(fixedSize: const Size(120.0, 36.0)), + child: const Text('Item 0'), + onPressed: () {}, + ), + ], + child: const Text('ABC'), + ), + ), + ), + ); + + // Test expanded state. + await tester.tap(find.text('ABC')); + await tester.pumpAndSettle(); + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: [ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: [ + TestSemantics( + id: 2, + children: [ + TestSemantics( + id: 3, + flags: [SemanticsFlag.scopesRoute], + children: [ + TestSemantics( + id: 4, + children: [ + TestSemantics( + id: 7, + children: [ + TestSemantics( + id: 8, + children: [ + TestSemantics( + id: 9, + flags: [ + if (kIsWeb) SemanticsFlag.isButton, + SemanticsFlag.hasImplicitScrolling, + ], + children: [ + TestSemantics( + id: 10, + label: 'Item 0', + flags: [ + SemanticsFlag.hasEnabledState, + SemanticsFlag.isEnabled, + SemanticsFlag.isFocusable, + ], + actions: [ + SemanticsAction.tap, + SemanticsAction.focus, + ], + ), + ], + ), + ], + ), + ], + ), + TestSemantics( + id: 5, + label: 'ABC', + flags: [ + SemanticsFlag.isFocused, + if (kIsWeb) SemanticsFlag.isButton, + SemanticsFlag.hasEnabledState, + SemanticsFlag.isEnabled, + SemanticsFlag.isFocusable, + SemanticsFlag.hasExpandedState, + SemanticsFlag.isExpanded, + ], + actions: [ + SemanticsAction.tap, + SemanticsAction.focus, + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreTransform: true, + ignoreRect: true, + ), + ); + // Test collapsed state. + await tester.tap(find.text('ABC')); + await tester.pumpAndSettle(); + + expect(find.byType(MenuItemButton), findsNothing); + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: [ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: [ + TestSemantics( + id: 2, + children: [ + TestSemantics( + id: 3, + flags: [SemanticsFlag.scopesRoute], + children: [ + TestSemantics( + id: 4, + children: [ + TestSemantics( + id: 5, + label: 'ABC', + textDirection: TextDirection.ltr, + flags: [ + if (kIsWeb) SemanticsFlag.isButton, + SemanticsFlag.isFocused, + SemanticsFlag.hasEnabledState, + SemanticsFlag.isEnabled, + SemanticsFlag.isFocusable, + SemanticsFlag.hasExpandedState, + ], + actions: [ + SemanticsAction.tap, + SemanticsAction.focus, + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreTransform: true, + ignoreRect: true, + ), + ); + + semantics.dispose(); + }); }, skip: kIsWeb); // [intended] the web traversal order by using ARIA-OWNS. // This is a regression test for https://github.com/flutter/flutter/issues/131676. @@ -5374,6 +5671,1079 @@ void main() { }); }); + group('Animations', () { + testWidgets('Animations can be disabled', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Item 0'))], + ), + ), + ), + ); + + // When animations are enabled, this will return the opacity of the + // FadeTransition wrapping the MenuItemButton. + // + // When animations are disabled, this will return the opacity of the + // FadeTransition wrapping the MenuAnchor's surface. + double getOpacity(String text) { + return tester + .firstWidget( + find.ancestor( + of: find.widgetWithText(MenuItemButton, text), + matching: find.byType(FadeTransition), + ), + ) + .opacity + .value; + } + + // Open the menu and verify animations are enabled. + controller.open(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(getOpacity('Item 0'), closeTo(0.2, 0.05)); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Item 0'))], + ), + ), + ), + ); + + expect(getOpacity('Item 0'), equals(1.0)); + }); + + testWidgets('MenuAnchor children can be changed', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Item 0'))], + ), + ), + ), + ); + + // When animations are enabled, this will return the opacity of the + // FadeTransition wrapping the MenuItemButton. + // + // When animations are disabled, this will return the opacity of the + // FadeTransition wrapping the MenuAnchor's surface. + double getOpacity(String text) { + return tester + .firstWidget( + find.ancestor( + of: find.widgetWithText(MenuItemButton, text), + matching: find.byType(FadeTransition), + ), + ) + .opacity + .value; + } + + controller.open(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(getOpacity('Item 0'), closeTo(0.2, 0.05)); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Item 1'))], + ), + ), + ), + ); + + expect(getOpacity('Item 1'), closeTo(0.2, 0.05)); + }); + + testWidgets('Menu panel fades in', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + MenuItemButton(onPressed: () {}, child: const Text('Item 1')), + MenuItemButton(onPressed: () {}, child: const Text('Item 2')), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + double getOpacity() { + return tester + .firstWidget( + find.ancestor(of: findMenuPanels(), matching: find.byType(FadeTransition)), + ) + .opacity + .value; + } + + // Opacity values at different millisecond offsets during the 50 ms fade-in animation. + const animationOpacities = {0: 0.0, 10: 0.2, 20: 0.4, 30: 0.6, 40: 0.8, 50: 1.0}; + + for (final int ms in animationOpacities.keys) { + expect(getOpacity(), closeTo(animationOpacities[ms]!, 0.05), reason: 'at t=$ms'); + await tester.pump(const Duration(milliseconds: 10)); + } + }); + + testWidgets('Menu panel fades out', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + MenuItemButton(onPressed: () {}, child: const Text('Item 1')), + MenuItemButton(onPressed: () {}, child: const Text('Item 2')), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + await tester.pumpAndSettle(); + controller.close(); + await tester.pump(); + + double getOpacity() { + return tester + .firstWidget( + find.ancestor(of: findMenuPanels(), matching: find.byType(FadeTransition)), + ) + .opacity + .value; + } + + // Opacity values at different millisecond offsets during the 50 ms fade-in animation. + const animationOpacities = {110: 1.0, 120: 0.8, 130: 0.6, 140: 0.4, 150: 0.2}; + + expect(getOpacity(), closeTo(1.0, 0.05), reason: 'at t=0'); + + await tester.pump(const Duration(milliseconds: 100)); + + for (final int ms in animationOpacities.keys) { + expect(getOpacity(), closeTo(animationOpacities[ms]!, 0.05), reason: 'at t=$ms'); + await tester.pump(const Duration(milliseconds: 10)); + } + }); + + testWidgets('Menu panel height eases out while opening', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + style: const MenuStyle( + padding: WidgetStatePropertyAll(EdgeInsets.zero), + ), + controller: controller, + animated: true, + // Different platforms have different default menu item heights. + // To make the test consistent across platforms, use a fixed + // height. + menuChildren: const [SizedBox(height: 160)], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + const animatedHeights = { + 0: 0.0, + 100: 60.5, + 200: 125.5, + 300: 148, + 400: 157.5, + 500: 160, + }; + + final Finder panel = find.descendant( + of: find.byType(MenuAnchor), + matching: find.byType(FocusScope), + ); + for (final int key in animatedHeights.keys) { + final double height = tester.getSize(panel).height; + expect(height, closeTo(animatedHeights[key]!, 1), reason: 'at t=$key'); + await tester.pump(const Duration(milliseconds: 100)); + } + }); + + testWidgets('Menu panel height eases in while closing', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + style: const MenuStyle( + padding: WidgetStatePropertyAll(EdgeInsets.zero), + ), + controller: controller, + animated: true, + // Different platforms have different default menu item heights. + // To make the test consistent across platforms, use a fixed + // height. + menuChildren: const [SizedBox(height: 160)], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + await tester.pumpAndSettle(); + controller.close(); + await tester.pump(); + + const animatedHeights = { + 100: 129, + 110: 120, + 120: 110, + 130: 97, + 140: 80, + 150: 0.0, + }; + + double getHeight() { + final Finder panel = find.descendant( + of: find.byType(MenuAnchor), + matching: find.byType(FocusScope), + ); + return tester.getSize(panel).height; + } + + expect(getHeight(), 160, reason: 'at t=0'); + + await tester.pump(const Duration(milliseconds: 50)); + + expect(getHeight(), closeTo(153, 2.0), reason: 'at t=50'); + + await tester.pump(const Duration(milliseconds: 50)); + + for (final int ms in animatedHeights.keys) { + expect(getHeight(), closeTo(animatedHeights[ms]!, 2.0), reason: 'at t=$ms'); + await tester.pump(const Duration(milliseconds: 10)); + } + }); + + testWidgets('Item fade-in animation staggers over 500 ms', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + MenuItemButton(onPressed: () {}, child: const Text('Item 1')), + MenuItemButton(onPressed: () {}, child: const Text('Item 2')), + MenuItemButton(onPressed: () {}, child: const Text('Item 3')), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + // Get opacity values at the start of animation + double getOpacity(String text) { + return tester + .firstWidget( + find.ancestor( + of: find.widgetWithText(MenuItemButton, text), + matching: find.byType(FadeTransition), + ), + ) + .opacity + .value; + } + + // Opacity values at different millisecond offsets during the 500ms opening animation. + const values = >{ + 100: [0.400, 0.0667, 0.00, 0.00], + 200: [0.800, 0.467, 0.133, 0.00], + 300: [1.00, 0.867, 0.533, 0.200], + 400: [1.00, 1.00, 0.933, 0.600], + 500: [1.00, 1.00, 1.00, 1.00], + }; + + for (final int time in values.keys) { + await tester.pump(const Duration(milliseconds: 100)); + final List expected = values[time]!; + expect(getOpacity('Item 0'), closeTo(expected[0], 0.05), reason: 'at t=$time'); + expect(getOpacity('Item 1'), closeTo(expected[1], 0.05), reason: 'at t=$time'); + expect(getOpacity('Item 2'), closeTo(expected[2], 0.05), reason: 'at t=$time'); + expect(getOpacity('Item 3'), closeTo(expected[3], 0.05), reason: 'at t=$time'); + } + }); + + testWidgets('Item fade-out animation staggers over 150 ms with 50 ms delay', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + builder: (BuildContext context, MenuController controller, Widget? child) { + return TextButton( + onPressed: () { + if (controller.isOpen) { + controller.close(); + } else { + controller.open(); + } + }, + child: const Text('Open Menu'), + ); + }, + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + MenuItemButton(onPressed: () {}, child: const Text('Item 1')), + MenuItemButton(onPressed: () {}, child: const Text('Item 2')), + MenuItemButton(onPressed: () {}, child: const Text('Item 3')), + ], + ), + ), + ), + ); + + await tester.tap(find.text('Open Menu')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); + controller.close(); + await tester.pump(); + + // Get opacity values at the start of animation + double getOpacity(String text) { + final Finder fadeTransition = find.widgetWithText(FadeTransition, text); + return tester.firstWidget(fadeTransition).opacity.value; + } + + // Opacity values at different millisecond offsets during the 150ms close animation. + const menuItemOpacities = >{ + 0: [1.00, 1.00, 1.00, 1.00], + 25: [1.00, 1.00, 1.00, 1.00], + 50: [1.00, 1.00, 1.00, 1.00], + 75: [1.00, 1.00, 0.833, 0.500], + 100: [1.00, 0.667, 0.333, 0.00], + 125: [0.500, 0.167, 0.00, 0.00], + 150: [0.00, 0.00, 0.00, 0.00], + }; + + for (final int time in menuItemOpacities.keys) { + final List expected = menuItemOpacities[time]!; + expect(getOpacity('Item 0'), closeTo(expected[0], 0.05), reason: 'at t=$time'); + expect(getOpacity('Item 1'), closeTo(expected[1], 0.05), reason: 'at t=$time'); + expect(getOpacity('Item 2'), closeTo(expected[2], 0.05), reason: 'at t=$time'); + expect(getOpacity('Item 3'), closeTo(expected[3], 0.05), reason: 'at t=$time'); + await tester.pump(const Duration(milliseconds: 25)); + } + }); + + testWidgets('MenuAnchor calls onAnimationStatusChanged with correct values', ( + WidgetTester tester, + ) async { + AnimationStatus? animationStatus; + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + onAnimationStatusChanged: (AnimationStatus status) { + animationStatus = status; + }, + menuChildren: [MenuItemButton(onPressed: () {}, child: const Text('Item 0'))], + ), + ), + ), + ); + + // Open the menu + controller.open(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.forward)); + + await tester.pump(const Duration(milliseconds: 200)); + + expect(animationStatus, equals(AnimationStatus.forward)); + + controller.close(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.reverse)); + + await tester.pump(const Duration(milliseconds: 50)); + + expect(animationStatus, equals(AnimationStatus.reverse)); + + controller.open(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.forward)); + + await tester.pumpAndSettle(); + + expect(animationStatus, equals(AnimationStatus.completed)); + + controller.close(); + + await tester.pumpAndSettle(); + + expect(animationStatus, equals(AnimationStatus.dismissed)); + }); + + testWidgets( + 'MenuAnchor without animations calls onAnimationStatusChanged with correct values', + (WidgetTester tester) async { + AnimationStatus? animationStatus; + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + onAnimationStatusChanged: (AnimationStatus status) { + animationStatus = status; + }, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + ], + ), + ), + ), + ); + + // Open the menu + controller.open(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.completed)); + + controller.close(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.dismissed)); + + controller.open(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.completed)); + }, + ); + + testWidgets('SubmenuButton onAnimationStatusChanged is invoked with correct values', ( + WidgetTester tester, + ) async { + AnimationStatus? animationStatus; + final submenuController = MenuController(); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + SubmenuButton( + controller: submenuController, + animated: true, + onAnimationStatusChanged: (AnimationStatus status) { + animationStatus = status; + }, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + ], + child: const Text('Submenu'), + ), + ], + ), + ), + ), + ); + + // Open the menu + controller.open(); + await tester.pump(); + submenuController.open(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.forward)); + + await tester.pump(const Duration(milliseconds: 200)); + + expect(animationStatus, equals(AnimationStatus.forward)); + + submenuController.close(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.reverse)); + + await tester.pump(const Duration(milliseconds: 50)); + + expect(animationStatus, equals(AnimationStatus.reverse)); + + submenuController.open(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.forward)); + + await tester.pumpAndSettle(); + + expect(animationStatus, equals(AnimationStatus.completed)); + + submenuController.close(); + + await tester.pumpAndSettle(); + + expect(animationStatus, equals(AnimationStatus.dismissed)); + + submenuController.open(); + await tester.pumpAndSettle(); + + expect(animationStatus, equals(AnimationStatus.completed)); + + controller.close(); + await tester.pump(); + + expect(animationStatus, equals(AnimationStatus.reverse)); + + await tester.pump(const Duration(milliseconds: 50)); + + submenuController.open(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 25)); + + // Reopen request should be ignored since the parent menu is closing. + expect(animationStatus, equals(AnimationStatus.reverse)); + + await tester.pump(); + await tester.pumpAndSettle(); + + expect(animationStatus, equals(AnimationStatus.dismissed)); + }); + + testWidgets('Menu items can be pressed during opening animation', (WidgetTester tester) async { + var pressCount = 0; + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton( + onPressed: () { + pressCount += 1; + }, + child: const Text('Item 0'), + ), + MenuItemButton( + onPressed: () { + pressCount += 1; + }, + child: const Text('Item 1'), + ), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + await tester.tap(find.text('Item 0')); + await tester.pump(); + + expect(pressCount, 1); + + controller.open(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 250)); + await tester.tap(find.text('Item 1')); + await tester.pump(); + + expect(pressCount, 2); + }); + + testWidgets('Pointer is blocked while menu is closing', (WidgetTester tester) async { + var itemPressed = false; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton( + onPressed: () { + itemPressed = true; + }, + child: const Text('Item 0'), + ), + ], + ), + ), + ), + ); + + // Open and wait for animation to complete + controller.open(); + await tester.pumpAndSettle(); + + expect(find.text('Item 0'), findsOneWidget); + + // Start closing + controller.close(); + await tester.pump(); + + // Try to tap the item while closing + await tester.tap(find.text('Item 0'), warnIfMissed: false); + await tester.pump(); + + // Item should not have been pressed + expect(itemPressed, false); + }); + + testWidgets('Menu items can be focused during opening animation', (WidgetTester tester) async { + final item0FocusNode = FocusNode(); + final item1FocusNode = FocusNode(); + addTearDown(item0FocusNode.dispose); + addTearDown(item1FocusNode.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton( + focusNode: item0FocusNode, + onPressed: () {}, + child: const Text('Item 0'), + ), + MenuItemButton( + focusNode: item1FocusNode, + onPressed: () {}, + child: const Text('Item 1'), + ), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + item0FocusNode.requestFocus(); + await tester.pump(); + + expect(item0FocusNode.hasFocus, true); + + item1FocusNode.requestFocus(); + await tester.pump(); + + expect(item1FocusNode.hasFocus, true); + }); + + testWidgets('Focus returns to parent scope during closing animation', ( + WidgetTester tester, + ) async { + final submenuFocusNode = FocusNode(); + final outsideFocusNode = FocusNode(); + addTearDown(submenuFocusNode.dispose); + addTearDown(outsideFocusNode.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ConstrainedBox( + constraints: const BoxConstraints(minWidth: 400, minHeight: 400), + child: Column( + children: [ + TextButton( + onPressed: () {}, + focusNode: outsideFocusNode, + child: const Text('Outside'), + ), + MenuAnchor( + controller: controller, + animated: true, + builder: (BuildContext context, MenuController controller, Widget? child) { + return TextButton( + autofocus: true, + onPressed: () { + if (controller.isOpen) { + controller.close(); + } else { + controller.open(); + } + }, + child: const Text('Open Menu'), + ); + }, + menuChildren: [ + MenuItemButton( + autofocus: true, + onPressed: () {}, + child: const Text('Item 0'), + ), + SubmenuButton( + animated: true, + menuChildren: [ + MenuItemButton( + focusNode: submenuFocusNode, + onPressed: () {}, + child: const Text('Nested'), + ), + ], + child: const Text('Submenu'), + ), + ], + ), + ], + ), + ), + ), + ), + ); + + outsideFocusNode.requestFocus(); + await tester.pump(); + + expect(outsideFocusNode.hasPrimaryFocus, true); + + await tester.tap(find.text('Open Menu')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + + await hoverOver(tester, find.text('Submenu')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + + expect(find.text('Nested'), findsOneWidget); + + submenuFocusNode.requestFocus(); + await tester.pump(); + + expect(submenuFocusNode.hasPrimaryFocus, true); + + controller.close(); + await tester.pump(); + + expect(outsideFocusNode.hasPrimaryFocus, true); + + await tester.pump(const Duration(milliseconds: 50)); + + expect(outsideFocusNode.hasPrimaryFocus, true); + + await tester.pumpAndSettle(); + + expect(outsideFocusNode.hasPrimaryFocus, true); + }); + + testWidgets('Submenu items can be traversed during opening animation', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuBar( + controller: controller, + children: [ + SubmenuButton( + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + SubmenuButton( + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Sub Item 0')), + MenuItemButton(onPressed: () {}, child: const Text('Sub Item 1')), + ], + child: const Text('Submenu'), + ), + ], + child: const Text('Menu'), + ), + ], + ), + ), + ), + ); + + listenForFocusChanges(); + + await tester.tap(find.text('Menu')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(focusedMenu, equals('SubmenuButton(Text("Menu"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + + expect(focusedMenu, equals('MenuItemButton(Text("Item 0"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(focusedMenu, equals('SubmenuButton(Text("Submenu"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Sub Item 0"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Sub Item 1"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + + expect(focusedMenu, equals('SubmenuButton(Text("Submenu"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Sub Item 0"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Item 0"))')); + }); + + testWidgets('Hover traversal works during opening animation', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Item 0')), + MenuItemButton(onPressed: () {}, child: const Text('Item 1')), + MenuItemButton(onPressed: () {}, child: const Text('Item 2')), + ], + ), + ), + ), + ); + + listenForFocusChanges(); + + controller.open(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + await hoverOver(tester, find.text('Item 0')); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Item 0"))')); + + await tester.pump(const Duration(milliseconds: 100)); + await hoverOver(tester, find.text('Item 1')); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Item 1"))')); + + await tester.pump(const Duration(milliseconds: 100)); + await hoverOver(tester, find.text('Item 2')); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Item 2"))')); + + await tester.pump(const Duration(milliseconds: 200)); + await hoverOver(tester, find.text('Item 0')); + await tester.pump(); + + expect(focusedMenu, equals('MenuItemButton(Text("Item 0"))')); + }); + + testWidgets('MenuBar items can be traversed during submenu opening animation', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuBar( + controller: controller, + children: [ + SubmenuButton( + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Menu 0 Item')), + ], + child: const Text('Menu 0'), + ), + SubmenuButton( + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Menu 1 Item')), + ], + child: const Text('Menu 1'), + ), + SubmenuButton( + animated: true, + menuChildren: [ + MenuItemButton(onPressed: () {}, child: const Text('Menu 2 Item')), + ], + child: const Text('Menu 2'), + ), + ], + ), + ), + ), + ); + + listenForFocusChanges(); + + await tester.tap(find.text('Menu 0')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 20)); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + + expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))')); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + + expect(focusedMenu, equals('SubmenuButton(Text("Menu 2"))')); + + await tester.pump(const Duration(milliseconds: 20)); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + + expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))')); + }); + + testWidgets('Focus state remains consistent throughout opening animation', ( + WidgetTester tester, + ) async { + final itemFocusNode = FocusNode(); + addTearDown(itemFocusNode.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: [ + TextButton(onPressed: () {}, autofocus: true, child: const Text('Outside')), + MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + MenuItemButton( + focusNode: itemFocusNode, + onPressed: () {}, + child: const Text('Item 0'), + ), + MenuItemButton(autofocus: true, onPressed: () {}, child: const Text('Item 1')), + ], + ), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + itemFocusNode.requestFocus(); + await tester.pump(); + + expect(itemFocusNode.hasPrimaryFocus, true); + + await tester.pump(const Duration(milliseconds: 200)); + + expect(itemFocusNode.hasPrimaryFocus, true); + + await tester.pumpAndSettle(); + + expect(itemFocusNode.hasPrimaryFocus, true); + }); + + testWidgets('Scrollbar thumb is not shown while animated menu is opening', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: MenuAnchor( + controller: controller, + animated: true, + menuChildren: [ + for (int i = 0; i < 20; i++) + MenuItemButton(onPressed: () {}, child: Text('Item $i')), + ], + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + expect(tester.widget(find.byType(Scrollbar)).thumbVisibility, isFalse); + + // Progress the animation to the middle. + await tester.pump(const Duration(milliseconds: 250)); + + expect(tester.widget(find.byType(Scrollbar)).thumbVisibility, isFalse); + + await tester.pumpAndSettle(); + + expect(tester.widget(find.byType(Scrollbar)).thumbVisibility, isTrue); + }); + }); + testWidgets('Menu panel default reserved padding', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp(