route.dart 35.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:math';
7
import 'dart:ui' show lerpDouble, ImageFilter;
8

9
import 'package:flutter/foundation.dart';
10 11
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
12
import 'package:flutter/widgets.dart';
13
import 'package:flutter/animation.dart' show Curves;
14

15
import 'colors.dart';
16
import 'interface_level.dart';
17

18 19
const double _kBackGestureWidth = 20.0;
const double _kMinFlingVelocity = 1.0; // Screen widths per second.
20

21 22 23 24 25 26 27 28
// An eyeballed value for the maximum time it takes for a page to animate forward
// if the user releases a page mid swipe.
const int _kMaxDroppedSwipePageForwardAnimationTime = 800; // Milliseconds.

// The maximum time for a page to get reset to it's original position if the
// user releases a page mid swipe.
const int _kMaxPageBackAnimationTime = 300; // Milliseconds.

29
// Barrier color for a Cupertino modal barrier.
30 31 32 33 34
// Extracted from https://developer.apple.com/design/resources/.
const Color _kModalBarrierColor = CupertinoDynamicColor.withBrightness(
  color: Color(0x33000000),
  darkColor: Color(0x7A000000),
);
35

36 37 38
// The duration of the transition used when a modal popup is shown.
const Duration _kModalPopupTransitionDuration = Duration(milliseconds: 335);

39
// Offset from offscreen to the right to fully on screen.
40
final Animatable<Offset> _kRightMiddleTween = Tween<Offset>(
41 42
  begin: const Offset(1.0, 0.0),
  end: Offset.zero,
43 44
);

45
// Offset from fully on screen to 1/3 offscreen to the left.
46
final Animatable<Offset> _kMiddleLeftTween = Tween<Offset>(
47 48
  begin: Offset.zero,
  end: const Offset(-1.0/3.0, 0.0),
49 50
);

51
// Offset from offscreen below to fully on screen.
52
final Animatable<Offset> _kBottomUpTween = Tween<Offset>(
53 54
  begin: const Offset(0.0, 1.0),
  end: Offset.zero,
55 56
);

57
// Custom decoration from no shadow to page shadow mimicking iOS page
58
// transitions using gradients.
59
final DecorationTween _kGradientShadowTween = DecorationTween(
60 61
  begin: _CupertinoEdgeShadowDecoration.none, // No decoration initially.
  end: const _CupertinoEdgeShadowDecoration(
62
    edgeGradient: LinearGradient(
63
      // Spans 5% of the page.
64
      begin: AlignmentDirectional(0.90, 0.0),
Ian Hickson's avatar
Ian Hickson committed
65 66
      end: AlignmentDirectional.centerEnd,
      // Eyeballed gradient used to mimic a drop shadow on the start side only.
67 68 69 70
      colors: <Color>[
        Color(0x00000000),
        Color(0x04000000),
        Color(0x12000000),
71
        Color(0x38000000),
72
      ],
73
      stops: <double>[0.0, 0.3, 0.6, 1.0],
74
    ),
75 76 77
  ),
);

78 79
/// A modal route that replaces the entire screen with an iOS transition.
///
80 81
/// The page slides in from the right and exits in reverse. The page also shifts
/// to the left in parallax when another page enters to cover it.
82
///
83 84
/// The page slides in from the bottom and exits in reverse with no parallax
/// effect for fullscreen dialogs.
85 86 87 88 89
///
/// By default, when a modal route is replaced by another, the previous route
/// remains in memory. To free all the resources when this is not necessary, set
/// [maintainState] to false.
///
90 91 92 93
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.pop] when an optional
/// `result` can be provided.
///
94 95
/// See also:
///
96 97 98 99 100 101
///  * [MaterialPageRoute], for an adaptive [PageRoute] that uses a
///    platform-appropriate transition.
///  * [CupertinoPageScaffold], for applications that have one page with a fixed
///    navigation bar on top.
///  * [CupertinoTabScaffold], for applications that have a tab bar at the
///    bottom with multiple pages.
102 103
class CupertinoPageRoute<T> extends PageRoute<T> {
  /// Creates a page route for use in an iOS designed app.
104
  ///
105 106
  /// The [builder], [maintainState], and [fullscreenDialog] arguments must not
  /// be null.
107 108
  CupertinoPageRoute({
    @required this.builder,
109
    this.title,
110
    RouteSettings settings,
111 112
    this.maintainState = true,
    bool fullscreenDialog = false,
113
  }) : assert(builder != null),
114 115
       assert(maintainState != null),
       assert(fullscreenDialog != null),
116 117
       assert(opaque),
       super(settings: settings, fullscreenDialog: fullscreenDialog);
118 119 120

