tooltip.dart 17.6 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5 6
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import 'package:flutter/gestures.dart';
8
import 'package:flutter/rendering.dart';
Hixie's avatar
Hixie committed
9 10
import 'package:flutter/widgets.dart';

11
import 'colors.dart';
12
import 'feedback.dart';
13 14
import 'theme.dart';
import 'theme_data.dart';
15
import 'tooltip_theme.dart';
16 17 18 19 20 21 22 23

/// A material design tooltip.
///
/// Tooltips provide text labels that help explain the function of a button or
/// other user interface action. Wrap the button in a [Tooltip] widget to
/// show a label when the widget long pressed (or when the user takes some
/// other appropriate action).
///
24 25
/// {@youtube 560 315 https://www.youtube.com/watch?v=EeEfD5fI-5Q}
///
26 27 28 29 30 31 32 33 34 35
/// Many widgets, such as [IconButton], [FloatingActionButton], and
/// [PopupMenuButton] have a `tooltip` property that, when non-null, causes the
/// widget to include a [Tooltip] in its build.
///
/// Tooltips improve the accessibility of visual widgets by proving a textual
/// representation of the widget, which, for example, can be vocalized by a
/// screen reader.
///
/// See also:
///
36
///  * <https://material.io/design/components/tooltips.html>
37
///  * [TooltipTheme] or [ThemeData.tooltipTheme]
38
class Tooltip extends StatefulWidget {
39 40
  /// Creates a tooltip.
  ///
41 42 43 44 45
  /// By default, tooltips should adhere to the
  /// [Material specification](https://material.io/design/components/tooltips.html#spec).
  /// If the optional constructor parameters are not defined, the values
  /// provided by [TooltipTheme.of] will be used if a [TooltipTheme] is present
  /// or specified in [ThemeData].
46
  ///
47 48
  /// All parameters that are defined in the constructor will
  /// override the default values _and_ the values in [TooltipTheme.of].
49
  const Tooltip({
Hixie's avatar
Hixie committed
50
    Key key,
51
    @required this.message,
52 53
    this.height,
    this.padding,
54
    this.margin,
55 56 57
    this.verticalOffset,
    this.preferBelow,
    this.excludeFromSemantics,
58
    this.decoration,
59 60 61
    this.textStyle,
    this.waitDuration,
    this.showDuration,
62
    this.child,
63 64
  }) : assert(message != null),
       super(key: key);
Hixie's avatar
Hixie committed
65

66
  /// The text to display in the tooltip.
Hixie's avatar
Hixie committed
67
  final String message;
68

69
  /// The height of the tooltip's [child].
70
  ///
71
  /// If the [child] is null, then this is the tooltip's intrinsic height.
Hixie's avatar
Hixie committed
72
  final double height;
73

74
  /// The amount of space by which to inset the tooltip's [child].
75 76
  ///
  /// Defaults to 16.0 logical pixels in each direction.
77
  final EdgeInsetsGeometry padding;
78

79 80 81 82 83 84 85 86 87 88 89 90 91
  /// The empty space that surrounds the tooltip.
  ///
  /// Defines the tooltip's outer [Container.margin]. By default, a
  /// long tooltip will span the width of its window. If long enough,
  /// a tooltip might also span the window's height. This property allows
  /// one to define how much space the tooltip must be inset from the edges
  /// of their display window.
  ///
  /// If this property is null, then [TooltipThemeData.margin] is used.
  /// If [TooltipThemeData.margin] is also null, the default margin is
  /// 0.0 logical pixels on all sides.
  final EdgeInsetsGeometry margin;

92
  /// The vertical gap between the widget and the displayed tooltip.
93 94 95 96 97 98
  ///
  /// When [preferBelow] is set to true and tooltips have sufficient space to
  /// display themselves, this property defines how much vertical space
  /// tooltips will position themselves under their corresponding widgets.
  /// Otherwise, tooltips will position themselves above their corresponding
  /// widgets with the given offset.
Hixie's avatar
Hixie committed
99
  final double verticalOffset;
100

101 102 103 104 105
  /// Whether the tooltip defaults to being displayed below the widget.
  ///
  /// Defaults to true. If there is insufficient space to display the tooltip in
  /// the preferred direction, the tooltip will be displayed in the opposite
  /// direction.
Hixie's avatar
Hixie committed
106
  final bool preferBelow;
107

108 109
  /// Whether the tooltip's [message] should be excluded from the semantics
  /// tree.
110 111 112 113
  ///
  /// Defaults to false. A tooltip will add a [Semantics.label] that is set to
  /// [Tooltip.message]. Set this property to true if the app is going to
  /// provide its own custom semantics label.
114 115
  final bool excludeFromSemantics;

116
  /// The widget below this widget in the tree.
117 118
  ///
  /// {@macro flutter.widgets.child}
Hixie's avatar
Hixie committed
119 120
  final Widget child;

121 122
  /// Specifies the tooltip's shape and background color.
  ///
123 124 125 126
  /// The tooltip shape defaults to a rounded rectangle with a border radius of
  /// 4.0. Tooltips will also default to an opacity of 90% and with the color
  /// [Colors.grey[700]] if [ThemeData.brightness] is [Brightness.dark], and
  /// [Colors.white] if it is [Brightness.light].
127 128
  final Decoration decoration;

129 130 131 132 133 134 135 136 137 138 139
  /// The style to use for the message of the tooltip.
  ///
  /// If null, the message's [TextStyle] will be determined based on
  /// [ThemeData]. If [ThemeData.brightness] is set to [Brightness.dark],
  /// [ThemeData.textTheme.body1] will be used with [Colors.white]. Otherwise,
  /// if [ThemeData.brightness] is set to [Brightness.light],
  /// [ThemeData.textTheme.body1] will be used with [Colors.black].
  final TextStyle textStyle;

