Line data Source code
1 : import 'dart:async';
2 :
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/theme/foss_theme.dart';
7 :
8 : part 'foss_tooltip_style.dart';
9 :
10 : /// Vertical padding inside the popup.
11 : const double _verticalPadding = 4;
12 :
13 : /// Scale the popup grows from on open.
14 : const double _openScale = 0.98;
15 :
16 : /// The side of the anchor a [FossTooltip] prefers to open on. The popup flips
17 : /// to the opposite side when it would overflow the viewport.
18 : enum FossTooltipSide {
19 : /// Above the anchor.
20 : top,
21 :
22 : /// Below the anchor.
23 : bottom,
24 :
25 : /// The start side of the anchor; mirrors to the right edge under RTL.
26 : left,
27 :
28 : /// The end side of the anchor; mirrors to the left edge under RTL.
29 : right,
30 : }
31 :
32 : /// {@category Overlays}
33 : /// {@template foss.tooltip.preview}
34 : /// <img src="https://fossui.org/components/tooltip/overview/light.png"
35 : /// alt="FossTooltip, light theme" width="480"
36 : /// style="max-width:100%;height:auto" />
37 : /// <img src="https://fossui.org/components/tooltip/overview/dark.png"
38 : /// alt="FossTooltip, dark theme" width="480"
39 : /// style="max-width:100%;height:auto" />
40 : ///
41 : /// See the [tooltip documentation ↗](https://fossui.org/docs/components/tooltip) or
42 : /// try it live in the
43 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/tooltip/fosstooltip/playground).
44 : /// {@endtemplate}
45 : ///
46 : /// Wraps a [child] trigger and shows a small floating hint next to it on hover,
47 : /// keyboard focus, or long-press, dismissing on exit, blur, `Escape`, or after
48 : /// [hideDelay].
49 : ///
50 : /// The hint is text only ([message]) and non-interactive: it never blocks
51 : /// pointer input and is announced through the trigger's tooltip semantics, so
52 : /// the visible popup stays out of the semantics tree. The popup opens on [side]
53 : /// and flips to the opposite side to stay on screen. Colors, type, radius, and
54 : /// shadow resolve from the theme; pass a [style] for a one-off override.
55 : ///
56 : /// {@macro foss.customize}
57 : ///
58 : /// ```dart
59 : /// FossTooltip(
60 : /// message: 'Copy link',
61 : /// child: FossButton(
62 : /// onPressed: copy,
63 : /// child: const Text('Copy'),
64 : /// ),
65 : /// );
66 : /// ```
67 : class FossTooltip extends StatefulWidget {
68 : /// {@macro foss.tooltip.preview}
69 : ///
70 : /// Creates a tooltip wrapping [child] that shows [message] on demand.
71 1 : const FossTooltip({
72 : required this.message,
73 : required this.child,
74 : this.side = FossTooltipSide.top,
75 : this.showDelay = const Duration(milliseconds: 500),
76 : this.hideDelay = Duration.zero,
77 : this.semanticLabel,
78 : this.style,
79 : super.key,
80 : });
81 :
82 : /// The hint text shown in the popup.
83 : final String message;
84 :
85 : /// The trigger. Rendered as-is; the tooltip adds no visual to it.
86 : final Widget child;
87 :
88 : /// The preferred side to open on. Defaults to [FossTooltipSide.top].
89 : final FossTooltipSide side;
90 :
91 : /// Delay before the popup appears after the trigger activates. `Escape`
92 : /// dismisses immediately and bypasses this delay.
93 : final Duration showDelay;
94 :
95 : /// Delay before the popup dismisses after the trigger ends. `Escape`
96 : /// dismisses immediately and bypasses this delay.
97 : final Duration hideDelay;
98 :
99 : /// Overrides the announced text when it should differ from [message].
100 : final String? semanticLabel;
101 :
102 : /// Per-instance visual overrides.
103 : final FossTooltipStyle? style;
104 :
105 1 : @override
106 1 : State<FossTooltip> createState() => _FossTooltipState();
107 : }
108 :
109 : class _FossTooltipState extends State<FossTooltip>
110 : with SingleTickerProviderStateMixin {
111 : final _portal = OverlayPortalController();
112 : final GlobalKey _anchorKey = GlobalKey();
113 :
114 : late final AnimationController _animation;
115 : late final CurvedAnimation _curve;
116 : late final Animation<double> _scale;
117 :
118 : Timer? _showTimer;
119 : Timer? _hideTimer;
120 :
121 1 : @override
122 : void initState() {
123 1 : super.initState();
124 : // Duration is set from the motion token on every forward/reverse.
125 2 : _animation = AnimationController(vsync: this);
126 3 : _curve = CurvedAnimation(parent: _animation, curve: Curves.easeOut);
127 4 : _scale = Tween<double>(begin: _openScale, end: 1).animate(_curve);
128 : }
129 :
130 1 : @override
131 : void dispose() {
132 1 : _showTimer?.cancel();
133 1 : _hideTimer?.cancel();
134 2 : _curve.dispose();
135 2 : _animation.dispose();
136 1 : super.dispose();
137 : }
138 :
139 1 : Duration get _duration {
140 : final reduceMotion =
141 3 : MediaQuery.maybeOf(context)?.disableAnimations ?? false;
142 4 : return reduceMotion ? Duration.zero : context.fossTheme.motion.overlay;
143 : }
144 :
145 1 : void _requestShow() {
146 1 : _hideTimer?.cancel();
147 1 : _hideTimer = null;
148 2 : if (_portal.isShowing) {
149 3 : _animation.duration = _duration;
150 2 : _animation.forward();
151 : return;
152 : }
153 5 : _showTimer ??= Timer(widget.showDelay, () {
154 1 : _showTimer = null;
155 1 : if (!mounted) return;
156 2 : _portal.show();
157 3 : _animation.duration = _duration;
158 2 : _animation.forward(from: 0);
159 : });
160 : }
161 :
162 1 : void _requestHide() {
163 1 : _showTimer?.cancel();
164 1 : _showTimer = null;
165 2 : if (!_portal.isShowing) return;
166 5 : _hideTimer ??= Timer(widget.hideDelay, _close);
167 : }
168 :
169 : /// Dismisses immediately, bypassing the hide delay (the `Escape` path).
170 1 : void _dismiss() {
171 1 : _showTimer?.cancel();
172 1 : _showTimer = null;
173 1 : _hideTimer?.cancel();
174 1 : _hideTimer = null;
175 3 : if (_portal.isShowing) _close();
176 : }
177 :
178 1 : void _close() {
179 1 : _hideTimer = null;
180 1 : if (!mounted) return;
181 3 : _animation.duration = _duration;
182 1 : unawaited(
183 4 : _animation.reverse().whenComplete(() {
184 4 : if (mounted && _animation.status == AnimationStatus.dismissed) {
185 2 : _portal.hide();
186 : }
187 : }),
188 : );
189 : }
190 :
191 1 : KeyEventResult _onKey(FocusNode node, KeyEvent event) {
192 1 : if (event is KeyDownEvent &&
193 2 : event.logicalKey == LogicalKeyboardKey.escape &&
194 2 : _portal.isShowing) {
195 1 : _dismiss();
196 : return KeyEventResult.handled;
197 : }
198 : return KeyEventResult.ignored;
199 : }
200 :
201 1 : Rect? _anchorRect(BuildContext overlayContext) {
202 3 : final anchor = _anchorKey.currentContext?.findRenderObject();
203 3 : final overlay = Overlay.of(overlayContext).context.findRenderObject();
204 3 : if (anchor is! RenderBox || overlay is! RenderBox || !anchor.attached) {
205 : return null;
206 : }
207 3 : return anchor.localToGlobal(Offset.zero, ancestor: overlay) & anchor.size;
208 : }
209 :
210 1 : Widget _buildOverlay(BuildContext context) {
211 1 : final anchor = _anchorRect(context);
212 : if (anchor == null) return const SizedBox.shrink();
213 1 : return Positioned.fill(
214 : // The hint never intercepts input; it floats above the page.
215 1 : child: IgnorePointer(
216 1 : child: CustomSingleChildLayout(
217 1 : delegate: AnchoredLayout(
218 : anchor: anchor,
219 4 : side: _anchorSide(widget.side, Directionality.of(context)),
220 1 : padding: overlaySafeArea(context),
221 : ),
222 1 : child: FadeTransition(
223 1 : opacity: _curve,
224 1 : child: ScaleTransition(
225 1 : scale: _scale,
226 1 : child: _TooltipPopup(
227 2 : message: widget.message,
228 2 : style: widget.style,
229 : ),
230 : ),
231 : ),
232 : ),
233 : ),
234 : );
235 : }
236 :
237 1 : @override
238 : Widget build(BuildContext context) {
239 1 : Widget trigger = GestureDetector(
240 1 : onLongPress: _requestShow,
241 2 : child: widget.child,
242 : );
243 1 : trigger = MouseRegion(
244 2 : onEnter: (_) => _requestShow(),
245 2 : onExit: (_) => _requestHide(),
246 : child: trigger,
247 : );
248 1 : trigger = Focus(
249 : canRequestFocus: false,
250 : skipTraversal: true,
251 3 : onFocusChange: (hasFocus) => hasFocus ? _requestShow() : _requestHide(),
252 1 : onKeyEvent: _onKey,
253 2 : child: KeyedSubtree(key: _anchorKey, child: trigger),
254 : );
255 :
256 1 : return Semantics(
257 4 : tooltip: widget.semanticLabel ?? widget.message,
258 1 : child: OverlayPortal(
259 1 : controller: _portal,
260 1 : overlayChildBuilder: _buildOverlay,
261 : child: trigger,
262 : ),
263 : );
264 : }
265 : }
266 :
267 : /// The resting popup: popover surface, 1px border, drop shadow, an inset
268 : /// highlight ring, and the centered hint text.
269 : class _TooltipPopup extends StatelessWidget {
270 1 : const _TooltipPopup({required this.message, required this.style});
271 :
272 : final String message;
273 : final FossTooltipStyle? style;
274 :
275 1 : @override
276 : Widget build(BuildContext context) {
277 1 : final theme = context.fossTheme;
278 1 : final colors = theme.colors;
279 1 : final s = style;
280 1 : final shape = RoundedSuperellipseBorder(
281 3 : side: BorderSide(color: s?.borderColor ?? colors.border),
282 4 : borderRadius: BorderRadius.circular(s?.borderRadius ?? theme.radii.md),
283 : );
284 2 : final textStyle = theme.typography.xs
285 3 : .copyWith(color: s?.foregroundColor ?? colors.popoverForeground)
286 2 : .merge(s?.textStyle);
287 :
288 : // The text is announced on the trigger; the popup stays out of semantics.
289 1 : return ExcludeSemantics(
290 1 : child: DecoratedBox(
291 1 : decoration: ShapeDecoration(
292 2 : color: s?.backgroundColor ?? colors.popover,
293 : shape: shape,
294 4 : shadows: s?.shadows ?? overlaySoftShadow(theme.shadows.md),
295 : ),
296 1 : child: ClipPath(
297 1 : clipper: ShapeBorderClipper(
298 : shape: shape,
299 1 : textDirection: Directionality.of(context),
300 : ),
301 1 : child: Stack(
302 1 : children: [
303 1 : Padding(
304 1 : padding: EdgeInsets.symmetric(
305 : vertical: _verticalPadding,
306 2 : horizontal: theme.spacing(2),
307 : ),
308 1 : child: Text(
309 1 : message,
310 : style: textStyle,
311 : textAlign: TextAlign.center,
312 : textWidthBasis: TextWidthBasis.longestLine,
313 : ),
314 : ),
315 2 : Positioned.fill(child: OverlayInnerRing(colors: colors)),
316 : ],
317 : ),
318 : ),
319 : ),
320 : );
321 : }
322 : }
323 :
324 : /// Maps the directional [FossTooltipSide] to a physical [AnchorSide], mirroring
325 : /// [FossTooltipSide.left] and [FossTooltipSide.right] under RTL.
326 1 : AnchorSide _anchorSide(FossTooltipSide side, TextDirection direction) {
327 1 : final mirror = direction == TextDirection.rtl;
328 : return switch (side) {
329 1 : FossTooltipSide.top => AnchorSide.top,
330 1 : FossTooltipSide.bottom => AnchorSide.bottom,
331 1 : FossTooltipSide.left => mirror ? AnchorSide.right : AnchorSide.left,
332 1 : FossTooltipSide.right => mirror ? AnchorSide.left : AnchorSide.right,
333 : };
334 : }
|