  /// Builds the primary contents of the route.
  final WidgetBuilder builder;
121

122 123
  /// A title string for this route.
  ///
124
  /// Used to auto-populate [CupertinoNavigationBar] and
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
  /// [CupertinoSliverNavigationBar]'s `middle`/`largeTitle` widgets when
  /// one is not manually supplied.
  final String title;

  ValueNotifier<String> _previousTitle;

  /// The title string of the previous [CupertinoPageRoute].
  ///
  /// The [ValueListenable]'s value is readable after the route is installed
  /// onto a [Navigator]. The [ValueListenable] will also notify its listeners
  /// if the value changes (such as by replacing the previous route).
  ///
  /// The [ValueListenable] itself will be null before the route is installed.
  /// Its content value will be null if the previous route has no title or
  /// is not a [CupertinoPageRoute].
  ///
  /// See also:
  ///
  ///  * [ValueListenableBuilder], which can be used to listen and rebuild
  ///    widgets based on a ValueListenable.
  ValueListenable<String> get previousTitle {
    assert(
      _previousTitle != null,
      'Cannot read the previousTitle for a route that has not yet been installed',
    );
    return _previousTitle;
  }

  @override
  void didChangePrevious(Route<dynamic> previousRoute) {
    final String previousTitleString = previousRoute is CupertinoPageRoute
        ? previousRoute.title
        : null;
    if (_previousTitle == null) {
159
      _previousTitle = ValueNotifier<String>(previousTitleString);
160 161 162 163 164 165
    } else {
      _previousTitle.value = previousTitleString;
    }
    super.didChangePrevious(previousRoute);
  }

166 167
  @override
  final bool maintainState;
168

169
  @override
170 171
  // A relatively rigorous eyeball estimation.
  Duration get transitionDuration => const Duration(milliseconds: 400);
172 173

  @override
174
  Color get barrierColor => null;
175

176 177 178
  @override
  String get barrierLabel => null;

179
  @override
180 181 182
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
    // Don't perform outgoing animation if the next route is a fullscreen dialog.
    return nextRoute is CupertinoPageRoute && !nextRoute.fullscreenDialog;
183 184
  }

185 186 187
  /// True if an iOS-style back swipe pop gesture is currently underway for [route].
  ///
  /// This just check the route's [NavigatorState.userGestureInProgress].
188
  ///
189 190 191 192
  /// See also:
  ///
  ///  * [popGestureEnabled], which returns true if a user-triggered pop gesture
  ///    would be allowed.
193 194 195
  static bool isPopGestureInProgress(PageRoute<dynamic> route) {
    return route.navigator.userGestureInProgress;
  }
196

197
  /// True if an iOS-style back swipe pop gesture is currently underway for this route.
198 199 200
  ///
  /// See also:
  ///
201 202 203 204 205
  ///  * [isPopGestureInProgress], which returns true if a Cupertino pop gesture
  ///    is currently underway for specific route.
  ///  * [popGestureEnabled], which returns true if a user-triggered pop gesture
  ///    would be allowed.
  bool get popGestureInProgress => isPopGestureInProgress(this);
206

207
  /// Whether a pop gesture can be started by the user.
208
  ///
209
  /// Returns true if the user can edge-swipe to a previous route.
210
  ///
211 212
  /// Returns false once [isPopGestureInProgress] is true, but
  /// [isPopGestureInProgress] can only become true if [popGestureEnabled] was
213
  /// true first.
214
  ///
215
  /// This should only be used between frames, not during build.
216 217 218
  bool get popGestureEnabled => _isPopGestureEnabled(this);

  static bool _isPopGestureEnabled<T>(PageRoute<T> route) {
219 220 221 222 223 224 225 226
    // If there's nothing to go back to, then obviously we don't support
    // the back gesture.
    if (route.isFirst)
      return false;
    // If the route wouldn't actually pop if we popped it, then the gesture
    // would be really confusing (or would skip internal routes), so disallow it.
    if (route.willHandlePopInternally)
      return false;
227 228
    // If attempts to dismiss this route might be vetoed such as in a page
    // with forms, then do not allow the user to dismiss the route with a swipe.
229 230
    if (route.hasScopedWillPopCallback)
      return false;
231
    // Fullscreen dialogs aren't dismissible by back swipe.
232
    if (route.fullscreenDialog)
233 234
      return false;
    // If we're in an animation already, we cannot be manually swiped.
235 236 237 238 239 240
    if (route.animation.status != AnimationStatus.completed)
      return false;
    // If we're being popped into, we also cannot be swiped until the pop above
    // it completes. This translates to our secondary animation being
    // dismissed.
    if (route.secondaryAnimation.status != AnimationStatus.dismissed)
241 242
      return false;
    // If we're in a gesture already, we cannot start another.
243
    if (isPopGestureInProgress(route))
244
      return false;
245

246 247 248
    // Looks like a back gesture would be welcome!
    return true;
  }
