Repository navigation
Expand file tree
/
Copy pathmenu_anchor.dart
More file actions
4102 lines (3745 loc) · 148 KB
/
Copy pathmenu_anchor.dart
File metadata and controls
4102 lines (3745 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:cupertino_ui/cupertino_ui.dart';
///
/// @docImport 'app.dart';
/// @docImport 'checkbox_theme.dart';
/// @docImport 'dropdown_menu.dart';
/// @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';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'button_style_button.dart';
import 'checkbox.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
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';
import 'text_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
part 'generated/menu_defaults_m3.g.dart';
// Examples can assume:
// bool _throwShotAway = false;
// late BuildContext context;
// 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;
// The default size of the arrow in _MenuItemLabel that indicates that a menu
// has a submenu.
const double _kDefaultSubmenuIconSize = 24;
// The default spacing between the leading icon, label, trailing icon, and
// shortcut label in a _MenuItemLabel.
const double _kLabelItemDefaultSpacing = 12;
// The minimum spacing between the leading icon, label, trailing icon, and
// shortcut label in a _MenuItemLabel.
const double _kLabelItemMinSpacing = 4;
// Navigation shortcuts that we need to make sure are active when menus are
// open.
const Map<ShortcutActivator, Intent> _kMenuTraversalShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.gameButtonA): ActivateIntent(),
SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(),
SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
};
// The minimum vertical spacing on the outside of menus.
const double _kMenuVerticalMinPadding = 8;
// How close to the edge of the safe area the menu will be placed.
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.
///
/// The `context` is the context that the widget is being built in.
///
/// The `controller` is the [MenuController] that can be used to open and close
/// the menu with.
///
/// The `child` is an optional child supplied as the [MenuAnchor.child]
/// attribute. The child is intended to be incorporated in the result of the
/// function.
typedef MenuAnchorChildBuilder = Widget Function(
BuildContext context,
MenuController controller,
Widget? child,
);
class _MenuAnchorScope extends InheritedWidget {
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 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.
///
/// When creating a menu with [MenuBar] or a [SubmenuButton], a [MenuAnchor] is
/// not needed, since they provide their own internally.
///
/// The [MenuAnchor] is meant to be a slightly lower level interface than
/// [MenuBar], used in situations where a [MenuBar] isn't appropriate, or to
/// construct widgets or screen regions that have submenus.
///
/// To programmatically control a [MenuAnchor], like opening or closing it, or checking its state,
/// you can get its associated [MenuController]. Use `MenuController.maybeOf(BuildContext context)`
/// to retrieve the controller for the closest [MenuAnchor] ancestor of a given [BuildContext].
/// More detailed usage of [MenuController] is available in its class documentation.
///
/// <callout-box>
///
/// This example shows how to use a [MenuAnchor] to wrap a button and open a
/// cascading menu from the button. This example also shows how to use
/// [onAnimationStatusChanged] to track animation status and toggle the menu.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/menu_anchor/menu_anchor.0.dart#body}
///
/// </callout-box>
///
/// <callout-box>
///
/// This example shows how to use a [MenuAnchor] to create a cascading context
/// menu in a region of the view, positioned where the user clicks the mouse
/// with Ctrl pressed. The [anchorTapClosesMenu] attribute is set to true so
/// that clicks on the [MenuAnchor] area will cause the menus to be closed.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/menu_anchor/menu_anchor.1.dart#body}
///
/// </callout-box>
///
/// <callout-box>
///
/// This example demonstrates a simplified cascading menu using the [MenuAnchor]
/// widget.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/menu_anchor/menu_anchor.3.dart#body}
///
/// </callout-box>
///
/// The [MenuStyle.visualDensity] setting only affects horizontal padding,
/// and it will never make it negative. Vertical padding is not affected at all.
class MenuAnchor extends StatefulWidget {
/// Creates a const [MenuAnchor].
///
/// The [menuChildren] argument is required.
const MenuAnchor({
super.key,
this.controller,
this.childFocusNode,
this.style,
this.alignmentOffset = Offset.zero,
this.reservedPadding,
this.layerLink,
this.clipBehavior = Clip.hardEdge,
@Deprecated(
'Use consumeOutsideTap instead. '
'This feature was deprecated after v3.16.0-8.0.pre.',
)
this.anchorTapClosesMenu = false,
this.consumeOutsideTap = false,
this.onOpen,
this.onClose,
this.crossAxisUnconstrained = true,
this.useRootOverlay = false,
this.animated = false,
this.onAnimationStatusChanged,
required this.menuChildren,
this.builder,
this.semanticLabel,
this.child,
});
/// An optional controller that allows opening and closing of the menu from
/// other widgets.
final MenuController? controller;
/// The [childFocusNode] attribute is the optional [FocusNode] also associated
/// to the [child] or [builder] widget that opens the menu.
///
/// The focus node should be attached to the widget that should receive focus
/// if keyboard focus traversal moves the focus off of the submenu with the
/// arrow keys.
///
/// If not supplied, then keyboard traversal from the menu back to the
/// controlling button when the menu is open is disabled.
final FocusNode? childFocusNode;
/// The [MenuStyle] that defines the visual attributes of the menu bar.
///
/// Colors and sizing of the menus is controllable via the [MenuStyle].
///
/// Defaults to the ambient [MenuThemeData.style].
final MenuStyle? style;
/// {@template material_ui.MenuAnchor.alignmentOffset}
/// The offset of the menu relative to the alignment origin determined by
/// [MenuStyle.alignment] on the [style] attribute and the ambient
/// [Directionality].
///
/// Use this for adjustments of the menu placement.
///
/// Increasing [Offset.dy] values of [alignmentOffset] move the menu position
/// down.
///
/// If the [MenuStyle.alignment] from [style] is not an [AlignmentDirectional]
/// (e.g. [Alignment]), then increasing [Offset.dx] values of
/// [alignmentOffset] move the menu position to the right.
///
/// If the [MenuStyle.alignment] from [style] is an [AlignmentDirectional],
/// then in a [TextDirection.ltr] [Directionality], increasing [Offset.dx]
/// values of [alignmentOffset] move the menu position to the right. In a
/// [TextDirection.rtl] directionality, increasing [Offset.dx] values of
/// [alignmentOffset] move the menu position to the left.
///
/// Defaults to [Offset.zero].
/// {@endtemplate}
final Offset? alignmentOffset;
/// An optional [LayerLink] to attach the menu to the widget that this
/// [MenuAnchor] surrounds.
///
/// When provided, the menu will follow the widget that this [MenuAnchor]
/// surrounds if it moves because of view insets changes.
final LayerLink? layerLink;
/// {@macro cupertino_ui.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// Whether the menus will be closed if the anchor area is tapped.
///
/// For menus opened by buttons that toggle the menu, if the button is tapped
/// when the menu is open, the button should close the menu. But if
/// [anchorTapClosesMenu] is true, then the menu will close, and
/// (surprisingly) immediately re-open. This is because tapping on the button
/// closes the menu before the `onPressed` or `onTap` handler is called
/// because of it being considered to be "outside" the menu system, and then
/// the button (seeing that the menu is closed) immediately reopens the menu.
/// The result is that the user thinks that tapping on the button does
/// nothing. So, for button-initiated menus, this value is typically false so
/// that the menu anchor area is considered "inside" of the menu system and
/// doesn't cause it to close unless [MenuController.close] is called.
///
/// For menus that are positioned using [MenuController.open]'s `position`
/// parameter, it is often desirable that clicking on the anchor always closes
/// the menu since the anchor area isn't usually considered part of the menu
/// system by the user. In this case [anchorTapClosesMenu] should be true.
///
/// Defaults to false.
@Deprecated(
'Use consumeOutsideTap instead. '
'This feature was deprecated after v3.16.0-8.0.pre.',
)
final bool anchorTapClosesMenu;
/// Whether or not a tap event that closes the menu will be permitted to
/// continue on to the gesture arena.
///
/// If false, then tapping outside of a menu when the menu is open will both
/// close the menu, and allow the tap to participate in the gesture arena. If
/// true, then it will only close the menu, and the tap event will be
/// consumed.
///
/// Defaults to false.
final bool consumeOutsideTap;
/// A callback that is invoked when the menu begins opening.
///
/// Defaults to null.
final VoidCallback? onOpen;
/// A callback that is invoked when the menu finishes closing.
///
/// Defaults to null.
final VoidCallback? onClose;
/// Determine if the menu panel can be wrapped by a [UnconstrainedBox] which allows
/// the panel to render at its "natural" size.
///
/// Defaults to true as it allows developers to render the menu panel at the
/// size it should be. When it is set to false, it can be useful when the menu should
/// be constrained in both main axis and cross axis, such as a [DropdownMenu].
final bool crossAxisUnconstrained;
/// {@macro flutter.widgets.RawMenuAnchor.useRootOverlay}
///
/// 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.
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// 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: <Widget>[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),
/// );
/// },
/// );
/// ```
///
/// </callout-box>
///
/// Defaults to null.
final ValueChanged<AnimationStatus>? onAnimationStatusChanged;
/// A list of children containing the menu items that are the contents of the
/// menu surrounded by this [MenuAnchor].
///
/// {@macro material_ui.MenuBar.shortcuts_note}
final List<Widget> menuChildren;
/// The widget that this [MenuAnchor] surrounds.
///
/// Typically this is a button used to open the menu by calling
/// [MenuController.open] on the `controller` passed to the builder.
///
/// If not supplied, then the [MenuAnchor] will be the size that its parent
/// allocates for it.
///
/// If provided, the builder will be called each time the menu is opened or
/// closed.
final MenuAnchorChildBuilder? builder;
/// The semantic label of the menu.
///
/// Defaults to null.
final String? semanticLabel;
/// The optional child to be passed to the [builder].
///
/// Supply this child if there is a portion of the widget tree built in
/// [builder] that doesn't depend on the `controller` or `context` supplied to
/// the [builder]. It will be more efficient, since Flutter doesn't then need
/// to rebuild this child when those change.
final Widget? child;
/// The padding between the edge of the safe area and the menu panel.
///
/// Defaults to EdgeInsets.all(8).
final EdgeInsetsGeometry? reservedPadding;
@override
State<MenuAnchor> createState() => _MenuAnchorState();
@override
List<DiagnosticsNode> debugDescribeChildren() {
return menuChildren.map<DiagnosticsNode>((Widget child) => child.toDiagnosticsNode()).toList();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
FlagProperty('anchorTapClosesMenu', value: anchorTapClosesMenu, ifTrue: 'AUTO-CLOSE'),
);
properties.add(DiagnosticsProperty<FocusNode?>('focusNode', childFocusNode));
properties.add(DiagnosticsProperty<MenuStyle?>('style', style));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior));
properties.add(DiagnosticsProperty<Offset?>('alignmentOffset', alignmentOffset));
}
}
class _MenuAnchorState extends State<MenuAnchor> with SingleTickerProviderStateMixin {
Axis get _orientation => Axis.vertical;
MenuController get _menuController => widget.controller ?? _internalMenuController!;
MenuController? _internalMenuController;
final FocusScopeNode _menuScopeNode = FocusScopeNode();
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<Widget> _menuChildren = <Widget>[];
List<CurvedAnimation> _cachedAnimations = <CurvedAnimation>[];
_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();
}
}
@override
void didUpdateWidget(MenuAnchor oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
if (widget.controller == null) {
_internalMenuController = MenuController();
} else {
_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 = <Widget>[];
for (final CurvedAnimation animation in _cachedAnimations) {
animation.dispose();
}
_cachedAnimations = <CurvedAnimation>[];
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();
if (isSubmenu || widget.childFocusNode != null) {
return;
}
final FocusScopeNode scope = FocusScope.of(context);
final BuildContext? focusedContext = scope.focusedChild?.context;
final bool isAnchorFocused = focusedContext != null && _maybeOf(focusedContext)?._root == this;
if (isAnchorFocused) {
return;
}
final FocusNode? initialFocus = FocusManager.instance.primaryFocus;
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
if (mounted && !isClosingOrClosed && FocusManager.instance.primaryFocus == initialFocus) {
scope.setFirstFocus(_menuScopeNode);
}
});
}
void _handleMenuCloseRequest(VoidCallback hideOverlay) {
if (!_animationController.isForwardOrCompleted) {
return;
}
_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,
consumeOutsideTaps: widget.consumeOutsideTap,
controller: _menuController,
childFocusNode: widget.childFocusNode,
overlayBuilder: _buildOverlay,
builder: widget.builder,
child: widget.child,
),
);
if (widget.layerLink == null) {
return child;
}
return CompositedTransformTarget(link: widget.layerLink!, child: child);
}
Widget _buildOverlay(BuildContext context, RawMenuOverlayInfo position) {
Widget submenu = _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),
);
// Only inject the semantics node if a label is provided
if (widget.semanticLabel != null) {
submenu = Semantics(
container: true,
explicitChildNodes: true,
label: widget.semanticLabel,
child: submenu,
);
}
// 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),
),
);
}
_MenuAnchorState get _root {
var anchor = this;
while (anchor._parent != null) {
anchor = anchor._parent!;
}
return anchor;
}
void _focusButton() {
if (widget.childFocusNode == null) {
return;
}
assert(_debugMenuInfo('Requesting focus for ${widget.childFocusNode}'));
widget.childFocusNode!.requestFocus();
}
void _focusFirstMenuItem() {
if (_menuScopeNode.context?.mounted != true) {
return;
}
final FocusTraversalPolicy policy =
FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy();
final FocusNode? firstFocus = policy.findFirstFocus(_menuScopeNode, ignoreCurrentFocus: true);
if (firstFocus != null) {
firstFocus.requestFocus();
}
}
void _focusLastMenuItem() {
if (_menuScopeNode.context?.mounted != true) {
return;
}
final FocusTraversalPolicy policy =
FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy();
final FocusNode lastFocus = policy.findLastFocus(_menuScopeNode, ignoreCurrentFocus: true);
lastFocus.requestFocus();
}
static _MenuAnchorState? _maybeOf(BuildContext context) {
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);
}
}
/// A menu bar that manages cascading child menus.
///
/// This is a Material Design menu bar that typically resides above the main
/// body of an application (but can go anywhere) that defines a menu system for
/// invoking callbacks in response to user selection of a menu item.
///
/// The menus can be opened with a click or tap. Once a menu is opened, it can
/// be navigated by using the arrow and tab keys or via mouse hover. Selecting a
/// menu item can be done by pressing enter, or by clicking or tapping on the
/// menu item. Clicking or tapping on any part of the user interface that isn't
/// part of the menu system controlled by the same controller will cause all of
/// the menus controlled by that controller to close, as will pressing the
/// escape key.
///
/// When a menu item with a submenu is clicked on, it toggles the visibility of
/// the submenu. When the menu item is hovered over, the submenu will open, and
/// hovering over other items will close the previous menu and open the newly
/// hovered one. When those open/close transitions occur,
/// [SubmenuButton.onOpen], and [SubmenuButton.onClose] are called on the
/// corresponding [SubmenuButton] child of the menu bar.
///
/// {@template material_ui.MenuBar.shortcuts_note}
/// Menus using [MenuItemButton] can have a [SingleActivator] or
/// [CharacterActivator] assigned to them as their [MenuItemButton.shortcut],
/// which will display an appropriate shortcut hint. Even though the shortcut
/// labels are displayed in the menu, shortcuts are not automatically handled.
/// They must be available in whatever context they are appropriate, and handled
/// via another mechanism.
///
/// If shortcuts should be generally enabled, but are not easily defined in a
/// context surrounding the menu bar, consider registering them with a
/// [ShortcutRegistry] (one is already included in the [WidgetsApp], and thus
/// also [MaterialApp] and [CupertinoApp]), as shown in the example below. To be
/// sure that selecting a menu item and triggering the shortcut do the same
/// thing, it is recommended that they call the same callback.
///
/// <callout-box>
///
/// This example shows a [MenuBar] that contains a single top
/// level menu, containing three items: "About", a checkbox menu item for
/// showing a message, and "Quit". The items are identified with an enum value,
/// and the shortcuts are registered globally with the [ShortcutRegistry].
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/menu_anchor/menu_bar.0.dart#body}
///
/// </callout-box>
/// {@endtemplate}
///
/// {@macro material_ui.MenuAcceleratorLabel.accelerator_sample}
///
/// See also:
///
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [SubmenuButton], a menu item which manages a submenu.
/// * [MenuItemButton], a leaf menu item which displays the label, an optional
/// shortcut label, and optional leading and trailing icons.
/// * [PlatformMenuBar], which creates a menu bar that is rendered by the host
/// platform instead of by Flutter (on macOS, for example).
/// * [ShortcutRegistry], a registry of shortcuts that apply for the entire
/// application.
/// * [VoidCallbackIntent], to define intents that will call a [VoidCallback] and
/// work with the [Actions] and [Shortcuts] system.
/// * [CallbackShortcuts], to define shortcuts that call a callback without
/// involving [Actions].
class MenuBar extends StatelessWidget {
/// Creates a const [MenuBar].
///
/// The [children] argument is required.
const MenuBar({
super.key,
this.style,
this.clipBehavior = Clip.none,
this.controller,
required this.children,
});
/// The [MenuStyle] that defines the visual attributes of the menu bar.
///
/// Colors and sizing of the menus is controllable via the [MenuStyle].
///
/// Defaults to the ambient [MenuThemeData.style].
final MenuStyle? style;
/// {@macro cupertino_ui.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// The [MenuController] to use for this menu bar.
final MenuController? controller;
/// The list of menu items that are the top level children of the [MenuBar].
///
/// A Widget in Flutter is immutable, so directly modifying the [children]
/// with [List] APIs such as `someMenuBarWidget.menus.add(...)` will result in
/// incorrect behaviors. Whenever the menus list is modified, a new list
/// object must be provided.
///
/// {@macro material_ui.MenuBar.shortcuts_note}
final List<Widget> children;
@override
Widget build(BuildContext context) {
assert(debugCheckHasOverlay(context));
return _MenuBarAnchor(
controller: controller,
clipBehavior: clipBehavior,
style: style,
menuChildren: children,
);
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
return <DiagnosticsNode>[
...children.map<DiagnosticsNode>((Widget item) => item.toDiagnosticsNode()),
];
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MenuStyle?>('style', style, defaultValue: null));
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: null));
}
}
/// A button for use in a [MenuBar], in a menu created with [MenuAnchor], or on
/// its own, that can be activated by click or keyboard navigation.
///
/// This widget represents a leaf entry in a menu hierarchy that is typically
/// part of a [MenuBar], but may be used independently, or as part of a menu
/// created with a [MenuAnchor].
///
/// {@macro material_ui.MenuBar.shortcuts_note}
///
/// See also:
///
/// * [MenuBar], a class that creates a top level menu bar in a Material Design
/// style.
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [SubmenuButton], a menu item similar to this one which manages a submenu.
/// * [PlatformMenuBar], which creates a menu bar that is rendered by the host
/// platform instead of by Flutter (on macOS, for example).
/// * [ShortcutRegistry], a registry of shortcuts that apply for the entire
/// application.
/// * [VoidCallbackIntent], to define intents that will call a [VoidCallback] and
/// work with the [Actions] and [Shortcuts] system.
/// * [CallbackShortcuts] to define shortcuts that call a callback without
/// involving [Actions].
class MenuItemButton extends StatefulWidget {
/// Creates a const [MenuItemButton].
///
/// The [child] attribute is required.
const MenuItemButton({
super.key,