heroes.dart 17.6 KB
Newer Older
Hixie's avatar
Hixie committed
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 'dart:collection';

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

import 'basic.dart';
import 'framework.dart';
11 12 13
import 'navigator.dart';
import 'overlay.dart';
import 'pages.dart';
Hixie's avatar
Hixie committed
14 15 16 17 18
import 'transitions.dart';

// Heroes are the parts of an application's screen-to-screen transitions where a
// component from one screen shifts to a position on the other. For example,
// album art from a list of albums growing to become the centerpiece of the
Hixie's avatar
Hixie committed
19
// album's details view. In this context, a screen is a navigator ModalRoute.
Hixie's avatar
Hixie committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

// To get this effect, all you have to do is wrap each hero on each route with a
// Hero widget, and give each hero a tag. Tag must either be unique within the
// current route's widget subtree, or all the Heroes with that tag on a
// particular route must have a key. When the app transitions from one route to
// another, each tag present is animated. When there's exactly one hero with
// that tag, that hero will be animated for that tag. When there are multiple
// heroes in a route with the same tag, then whichever hero has a key that
// matches one of the keys in the "most important key" list given to the
// navigator when the route was pushed will be animated. If a hero is only
// present on one of the routes and not the other, then it will be made to
// appear or disappear as needed.

// TODO(ianh): Make the appear/disappear animations pretty. Right now they're
// pretty crude (just rotate and shrink the constraints). They should probably
// involve actually scaling and fading, at a minimum.

// Heroes and the Navigator's Stack must be axis-aligned for all this to work.
// The top left and bottom right coordinates of each animated Hero will be
// converted to global coordinates and then from there converted to the
// Navigator Stack's coordinate space, and the entire Hero subtree will, for the
// duration of the animation, be lifted out of its original place, and
// positioned on that stack. If the Hero isn't axis aligned, this is going to
// fail in a rather ugly fashion. Don't rotate your heroes!

// To make the animations look good, it's critical that the widget tree for the
// hero in both locations be essentially identical. The widget of the target is
// used to do the transition: when going from route A to route B, route B's
// hero's widget is placed over route A's hero's widget, and route A's hero is
// hidden. Then the widget is animated to route B's hero's position, and then
// the widget is inserted into route B. When going back from B to A, route A's
// hero's widget is placed over where route B's hero's widget was, and then the
// animation goes the other way.

// TODO(ianh): If the widgets use Inherited properties, they are taken from the
// Navigator's position in the widget hierarchy, not the source or target. We
// should interpolate the inherited properties from their value at the source to
Hixie's avatar
Hixie committed
57
// their value at the target. See: https://github.com/flutter/flutter/issues/213
Hixie's avatar
Hixie committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

class _HeroManifest {
  const _HeroManifest({
    this.key,
    this.config,
    this.sourceStates,
    this.currentRect,
    this.currentTurns
  });
  final GlobalKey key;
  final Widget config;
  final Set<HeroState> sourceStates;
  final RelativeRect currentRect;
  final double currentTurns;
}

abstract class HeroHandle {
75
  bool get alwaysAnimate;
76
  _HeroManifest _takeChild(Rect animationArea, Animation<double> currentAnimation);
Hixie's avatar
Hixie committed
77 78 79 80 81 82 83
}

class Hero extends StatefulComponent {
  Hero({
    Key key,
    this.tag,
    this.child,
84 85
    this.turns: 1,
    this.alwaysAnimate: false
Hixie's avatar
Hixie committed
86 87 88 89 90 91 92 93
  }) : super(key: key) {
    assert(tag != null);
  }

