mimic.dart 7.58 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 'dart:async';

7
import 'package:flutter/rendering.dart' show RenderStack;
8 9 10

import 'basic.dart';
import 'framework.dart';
11
import 'overlay.dart';
12

13 14 15
/// An opaque reference to a widget that can be mimicked.
class MimicableHandle {
  MimicableHandle._(this._state);
16

17
  final MimicableState _state;
18

19
  /// The size and position of the original widget in global coordinates.
20
  Rect get globalBounds => _state._globalBounds;
21

22
  /// Stop the mimicking process, restoring the widget to its original location in the tree.
23 24
  void stopMimic() {
    _state._stopMimic();
25
  }
26
}
27

28
/// An overlay entry that is mimicking another widget.
29
class MimicOverlayEntry {
Hixie's avatar
Hixie committed
30
  MimicOverlayEntry._(this._handle) {
31
    _overlayEntry = new OverlayEntry(builder: _build);
Hixie's avatar
Hixie committed
32
    _initialGlobalBounds = _handle.globalBounds;
33 34 35 36
  }

  Rect _initialGlobalBounds;

Hixie's avatar
Hixie committed
37
  MimicableHandle _handle;
38 39 40 41 42
  OverlayEntry _overlayEntry;

  // Animation state
  GlobalKey _targetKey;
  Curve _curve;
43
  AnimationController _controller;
44

45 46 47 48 49
  /// Animate the entry to the location of the widget that has the given target key.
  ///
  /// The animation will take place over the given duration and will apply the
  /// given curve.
  ///
50
  /// This function can only be called once per overlay entry.
51
  Future<Null> animateTo({
52 53 54 55
    GlobalKey targetKey,
    Duration duration,
    Curve curve: Curves.linear
  }) {
Hixie's avatar
Hixie committed
56
    assert(_handle != null);
57 58 59 60 61 62 63
    assert(_overlayEntry != null);
    assert(targetKey != null);
    assert(duration != null);
    assert(curve != null);
    _targetKey = targetKey;
    _curve = curve;
    // TODO(abarth): Support changing the animation target when in flight.
64 65
    assert(_controller == null);
    _controller = new AnimationController(duration: duration)
66
      ..addListener(_overlayEntry.markNeedsBuild);
67
    return _controller.forward();
68 69
  }

70 71 72 73 74
  /// Cause the overlay entry to rebuild during the next pipeline flush.
  ///
  /// You need to call this function if you rebuild the widget that this entry
  /// is mimicking in order for the overlay entry to pick up the changes that
  /// you've made to the [Mimicable].
75 76 77 78
  void markNeedsBuild() {
   _overlayEntry?.markNeedsBuild();
 }

79 80 81
  /// Remove this entry from the overlay and restore the widget to its original place in the tree.
  ///
  /// Once removed, the overlay entry cannot be used further.
82 83 84
  void dispose() {
    _targetKey = null;
    _curve = null;
85 86
    _controller?.stop();
    _controller = null;
Hixie's avatar
Hixie committed
87 88
    _handle.stopMimic();
    _handle = null;
89 90 91 92 93
    _overlayEntry.remove();
    _overlayEntry = null;
  }

  Widget _build(BuildContext context) {
Hixie's avatar
Hixie committed
94
    assert(_handle != null);
95 96 97 98
    assert(_overlayEntry != null);
    Rect globalBounds = _initialGlobalBounds;
    Point globalPosition = globalBounds.topLeft;
    if (_targetKey != null) {
99
      assert(_controller != null);
100 101 102 103 104
      assert(_curve != null);
      RenderBox box = _targetKey.currentContext?.findRenderObject();
      if (box != null) {
        // TODO(abarth): Handle the case where the transform here isn't just a translation.
        Point localPosition = box.localToGlobal(Point.origin);
105 106
        double t = _curve.transform(_controller.value);
        globalPosition = Point.lerp(globalPosition, localPosition, t);
107 108 109
      }
    }

Ian Hickson's avatar
Ian Hickson committed
110
    RenderBox stack = context.ancestorRenderObjectOfType(const TypeMatcher<RenderStack>());
111
    // TODO(abarth): Handle the case where the transform here isn't just a translation.
112 113 114
    // TODO(ianh): We should probably be getting the overlay's render object rather than looking for a RenderStack.
    assert(stack != null);
    Point localPosition = stack.globalToLocal(globalPosition);
115 116 117 118 119
    return new Positioned(
      left: localPosition.x,
      top: localPosition.y,
      width: globalBounds.width,
      height: globalBounds.height,
Hixie's avatar
Hixie committed
120
      child: new Mimic(original: _handle)
121 122 123 124
    );
  }
}