249

250
  @override
251
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
252
    final Widget child = builder(context);
253
    final Widget result = Semantics(
254 255
      scopesRoute: true,
      explicitChildNodes: true,
256
      child: child,
257
    );
258
    assert(() {
259 260 261 262 263
      if (child == null) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('The builder for route "${settings.name}" returned null.'),
          ErrorDescription('Route builders must never return null.'),
        ]);
264 265
      }
      return true;
266
    }());
267 268
    return result;
  }
269

270
  // Called by _CupertinoBackGestureDetector when a pop ("back") drag start
xster's avatar
xster committed
271
  // gesture is detected. The returned controller handles all of the subsequent
272 273 274 275
  // drag events.
  static _CupertinoBackGestureController<T> _startPopGesture<T>(PageRoute<T> route) {
    assert(_isPopGestureEnabled(route));

276 277
    return _CupertinoBackGestureController<T>(
      navigator: route.navigator,
278
      controller: route.controller, // protected access
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    );
  }

  /// Returns a [CupertinoFullscreenDialogTransition] if [route] is a full
  /// screen dialog, otherwise a [CupertinoPageTransition] is returned.
  ///
  /// Used by [CupertinoPageRoute.buildTransitions].
  ///
  /// This method can be applied to any [PageRoute], not just
  /// [CupertinoPageRoute]. It's typically used to provide a Cupertino style
  /// horizontal transition for material widgets when the target platform
  /// is [TargetPlatform.iOS].
  ///
  /// See also:
  ///
  ///  * [CupertinoPageTransitionsBuilder], which uses this method to define a
  ///    [PageTransitionsBuilder] for the [PageTransitionsTheme].
  static Widget buildPageTransitions<T>(
    PageRoute<T> route,
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
  ) {
    if (route.fullscreenDialog) {
304
      return CupertinoFullscreenDialogTransition(
305 306 307
        animation: animation,
        child: child,
      );
308
    } else {
309
      return CupertinoPageTransition(
310 311
        primaryRouteAnimation: animation,
        secondaryRouteAnimation: secondaryAnimation,
312 313 314
        // Check if the route has an animation that's currently participating
        // in a back swipe gesture.
        //
315 316
        // In the middle of a back gesture drag, let the transition be linear to
        // match finger motions.
317
        linearTransition: isPopGestureInProgress(route),
318
        child: _CupertinoBackGestureDetector<T>(
319 320
          enabledCallback: () => _isPopGestureEnabled<T>(route),
          onStartPopGesture: () => _startPopGesture<T>(route),
321 322
          child: child,
        ),
323
      );
324
    }
325
  }
326

327 328 329 330 331
  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return buildPageTransitions<T>(this, context, animation, secondaryAnimation, child);
  }

332 333
  @override
  String get debugLabel => '${super.debugLabel}(${settings.name})';
334 335
}

336
/// Provides an iOS-style page transition animation.
337 338 339
///
/// The page slides in from the right and exits in reverse. It also shifts to the left in
/// a parallax motion when another page enters to cover it.
340
class CupertinoPageTransition extends StatelessWidget {
341 342 343 344 345 346 347 348
  /// Creates an iOS-style page transition.
  ///
  ///  * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when this screen is being pushed.
  ///  * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when another screen is being pushed on top of this one.
  ///  * `linearTransition` is whether to perform primary transition linearly.
  ///    Used to precisely track back gesture drags.
349 350
  CupertinoPageTransition({
    Key key,
351 352
    @required Animation<double> primaryRouteAnimation,
    @required Animation<double> secondaryRouteAnimation,
353
    @required this.child,
Ian Hickson's avatar
Ian Hickson committed
354 355
    @required bool linearTransition,
  }) : assert(linearTransition != null),
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
       _primaryPositionAnimation =
           (linearTransition
             ? primaryRouteAnimation
             : CurvedAnimation(
                 // The curves below have been rigorously derived from plots of native
                 // iOS animation frames. Specifically, a video was taken of a page
                 // transition animation and the distance in each frame that the page
                 // moved was measured. A best fit bezier curve was the fitted to the
                 // point set, which is linearToEaseIn. Conversely, easeInToLinear is the
                 // reflection over the origin of linearToEaseIn.
                 parent: primaryRouteAnimation,
                 curve: Curves.linearToEaseOut,
                 reverseCurve: Curves.easeInToLinear,
               )
           ).drive(_kRightMiddleTween),
       _secondaryPositionAnimation =
           (linearTransition
             ? secondaryRouteAnimation
             : CurvedAnimation(
                 parent: secondaryRouteAnimation,
                 curve: Curves.linearToEaseOut,
                 reverseCurve: Curves.easeInToLinear,
               )
           ).drive(_kMiddleLeftTween),
       _primaryShadowAnimation =
           (linearTransition
             ? primaryRouteAnimation
             : CurvedAnimation(
                 parent: primaryRouteAnimation,
                 curve: Curves.linearToEaseOut,
               )
           ).drive(_kGradientShadowTween),
Ian Hickson's avatar
Ian Hickson committed
388
       super(key: key);
389 390

