tooltip.dart 17.7 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    final Widget overlay = Directionality(
      textDirection: Directionality.of(context),
      child: _TooltipOverlay(
        message: widget.message,
        height: height,
        padding: padding,
        margin: margin,
        decoration: decoration,
        textStyle: textStyle,
        animation: CurvedAnimation(
          parent: _controller,
          curve: Curves.fastOutSlowIn,
        ),
        target: target,
        verticalOffset: verticalOffset,
        preferBelow: preferBelow,
305 306
      ),
    );
307
    _entry = OverlayEntry(builder: (BuildContext context) => overlay);
308
    Overlay.of(context, debugRequiredFor: widget).insert(_entry);
309
    SemanticsService.tooltip(widget.message);
Hixie's avatar
Hixie committed
310 311
  }

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

321
  void _handlePointerEvent(PointerEvent event) {
322 323 324 325 326 327 328 329
    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
330 331
  }

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

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

350
  void _handleLongPress() {
351
    _longPressActivated = true;
352 353 354 355 356
    final bool tooltipCreated = ensureTooltipVisible();
    if (tooltipCreated)
      Feedback.forLongPress(context);
  }

357
  @override
Hixie's avatar
Hixie committed
358
  Widget build(BuildContext context) {
359
    assert(Overlay.of(context, debugRequiredFor: widget) != null);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    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;
384
    margin = widget.margin ?? tooltipTheme.margin ?? _defaultMargin;
385 386 387 388 389 390 391 392
    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;

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

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

    return result;
Hixie's avatar
Hixie committed
413 414 415
  }
}

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

430 431
  /// The offset of the target the tooltip is positioned near in the global
  /// coordinate system.
432
  final Offset target;
433 434 435

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

438
  /// Whether the tooltip is displayed below its widget by default.
439 440 441
  ///
  /// 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
442 443
  final bool preferBelow;

444
  @override
Hixie's avatar
Hixie committed
445 446
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints.loosen();

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

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

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

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

492
  @override
Hixie's avatar
Hixie committed
493
  Widget build(BuildContext context) {
494 495 496 497
    return Positioned.fill(
      child: IgnorePointer(
        child: CustomSingleChildLayout(
          delegate: _TooltipPositionDelegate(
Hixie's avatar
Hixie committed
498 499
            target: target,
            verticalOffset: verticalOffset,
500
            preferBelow: preferBelow,
Hixie's avatar
Hixie committed
501
          ),
502
          child: FadeTransition(
503
            opacity: animation,
504 505
            child: ConstrainedBox(
              constraints: BoxConstraints(minHeight: height),
506 507 508 509 510 511 512 513 514 515 516 517 518
              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,
                    ),
519
                  ),
520 521 522 523 524 525
                ),
              ),
            ),
          ),
        ),
      ),
Hixie's avatar
Hixie committed
526 527 528
    );
  }
}