Line data Source code
1 : import 'dart:async';
2 :
3 : import 'package:flutter/semantics.dart' show SemanticsRole;
4 : import 'package:flutter/services.dart';
5 : import 'package:flutter/widgets.dart';
6 : import 'package:fossui/src/foundation/anchored_overlay.dart';
7 : import 'package:fossui/src/foundation/foss_since.dart';
8 : import 'package:fossui/src/theme/foss_theme.dart';
9 :
10 : part 'foss_popover_style.dart';
11 :
12 : /// Scale the surface grows from on open.
13 : const double _openScale = 0.98;
14 :
15 : /// The scrim tint behind a modal surface: black at 32% opacity, matching the
16 : /// dialog and drawer barrier.
17 : const Color _scrimColor = Color(0x52000000);
18 :
19 : /// The side of the trigger a [FossPopover] prefers to open on. The surface
20 : /// flips to the opposite side when it would overflow the viewport.
21 : enum FossPopoverSide {
22 : /// Above the trigger.
23 : top,
24 :
25 : /// Below the trigger.
26 : bottom,
27 :
28 : /// The start side of the trigger; mirrors to the right under RTL.
29 : left,
30 :
31 : /// The end side of the trigger; mirrors to the left under RTL.
32 : right,
33 : }
34 :
35 : /// How the surface aligns to the trigger along the cross axis of its
36 : /// [FossPopoverSide].
37 : enum FossPopoverAlign {
38 : /// Flush with the trigger's leading edge.
39 : start,
40 :
41 : /// Centered on the trigger.
42 : center,
43 :
44 : /// Flush with the trigger's trailing edge.
45 : end,
46 : }
47 :
48 : /// Drives a [FossPopover] imperatively, so content inside the surface can open,
49 : /// close, or toggle it without threading callbacks through the tree. Works in
50 : /// both the controlled and uncontrolled modes.
51 : ///
52 : /// The controller holds no disposable resources; create one per popover and let
53 : /// it go out of scope with the widget.
54 : ///
55 : /// ```dart
56 : /// final controller = FossPopoverController();
57 : /// // Inside the content builder:
58 : /// FossButton(onPressed: controller.close, child: const Text('Done'));
59 : /// ```
60 : class FossPopoverController {
61 : _FossPopoverState? _state;
62 :
63 1 : void _detach(_FossPopoverState state) {
64 2 : if (identical(_state, state)) _state = null;
65 : }
66 :
67 : /// Whether the popover is currently open.
68 3 : bool get isOpen => _state?._isOpen ?? false;
69 :
70 : /// Opens the popover.
71 3 : void open() => _state?._setOpen(true);
72 :
73 : /// Closes the popover.
74 3 : void close() => _state?._setOpen(false);
75 :
76 : /// Toggles the popover between open and closed.
77 3 : void toggle() => _state?._toggle();
78 : }
79 :
80 : /// {@category Overlays}
81 : /// {@template foss.popover.preview}
82 : /// <img src="https://fossui.org/components/popover/overview/light.png"
83 : /// alt="FossPopover, light theme" width="480"
84 : /// style="max-width:100%;height:auto" />
85 : /// <img src="https://fossui.org/components/popover/overview/dark.png"
86 : /// alt="FossPopover, dark theme" width="480"
87 : /// style="max-width:100%;height:auto" />
88 : ///
89 : /// See the [popover documentation ↗](https://fossui.org/docs/components/popover) or
90 : /// try it live in the
91 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/popover/fosspopover/playground).
92 : /// {@endtemplate}
93 : ///
94 : /// An interactive floating panel anchored to a [child] trigger. Tapping the
95 : /// trigger opens a surface built by [builder] on the preferred [side] and
96 : /// [align]; the surface flips and clamps to stay on screen, and an outside tap
97 : /// or `Escape` dismisses it (when [dismissible]).
98 : ///
99 : /// Drive the open state in one of three ways: leave it uncontrolled and let the
100 : /// popover manage itself, control it with [open] plus [onOpenChange], or reach
101 : /// for a [FossPopoverController]. The [controller] works in either mode, so
102 : /// content can close the surface itself.
103 : ///
104 : /// Non-modal by default: focus moves into the surface and the background stays
105 : /// interactive. Set [modal] for a scrim and a focus trap. Colors, radius, and
106 : /// shadow resolve from the theme; pass a [style] for a one-off override.
107 : ///
108 : /// {@macro foss.customize}
109 : ///
110 : /// See also `FossTooltip` for a small, non-interactive hint.
111 : ///
112 : /// ```dart
113 : /// FossPopover(
114 : /// builder: (context) => const Padding(
115 : /// padding: EdgeInsets.all(8),
116 : /// child: Text('Anchored content'),
117 : /// ),
118 : /// child: FossButton(child: const Text('Open')),
119 : /// );
120 : /// ```
121 : @FossSince('0.1.1')
122 : class FossPopover extends StatefulWidget {
123 : /// {@macro foss.popover.preview}
124 : ///
125 : /// Creates a popover anchored to [child], showing [builder] when open.
126 1 : const FossPopover({
127 : required this.builder,
128 : required this.child,
129 : this.controller,
130 : this.open,
131 : this.onOpenChange,
132 : this.side = FossPopoverSide.bottom,
133 : this.align = FossPopoverAlign.center,
134 : this.sideOffset = kAnchorSideOffset,
135 : this.alignOffset = 0,
136 : this.modal = false,
137 : this.dismissible = true,
138 : this.semanticsLabel,
139 : this.style,
140 : super.key,
141 : });
142 :
143 : /// Builds the surface content, lazily when open. Free to call [controller] to
144 : /// close the popover.
145 : final WidgetBuilder builder;
146 :
147 : /// The trigger. Rendered as-is and used as the anchor; tapping it toggles the
148 : /// popover.
149 : final Widget child;
150 :
151 : /// Imperative handle for open, close, and toggle. Optional.
152 : final FossPopoverController? controller;
153 :
154 : /// The controlled open state. Non-null puts the popover in controlled mode:
155 : /// pair it with [onOpenChange] and rebuild on change. Null is uncontrolled.
156 : final bool? open;
157 :
158 : /// Called with the requested open state on every open or close, including
159 : /// dismissals. Required to observe changes in controlled mode.
160 : final ValueChanged<bool>? onOpenChange;
161 :
162 : /// The preferred side to open on. Defaults to [FossPopoverSide.bottom].
163 : final FossPopoverSide side;
164 :
165 : /// The cross-axis alignment to the trigger. Defaults to
166 : /// [FossPopoverAlign.center].
167 : final FossPopoverAlign align;
168 :
169 : /// The gap from the trigger along the main axis, in logical pixels.
170 : final double sideOffset;
171 :
172 : /// The shift along the cross axis, in logical pixels.
173 : final double alignOffset;
174 :
175 : /// Whether to draw a scrim behind the surface and trap focus inside it.
176 : /// Defaults to false (non-modal).
177 : final bool modal;
178 :
179 : /// Whether an outside tap or `Escape` dismisses the popover. Default true.
180 : final bool dismissible;
181 :
182 : /// Accessible name for the surface. Announced with its dialog role.
183 : final String? semanticsLabel;
184 :
185 : /// Per-instance visual overrides for the surface.
186 : final FossPopoverStyle? style;
187 :
188 1 : @override
189 1 : State<FossPopover> createState() => _FossPopoverState();
190 : }
191 :
192 : class _FossPopoverState extends State<FossPopover>
193 : with SingleTickerProviderStateMixin, WidgetsBindingObserver {
194 : final OverlayPortalController _portal = OverlayPortalController();
195 : final GlobalKey _anchorKey = GlobalKey();
196 : final FocusNode _triggerFocus = FocusNode(debugLabel: 'FossPopover trigger');
197 : final FocusScopeNode _surfaceScope = FocusScopeNode(
198 : debugLabel: 'FossPopover surface',
199 : );
200 : final Object _tapGroup = Object();
201 : final List<ScrollPosition> _scrollPositions = <ScrollPosition>[];
202 :
203 : late final AnimationController _animation;
204 : late final CurvedAnimation _curve;
205 : late final Animation<double> _scale;
206 :
207 : /// The uncontrolled open state; ignored when [FossPopover.open] is non-null.
208 : bool _open = false;
209 :
210 1 : @override
211 : void initState() {
212 1 : super.initState();
213 2 : WidgetsBinding.instance.addObserver(this);
214 3 : widget.controller?._state = this;
215 : // Duration is set from the motion token on every forward/reverse.
216 2 : _animation = AnimationController(vsync: this);
217 3 : _curve = CurvedAnimation(parent: _animation, curve: Curves.easeOut);
218 4 : _scale = Tween<double>(begin: _openScale, end: 1).animate(_curve);
219 2 : if (widget.open ?? false) {
220 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
221 3 : if (mounted && _isOpen) _show();
222 : });
223 : }
224 : }
225 :
226 1 : @override
227 : void didUpdateWidget(FossPopover old) {
228 1 : super.didUpdateWidget(old);
229 4 : if (old.controller != widget.controller) {
230 2 : old.controller?._detach(this);
231 3 : widget.controller?._state = this;
232 : }
233 : // In controlled mode the parent owns the state; sync the surface to it
234 : // after the frame, since driving the overlay during a build is unsafe.
235 2 : final target = widget.open;
236 2 : if (target != null && target != old.open) {
237 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
238 3 : if (!mounted || _isOpen != target) return;
239 2 : target ? _show() : _hide();
240 : });
241 : }
242 : }
243 :
244 1 : @override
245 : void dispose() {
246 2 : WidgetsBinding.instance.removeObserver(this);
247 3 : widget.controller?._detach(this);
248 1 : _detachScrollDismiss();
249 2 : _curve.dispose();
250 2 : _animation.dispose();
251 2 : _triggerFocus.dispose();
252 2 : _surfaceScope.dispose();
253 1 : super.dispose();
254 : }
255 :
256 : // The Android system back closes the popover rather than popping the route.
257 1 : @override
258 : Future<bool> didPopRoute() async {
259 1 : if (!_isOpen) return false;
260 1 : _dismiss();
261 : return true;
262 : }
263 :
264 4 : bool get _isOpen => widget.open ?? _open;
265 :
266 1 : bool get _reduceMotion =>
267 3 : MediaQuery.maybeOf(context)?.disableAnimations ?? false;
268 :
269 5 : Duration get _duration => context.fossTheme.motion.overlay;
270 :
271 3 : void _toggle() => _setOpen(!_isOpen);
272 :
273 : /// The single entry point for every open and close request. Fires
274 : /// [FossPopover.onOpenChange]; in controlled mode the parent drives the
275 : /// surface through [didUpdateWidget], otherwise this owns the state.
276 1 : void _setOpen(bool next) {
277 2 : if (next == _isOpen) return;
278 3 : widget.onOpenChange?.call(next);
279 2 : if (widget.open != null) return;
280 3 : setState(() => _open = next);
281 2 : next ? _show() : _hide();
282 : }
283 :
284 : /// Closes on an outside tap, `Escape`, or a scroll, when dismissible.
285 1 : void _dismiss() {
286 3 : if (widget.dismissible) _setOpen(false);
287 : }
288 :
289 1 : void _show() {
290 2 : if (_portal.isShowing) return;
291 2 : _portal.show();
292 1 : _attachScrollDismiss();
293 4 : _animation.duration = _reduceMotion ? Duration.zero : _duration;
294 3 : _animation.forward(from: _reduceMotion ? 1 : 0);
295 : // Move focus into the surface once it has mounted: the first focusable
296 : // content, or the surface scope itself when the content has none.
297 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
298 3 : if (!mounted || !_portal.isShowing) return;
299 3 : final focusable = _surfaceScope.traversalDescendants.where(
300 3 : (node) => node.canRequestFocus && !node.skipTraversal,
301 : );
302 4 : (focusable.isEmpty ? _surfaceScope : focusable.first).requestFocus();
303 : });
304 : }
305 :
306 1 : void _hide() {
307 1 : _detachScrollDismiss();
308 : // Only pull focus back to the trigger when it still lives in the surface;
309 : // a programmatic close must not steal focus the user moved elsewhere.
310 4 : if (_surfaceScope.hasFocus) _focusTarget.requestFocus();
311 1 : if (_reduceMotion) {
312 2 : _animation.value = 0;
313 2 : _portal.hide();
314 : return;
315 : }
316 3 : _animation.duration = _duration;
317 1 : unawaited(
318 4 : _animation.reverse().whenComplete(() {
319 4 : if (mounted && _animation.status == AnimationStatus.dismissed) {
320 2 : _portal.hide();
321 : }
322 : }),
323 : );
324 : }
325 :
326 : // React when any enclosing scrollable moves, so the surface never floats
327 : // detached from its trigger: a dismissible popover closes, a non-dismissible
328 : // one follows the trigger. Every ancestor is tracked, not just the nearest.
329 1 : void _onScroll() {
330 1 : if (!_isOpen) return;
331 2 : if (widget.dismissible) {
332 1 : _setOpen(false);
333 : } else {
334 : // Reposition against the moved anchor.
335 2 : setState(() {});
336 : }
337 : }
338 :
339 1 : void _attachScrollDismiss() {
340 : for (
341 2 : var scrollable = Scrollable.maybeOf(context);
342 : scrollable != null;
343 2 : scrollable = Scrollable.maybeOf(scrollable.context)
344 : ) {
345 3 : scrollable.position.addListener(_onScroll);
346 3 : _scrollPositions.add(scrollable.position);
347 : }
348 : }
349 :
350 1 : void _detachScrollDismiss() {
351 2 : for (final position in _scrollPositions) {
352 2 : position.removeListener(_onScroll);
353 : }
354 2 : _scrollPositions.clear();
355 : }
356 :
357 1 : KeyEventResult _onKey(FocusNode node, KeyEvent event) {
358 1 : if (event is! KeyDownEvent ||
359 2 : event.logicalKey != LogicalKeyboardKey.escape ||
360 1 : !_isOpen) {
361 : return KeyEventResult.ignored;
362 : }
363 2 : if (widget.dismissible) {
364 1 : _dismiss();
365 : return KeyEventResult.handled;
366 : }
367 : // A modal traps Escape behind its scrim, so it never reaches the app; a
368 : // non-modal, non-dismissible popover lets Escape propagate.
369 2 : return widget.modal ? KeyEventResult.handled : KeyEventResult.ignored;
370 : }
371 :
372 : /// The node that holds the trigger's one Tab stop: the first focusable
373 : /// node inside [FossPopover.child], or the wrapper when there is none.
374 1 : FocusNode get _focusTarget =>
375 4 : _triggerFocus.traversalDescendants.firstOrNull ?? _triggerFocus;
376 :
377 : // The wrapper is a Tab stop only for a trigger with no focusable node of its
378 : // own, so a button trigger is reached in one press, not two. Children attach
379 : // their nodes during the build, so this runs once the frame is done.
380 1 : void _syncTriggerFocus() {
381 1 : if (!mounted) return;
382 5 : _triggerFocus.canRequestFocus = _triggerFocus.traversalDescendants.isEmpty;
383 : }
384 :
385 : // Enter and Space toggle a trigger that takes no input of its own. Only while
386 : // the trigger node itself holds focus: a focusable child, a button for
387 : // instance, takes the key first and toggles through the controller.
388 1 : KeyEventResult _onTriggerKey(FocusNode node, KeyEvent event) {
389 1 : final key = event.logicalKey;
390 1 : if (event is! KeyDownEvent ||
391 1 : !node.hasPrimaryFocus ||
392 2 : (key != LogicalKeyboardKey.enter && key != LogicalKeyboardKey.space)) {
393 : return KeyEventResult.ignored;
394 : }
395 1 : _toggle();
396 : return KeyEventResult.handled;
397 : }
398 :
399 1 : Rect? _anchorRect(BuildContext overlayContext) {
400 3 : final anchor = _anchorKey.currentContext?.findRenderObject();
401 3 : final overlay = Overlay.of(overlayContext).context.findRenderObject();
402 3 : if (anchor is! RenderBox || overlay is! RenderBox || !anchor.attached) {
403 : return null;
404 : }
405 3 : return anchor.localToGlobal(Offset.zero, ancestor: overlay) & anchor.size;
406 : }
407 :
408 1 : Widget _buildOverlay(BuildContext context) {
409 1 : final anchor = _anchorRect(context);
410 : if (anchor == null) return const SizedBox.shrink();
411 1 : final direction = Directionality.of(context);
412 3 : final side = _anchorSide(widget.side, direction);
413 : // Only the horizontal cross axis (top/bottom sides) mirrors under RTL.
414 : final mirror =
415 1 : direction == TextDirection.rtl &&
416 2 : (side == AnchorSide.top || side == AnchorSide.bottom);
417 :
418 1 : final surface = Positioned.fill(
419 1 : child: CustomSingleChildLayout(
420 1 : delegate: AnchoredLayout(
421 : anchor: anchor,
422 : side: side,
423 6 : align: mirror ? _flipAlign(widget.align) : _anchorAlign(widget.align),
424 2 : sideOffset: widget.sideOffset,
425 5 : alignOffset: mirror ? -widget.alignOffset : widget.alignOffset,
426 1 : padding: overlaySafeArea(context),
427 : ),
428 1 : child: FadeTransition(
429 1 : opacity: _curve,
430 3 : child: ScaleTransition(scale: _scale, child: _surfaceContent()),
431 : ),
432 : ),
433 : );
434 :
435 2 : if (!widget.modal) return surface;
436 : // No BlockSemantics here: on iOS it hides the surface from assistive tech
437 : // along with the background. The scrim already takes every stray tap.
438 1 : return Stack(
439 1 : children: [
440 1 : Positioned.fill(
441 3 : child: _Scrim(animation: _curve, onTap: _dismiss),
442 : ),
443 : surface,
444 : ],
445 : );
446 : }
447 :
448 1 : Widget _surfaceContent() {
449 : // The FocusScope traps Tab inside the surface for a modal popover; a
450 : // non-modal one leaves the background interactive, so Tab can exit.
451 : // Non-modal dismisses on an outside tap via TapRegion.
452 4 : _surfaceScope.traversalEdgeBehavior = widget.modal
453 : ? TraversalEdgeBehavior.closedLoop
454 : : TraversalEdgeBehavior.leaveFlutterView;
455 1 : return FocusScope(
456 1 : node: _surfaceScope,
457 1 : onKeyEvent: _onKey,
458 1 : child: TapRegion(
459 1 : groupId: _tapGroup,
460 4 : onTapOutside: widget.modal ? null : (_) => _dismiss(),
461 1 : child: _PopoverSurface(
462 2 : builder: widget.builder,
463 2 : style: widget.style,
464 2 : semanticsLabel: widget.semanticsLabel,
465 : ),
466 : ),
467 : );
468 : }
469 :
470 1 : @override
471 : Widget build(BuildContext context) {
472 4 : WidgetsBinding.instance.addPostFrameCallback((_) => _syncTriggerFocus());
473 1 : Widget trigger = GestureDetector(
474 : behavior: HitTestBehavior.opaque,
475 1 : onTap: _toggle,
476 4 : child: KeyedSubtree(key: _anchorKey, child: widget.child),
477 : );
478 : // Membership in the same tap group as the surface so a tap on the trigger
479 : // is never treated as an outside tap by the surface's TapRegion.
480 2 : trigger = TapRegion(groupId: _tapGroup, child: trigger);
481 1 : trigger = Focus(
482 1 : focusNode: _triggerFocus,
483 1 : onKeyEvent: _onTriggerKey,
484 : child: trigger,
485 : );
486 :
487 1 : return Semantics(
488 : button: true,
489 1 : expanded: _isOpen,
490 1 : child: OverlayPortal(
491 1 : controller: _portal,
492 1 : overlayChildBuilder: _buildOverlay,
493 : child: trigger,
494 : ),
495 : );
496 : }
497 : }
498 :
499 : /// The floating surface: popover fill, 1px border, softened drop shadow, an
500 : /// inset highlight ring, and the [builder] content under a padded, clipped box.
501 : class _PopoverSurface extends StatelessWidget {
502 1 : const _PopoverSurface({
503 : required this.builder,
504 : required this.style,
505 : required this.semanticsLabel,
506 : });
507 :
508 : final WidgetBuilder builder;
509 : final FossPopoverStyle? style;
510 : final String? semanticsLabel;
511 :
512 1 : @override
513 : Widget build(BuildContext context) {
514 1 : final theme = context.fossTheme;
515 1 : final colors = theme.colors;
516 1 : final s = style;
517 1 : final shape = RoundedSuperellipseBorder(
518 3 : side: BorderSide(color: s?.borderColor ?? colors.border),
519 4 : borderRadius: BorderRadius.circular(s?.borderRadius ?? theme.radii.lg),
520 : );
521 :
522 1 : return Semantics(
523 : role: SemanticsRole.dialog,
524 : container: true,
525 : explicitChildNodes: true,
526 1 : label: semanticsLabel,
527 1 : child: DecoratedBox(
528 1 : decoration: ShapeDecoration(
529 2 : color: s?.backgroundColor ?? colors.popover,
530 : shape: shape,
531 4 : shadows: s?.shadows ?? overlaySoftShadow(theme.shadows.lg),
532 : ),
533 1 : child: ClipPath(
534 1 : clipper: ShapeBorderClipper(
535 : shape: shape,
536 1 : textDirection: Directionality.of(context),
537 : ),
538 1 : child: Stack(
539 1 : children: [
540 1 : Padding(
541 4 : padding: s?.padding ?? EdgeInsets.all(theme.spacing(4)),
542 1 : child: DefaultTextStyle.merge(
543 3 : style: theme.typography.sm.copyWith(
544 2 : color: s?.foregroundColor ?? colors.popoverForeground,
545 : ),
546 2 : child: Builder(builder: builder),
547 : ),
548 : ),
549 : // Purely decorative, and above the content, so it must not
550 : // intercept taps meant for interactive children.
551 1 : Positioned.fill(
552 2 : child: IgnorePointer(child: OverlayInnerRing(colors: colors)),
553 : ),
554 : ],
555 : ),
556 : ),
557 : ),
558 : );
559 : }
560 : }
561 :
562 : /// The tinted, tap-dismissable scrim behind a modal surface, fading on the open
563 : /// animation. Opaque to pointers so the background never takes a stray tap.
564 : class _Scrim extends StatelessWidget {
565 1 : const _Scrim({required this.animation, required this.onTap});
566 :
567 : final Animation<double> animation;
568 : final VoidCallback onTap;
569 :
570 1 : @override
571 : Widget build(BuildContext context) {
572 1 : return GestureDetector(
573 : behavior: HitTestBehavior.opaque,
574 1 : onTap: onTap,
575 1 : child: FadeTransition(
576 1 : opacity: animation,
577 : child: const ColoredBox(color: _scrimColor),
578 : ),
579 : );
580 : }
581 : }
582 :
583 : /// Maps the directional [FossPopoverSide] to a physical [AnchorSide], mirroring
584 : /// [FossPopoverSide.left] and [FossPopoverSide.right] under RTL.
585 1 : AnchorSide _anchorSide(FossPopoverSide side, TextDirection direction) {
586 1 : final mirror = direction == TextDirection.rtl;
587 : return switch (side) {
588 1 : FossPopoverSide.top => AnchorSide.top,
589 1 : FossPopoverSide.bottom => AnchorSide.bottom,
590 1 : FossPopoverSide.left => mirror ? AnchorSide.right : AnchorSide.left,
591 1 : FossPopoverSide.right => mirror ? AnchorSide.left : AnchorSide.right,
592 : };
593 : }
594 :
595 1 : AnchorAlign _anchorAlign(FossPopoverAlign align) => switch (align) {
596 1 : FossPopoverAlign.start => AnchorAlign.start,
597 1 : FossPopoverAlign.center => AnchorAlign.center,
598 1 : FossPopoverAlign.end => AnchorAlign.end,
599 : };
600 :
601 1 : AnchorAlign _flipAlign(FossPopoverAlign align) => switch (align) {
602 1 : FossPopoverAlign.start => AnchorAlign.end,
603 1 : FossPopoverAlign.center => AnchorAlign.center,
604 1 : FossPopoverAlign.end => AnchorAlign.start,
605 : };
|