  // When this page is coming in to cover another page.
391
  final Animation<Offset> _primaryPositionAnimation;
392
  // When this page is becoming covered by another page.
393
  final Animation<Offset> _secondaryPositionAnimation;
394
  final Animation<Decoration> _primaryShadowAnimation;
395 396

  /// The widget below this widget in the tree.
397 398 399 400
  final Widget child;

  @override
  Widget build(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
401 402
    assert(debugCheckHasDirectionality(context));
    final TextDirection textDirection = Directionality.of(context);
403
    return SlideTransition(
404
      position: _secondaryPositionAnimation,
Ian Hickson's avatar
Ian Hickson committed
405
      textDirection: textDirection,
406
      transformHitTests: false,
407
      child: SlideTransition(
408
        position: _primaryPositionAnimation,
Ian Hickson's avatar
Ian Hickson committed
409
        textDirection: textDirection,
410
        child: DecoratedBoxTransition(
411
          decoration: _primaryShadowAnimation,
412 413 414
          child: child,
        ),
      ),
415 416 417 418
    );
  }
}

419 420 421 422
/// An iOS-style transition used for summoning fullscreen dialogs.
///
/// For example, used when creating a new calendar event by bringing in the next
/// screen from the bottom.
423
class CupertinoFullscreenDialogTransition extends StatelessWidget {
424
  /// Creates an iOS-style transition used for summoning fullscreen dialogs.
425 426 427 428
  CupertinoFullscreenDialogTransition({
    Key key,
    @required Animation<double> animation,
    @required this.child,
429 430 431 432 433 434 435
  }) : _positionAnimation = CurvedAnimation(
         parent: animation,
         curve: Curves.linearToEaseOut,
         // The curve must be flipped so that the reverse animation doesn't play
         // an ease-in curve, which iOS does not use.
         reverseCurve: Curves.linearToEaseOut.flipped,
       ).drive(_kBottomUpTween),
436
       super(key: key);
437

438
  final Animation<Offset> _positionAnimation;
439 440

  /// The widget below this widget in the tree.
441
  final Widget child;
442 443

  @override
444
  Widget build(BuildContext context) {
445
    return SlideTransition(
446
      position: _positionAnimation,
447 448
      child: child,
    );
449 450 451
  }
}

452 453 454 455 456
/// This is the widget side of [_CupertinoBackGestureController].
///
/// This widget provides a gesture recognizer which, when it determines the
/// route can be closed with a back gesture, creates the controller and
/// feeds it the input from the gesture recognizer.
Ian Hickson's avatar
Ian Hickson committed
457 458 459
///
/// The gesture data is converted from absolute coordinates to logical
/// coordinates by this widget.
460 461 462 463
///
/// The type `T` specifies the return type of the route with which this gesture
/// detector is associated.
class _CupertinoBackGestureDetector<T> extends StatefulWidget {
464 465 466 467 468 469 470 471 472 473 474 475 476 477
  const _CupertinoBackGestureDetector({
    Key key,
    @required this.enabledCallback,
    @required this.onStartPopGesture,
    @required this.child,
  }) : assert(enabledCallback != null),
       assert(onStartPopGesture != null),
       assert(child != null),
       super(key: key);

  final Widget child;

  final ValueGetter<bool> enabledCallback;

478
  final ValueGetter<_CupertinoBackGestureController<T>> onStartPopGesture;
479 480

  @override
481
  _CupertinoBackGestureDetectorState<T> createState() => _CupertinoBackGestureDetectorState<T>();
482 483
}

484 485
class _CupertinoBackGestureDetectorState<T> extends State<_CupertinoBackGestureDetector<T>> {
  _CupertinoBackGestureController<T> _backGestureController;
486 487 488 489 490 491

  HorizontalDragGestureRecognizer _recognizer;

  @override
  void initState() {
    super.initState();
492
    _recognizer = HorizontalDragGestureRecognizer(debugOwner: this)
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd
      ..onCancel = _handleDragCancel;
  }

  @override
  void dispose() {
    _recognizer.dispose();
    super.dispose();
  }

  void _handleDragStart(DragStartDetails details) {
    assert(mounted);
    assert(_backGestureController == null);
    _backGestureController = widget.onStartPopGesture();
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    assert(mounted);
    assert(_backGestureController != null);
Ian Hickson's avatar
Ian Hickson committed
514
    _backGestureController.dragUpdate(_convertToLogical(details.primaryDelta / context.size.width));
515 516 517 518 519
  }