  final Object tag;
  final Widget child;
  final int turns;

94 95 96 97 98 99
  /// If true, the hero will always animate, even if it has no matching hero to
  /// animate to or from. (This only applies if the hero is relevant; if there
  /// are multiple heroes with the same tag, only the one whose key matches the
  /// "most valuable keys" will be used.)
  final bool alwaysAnimate;

Hixie's avatar
Hixie committed
100
  static Map<Object, HeroHandle> of(BuildContext context, Set<Key> mostValuableKeys) {
101
    mostValuableKeys ??= new HashSet<Key>();
Hixie's avatar
Hixie committed
102 103 104 105 106
    assert(!mostValuableKeys.contains(null));
    // first we collect ALL the heroes, sorted by their tags
    Map<Object, Map<Key, HeroState>> heroes = <Object, Map<Key, HeroState>>{};
    void visitor(Element element) {
      if (element.widget is Hero) {
107 108 109
        StatefulComponentElement hero = element;
        Hero heroWidget = element.widget;
        Object tag = heroWidget.tag;
Hixie's avatar
Hixie committed
110
        assert(tag != null);
111
        Key key = heroWidget.key;
Hixie's avatar
Hixie committed
112
        final Map<Key, HeroState> tagHeroes = heroes.putIfAbsent(tag, () => <Key, HeroState>{});
113 114
        assert(() {
          if (tagHeroes.containsKey(key)) {
Hixie's avatar
Hixie committed
115 116
            new WidgetError(
              'There are multiple heroes that share the same key within the same subtree.\n'
117 118
              'Within each subtree for which heroes are to be animated (typically a PageRoute subtree), '
              'either each Hero must have a unique tag, or, all the heroes with a particular tag must '
Hixie's avatar
Hixie committed
119 120 121
              'have different keys.\n'
              'In this case, the tag "$tag" had multiple heroes with the key "$key".'
            );
122 123 124
          }
          return true;
        });
Hixie's avatar
Hixie committed
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
        tagHeroes[key] = hero.state;
      }
      element.visitChildren(visitor);
    }
    context.visitChildElements(visitor);
    // next, for each tag, we're going to decide on the one hero we care about for that tag
    Map<Object, HeroHandle> result = <Object, HeroHandle>{};
    for (Object tag in heroes.keys) {
      assert(tag != null);
      if (heroes[tag].length == 1) {
        result[tag] = heroes[tag].values.first;
      } else {
        assert(heroes[tag].length > 1);
        assert(!heroes[tag].containsKey(null));
        assert(heroes[tag].keys.where((Key key) => mostValuableKeys.contains(key)).length <= 1);
        Key mostValuableKey = mostValuableKeys.firstWhere((Key key) => heroes[tag].containsKey(key), orElse: () => null);
        if (mostValuableKey != null)
          result[tag] = heroes[tag][mostValuableKey];
      }
    }
    assert(!result.containsKey(null));
    return result;
  }

  HeroState createState() => new HeroState();
}

class HeroState extends State<Hero> implements HeroHandle {

Hixie's avatar
Hixie committed
154 155
  GlobalKey _key = new GlobalKey();
  Size _placeholderSize;
Hixie's avatar
Hixie committed
156

157 158
  bool get alwaysAnimate => config.alwaysAnimate;

159
  _HeroManifest _takeChild(Rect animationArea, Animation<double> currentAnimation) {
Hixie's avatar
Hixie committed
160
    assert(mounted);
Hixie's avatar
Hixie committed
161
    final RenderBox renderObject = context.findRenderObject();
Hixie's avatar
Hixie committed
162 163 164 165 166 167 168 169
    assert(renderObject != null);
    assert(!renderObject.needsLayout);
    assert(renderObject.hasSize);
    if (_placeholderSize == null) {
      // We are a "from" hero, about to depart on a quest.
      // Remember our size so that we can leave a placeholder.
      _placeholderSize = renderObject.size;
    }
Hixie's avatar
Hixie committed
170 171 172 173 174
    final Point heroTopLeft = renderObject.localToGlobal(Point.origin);
    final Point heroBottomRight = renderObject.localToGlobal(renderObject.size.bottomRight(Point.origin));
    final Rect heroArea = new Rect.fromLTRB(heroTopLeft.x, heroTopLeft.y, heroBottomRight.x, heroBottomRight.y);
    final RelativeRect startRect = new RelativeRect.fromRect(heroArea, animationArea);
    _HeroManifest result = new _HeroManifest(
Hixie's avatar
Hixie committed
175
      key: _key, // might be null, e.g. if the hero is returning to us
Hixie's avatar
Hixie committed
176
      config: config,
177
      sourceStates: new HashSet<HeroState>.from(<HeroState>[this]),
Hixie's avatar
Hixie committed
178 179 180
      currentRect: startRect,
      currentTurns: config.turns.toDouble()
    );
Hixie's avatar
Hixie committed
181 182
    if (_key != null)
      setState(() { _key = null; });
Hixie's avatar
Hixie committed
183 184 185 186 187
    return result;
  }

