dismissable.dart 13.8 KB
Newer Older
1 2 3 4
// 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.

5 6
import 'package:meta/meta.dart';

7 8 9
import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.dart';
10 11
import 'ticker_provider.dart';
import 'transitions.dart';
12

Hans Muller's avatar
Hans Muller committed
13 14
const Duration _kDismissDuration = const Duration(milliseconds: 200);
const Curve _kResizeTimeCurve = const Interval(0.4, 1.0, curve: Curves.ease);
15 16
const double _kMinFlingVelocity = 700.0;
const double _kMinFlingVelocityDelta = 400.0;
17
const double _kFlingVelocityScale = 1.0 / 300.0;
Hans Muller's avatar
Hans Muller committed
18
const double _kDismissThreshold = 0.4;
19

20 21 22 23
/// Signature used by [Dismissable] to indicate that it has been dismissed in
/// the given `direction`.
///
/// Used by [Dismissable.onDismissed].
24 25
typedef void DismissDirectionCallback(DismissDirection direction);

Adam Barth's avatar
Adam Barth committed
26
/// The direction in which a [Dismissable] can be dismissed.
27
enum DismissDirection {
Adam Barth's avatar
Adam Barth committed
28
  /// The [Dismissable] can be dismissed by dragging either up or down.
29
  vertical,
Adam Barth's avatar
Adam Barth committed
30 31

  /// The [Dismissable] can be dismissed by dragging either left or right.
32
  horizontal,
Adam Barth's avatar
Adam Barth committed
33

34 35 36
  /// The [Dismissable] can be dismissed by dragging in the reverse of the
  /// reading direction (e.g., from right to left in left-to-right languages).
  endToStart,
Adam Barth's avatar
Adam Barth committed
37

38 39 40
  /// The [Dismissable] can be dismissed by dragging in the reading direction
  /// (e.g., from left to right in left-to-right languages).
  startToEnd,
Adam Barth's avatar
Adam Barth committed
41 42

  /// The [Dismissable] can be dismissed by dragging up only.
43
  up,
Adam Barth's avatar
Adam Barth committed
44 45

  /// The [Dismissable] can be dismissed by dragging down only.
46 47 48
  down
}

49
/// A widget that can be dismissed by dragging in the indicated [direction].
Adam Barth's avatar
Adam Barth committed
50
///
51
/// Dragging or flinging this widget in the [DismissDirection] causes the child
52 53 54
/// to slide out of view. Following the slide animation, if [resizeDuration] is
/// non-null, the Dismissable widget animates its height (or width, whichever is
/// perpendicular to the dismiss direction) to zero over the [resizeDuration].
55 56 57 58 59
///
/// Backgrounds can be used to implement the "leave-behind" idiom. If a background
/// is specified it is stacked behind the Dismissable's child and is exposed when
/// the child moves.
///
60 61 62 63 64
/// The widget calls the [onDimissed] callback either after its size has
/// collapsed to zero (if [resizeDuration] is non-null) or immediately after
/// the slide animation (if [resizeDuration] is null). If the Dismissable is a
/// list item, it must have a key that distinguishes it from the other items and
/// its [onDismissed] callback must remove the item from the list.
65
class Dismissable extends StatefulWidget {
66 67 68 69 70 71 72 73
  /// Creates a widget that can be dismissed.
  ///
  /// The [key] argument must not be null because [Dismissable]s are commonly
  /// used in lists and removed from the list when dismissed. Without keys, the
  /// default behavior is to sync widgets based on their index in the list,
  /// which means the item after the dismissed item would be synced with the
  /// state of the dismissed item. Using keys causes the widgets to sync
  /// according to their keys and avoids this pitfall.
74
  Dismissable({
75
    @required Key key,
76
    this.child,
77 78
    this.background,
    this.secondaryBackground,
79
    this.onResize,
80
    this.onDismissed,
81 82
    this.direction: DismissDirection.horizontal,
    this.resizeDuration: const Duration(milliseconds: 300)
83 84 85 86
  }) : super(key: key) {
    assert(key != null);
    assert(secondaryBackground != null ? background != null : true);
  }
87

88
  /// The widget below this widget in the tree.
89
  final Widget child;
Adam Barth's avatar
Adam Barth committed
90

91 92 93
  /// A widget that is stacked behind the child. If secondaryBackground is also
  /// specified then this widget only appears when the child has been dragged
  /// down or to the right.
94
  final Widget background;
95 96 97 98 99 100 101