  /// The length of time that a pointer must hover over a tooltip's widget
  /// before the tooltip will be shown.
140
  ///
141 142 143
  /// Once the pointer leaves the widget, the tooltip will immediately
  /// disappear.
  ///
144
  /// Defaults to 0 milliseconds (tooltips are shown immediately upon hover).
145 146
  final Duration waitDuration;

147 148
  /// The length of time that the tooltip will be shown after a long press
  /// is released.
149 150 151 152
  ///
  /// Defaults to 1.5 seconds.
  final Duration showDuration;

153
  @override
154
  _TooltipState createState() => _TooltipState();
Hixie's avatar
Hixie committed
155

156
  @override
157 158
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
159
    properties.add(StringProperty('message', message, showName: false));
160 161
    properties.add(DoubleProperty('height', height, defaultValue: null));
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
162
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('margin', margin, defaultValue: null));
163 164 165 166 167
    properties.add(DoubleProperty('vertical offset', verticalOffset, defaultValue: null));
    properties.add(FlagProperty('position', value: preferBelow, ifTrue: 'below', ifFalse: 'above', showName: true, defaultValue: null));
    properties.add(FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true, defaultValue: null));
    properties.add(DiagnosticsProperty<Duration>('wait duration', waitDuration, defaultValue: null));
    properties.add(DiagnosticsProperty<Duration>('show duration', showDuration, defaultValue: null));
Hixie's avatar
Hixie committed
168
  }
Hixie's avatar
Hixie committed
169 170
}

171
class _TooltipState extends State<Tooltip> with SingleTickerProviderStateMixin {
172 173 174 175
  static const double _defaultTooltipHeight = 32.0;
  static const double _defaultVerticalOffset = 24.0;
  static const bool _defaultPreferBelow = true;
  static const EdgeInsetsGeometry _defaultPadding = EdgeInsets.symmetric(horizontal: 16.0);
176
  static const EdgeInsetsGeometry _defaultMargin = EdgeInsets.all(0.0);
177 178
  static const Duration _fadeInDuration = Duration(milliseconds: 150);
  static const Duration _fadeOutDuration = Duration(milliseconds: 75);
179 180 181 182 183 184
  static const Duration _defaultShowDuration = Duration(milliseconds: 1500);
  static const Duration _defaultWaitDuration = Duration(milliseconds: 0);
  static const bool _defaultExcludeFromSemantics = false;