  void _handleDragEnd(DragEndDetails details) {
    assert(mounted);
    assert(_backGestureController != null);
Ian Hickson's avatar
Ian Hickson committed
520
    _backGestureController.dragEnd(_convertToLogical(details.velocity.pixelsPerSecond.dx / context.size.width));
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    _backGestureController = null;
  }

  void _handleDragCancel() {
    assert(mounted);
    // This can be called even if start is not called, paired with the "down" event
    // that we don't consider here.
    _backGestureController?.dragEnd(0.0);
    _backGestureController = null;
  }

  void _handlePointerDown(PointerDownEvent event) {
    if (widget.enabledCallback())
      _recognizer.addPointer(event);
  }

Ian Hickson's avatar
Ian Hickson committed
537 538 539 540 541 542 543 544 545 546
  double _convertToLogical(double value) {
    switch (Directionality.of(context)) {
      case TextDirection.rtl:
        return -value;
      case TextDirection.ltr:
        return value;
    }
    return null;
  }

547 548
  @override
  Widget build(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
549
    assert(debugCheckHasDirectionality(context));
550 551 552 553 554 555
    // For devices with notches, the drag area needs to be larger on the side
    // that has the notch.
    double dragAreaWidth = Directionality.of(context) == TextDirection.ltr ?
                           MediaQuery.of(context).padding.left :
                           MediaQuery.of(context).padding.right;
    dragAreaWidth = max(dragAreaWidth, _kBackGestureWidth);
556
    return Stack(
557 558 559
      fit: StackFit.passthrough,
      children: <Widget>[
        widget.child,
560
        PositionedDirectional(
Ian Hickson's avatar
Ian Hickson committed
561
          start: 0.0,
562
          width: dragAreaWidth,
563 564
          top: 0.0,
          bottom: 0.0,
565
          child: Listener(
566 567 568
            onPointerDown: _handlePointerDown,
            behavior: HitTestBehavior.translucent,
          ),
569 570 571 572 573 574
        ),
      ],
    );
  }
}

575 576
/// A controller for an iOS-style back gesture.
///
577 578 579 580
/// This is created by a [CupertinoPageRoute] in response from a gesture caught
/// by a [_CupertinoBackGestureDetector] widget, which then also feeds it input
/// from the gesture. It controls the animation controller owned by the route,
/// based on the input provided by the gesture detector.
Ian Hickson's avatar
Ian Hickson committed
581 582 583
///
/// This class works entirely in logical coordinates (0.0 is new page dismissed,
/// 1.0 is new page on top).
584 585 586 587
///
/// The type `T` specifies the return type of the route with which this gesture
/// detector controller is associated.
class _CupertinoBackGestureController<T> {
588 589 590
  /// Creates a controller for an iOS-style back gesture.
  ///
  /// The [navigator] and [controller] arguments must not be null.
591
  _CupertinoBackGestureController({
592
    @required this.navigator,
593
    @required this.controller,
594 595 596
  }) : assert(navigator != null),
       assert(controller != null) {
    navigator.didStartUserGesture();
597 598
  }

599
  final AnimationController controller;
600
  final NavigatorState navigator;
601 602 603

  /// The drag gesture has changed by [fractionalDelta]. The total range of the
  /// drag should be 0.0 to 1.0.
604 605 606 607
  void dragUpdate(double delta) {
    controller.value -= delta;
  }

608 609 610 611 612 613
  /// The drag gesture has ended with a horizontal motion of
  /// [fractionalVelocity] as a fraction of screen width per second.
  void dragEnd(double velocity) {
    // Fling in the appropriate direction.
    // AnimationController.fling is guaranteed to
    // take at least one frame.
614 615 616 617 618 619 620 621 622 623
    //
    // This curve has been determined through rigorously eyeballing native iOS
    // animations.
    const Curve animationCurve = Curves.fastLinearToSlowEaseIn;
    bool animateForward;

    // If the user releases the page before mid screen with sufficient velocity,
    // or after mid screen, we should animate the page out. Otherwise, the page
    // should be animated back in.
    if (velocity.abs() >= _kMinFlingVelocity)
624
      animateForward = velocity <= 0;
625
    else
626
      animateForward = controller.value > 0.5;
627

628 629 630 631
    if (animateForward) {
      // The closer the panel is to dismissing, the shorter the animation is.
      // We want to cap the animation time, but we want to use a linear curve
      // to determine it.
632 633 634 635
      final int droppedPageForwardAnimationTime = min(
        lerpDouble(_kMaxDroppedSwipePageForwardAnimationTime, 0, controller.value).floor(),
        _kMaxPageBackAnimationTime,
      );
636
      controller.animateTo(1.0, duration: Duration(milliseconds: droppedPageForwardAnimationTime), curve: animationCurve);
637
    } else {
638 639 640 641 642 643 644 645 646
      // This route is destined to pop at this point. Reuse navigator's pop.
      navigator.pop();

      // The popping may have finished inline if already at the target destination.
      if (controller.isAnimating) {
        // Otherwise, use a custom popping animation duration and curve.
        final int droppedPageBackAnimationTime = lerpDouble(0, _kMaxDroppedSwipePageForwardAnimationTime, controller.value).floor();
        controller.animateBack(0.0, duration: Duration(milliseconds: droppedPageBackAnimationTime), curve: animationCurve);
      }
647
    }
648

649
    if (controller.isAnimating) {
650 651 652 653 654 655 656 657 658
      // Keep the userGestureInProgress in true state so we don't change the
      // curve of the page transition mid-flight since CupertinoPageTransition
      // depends on userGestureInProgress.
      AnimationStatusListener animationStatusCallback;
      animationStatusCallback = (AnimationStatus status) {
        navigator.didStopUserGesture();
        controller.removeStatusListener(animationStatusCallback);
      };
      controller.addStatusListener(animationStatusCallback);
659 660
    } else {
      navigator.didStopUserGesture();
661
    }
662 663
  }
}
664