  /// A widget that is stacked behind the child and is exposed when the child
  /// has been dragged up or to the left. It may only be specified when background
  /// has also been specified.
  final Widget secondaryBackground;

  /// Called when the widget changes size (i.e., when contracting before being dismissed).
102
  final VoidCallback onResize;
Adam Barth's avatar
Adam Barth committed
103

104
  /// Called when the widget has been dismissed, after finishing resizing.
105
  final DismissDirectionCallback onDismissed;
Adam Barth's avatar
Adam Barth committed
106 107

  /// The direction in which the widget can be dismissed.
108
  final DismissDirection direction;
109

110 111 112 113 114 115
  /// The amount of time the widget will spend contracting before [onDismissed] is called.
  ///
  /// If null, the widget will not contract and [onDismissed] will be called
  /// immediately after the the widget is dismissed.
  final Duration resizeDuration;

116
  @override
117
  _DismissableState createState() => new _DismissableState();
118
}
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
class _DismissableClipper extends CustomClipper<Rect> {
  _DismissableClipper({
    this.axis,
    Animation<FractionalOffset> moveAnimation
  }) : moveAnimation = moveAnimation, super(reclip: moveAnimation) {
    assert(axis != null);
    assert(moveAnimation != null);
  }

  final Axis axis;
  final Animation<FractionalOffset> moveAnimation;

  @override
  Rect getClip(Size size) {
    assert(axis != null);
    switch (axis) {
      case Axis.horizontal:
        final double offset = moveAnimation.value.dx * size.width;
        if (offset < 0)
          return new Rect.fromLTRB(size.width + offset, 0.0, size.width, size.height);
        return new Rect.fromLTRB(0.0, 0.0, offset, size.height);
      case Axis.vertical:
        final double offset = moveAnimation.value.dy * size.height;
        if (offset < 0)
          return new Rect.fromLTRB(0.0, size.height + offset, size.width, size.height);
        return new Rect.fromLTRB(0.0, 0.0, size.width, offset);
    }
    return null;
  }

  @override
  Rect getApproximateClipRect(Size size) => getClip(size);

  @override
  bool shouldReclip(_DismissableClipper oldClipper) {
    return oldClipper.axis != axis
        || oldClipper.moveAnimation.value != moveAnimation.value;
  }
}

160
class _DismissableState extends State<Dismissable> with TickerProviderStateMixin {
161
  @override
162
  void initState() {
163
    super.initState();
164
    _moveController = new AnimationController(duration: _kDismissDuration, vsync: this)
165 166
      ..addStatusListener(_handleDismissStatusChanged);
    _updateMoveAnimation();
167 168
  }

169 170 171
  AnimationController _moveController;
  Animation<FractionalOffset> _moveAnimation;

172
  AnimationController _resizeController;
173
  Animation<double> _resizeAnimation;
174 175 176