  void _setChild(GlobalKey value) {
    assert(_key == null);
Hixie's avatar
Hixie committed
188 189 190 191 192 193
    assert(_placeholderSize != null);
    assert(mounted);
    setState(() {
      _key = value;
      _placeholderSize = null;
    });
Hixie's avatar
Hixie committed
194 195 196 197
  }

  void _resetChild() {
    if (mounted)
Hixie's avatar
Hixie committed
198
      _setChild(null);
Hixie's avatar
Hixie committed
199 200 201
  }

  Widget build(BuildContext context) {
Hixie's avatar
Hixie committed
202 203 204
    if (_placeholderSize != null) {
      assert(_key == null);
      return new SizedBox(width: _placeholderSize.width, height: _placeholderSize.height);
Hixie's avatar
Hixie committed
205
    }
Hixie's avatar
Hixie committed
206 207 208 209
    return new KeyedSubtree(
      key: _key,
      child: config.child
    );
Hixie's avatar
Hixie committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  }

}


class _HeroQuestState implements HeroHandle {
  _HeroQuestState({
    this.tag,
    this.key,
    this.child,
    this.sourceStates,
    this.targetRect,
    this.targetTurns,
    this.targetState,
    this.currentRect,
    this.currentTurns
  }) {
    assert(tag != null);
  }

  final Object tag;
  final GlobalKey key;
  final Widget child;
  final Set<HeroState> sourceStates;
  final RelativeRect targetRect;
  final int targetTurns;
  final HeroState targetState;
237 238
  final RelativeRectTween currentRect;
  final Tween<double> currentTurns;
Hixie's avatar
Hixie committed
239

240 241
  bool get alwaysAnimate => true;

Hixie's avatar
Hixie committed
242 243
  bool get taken => _taken;
  bool _taken = false;
244
  _HeroManifest _takeChild(Rect animationArea, Animation<double> currentAnimation) {
Hixie's avatar
Hixie committed
245 246 247 248
    assert(!taken);
    _taken = true;
    Set<HeroState> states = sourceStates;
    if (targetState != null)
249
      states = states.union(new HashSet<HeroState>.from(<HeroState>[targetState]));
Hixie's avatar
Hixie committed
250 251 252 253
    return new _HeroManifest(
      key: key,
      config: child,
      sourceStates: states,
254 255
      currentRect: currentRect.evaluate(currentAnimation),
      currentTurns: currentTurns.evaluate(currentAnimation)
Hixie's avatar
Hixie committed
256 257 258
    );
  }

259
  Widget build(BuildContext context, Animation<double> animation) {
Hixie's avatar
Hixie committed
260
    return new PositionedTransition(
261
      rect: currentRect.animate(animation),
Hixie's avatar
Hixie committed
262
      child: new RotationTransition(
263
        turns: currentTurns.animate(animation),
Hixie's avatar
Hixie committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        child: new KeyedSubtree(
          key: key,
          child: child
        )
      )
    );
  }
}

class _HeroMatch {
  const _HeroMatch(this.from, this.to, this.tag);
  final HeroHandle from;
  final HeroHandle to;
  final Object tag;
}

class HeroParty {
  HeroParty({ this.onQuestFinished });

283
  final VoidCallback onQuestFinished;
Hixie's avatar
Hixie committed
284 285 286 287 288 289 290 291 292 293 294 295

  List<_HeroQuestState> _heroes = <_HeroQuestState>[];
  bool get isEmpty => _heroes.isEmpty;