Ian Hickson's avatar
Ian Hickson committed
665 666 667 668 669 670 671 672 673
// A custom [Decoration] used to paint an extra shadow on the start edge of the
// box it's decorating. It's like a [BoxDecoration] with only a gradient except
// it paints on the start side of the box instead of behind the box.
//
// The [edgeGradient] will be given a [TextDirection] when its shader is
// created, and so can be direction-sensitive; in this file we set it to a
// gradient that uses an AlignmentDirectional to position the gradient on the
// end edge of the gradient's box (which will be the edge adjacent to the start
// edge of the actual box we're supposed to paint in).
674 675 676
class _CupertinoEdgeShadowDecoration extends Decoration {
  const _CupertinoEdgeShadowDecoration({ this.edgeGradient });

677 678
  // An edge shadow decoration where the shadow is null. This is used
  // for interpolating from no shadow.
679
  static const _CupertinoEdgeShadowDecoration none =
680
      _CupertinoEdgeShadowDecoration();
681

682 683 684
  // A gradient to draw to the left of the box being decorated.
  // Alignments are relative to the original box translated one box
  // width to the left.
685 686
  final LinearGradient edgeGradient;

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
  // Linearly interpolate between two edge shadow decorations decorations.
  //
  // The `t` argument represents position on the timeline, with 0.0 meaning
  // that the interpolation has not started, returning `a` (or something
  // equivalent to `a`), 1.0 meaning that the interpolation has finished,
  // returning `b` (or something equivalent to `b`), and values in between
  // meaning that the interpolation is at the relevant point on the timeline
  // between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
  // 1.0, so negative values and values greater than 1.0 are valid (and can
  // easily be generated by curves such as [Curves.elasticInOut]).
  //
  // Values for `t` are usually obtained from an [Animation<double>], such as
  // an [AnimationController].
  //
  // See also:
  //
  //  * [Decoration.lerp].
704 705 706
  static _CupertinoEdgeShadowDecoration lerp(
    _CupertinoEdgeShadowDecoration a,
    _CupertinoEdgeShadowDecoration b,
707
    double t,
708
  ) {
709
    assert(t != null);
710 711
    if (a == null && b == null)
      return null;
712
    return _CupertinoEdgeShadowDecoration(
713 714 715 716 717 718
      edgeGradient: LinearGradient.lerp(a?.edgeGradient, b?.edgeGradient, t),
    );
  }

  @override
  _CupertinoEdgeShadowDecoration lerpFrom(Decoration a, double t) {
719 720 721
    if (a is _CupertinoEdgeShadowDecoration)
      return _CupertinoEdgeShadowDecoration.lerp(a, this, t);
    return _CupertinoEdgeShadowDecoration.lerp(null, this, t);
722 723 724 725
  }

  @override
  _CupertinoEdgeShadowDecoration lerpTo(Decoration b, double t) {
726 727 728
    if (b is _CupertinoEdgeShadowDecoration)
      return _CupertinoEdgeShadowDecoration.lerp(this, b, t);
    return _CupertinoEdgeShadowDecoration.lerp(this, null, t);
729 730 731
  }

  @override
732
  _CupertinoEdgeShadowPainter createBoxPainter([ VoidCallback onChanged ]) {
733
    return _CupertinoEdgeShadowPainter(this, onChanged);
734 735 736
  }

  @override
737 738
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType)
739
      return false;
740 741
    return other is _CupertinoEdgeShadowDecoration
        && other.edgeGradient == edgeGradient;
742 743 744
  }

  @override