  double _dragExtent = 0.0;
  bool _dragUnderway = false;
177
  Size _sizePriorToCollapse;
178

179
  @override
180
  void dispose() {
181 182
    _moveController.dispose();
    _resizeController?.dispose();
183 184 185
    super.dispose();
  }

186 187
  bool get _directionIsXAxis {
    return config.direction == DismissDirection.horizontal
188 189
        || config.direction == DismissDirection.endToStart
        || config.direction == DismissDirection.startToEnd;
190 191
  }

192 193
  DismissDirection get _dismissDirection {
    if (_directionIsXAxis)
194
      return  _dragExtent > 0 ? DismissDirection.startToEnd : DismissDirection.endToStart;
195 196 197
    return _dragExtent > 0 ? DismissDirection.down : DismissDirection.up;
  }

198
  bool get _isActive {
199
    return _dragUnderway || _moveController.isAnimating;
200 201
  }

202
  double get _overallDragAxisExtent {
203
    final Size size = context.size;
204
    return _directionIsXAxis ? size.width : size.height;
205 206
  }

207
  void _handleDragStart(DragStartDetails details) {
208 209
    _dragUnderway = true;
    if (_moveController.isAnimating) {
210
      _dragExtent = _moveController.value * _overallDragAxisExtent * _dragExtent.sign;
211 212 213 214 215
      _moveController.stop();
    } else {
      _dragExtent = 0.0;
      _moveController.value = 0.0;
    }
216
    setState(() {
217
      _updateMoveAnimation();
218
    });
219 220
  }

221
  void _handleDragUpdate(DragUpdateDetails details) {
222
    if (!_isActive || _moveController.isAnimating)
223
      return;
224

225 226
    final double delta = details.primaryDelta;
    final double oldDragExtent = _dragExtent;
227
    switch (config.direction) {
228 229
      case DismissDirection.horizontal:
      case DismissDirection.vertical:
230
        _dragExtent += delta;
231 232 233
        break;

      case DismissDirection.up:
234
      case DismissDirection.endToStart:
235 236
        if (_dragExtent + delta < 0)
          _dragExtent += delta;
237 238 239
        break;

      case DismissDirection.down:
240
      case DismissDirection.startToEnd:
241 242
        if (_dragExtent + delta > 0)
          _dragExtent += delta;
243 244
        break;
    }
245 246
    if (oldDragExtent.sign != _dragExtent.sign) {
      setState(() {
247
        _updateMoveAnimation();
248 249
      });
    }
250
    if (!_moveController.isAnimating) {
251
      _moveController.value = _dragExtent.abs() / _overallDragAxisExtent;
252 253 254 255 256
    }
  }