  double height;
  EdgeInsetsGeometry padding;
185
  EdgeInsetsGeometry margin;
186 187 188 189 190
  Decoration decoration;
  TextStyle textStyle;
  double verticalOffset;
  bool preferBelow;
  bool excludeFromSemantics;
191
  AnimationController _controller;
Hixie's avatar
Hixie committed
192
  OverlayEntry _entry;
193 194
  Timer _hideTimer;
  Timer _showTimer;
195 196
  Duration showDuration;
  Duration waitDuration;
197 198
  bool _mouseIsConnected;
  bool _longPressActivated = false;
Hixie's avatar
Hixie committed
199

200
  @override
Hixie's avatar
Hixie committed
201 202
  void initState() {
    super.initState();
203
    _mouseIsConnected = RendererBinding.instance.mouseTracker.mouseIsConnected;
204 205 206 207 208
    _controller = AnimationController(
      duration: _fadeInDuration,
      reverseDuration: _fadeOutDuration,
      vsync: this,
    )
209
      ..addStatusListener(_handleStatusChanged);
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    // Listen to see when a mouse is added.
    RendererBinding.instance.mouseTracker.addListener(_handleMouseTrackerChange);
    // Listen to global pointer events so that we can hide a tooltip immediately
    // if some other control is clicked on.
    GestureBinding.instance.pointerRouter.addGlobalRoute(_handlePointerEvent);
  }

  // Forces a rebuild if a mouse has been added or removed.
  void _handleMouseTrackerChange() {
    if (!mounted) {
      return;
    }
    final bool mouseIsConnected = RendererBinding.instance.mouseTracker.mouseIsConnected;
    if (mouseIsConnected != _mouseIsConnected) {
      setState((){
        _mouseIsConnected = mouseIsConnected;
      });
    }
228 229 230
  }

  void _handleStatusChanged(AnimationStatus status) {
231 232 233 234 235 236 237 238 239
    if (status == AnimationStatus.dismissed) {
      _hideTooltip(immediately: true);
    }
  }

  void _hideTooltip({ bool immediately = false }) {
    _showTimer?.cancel();
    _showTimer = null;
    if (immediately) {
240
      _removeEntry();
241 242 243
      return;
    }
    if (_longPressActivated) {
244
      // Tool tips activated by long press should stay around for the showDuration.
245
      _hideTimer ??= Timer(showDuration, _controller.reverse);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    } else {
      // Tool tips activated by hover should disappear as soon as the mouse
      // leaves the control.
      _controller.reverse();
    }
    _longPressActivated = false;
  }

  void _showTooltip({ bool immediately = false }) {
    _hideTimer?.cancel();
    _hideTimer = null;
    if (immediately) {
      ensureTooltipVisible();
      return;
    }
261
    _showTimer ??= Timer(waitDuration, ensureTooltipVisible);
Hixie's avatar
Hixie committed
262 263
  }

264 265 266 267
  /// Shows the tooltip if it is not already visible.
  ///
  /// Returns `false` when the tooltip was already visible.
  bool ensureTooltipVisible() {
268 269
    _showTimer?.cancel();
    _showTimer = null;
270
    if (_entry != null) {
271 272 273
      // Stop trying to hide, if we were.
      _hideTimer?.cancel();
      _hideTimer = null;
274
      _controller.forward();
275
      return false; // Already visible.
276
    }
277 278 279 280 281 282
    _createNewEntry();
    _controller.forward();
    return true;
  }