Ian Hickson's avatar
Ian Hickson committed
745
  int get hashCode => edgeGradient.hashCode;
746 747

  @override
748 749
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
750
    properties.add(DiagnosticsProperty<LinearGradient>('edgeGradient', edgeGradient));
751
  }
752 753 754 755 756 757
}

/// A [BoxPainter] used to draw the page transition shadow using gradients.
class _CupertinoEdgeShadowPainter extends BoxPainter {
  _CupertinoEdgeShadowPainter(
    this._decoration,
Ian Hickson's avatar
Ian Hickson committed
758
    VoidCallback onChange,
759 760 761 762 763 764 765 766 767 768 769
  ) : assert(_decoration != null),
      super(onChange);

  final _CupertinoEdgeShadowDecoration _decoration;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final LinearGradient gradient = _decoration.edgeGradient;
    if (gradient == null)
      return;
    // The drawable space for the gradient is a rect with the same size as
Ian Hickson's avatar
Ian Hickson committed
770 771 772 773 774 775 776 777 778 779 780 781 782
    // its parent box one box width on the start side of the box.
    final TextDirection textDirection = configuration.textDirection;
    assert(textDirection != null);
    double deltaX;
    switch (textDirection) {
      case TextDirection.rtl:
        deltaX = configuration.size.width;
        break;
      case TextDirection.ltr:
        deltaX = -configuration.size.width;
        break;
    }
    final Rect rect = (offset & configuration.size).translate(deltaX, 0.0);
783
    final Paint paint = Paint()
Ian Hickson's avatar
Ian Hickson committed
784
      ..shader = gradient.createShader(rect, textDirection: textDirection);
785 786 787 788

    canvas.drawRect(rect, paint);
  }
}
789

790 791
class _CupertinoModalPopupRoute<T> extends PopupRoute<T> {
  _CupertinoModalPopupRoute({
792
    this.barrierColor,
793 794
    this.barrierLabel,
    this.builder,
Dan Field's avatar
Dan Field committed
795
    bool semanticsDismissible,
796
    ImageFilter filter,
797
    RouteSettings settings,
798 799 800
  }) : super(
         filter: filter,
         settings: settings,
Dan Field's avatar
Dan Field committed
801 802 803
       ) {
    _semanticsDismissible = semanticsDismissible;
  }
804 805

  final WidgetBuilder builder;
Dan Field's avatar
Dan Field committed
806
  bool _semanticsDismissible;
807 808 809 810 811

  @override
  final String barrierLabel;

  @override
812
  final Color barrierColor;
813 814 815 816 817

  @override
  bool get barrierDismissible => true;

  @override
Dan Field's avatar
Dan Field committed
818
  bool get semanticsDismissible => _semanticsDismissible ?? false;
819 820 821 822 823 824 825 826 827 828 829

  @override
  Duration get transitionDuration => _kModalPopupTransitionDuration;

  Animation<double> _animation;

  Tween<Offset> _offsetTween;

  @override
  Animation<double> createAnimation() {
    assert(_animation == null);
830
    _animation = CurvedAnimation(
831
      parent: super.createAnimation(),
832 833 834 835 836

      // These curves were initially measured from native iOS horizontal page
      // route animations and seemed to be a good match here as well.
      curve: Curves.linearToEaseOut,
      reverseCurve: Curves.linearToEaseOut.flipped,
837
    );
838
    _offsetTween = Tween<Offset>(
839 840 841 842 843 844 845 846
      begin: const Offset(0.0, 1.0),
      end: const Offset(0.0, 0.0),
    );
    return _animation;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
847 848 849 850
    return CupertinoUserInterfaceLevel(
      data: CupertinoUserInterfaceLevelData.elevated,
      child: Builder(builder: builder),
    );
851 852 853 854
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
855
    return Align(
856
      alignment: Alignment.bottomCenter,
857
      child: FractionalTranslation(
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
        translation: _offsetTween.evaluate(_animation),
        child: child,
      ),
    );
  }
}