  Map<Object, HeroHandle> getHeroesToAnimate() {
    Map<Object, HeroHandle> result = new Map<Object, HeroHandle>();
    for (_HeroQuestState hero in _heroes)
      result[hero.tag] = hero;
    assert(!result.containsKey(null));
    return result;
  }

296 297
  RelativeRectTween createRectTween(RelativeRect begin, RelativeRect end) {
    return new RelativeRectTween(begin: begin, end: end);
Hixie's avatar
Hixie committed
298 299
  }

300
  Tween<double> createTurnsTween(double begin, double end) {
Hixie's avatar
Hixie committed
301
    assert(end.floor() == end);
302
    return new Tween<double>(begin: begin, end: end);
Hixie's avatar
Hixie committed
303 304
  }

305
  void animate(Map<Object, HeroHandle> heroesFrom, Map<Object, HeroHandle> heroesTo, Rect animationArea) {
Hixie's avatar
Hixie committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    assert(!heroesFrom.containsKey(null));
    assert(!heroesTo.containsKey(null));

    // make a list of pairs of heroes, based on the from and to lists
    Map<Object, _HeroMatch> heroes = <Object, _HeroMatch>{};
    for (Object tag in heroesFrom.keys)
      heroes[tag] = new _HeroMatch(heroesFrom[tag], heroesTo[tag], tag);
    for (Object tag in heroesTo.keys) {
      if (!heroes.containsKey(tag))
        heroes[tag] = new _HeroMatch(heroesFrom[tag], heroesTo[tag], tag);
    }

    // create a heroating hero out of each pair
    final List<_HeroQuestState> _newHeroes = <_HeroQuestState>[];
    for (_HeroMatch heroPair in heroes.values) {
      assert(heroPair.from != null || heroPair.to != null);
322 323 324
      if ((heroPair.from == null && !heroPair.to.alwaysAnimate) ||
          (heroPair.to == null && !heroPair.from.alwaysAnimate))
        continue;
325
      _HeroManifest from = heroPair.from?._takeChild(animationArea, _currentAnimation);
Hixie's avatar
Hixie committed
326
      assert(heroPair.to == null || heroPair.to is HeroState);
327
      _HeroManifest to = heroPair.to?._takeChild(animationArea, _currentAnimation);
Hixie's avatar
Hixie committed
328 329 330 331
      assert(from != null || to != null);
      assert(to == null || to.sourceStates.length == 1);
      assert(to == null || to.currentTurns.floor() == to.currentTurns);
      HeroState targetState = to != null ? to.sourceStates.elementAt(0) : null;
332
      Set<HeroState> sourceStates = from != null ? from.sourceStates : new HashSet<HeroState>();
Hixie's avatar
Hixie committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
      sourceStates.remove(targetState);
      RelativeRect sourceRect = from != null ? from.currentRect :
        new RelativeRect.fromRect(to.currentRect.toRect(animationArea).center & Size.zero, animationArea);
      RelativeRect targetRect = to != null ? to.currentRect :
        new RelativeRect.fromRect(from.currentRect.toRect(animationArea).center & Size.zero, animationArea);
      double sourceTurns = from != null ? from.currentTurns : 0.0;
      double targetTurns = to != null ? to.currentTurns : 0.0;
      _newHeroes.add(new _HeroQuestState(
        tag: heroPair.tag,
        key: from != null ? from.key : to.key,
        child: to != null ? to.config : from.config,
        sourceStates: sourceStates,
        targetRect: targetRect,
        targetTurns: targetTurns.floor(),
        targetState: targetState,
348 349
        currentRect: createRectTween(sourceRect, targetRect),
        currentTurns: createTurnsTween(sourceTurns, targetTurns)
Hixie's avatar
Hixie committed
350 351 352 353 354 355 356
      ));
    }

    assert(!_heroes.any((_HeroQuestState hero) => !hero.taken));
    _heroes = _newHeroes;
  }

357
  Animation<double> _currentAnimation;
Hixie's avatar
Hixie committed
358

359
  void _clearCurrentAnimation() {
360 361
    _currentAnimation?.removeStatusListener(_handleUpdate);
    _currentAnimation = null;
362 363
  }

364
  void setAnimation(Animation<double> animation) {
365 366
    assert(animation != null || _heroes.length == 0);
    if (animation != _currentAnimation) {
367
      _clearCurrentAnimation();
368 369
      _currentAnimation = animation;
      _currentAnimation?.addStatusListener(_handleUpdate);
Hixie's avatar
Hixie committed
370 371 372
    }
  }

373 374 375
  void _handleUpdate(AnimationStatus status) {
    if (status == AnimationStatus.completed ||
        status == AnimationStatus.dismissed) {
Hixie's avatar
Hixie committed
376 377 378 379 380 381 382
      for (_HeroQuestState hero in _heroes) {
        if (hero.targetState != null)
          hero.targetState._setChild(hero.key);
        for (HeroState source in hero.sourceStates)
          source._resetChild();
      }
      _heroes.clear();
383
      _clearCurrentAnimation();
384 385
      if (onQuestFinished != null)
        onQuestFinished();
Hixie's avatar
Hixie committed
386 387 388 389 390
    }
  }

  String toString() => '$_heroes';
}
391 392 393 394 395 396 397