  void _createNewEntry() {
283
    final RenderBox box = context.findRenderObject();
284
    final Offset target = box.localToGlobal(box.size.center(Offset.zero));
285

286 287 288
    // We create this widget outside of the overlay entry's builder to prevent
    // updated values from happening to leak into the overlay when the overlay
    // rebuilds.
289
    final Widget overlay = _TooltipOverlay(
290
      message: widget.message,
291 292
      height: height,
      padding: padding,
293
      margin: margin,
294 295
      decoration: decoration,
      textStyle: textStyle,
296
      animation: CurvedAnimation(
297
        parent: _controller,
298
        curve: Curves.fastOutSlowIn,
299 300
      ),
      target: target,
301 302
      verticalOffset: verticalOffset,
      preferBelow: preferBelow,
303
    );
304
    _entry = OverlayEntry(builder: (BuildContext context) => overlay);
305
    Overlay.of(context, debugRequiredFor: widget).insert(_entry);
306
    SemanticsService.tooltip(widget.message);
Hixie's avatar
Hixie committed
307 308
  }

309
  void _removeEntry() {
310 311 312 313 314
    _hideTimer?.cancel();
    _hideTimer = null;
    _showTimer?.cancel();
    _showTimer = null;
    _entry?.remove();
315
    _entry = null;
Hixie's avatar
Hixie committed
316 317
  }

318
  void _handlePointerEvent(PointerEvent event) {
319 320 321 322 323 324 325 326
    if (_entry == null) {
      return;
    }
    if (event is PointerUpEvent || event is PointerCancelEvent) {
      _hideTooltip();
    } else if (event is PointerDownEvent) {
      _hideTooltip(immediately: true);
    }
Hixie's avatar
Hixie committed
327 328
  }

329
  @override
Hixie's avatar
Hixie committed
330
  void deactivate() {
331 332 333
    if (_entry != null) {
      _hideTooltip(immediately: true);
    }
334
    super.deactivate();
Hixie's avatar
Hixie committed
335 336
  }

337 338
  @override
  void dispose() {
339 340
    GestureBinding.instance.pointerRouter.removeGlobalRoute(_handlePointerEvent);
    RendererBinding.instance.mouseTracker.removeListener(_handleMouseTrackerChange);
341 342
    if (_entry != null)
      _removeEntry();
343
    _controller.dispose();
344 345 346
    super.dispose();
  }

347
  void _handleLongPress() {
348
    _longPressActivated = true;
349 350 351 352 353
    final bool tooltipCreated = ensureTooltipVisible();
    if (tooltipCreated)
      Feedback.forLongPress(context);
  }

354
  @override
Hixie's avatar
Hixie committed
355
  Widget build(BuildContext context) {
356
    assert(Overlay.of(context, debugRequiredFor: widget) != null);
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    final ThemeData theme = Theme.of(context);
    final TooltipThemeData tooltipTheme = TooltipTheme.of(context);
    TextStyle defaultTextStyle;
    BoxDecoration defaultDecoration;
    if (theme.brightness == Brightness.dark) {
      defaultTextStyle = theme.textTheme.body1.copyWith(
        color: Colors.black,
      );
      defaultDecoration = BoxDecoration(
        color: Colors.white.withOpacity(0.9),
        borderRadius: const BorderRadius.all(Radius.circular(4)),
      );
    } else {
      defaultTextStyle = theme.textTheme.body1.copyWith(
        color: Colors.white,
      );
      defaultDecoration = BoxDecoration(
        color: Colors.grey[700].withOpacity(0.9),
        borderRadius: const BorderRadius.all(Radius.circular(4)),
      );
    }

    height = widget.height ?? tooltipTheme.height ?? _defaultTooltipHeight;
    padding = widget.padding ?? tooltipTheme.padding ?? _defaultPadding;
381
    margin = widget.margin ?? tooltipTheme.margin ?? _defaultMargin;
382 383 384 385 386 387 388 389
    verticalOffset = widget.verticalOffset ?? tooltipTheme.verticalOffset ?? _defaultVerticalOffset;
    preferBelow = widget.preferBelow ?? tooltipTheme.preferBelow ?? _defaultPreferBelow;
    excludeFromSemantics = widget.excludeFromSemantics ?? tooltipTheme.excludeFromSemantics ?? _defaultExcludeFromSemantics;
    decoration = widget.decoration ?? tooltipTheme.decoration ?? defaultDecoration;
    textStyle = widget.textStyle ?? tooltipTheme.textStyle ?? defaultTextStyle;
    waitDuration = widget.waitDuration ?? tooltipTheme.waitDuration ?? _defaultWaitDuration;
    showDuration = widget.showDuration ?? tooltipTheme.showDuration ?? _defaultShowDuration;

390
    Widget result = GestureDetector(
391 392 393 394
      behavior: HitTestBehavior.opaque,
      onLongPress: _handleLongPress,
      excludeFromSemantics: true,
      child: Semantics(
395
        label: excludeFromSemantics ? null : widget.message,
396
        child: widget.child,
397
      ),
Hixie's avatar
Hixie committed
398
    );
399 400 401

    // Only check for hovering if there is a mouse connected.
    if (_mouseIsConnected) {
402 403 404
      result = MouseRegion(
        onEnter: (PointerEnterEvent event) => _showTooltip(),
        onExit: (PointerExitEvent event) => _hideTooltip(),
405 406 407 408 409
        child: result,
      );
    }

    return result;
Hixie's avatar
Hixie committed
410 411 412
  }
}