  void _updateMoveAnimation() {
    _moveAnimation = new Tween<FractionalOffset>(
257
      begin: FractionalOffset.topLeft,
258 259 260 261
      end: _directionIsXAxis ?
             new FractionalOffset(_dragExtent.sign, 0.0) :
             new FractionalOffset(0.0, _dragExtent.sign)
    ).animate(_moveController);
262 263
  }

264
  bool _isFlingGesture(Velocity velocity) {
265 266
    final double vx = velocity.pixelsPerSecond.dx;
    final double vy = velocity.pixelsPerSecond.dy;
267
    if (_directionIsXAxis) {
268 269
      if (vx.abs() - vy.abs() < _kMinFlingVelocityDelta)
        return false;
270
      switch(config.direction) {
271 272
        case DismissDirection.horizontal:
          return vx.abs() > _kMinFlingVelocity;
273
        case DismissDirection.endToStart:
274 275 276 277
          return -vx > _kMinFlingVelocity;
        default:
          return vx > _kMinFlingVelocity;
      }
278 279 280 281 282 283 284 285 286 287 288
    } else {
      if (vy.abs() - vx.abs() < _kMinFlingVelocityDelta)
        return false;
      switch(config.direction) {
        case DismissDirection.vertical:
          return vy.abs() > _kMinFlingVelocity;
        case DismissDirection.up:
          return -vy > _kMinFlingVelocity;
        default:
          return vy > _kMinFlingVelocity;
      }
289
    }
290 291
  }

292
  void _handleDragEnd(DragEndDetails details) {
293
    if (!_isActive || _moveController.isAnimating)
294
      return;
295 296 297
    _dragUnderway = false;
    if (_moveController.isCompleted) {
      _startResizeAnimation();
298
    } else if (_isFlingGesture(details.velocity)) {
299
      final double flingVelocity = _directionIsXAxis ? details.velocity.pixelsPerSecond.dx : details.velocity.pixelsPerSecond.dy;
300 301
      _dragExtent = flingVelocity.sign;
      _moveController.fling(velocity: flingVelocity.abs() * _kFlingVelocityScale);
Hans Muller's avatar
Hans Muller committed
302
    } else if (_moveController.value > _kDismissThreshold) {
303 304 305 306
      _moveController.forward();
    } else {
      _moveController.reverse();
    }
307 308
  }

309 310 311
  void _handleDismissStatusChanged(AnimationStatus status) {
    if (status == AnimationStatus.completed && !_dragUnderway)
      _startResizeAnimation();
312 313
  }

314 315 316 317
  void _startResizeAnimation() {
    assert(_moveController != null);
    assert(_moveController.isCompleted);
    assert(_resizeController == null);
318
    assert(_sizePriorToCollapse == null);
319 320 321 322
    if (config.resizeDuration == null) {
      if (config.onDismissed != null)
        config.onDismissed(_dismissDirection);
    } else {
323
      _resizeController = new AnimationController(duration: config.resizeDuration, vsync: this)
324 325 326
        ..addListener(_handleResizeProgressChanged);
      _resizeController.forward();
      setState(() {
327
        _sizePriorToCollapse = context.size;
328 329 330 331 332 333 334 335 336
        _resizeAnimation = new Tween<double>(
          begin: 1.0,
          end: 0.0
        ).animate(new CurvedAnimation(
          parent: _resizeController,
          curve: _kResizeTimeCurve
        ));
      });
    }
337
  }
338

339 340
  void _handleResizeProgressChanged() {
    if (_resizeController.isCompleted) {
341
      if (config.onDismissed != null)
342
        config.onDismissed(_dismissDirection);
343
    } else {
344 345
      if (config.onResize != null)
        config.onResize();
346 347 348
    }
  }

349
  @override
350
  Widget build(BuildContext context) {
351 352 353
    Widget background = config.background;
    if (config.secondaryBackground != null) {
      final DismissDirection direction = _dismissDirection;
354
      if (direction == DismissDirection.endToStart || direction == DismissDirection.up)
355 356 357
        background = config.secondaryBackground;
    }

358 359 360 361 362
    if (_resizeAnimation != null) {
      // we've been dragged aside, and are now resizing.
      assert(() {
        if (_resizeAnimation.status != AnimationStatus.forward) {
          assert(_resizeAnimation.status == AnimationStatus.completed);
363
          throw new FlutterError(
364 365
            'A dismissed Dismissable widget is still part of the tree.\n' +
            'Make sure to implement the onDismissed handler and to immediately remove the Dismissable\n' +
366 367 368 369 370
            'widget from the application once that handler has fired.'
          );
        }
        return true;
      });
371

Hans Muller's avatar
Hans Muller committed
372 373
      return new SizeTransition(
        sizeFactor: _resizeAnimation,
374 375 376 377 378 379
        axis: _directionIsXAxis ? Axis.vertical : Axis.horizontal,
        child: new SizedBox(
          width: _sizePriorToCollapse.width,
          height: _sizePriorToCollapse.height,
          child: background
        )
380
      );
Adam Barth's avatar
Adam Barth committed
381
    }
382

383
    Widget content = new SlideTransition(
384 385 386
      position: _moveAnimation,
      child: config.child
    );
387

388
    if (background != null) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
      List<Widget> children = <Widget>[];

      if (!_moveAnimation.isDismissed) {
        children.add(new Positioned.fill(
          child: new ClipRect(
            clipper: new _DismissableClipper(
              axis: _directionIsXAxis ? Axis.horizontal : Axis.vertical,
              moveAnimation: _moveAnimation,
            ),
            child: background
          )
        ));
      }

      children.add(content);
      content = new Stack(children: children);
405 406 407
    }

    // We are not resizing but we may be being dragging in config.direction.
408
    return new GestureDetector(
409 410 411 412 413 414
      onHorizontalDragStart: _directionIsXAxis ? _handleDragStart : null,
      onHorizontalDragUpdate: _directionIsXAxis ? _handleDragUpdate : null,
      onHorizontalDragEnd: _directionIsXAxis ? _handleDragEnd : null,
      onVerticalDragStart: _directionIsXAxis ? null : _handleDragStart,
      onVerticalDragUpdate: _directionIsXAxis ? null : _handleDragUpdate,
      onVerticalDragEnd: _directionIsXAxis ? null : _handleDragEnd,
Hixie's avatar
Hixie committed
415
      behavior: HitTestBehavior.opaque,
416
      child: content
417 418 419
    );
  }
}