/// Shows a modal iOS-style popup that slides up from the bottom of the screen.
///
/// Such a popup is an alternative to a menu or a dialog and prevents the user
/// from interacting with the rest of the app.
///
/// The `context` argument is used to look up the [Navigator] for the popup.
/// It is only used when the method is called. Its corresponding widget can be
/// safely removed from the tree before the popup is closed.
///
874 875 876 877
/// The `useRootNavigator` argument is used to determine whether to push the
/// popup to the [Navigator] furthest from or nearest to the given `context`. It
/// is `false` by default.
///
Dan Field's avatar
Dan Field committed
878 879 880
/// The `semanticsDismissble` argument is used to determine whether the
/// semantics of the modal barrier are included in the semantics tree.
///
881 882 883 884 885 886 887 888 889 890 891 892
/// The `builder` argument typically builds a [CupertinoActionSheet] widget.
/// Content below the widget is dimmed with a [ModalBarrier]. The widget built
/// by the `builder` does not share a context with the location that
/// `showCupertinoModalPopup` is originally called from. Use a
/// [StatefulBuilder] or a custom [StatefulWidget] if the widget needs to
/// update dynamically.
///
/// Returns a `Future` that resolves to the value that was passed to
/// [Navigator.pop] when the popup was closed.
///
/// See also:
///
Dan Field's avatar
Dan Field committed
893 894
///  * [CupertinoActionSheet], which is the widget usually returned by the
///    `builder` argument to [showCupertinoModalPopup].
895 896 897 898
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/views/action-sheets/>
Future<T> showCupertinoModalPopup<T>({
  @required BuildContext context,
  @required WidgetBuilder builder,
899
  ImageFilter filter,
900
  bool useRootNavigator = true,
Dan Field's avatar
Dan Field committed
901
  bool semanticsDismissible,
902
}) {
903 904
  assert(useRootNavigator != null);
  return Navigator.of(context, rootNavigator: useRootNavigator).push(
905
    _CupertinoModalPopupRoute<T>(
906
      barrierColor: CupertinoDynamicColor.resolve(_kModalBarrierColor, context),
907 908 909
      barrierLabel: 'Dismiss',
      builder: builder,
      filter: filter,
Dan Field's avatar
Dan Field committed
910
      semanticsDismissible: semanticsDismissible,
911 912 913 914
    ),
  );
}

915
// The curve and initial scale values were mostly eyeballed from iOS, however
916
// they reuse the same animation curve that was modeled after native page
917 918 919
// transitions.
final Animatable<double> _dialogScaleTween = Tween<double>(begin: 1.3, end: 1.0)
  .chain(CurveTween(curve: Curves.linearToEaseOut));
920

921
Widget _buildCupertinoDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
922
  final CurvedAnimation fadeAnimation = CurvedAnimation(
923 924 925 926
    parent: animation,
    curve: Curves.easeInOut,
  );
  if (animation.status == AnimationStatus.reverse) {
927
    return FadeTransition(
928 929 930 931
      opacity: fadeAnimation,
      child: child,
    );
  }
932
  return FadeTransition(
933 934 935
    opacity: fadeAnimation,
    child: ScaleTransition(
      child: child,
936
      scale: animation.drive(_dialogScaleTween),
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
    ),
  );
}

/// Displays an iOS-style dialog above the current contents of the app, with
/// iOS-style entrance and exit animations, modal barrier color, and modal
/// barrier behavior (the dialog is not dismissible with a tap on the barrier).
///
/// This function takes a `builder` which typically builds a [CupertinoDialog]
/// or [CupertinoAlertDialog] widget. Content below the dialog is dimmed with a
/// [ModalBarrier]. The widget returned by the `builder` does not share a
/// context with the location that `showCupertinoDialog` is originally called
/// from. Use a [StatefulBuilder] or a custom [StatefulWidget] if the dialog
/// needs to update dynamically.
///
/// The `context` argument is used to look up the [Navigator] for the dialog.
/// It is only used when the method is called. Its corresponding widget can
/// be safely removed from the tree before the dialog is closed.
///
956 957 958 959
/// The `useRootNavigator` argument is used to determine whether to push the
/// dialog to the [Navigator] furthest from or nearest to the given `context`.
/// By default, `useRootNavigator` is `true` and the dialog route created by
/// this method is pushed to the root navigator.
960 961 962 963 964
///
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
/// dialog rather than just `Navigator.pop(context, result)`.
///
965 966 967
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
968
/// See also:
969
///
970 971 972 973 974 975 976 977
///  * [CupertinoDialog], an iOS-style dialog.
///  * [CupertinoAlertDialog], an iOS-style alert dialog.
///  * [showDialog], which displays a Material-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
///  * <https://developer.apple.com/ios/human-interface-guidelines/views/alerts/>
Future<T> showCupertinoDialog<T>({
  @required BuildContext context,
  @required WidgetBuilder builder,
978
  bool useRootNavigator = true,
979
  RouteSettings routeSettings,
980 981
}) {
  assert(builder != null);
982
  assert(useRootNavigator != null);
983 984 985
  return showGeneralDialog(
    context: context,
    barrierDismissible: false,
986
    barrierColor: CupertinoDynamicColor.resolve(_kModalBarrierColor, context),
987 988
    // This transition duration was eyeballed comparing with iOS
    transitionDuration: const Duration(milliseconds: 250),
989 990 991 992
    pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
      return builder(context);
    },
    transitionBuilder: _buildCupertinoDialogTransitions,
993
    useRootNavigator: useRootNavigator,
994
    routeSettings: routeSettings,
995
  );
996
}