413 414
/// A delegate for computing the layout of a tooltip to be displayed above or
/// bellow a target specified in the global coordinate system.
415
class _TooltipPositionDelegate extends SingleChildLayoutDelegate {
416 417 418
  /// Creates a delegate for computing the layout of a tooltip.
  ///
  /// The arguments must not be null.
Hixie's avatar
Hixie committed
419
  _TooltipPositionDelegate({
420 421 422
    @required this.target,
    @required this.verticalOffset,
    @required this.preferBelow,
423 424 425
  }) : assert(target != null),
       assert(verticalOffset != null),
       assert(preferBelow != null);
426

427 428
  /// The offset of the target the tooltip is positioned near in the global
  /// coordinate system.
429
  final Offset target;
430 431 432

  /// The amount of vertical distance between the target and the displayed
  /// tooltip.
Hixie's avatar
Hixie committed
433
  final double verticalOffset;
434

435
  /// Whether the tooltip is displayed below its widget by default.
436 437 438
  ///
  /// If there is insufficient space to display the tooltip in the preferred
  /// direction, the tooltip will be displayed in the opposite direction.
Hixie's avatar
Hixie committed
439 440
  final bool preferBelow;

441
  @override
Hixie's avatar
Hixie committed
442 443
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints.loosen();

444
  @override
Hixie's avatar
Hixie committed
445
  Offset getPositionForChild(Size size, Size childSize) {
446 447 448 449 450 451 452
    return positionDependentBox(
      size: size,
      childSize: childSize,
      target: target,
      verticalOffset: verticalOffset,
      preferBelow: preferBelow,
    );
Hixie's avatar
Hixie committed
453 454
  }

455
  @override
Hixie's avatar
Hixie committed
456
  bool shouldRelayout(_TooltipPositionDelegate oldDelegate) {
457 458 459
    return target != oldDelegate.target
        || verticalOffset != oldDelegate.verticalOffset
        || preferBelow != oldDelegate.preferBelow;
Hixie's avatar
Hixie committed
460 461 462
  }
}

463
class _TooltipOverlay extends StatelessWidget {
464
  const _TooltipOverlay({
Hixie's avatar
Hixie committed
465 466 467 468
    Key key,
    this.message,
    this.height,
    this.padding,
469
    this.margin,
470
    this.decoration,
471
    this.textStyle,
472
    this.animation,
Hixie's avatar
Hixie committed
473 474
    this.target,
    this.verticalOffset,
475
    this.preferBelow,
Hixie's avatar
Hixie committed
476 477 478 479
  }) : super(key: key);

  final String message;
  final double height;
480
  final EdgeInsetsGeometry padding;
481
  final EdgeInsetsGeometry margin;
482
  final Decoration decoration;
483
  final TextStyle textStyle;
484
  final Animation<double> animation;
485
  final Offset target;
Hixie's avatar
Hixie committed
486 487 488
  final double verticalOffset;
  final bool preferBelow;

489
  @override
Hixie's avatar
Hixie committed
490
  Widget build(BuildContext context) {
491 492 493 494
    return Positioned.fill(
      child: IgnorePointer(
        child: CustomSingleChildLayout(
          delegate: _TooltipPositionDelegate(
Hixie's avatar
Hixie committed
495 496
            target: target,
            verticalOffset: verticalOffset,
497
            preferBelow: preferBelow,
Hixie's avatar
Hixie committed
498
          ),
499
          child: FadeTransition(
500
            opacity: animation,
501 502
            child: ConstrainedBox(
              constraints: BoxConstraints(minHeight: height),
503 504 505 506 507 508 509 510 511 512 513 514 515
              child: DefaultTextStyle(
                style: Theme.of(context).textTheme.body1,
                child: Container(
                  decoration: decoration,
                  padding: padding,
                  margin: margin,
                  child: Center(
                    widthFactor: 1.0,
                    heightFactor: 1.0,
                    child: Text(
                      message,
                      style: textStyle,
                    ),
516
                  ),
517 518 519 520 521 522
                ),
              ),
            ),
          ),
        ),
      ),
Hixie's avatar
Hixie committed
523 524 525
    );
  }
}