class HeroController extends NavigatorObserver {
  HeroController() {
    _party = new HeroParty(onQuestFinished: _handleQuestFinished);
  }

  HeroParty _party;
398
  Animation<double> _animation;
399 400
  PageRoute<dynamic> _from;
  PageRoute<dynamic> _to;
401 402 403

  final List<OverlayEntry> _overlayEntries = new List<OverlayEntry>();

404
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
405 406
    assert(navigator != null);
    assert(route != null);
407
    if (route is PageRoute<dynamic>) {
408
      assert(route.animation != null);
409
      if (previousRoute is PageRoute<dynamic>) // could be null
410 411
        _from = previousRoute;
      _to = route;
412
      _animation = route.animation;
413 414 415 416
      _checkForHeroQuest();
    }
  }

417
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
418 419
    assert(navigator != null);
    assert(route != null);
420
    if (route is PageRoute<dynamic>) {
421
      assert(route.animation != null);
422
      if (previousRoute is PageRoute<dynamic>) {
423 424
        _to = previousRoute;
        _from = route;
425
        _animation = route.animation;
426 427 428 429 430 431 432
        _checkForHeroQuest();
      }
    }
  }

  void _checkForHeroQuest() {
    if (_from != null && _to != null && _from != _to) {
433
      _to.offstage = _to.animation.status != AnimationStatus.completed;
Ian Hickson's avatar
Ian Hickson committed
434
      Scheduler.instance.addPostFrameCallback(_updateQuest);
435 436 437 438 439 440 441
    }
  }

  void _handleQuestFinished() {
    _removeHeroesFromOverlay();
    _from = null;
    _to = null;
442
    _animation = null;
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
  }

  Rect _getAnimationArea(BuildContext context) {
    RenderBox box = context.findRenderObject();
    Point topLeft = box.localToGlobal(Point.origin);
    Point bottomRight = box.localToGlobal(box.size.bottomRight(Point.origin));
    return new Rect.fromLTRB(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
  }

  void _removeHeroesFromOverlay() {
    for (OverlayEntry entry in _overlayEntries)
      entry.remove();
    _overlayEntries.clear();
  }

458 459
  void _addHeroToOverlay(Widget hero, Object tag, OverlayState overlay) {
    OverlayEntry entry = new OverlayEntry(builder: (_) => hero);
Adam Barth's avatar
Adam Barth committed
460 461
    assert(_animation.status != AnimationStatus.dismissed && _animation.status != AnimationStatus.completed);
    if (_animation.status == AnimationStatus.forward)
462 463 464 465
      _to.insertHeroOverlayEntry(entry, tag, overlay);
    else
      _from.insertHeroOverlayEntry(entry, tag, overlay);
    _overlayEntries.add(entry);
466 467 468 469 470
  }

  Set<Key> _getMostValuableKeys() {
    assert(_from != null);
    assert(_to != null);
471
    Set<Key> result = new HashSet<Key>();
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    if (_from.settings.mostValuableKeys != null)
      result.addAll(_from.settings.mostValuableKeys);
    if (_to.settings.mostValuableKeys != null)
      result.addAll(_to.settings.mostValuableKeys);
    return result;
  }

  void _updateQuest(Duration timeStamp) {
    Set<Key> mostValuableKeys = _getMostValuableKeys();
    Map<Object, HeroHandle> heroesFrom = _party.isEmpty ?
        Hero.of(_from.subtreeContext, mostValuableKeys) : _party.getHeroesToAnimate();

    Map<Object, HeroHandle> heroesTo = Hero.of(_to.subtreeContext, mostValuableKeys);
    _to.offstage = false;

487
    Animation<double> animation = _animation;
488
    Curve curve = Curves.ease;
489
    if (animation.status == AnimationStatus.reverse) {
490 491
      animation = new ReverseAnimation(animation);
      curve = new Interval(animation.value, 1.0, curve: curve);
492 493
    }

494
    _party.animate(heroesFrom, heroesTo, _getAnimationArea(navigator.context));
495
    _removeHeroesFromOverlay();
496 497 498 499
    _party.setAnimation(new CurvedAnimation(
      parent: animation,
      curve: curve
    ));
500
    for (_HeroQuestState hero in _party._heroes) {
501
      Widget widget = hero.build(navigator.context, animation);
502 503
      _addHeroToOverlay(widget, hero.tag, navigator.overlay);
    }
504 505
  }
}