Line data Source code
1 : import 'package:flutter/scheduler.dart' show SchedulerPhase;
2 : import 'package:flutter/semantics.dart' show SemanticsRole;
3 : import 'package:flutter/services.dart';
4 : import 'package:flutter/widgets.dart';
5 : import 'package:fossui/src/foundation/anchored_overlay.dart';
6 : import 'package:fossui/src/foundation/foss_since.dart';
7 : import 'package:fossui/src/theme/theme.dart';
8 :
9 : part '_foss_menu_panel.dart';
10 : part 'foss_menu_item.dart';
11 : part 'foss_menu_style.dart';
12 : part 'foss_menu_visuals.dart';
13 :
14 : /// Smallest panel width. The panel grows past it to fit its widest row.
15 : const double _minPanelWidth = 128;
16 :
17 : /// Row height floor. A row grows past it at a larger text scale.
18 : const double _rowMinHeight = 32;
19 :
20 : /// Glyph size in a row's icon slot.
21 : const double _iconSize = 18;
22 :
23 : /// Start inset of a row that lines its text up with the glyph rows above it.
24 : const double _insetStart = 32;
25 :
26 : /// Start inset of a group heading, a step wider than a row's so the heading
27 : /// sits above the text rather than above the glyph.
28 : const double _labelInsetStart = 36;
29 :
30 : const double _separatorThickness = 1;
31 :
32 : const double _disabledOpacity = 0.64;
33 :
34 : /// A row glyph reads a step quieter than the label beside it.
35 : const double _iconOpacity = 0.8;
36 :
37 : /// A shortcut reads quieter again, behind the label it belongs to.
38 : const double _shortcutOpacity = 0.72;
39 :
40 : /// Scale the panel grows from on open.
41 : const double _openScale = 0.98;
42 :
43 : /// The side of the trigger a [FossMenu] prefers to open on. The panel flips to
44 : /// the opposite side when it would overflow the viewport.
45 : enum FossMenuSide {
46 : /// Above the trigger.
47 : top,
48 :
49 : /// Below the trigger.
50 : bottom,
51 :
52 : /// The start side of the trigger; mirrors to the right under RTL.
53 : left,
54 :
55 : /// The end side of the trigger; mirrors to the left under RTL.
56 : right,
57 : }
58 :
59 : /// How the panel aligns to the trigger along the cross axis of its
60 : /// [FossMenuSide].
61 : enum FossMenuAlign {
62 : /// Flush with the trigger's leading edge.
63 : start,
64 :
65 : /// Centered on the trigger.
66 : center,
67 :
68 : /// Flush with the trigger's trailing edge.
69 : end,
70 : }
71 :
72 : /// Drives a [FossMenu] imperatively, so a trigger that handles its own taps can
73 : /// still open the panel. A `FossButton` is the common case: its `onPressed`
74 : /// wins the tap, so wire that callback to [toggle] instead of relying on the
75 : /// menu's own trigger gesture.
76 : ///
77 : /// The controller holds no disposable resources; create one per menu and let it
78 : /// go out of scope with the widget.
79 : ///
80 : /// ```dart
81 : /// final controller = FossMenuController();
82 : /// FossMenu(
83 : /// controller: controller,
84 : /// items: items,
85 : /// child: FossButton(
86 : /// onPressed: controller.toggle,
87 : /// child: const Text('Actions'),
88 : /// ),
89 : /// );
90 : /// ```
91 : @FossSince('0.1.3')
92 : class FossMenuController {
93 : _FossMenuState? _state;
94 :
95 2 : void _detach(_FossMenuState state) {
96 4 : if (identical(_state, state)) _state = null;
97 : }
98 :
99 : /// Whether the panel is currently open.
100 6 : bool get isOpen => _state?._open ?? false;
101 :
102 : /// Opens the panel.
103 6 : void open() => _state?._openPanel();
104 :
105 : /// Closes the panel.
106 3 : void close() => _state?._close();
107 :
108 : /// Opens the panel when it is closed, closes it when it is open.
109 7 : void toggle() => isOpen ? close() : open();
110 : }
111 :
112 : /// {@category Overlays}
113 : /// {@template foss.menu.preview}
114 : /// <img src="https://fossui.org/components/menu/overview/light.png"
115 : /// alt="FossMenu, light theme" width="480"
116 : /// style="max-width:100%;height:auto" />
117 : /// <img src="https://fossui.org/components/menu/overview/dark.png"
118 : /// alt="FossMenu, dark theme" width="480"
119 : /// style="max-width:100%;height:auto" />
120 : ///
121 : /// See the [menu documentation ↗](https://fossui.org/docs/components/menu) or
122 : /// try it live in the
123 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/menu/fossmenu/playground).
124 : /// {@endtemplate}
125 : ///
126 : /// A dropdown menu: a [child] trigger that opens a panel of [items] over the
127 : /// page, each a label with an optional glyph and an optional shortcut, under a
128 : /// highlight that follows the pointer and the arrow keys.
129 : ///
130 : /// The panel opens below the trigger and flush with its start edge, flips above
131 : /// when there is no room, clamps inside the viewport, and scrolls internally
132 : /// when a long list still does not fit. Tapping a row runs its
133 : /// [FossMenuItem.onSelected] and closes the panel; a row without one does
134 : /// nothing and stays open. `Enter` or `Space` on the focused trigger opens the
135 : /// panel. `ArrowUp` and `ArrowDown` move the highlight, keep it in view, and
136 : /// wrap, `Enter` and `Space` select, and `Escape` or a tap outside closes and
137 : /// returns focus to the trigger.
138 : ///
139 : /// A trigger that handles its own taps, a `FossButton` with an `onPressed` for
140 : /// instance, wins the gesture, so the menu never sees it. Give the menu a
141 : /// [FossMenuController] and point that callback at [FossMenuController.toggle].
142 : /// A trigger that takes no input of its own needs no controller.
143 : ///
144 : /// Pass [FossMenuItem.separator] and [FossMenuItem.label] inside [items] to
145 : /// divide and head groups of rows. Colors, radius, and type come from
146 : /// `context.fossTheme`; pass a [FossMenuStyle] to [style] for a one-off.
147 : ///
148 : /// {@macro foss.customize}
149 : ///
150 : /// See also FossPopover for a panel of arbitrary content rather than rows.
151 : ///
152 : /// ```dart
153 : /// final controller = FossMenuController();
154 : ///
155 : /// FossMenu(
156 : /// controller: controller,
157 : /// items: [
158 : /// FossMenuItem(label: 'New file', shortcut: 'Ctrl N', onSelected: create),
159 : /// const FossMenuItem.separator(),
160 : /// FossMenuItem(label: 'Delete', destructive: true, onSelected: remove),
161 : /// ],
162 : /// child: FossButton(
163 : /// onPressed: controller.toggle,
164 : /// child: const Text('Actions'),
165 : /// ),
166 : /// );
167 : /// ```
168 : @FossSince('0.1.3')
169 : class FossMenu extends StatefulWidget {
170 : /// {@macro foss.menu.preview}
171 : ///
172 : /// Creates a menu anchored to [child], showing [items] when open.
173 4 : const FossMenu({
174 : required this.items,
175 : required this.child,
176 : this.controller,
177 : this.side = FossMenuSide.bottom,
178 : this.align = FossMenuAlign.start,
179 : this.onOpenChange,
180 : this.style,
181 : super.key,
182 : });
183 :
184 : /// The rows, in order. Action rows, separators, and group headings all live
185 : /// in this one list.
186 : final List<FossMenuItem> items;
187 :
188 : /// The trigger. Rendered as-is and used as the anchor; tapping it opens the
189 : /// panel, unless the trigger handles the tap itself.
190 : ///
191 : /// The panel anchors to the box this widget occupies, not to what it paints
192 : /// inside it. A trigger stretched by its parent, a list child for instance,
193 : /// anchors the panel to the full width; wrap it in an `Align` to anchor to
194 : /// the trigger itself.
195 : final Widget child;
196 :
197 : /// Imperative handle for open, close, and toggle. Needed when [child]
198 : /// consumes its own taps.
199 : final FossMenuController? controller;
200 :
201 : /// The preferred side to open on. Defaults to [FossMenuSide.bottom].
202 : final FossMenuSide side;
203 :
204 : /// The cross-axis alignment to the trigger. Defaults to
205 : /// [FossMenuAlign.start], because rows of start-aligned text read wrong
206 : /// centered under a trigger.
207 : final FossMenuAlign align;
208 :
209 : /// Called with the new state on every open and close, including dismissals.
210 : final ValueChanged<bool>? onOpenChange;
211 :
212 : /// Per-instance overrides layered on the theme-resolved style.
213 : final FossMenuStyle? style;
214 :
215 4 : @override
216 4 : State<FossMenu> createState() => _FossMenuState();
217 : }
218 :
219 : class _FossMenuState extends State<FossMenu>
220 : with SingleTickerProviderStateMixin, WidgetsBindingObserver {
221 : final OverlayPortalController _portal = OverlayPortalController();
222 : final GlobalKey _anchorKey = GlobalKey();
223 : final FocusNode _triggerFocus = FocusNode(debugLabel: 'FossMenu trigger');
224 : final FocusScopeNode _panelScope = FocusScopeNode(
225 : debugLabel: 'FossMenu panel scope',
226 : );
227 : final List<ScrollPosition> _scrollPositions = <ScrollPosition>[];
228 :
229 : late final AnimationController _animation;
230 : late final CurvedAnimation _curve;
231 :
232 : bool _open = false;
233 :
234 4 : @override
235 : void initState() {
236 4 : super.initState();
237 8 : WidgetsBinding.instance.addObserver(this);
238 10 : widget.controller?._state = this;
239 : // Duration is set from the motion token on every forward and reverse.
240 16 : _animation = AnimationController(vsync: this)..addStatusListener(_onStatus);
241 12 : _curve = CurvedAnimation(parent: _animation, curve: Curves.easeOut);
242 : }
243 :
244 1 : @override
245 : void didUpdateWidget(FossMenu oldWidget) {
246 1 : super.didUpdateWidget(oldWidget);
247 4 : if (oldWidget.controller != widget.controller) {
248 2 : oldWidget.controller?._detach(this);
249 3 : widget.controller?._state = this;
250 : }
251 : }
252 :
253 4 : @override
254 : void dispose() {
255 8 : WidgetsBinding.instance.removeObserver(this);
256 10 : widget.controller?._detach(this);
257 4 : _detachScrollDismiss();
258 8 : _curve.dispose();
259 8 : _animation.dispose();
260 8 : _triggerFocus.dispose();
261 8 : _panelScope.dispose();
262 4 : super.dispose();
263 : }
264 :
265 : // The Android system back closes the panel rather than popping the route.
266 1 : @override
267 : Future<bool> didPopRoute() async {
268 1 : if (!_open) return false;
269 1 : _close();
270 : return true;
271 : }
272 :
273 : // A rotation, a resize, or a keyboard inset moves the trigger. Rebuild once
274 : // the frame has laid it out, so the panel anchors to its new bounds.
275 1 : @override
276 : void didChangeMetrics() {
277 1 : if (!_open) return;
278 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
279 4 : if (mounted && _open) setState(() {});
280 : });
281 : }
282 :
283 4 : bool get _reduceMotion =>
284 12 : MediaQuery.maybeOf(context)?.disableAnimations ?? false;
285 :
286 20 : Duration get _duration => context.fossTheme.motion.overlay;
287 :
288 4 : void _openPanel() {
289 4 : if (_open) return;
290 12 : setState(() => _open = true);
291 9 : widget.onOpenChange?.call(true);
292 8 : _portal.show();
293 4 : _attachScrollDismiss();
294 16 : _animation.duration = _reduceMotion ? Duration.zero : _duration;
295 12 : _animation.forward(from: _reduceMotion ? 1 : 0);
296 : }
297 :
298 4 : void _close() {
299 4 : if (!_open) return;
300 4 : _detachScrollDismiss();
301 12 : setState(() => _open = false);
302 9 : widget.onOpenChange?.call(false);
303 : // Only pull focus back when it still sits in the panel, so a programmatic
304 : // close never steals focus the user moved elsewhere.
305 16 : if (_panelScope.hasFocus) _focusTarget.requestFocus();
306 16 : _animation.duration = _reduceMotion ? Duration.zero : _duration;
307 8 : _animation.reverse();
308 : }
309 :
310 : // The panel unmounts once the close transition runs out, but not when a
311 : // reopen caught it on the way out.
312 4 : void _onStatus(AnimationStatus status) {
313 16 : if (status.isDismissed && !_open) _portal.hide();
314 : }
315 :
316 : /// Runs a selected row's action, then closes. A row without an action leaves
317 : /// the panel open: closing on a row that did nothing reads as a cancel the
318 : /// caller never asked for.
319 3 : void _selected(int index) {
320 12 : final action = widget.items[index].onSelected;
321 : if (action == null) return;
322 3 : action();
323 3 : _close();
324 : }
325 :
326 : // Close when any enclosing scrollable moves, so the panel never floats
327 : // detached from its trigger. Every ancestor is tracked, not just the
328 : // nearest, so a page swipe dismisses it even inside a nested scroll view.
329 4 : void _attachScrollDismiss() {
330 : for (
331 8 : var scrollable = Scrollable.maybeOf(context);
332 : scrollable != null;
333 2 : scrollable = Scrollable.maybeOf(scrollable.context)
334 : ) {
335 3 : scrollable.position.addListener(_onScroll);
336 3 : _scrollPositions.add(scrollable.position);
337 : }
338 : }
339 :
340 4 : void _detachScrollDismiss() {
341 5 : for (final position in _scrollPositions) {
342 2 : position.removeListener(_onScroll);
343 : }
344 8 : _scrollPositions.clear();
345 : }
346 :
347 : // A scroll can land mid-frame, a jump from a build or a correction during
348 : // layout, where nothing may rebuild. Close after that frame instead.
349 1 : void _onScroll() {
350 1 : final binding = WidgetsBinding.instance;
351 2 : if (binding.schedulerPhase != SchedulerPhase.persistentCallbacks) {
352 1 : _close();
353 : return;
354 : }
355 2 : binding.addPostFrameCallback((_) {
356 2 : if (mounted) _close();
357 : });
358 : }
359 :
360 : /// The node that holds the trigger's one Tab stop: the first focusable
361 : /// node inside [FossMenu.child], or the wrapper when there is none.
362 4 : FocusNode get _focusTarget =>
363 16 : _triggerFocus.traversalDescendants.firstOrNull ?? _triggerFocus;
364 :
365 : // The wrapper is a Tab stop only for a trigger with no focusable node of its
366 : // own, so a button trigger is reached in one press, not two. Children attach
367 : // their nodes during the build, so this runs once the frame is done.
368 4 : void _syncTriggerFocus() {
369 4 : if (!mounted) return;
370 20 : _triggerFocus.canRequestFocus = _triggerFocus.traversalDescendants.isEmpty;
371 : }
372 :
373 : // Enter and Space open a trigger that takes no input of its own. Only while
374 : // the trigger node itself holds focus: a focusable child, a button for
375 : // instance, takes the key first and toggles through the controller.
376 3 : KeyEventResult _onTriggerKey(FocusNode node, KeyEvent event) {
377 3 : final key = event.logicalKey;
378 3 : if (event is! KeyDownEvent ||
379 1 : !node.hasPrimaryFocus ||
380 2 : (key != LogicalKeyboardKey.enter && key != LogicalKeyboardKey.space)) {
381 : return KeyEventResult.ignored;
382 : }
383 2 : _open ? _close() : _openPanel();
384 : return KeyEventResult.handled;
385 : }
386 :
387 4 : Rect? _anchorRect(BuildContext overlayContext) {
388 12 : final anchor = _anchorKey.currentContext?.findRenderObject();
389 12 : final overlay = Overlay.of(overlayContext).context.findRenderObject();
390 12 : if (anchor is! RenderBox || overlay is! RenderBox || !anchor.attached) {
391 : return null;
392 : }
393 12 : return anchor.localToGlobal(Offset.zero, ancestor: overlay) & anchor.size;
394 : }
395 :
396 4 : Widget _buildOverlay(BuildContext context) {
397 4 : final anchor = _anchorRect(context);
398 : if (anchor == null) return const SizedBox.shrink();
399 4 : final direction = Directionality.of(context);
400 12 : final side = _anchorSide(widget.side, direction);
401 : // Only the horizontal cross axis (the top and bottom sides) mirrors.
402 : final mirror =
403 4 : direction == TextDirection.rtl &&
404 4 : (side == AnchorSide.top || side == AnchorSide.bottom);
405 :
406 : // Positioned.fill on the outside, so the stack is laid out against the
407 : // overlay rather than against its own children. An overlay that hands out
408 : // loose constraints would otherwise collapse a bare stack of positioned
409 : // children to nothing, and the panel would land on the trigger.
410 4 : return Positioned.fill(
411 4 : child: Stack(
412 4 : children: [
413 : // The barrier takes the tap that dismisses the panel, including a
414 : // second tap on the trigger underneath it.
415 4 : Positioned.fill(
416 4 : child: GestureDetector(
417 : behavior: HitTestBehavior.opaque,
418 4 : onTap: _close,
419 : ),
420 : ),
421 4 : FocusScope(
422 4 : node: _panelScope,
423 4 : child: _FossMenuPanel(
424 8 : items: widget.items,
425 : anchor: anchor,
426 : side: side,
427 : align: mirror
428 6 : ? _flipAlign(widget.align)
429 12 : : _anchorAlign(widget.align),
430 4 : animation: _curve,
431 : sideOffset: kAnchorSideOffset,
432 4 : onSelected: _selected,
433 4 : onDismiss: _close,
434 8 : style: widget.style,
435 : ),
436 : ),
437 : ],
438 : ),
439 : );
440 : }
441 :
442 4 : @override
443 : Widget build(BuildContext context) {
444 16 : WidgetsBinding.instance.addPostFrameCallback((_) => _syncTriggerFocus());
445 4 : final trigger = Focus(
446 4 : focusNode: _triggerFocus,
447 4 : onKeyEvent: _onTriggerKey,
448 4 : child: GestureDetector(
449 : behavior: HitTestBehavior.opaque,
450 4 : onTap: _openPanel,
451 16 : child: KeyedSubtree(key: _anchorKey, child: widget.child),
452 : ),
453 : );
454 :
455 4 : return Semantics(
456 : button: true,
457 4 : expanded: _open,
458 4 : child: OverlayPortal(
459 4 : controller: _portal,
460 4 : overlayChildBuilder: _buildOverlay,
461 : child: trigger,
462 : ),
463 : );
464 : }
465 : }
466 :
467 : /// Maps the directional [FossMenuSide] to a physical [AnchorSide], mirroring
468 : /// [FossMenuSide.left] and [FossMenuSide.right] under RTL.
469 4 : AnchorSide _anchorSide(FossMenuSide side, TextDirection direction) {
470 4 : final mirror = direction == TextDirection.rtl;
471 : return switch (side) {
472 4 : FossMenuSide.top => AnchorSide.top,
473 4 : FossMenuSide.bottom => AnchorSide.bottom,
474 1 : FossMenuSide.left => mirror ? AnchorSide.right : AnchorSide.left,
475 1 : FossMenuSide.right => mirror ? AnchorSide.left : AnchorSide.right,
476 : };
477 : }
478 :
479 4 : AnchorAlign _anchorAlign(FossMenuAlign align) => switch (align) {
480 4 : FossMenuAlign.start => AnchorAlign.start,
481 1 : FossMenuAlign.center => AnchorAlign.center,
482 1 : FossMenuAlign.end => AnchorAlign.end,
483 : };
484 :
485 2 : AnchorAlign _flipAlign(FossMenuAlign align) => switch (align) {
486 2 : FossMenuAlign.start => AnchorAlign.end,
487 1 : FossMenuAlign.center => AnchorAlign.center,
488 1 : FossMenuAlign.end => AnchorAlign.start,
489 : };
|