125
/// A widget that copies the appearance of another widget.
126
class Mimic extends StatelessWidget {
127
  Mimic({ Key key, this.original }) : super(key: key);
128

129 130
  /// A handle to the widget that this widget should copy.
  final MimicableHandle original;
131

132
  @override
133
  Widget build(BuildContext context) {
Hixie's avatar
Hixie committed
134
    if (original != null && original._state.mounted && original._state._placeholderSize != null)
135 136
      return original._state.config.child;
    return new Container();
137 138 139
  }
}

140
/// A widget that can be copied by a [Mimic].
141 142 143
///
/// This widget's State, [MimicableState], contains an API for initiating the
/// mimic operation.
144
class Mimicable extends StatefulWidget {
145
  Mimicable({ Key key, this.child }) : super(key: key);
146

147
  /// The widget below this widget in the tree.
148
  final Widget child;
149

150
  @override
151
  MimicableState createState() => new MimicableState();
152
}
153

154 155 156
/// The state for a [Mimicable].
///
/// Exposes an API for starting and stopping mimicking.
157
class MimicableState extends State<Mimicable> {
Hixie's avatar
Hixie committed
158 159 160 161 162 163 164 165 166 167 168
  Size _placeholderSize;

  Rect get _globalBounds {
    assert(mounted);
    RenderBox box = context.findRenderObject();
    assert(box != null);
    assert(box.hasSize);
    assert(!box.needsLayout);
    // TODO(abarth): The bounds will be wrong if there's a scale or rotation transform involved
    return box.localToGlobal(Point.origin) & box.size;
  }
169

170 171
  /// Start the mimicking process.
  ///
Hixie's avatar
Hixie committed
172 173 174 175 176 177 178 179 180
  /// The child of this object will no longer be built at this
  /// location in the tree. Instead, this widget will build a
  /// transparent placeholder with the same dimensions as the widget
  /// had when the mimicking process started.
  ///
  /// If you use startMimic(), it is your responsibility to do
  /// something with the returned [MimicableHandle]; typically,
  /// passing it to a [Mimic] widget. To mimic the child in the
  /// [Overlay], consider using [liftToOverlay()] instead.
181
  MimicableHandle startMimic() {
182 183
    assert(() {
      if (_placeholderSize != null) {
184
        throw new FlutterError(
185 186 187 188 189 190 191 192 193
          'Mimicable started while already active.\n'
          'When startMimic() or liftToOverlay() is called on a MimicableState, the mimic becomes active. '
          'While active, it cannot be reactivated until it is stopped. '
          'To stop a Mimicable started with startMimic(), call the MimicableHandle object\'s stopMimic() method. '
          'To stop a Mimicable started with liftToOverlay(), call dispose() on the MimicOverlayEntry.'
        );
      }
      return true;
    });
Hixie's avatar
Hixie committed
194 195 196 197
    RenderBox box = context.findRenderObject();
    assert(box != null);
    assert(box.hasSize);
    assert(!box.needsLayout);
198
    setState(() {
Hixie's avatar
Hixie committed
199
      _placeholderSize = box.size;
200
    });
201
    return new MimicableHandle._(this);
202 203
  }

Hixie's avatar
Hixie committed
204 205
  /// Start the mimicking process and mimic this object in the
  /// enclosing [Overlay].
206
  ///
Hixie's avatar
Hixie committed
207 208 209 210 211
  /// The child of this object will no longer be built at this
  /// location in the tree. Instead, (1) this widget will build a
  /// transparent placeholder with the same dimensions as the widget
  /// had when the mimicking process started and (2) the child will be
  /// placed in the enclosing overlay.
212
  MimicOverlayEntry liftToOverlay() {
213
    OverlayState overlay = Overlay.of(context, debugRequiredFor: config);
214 215 216 217 218
    MimicOverlayEntry entry = new MimicOverlayEntry._(startMimic());
    overlay.insert(entry._overlayEntry);
    return entry;
  }

219
  void _stopMimic() {
Hixie's avatar
Hixie committed
220 221 222 223 224
    assert(_placeholderSize != null);
    if (mounted) {
      setState(() {
        _placeholderSize = null;
      });
225
    }
226 227
  }

228
  @override
229
  Widget build(BuildContext context) {
Hixie's avatar
Hixie committed
230
    if (_placeholderSize != null) {
231
      return new ConstrainedBox(
Hixie's avatar
Hixie committed
232
        constraints: new BoxConstraints.tight(_placeholderSize)
233
      );
234
    }
Hixie's avatar
Hixie committed
235
    return config.child;
236 237
  }
}