material.dart 13.7 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:math' as math;

7
import 'package:flutter/animation.dart';
8 9
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
10
import 'package:flutter/widgets.dart';
11
import 'package:vector_math/vector_math_64.dart';
12

13 14
import 'constants.dart';
import 'shadows.dart';
15
import 'theme.dart';
16

17 18 19 20 21 22
enum MaterialType {
  /// Infinite extent using default theme canvas color.
  canvas,

  /// Rounded edges, card theme color.
  card,
23

24 25 26 27
  /// A circle, no color by default (used for floating action buttons).
  circle,

  /// Rounded edges, no color by default (used for MaterialButton buttons).
28 29 30 31
  button,

  /// A transparent piece of material that draws ink splashes and highlights.
  transparency
32 33 34
}

const Map<MaterialType, double> kMaterialEdges = const <MaterialType, double>{
35 36 37 38
  MaterialType.canvas: null,
  MaterialType.card: 2.0,
  MaterialType.circle: null,
  MaterialType.button: 2.0,
39
  MaterialType.transparency: null,
40 41
};

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
abstract class InkSplash {
  void confirm();
  void cancel();
  void dispose();
}

abstract class InkHighlight {
  void activate();
  void deactivate();
  void dispose();
  bool get active;
  Color get color;
  void set color(Color value);
}

abstract class MaterialInkController {
  /// The color of the material
  Color get color;

  /// Begin a splash, centered at position relative to referenceBox.
  /// If containedInWell is true, then the splash will be sized to fit
  /// the referenceBox, then clipped to it when drawn.
  /// When the splash is removed, onRemoved will be invoked.
65
  InkSplash splashAt({ RenderBox referenceBox, Point position, Color color, bool containedInWell, VoidCallback onRemoved });
66 67

  /// Begin a highlight, coincident with the referenceBox.
68
  InkHighlight highlightAt({ RenderBox referenceBox, Color color, BoxShape shape: BoxShape.rectangle, VoidCallback onRemoved });
69 70 71 72 73 74 75 76 77 78

  /// Add an arbitrary InkFeature to this InkController.
  void addInkFeature(InkFeature feature);
}

/// Describes a sheet of Material. If the layout changes (e.g. because there's a
/// list on the paper, and it's been scrolled), a LayoutChangedNotification must
/// be dispatched at the relevant subtree. (This in particular means that
/// Transitions should not be placed inside Material.)
class Material extends StatefulComponent {
79
  Material({
80
    Key key,
81
    this.child,
82
    this.type: MaterialType.canvas,
Hans Muller's avatar
Hans Muller committed
83
    this.elevation: 0,
84 85
    this.color,
    this.textStyle
86
  }) : super(key: key) {
Hans Muller's avatar
Hans Muller committed
87
    assert(elevation != null);
88 89
  }

90 91
  final Widget child;
  final MaterialType type;
Hans Muller's avatar
Hans Muller committed
92
  final int elevation;
93
  final Color color;
94
  final TextStyle textStyle;
95

96
  /// The ink controller from the closest instance of this class that encloses the given context.
97 98 99 100 101 102 103 104 105 106 107
  static MaterialInkController of(BuildContext context) {
    final RenderInkFeatures result = context.ancestorRenderObjectOfType(RenderInkFeatures);
    return result;
  }

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

class _MaterialState extends State<Material> {
  final GlobalKey _inkFeatureRenderer = new GlobalKey(debugLabel: 'ink renderer');

108
  Color _getBackgroundColor(BuildContext context) {
109 110 111
    if (config.color != null)
      return config.color;
    switch (config.type) {
112
      case MaterialType.canvas:
113
        return Theme.of(context).canvasColor;
114
      case MaterialType.card:
115
        return Theme.of(context).cardColor;
116 117
      default:
        return null;
118 119 120
    }
  }

121
  Widget build(BuildContext context) {
122 123 124
    Color backgroundColor = _getBackgroundColor(context);
    Widget contents = config.child;
    if (contents != null) {
125
      contents = new DefaultTextStyle(
126
        style: config.textStyle ?? Theme.of(context).text.body1,
127 128 129
        child: contents
      );
    }
130 131 132 133 134 135 136
    contents = new NotificationListener<LayoutChangedNotification>(
      onNotification: (LayoutChangedNotification notification) {
        _inkFeatureRenderer.currentContext.findRenderObject().markNeedsPaint();
      },
      child: new InkFeatures(
        key: _inkFeatureRenderer,
        color: backgroundColor,
137 138
        child: contents
      )
139
    );
140 141 142 143 144 145 146 147 148
    if (config.type == MaterialType.circle) {
      contents = new ClipOval(child: contents);
    } else if (kMaterialEdges[config.type] != null) {
      contents = new ClipRRect(
        xRadius: kMaterialEdges[config.type],
        yRadius: kMaterialEdges[config.type],
        child: contents
      );
    }
149 150 151 152 153 154 155 156
    if (config.type != MaterialType.transparency) {
      contents = new AnimatedContainer(
        curve: Curves.ease,
        duration: kThemeChangeDuration,
        decoration: new BoxDecoration(
          backgroundColor: backgroundColor,
          borderRadius: kMaterialEdges[config.type],
          boxShadow: config.elevation == 0 ? null : elevationToShadow[config.elevation],
157
          shape: config.type == MaterialType.circle ? BoxShape.circle : BoxShape.rectangle
158 159 160 161
        ),
        child: contents
      );
    }
162 163 164 165
    return contents;
  }
}

166 167
const Duration _kHighlightFadeDuration = const Duration(milliseconds: 200);
const Duration _kUnconfirmedSplashDuration = const Duration(seconds: 1);
168 169

const double _kDefaultSplashRadius = 35.0; // logical pixels
170
const double _kSplashConfirmedVelocity = 1.0; // logical pixels per millisecond
171 172 173 174 175 176 177 178 179 180 181 182
const double _kSplashInitialSize = 0.0; // logical pixels

class RenderInkFeatures extends RenderProxyBox implements MaterialInkController {
  RenderInkFeatures({ RenderBox child, this.color }) : super(child);

  // This is here to satisfy the MaterialInkController contract.
  // The actual painting of this color is done by a Container in the
  // MaterialState build method.
  Color color;

  final List<InkFeature> _inkFeatures = <InkFeature>[];

183 184 185 186 187 188 189
  InkSplash splashAt({
    RenderBox referenceBox,
    Point position,
    Color color,
    bool containedInWell,
    VoidCallback onRemoved
  }) {
190 191 192 193 194 195 196 197 198 199
    double radius;
    if (containedInWell) {
      radius = _getSplashTargetSize(referenceBox.size, position);
    } else {
      radius = _kDefaultSplashRadius;
    }
    _InkSplash splash = new _InkSplash(
      renderer: this,
      referenceBox: referenceBox,
      position: position,
200
      color: color,
201 202
      targetRadius: radius,
      clipToReferenceBox: containedInWell,
203
      repositionToReferenceBox: !containedInWell,
204 205 206 207 208 209 210 211 212 213 214 215 216 217
      onRemoved: onRemoved
    );
    addInkFeature(splash);
    return splash;
  }

  double _getSplashTargetSize(Size bounds, Point position) {
    double d1 = (position - bounds.topLeft(Point.origin)).distance;
    double d2 = (position - bounds.topRight(Point.origin)).distance;
    double d3 = (position - bounds.bottomLeft(Point.origin)).distance;
    double d4 = (position - bounds.bottomRight(Point.origin)).distance;
    return math.max(math.max(d1, d2), math.max(d3, d4)).ceilToDouble();
  }

218 219 220
  InkHighlight highlightAt({
    RenderBox referenceBox,
    Color color,
221
    BoxShape shape: BoxShape.rectangle,
222 223
    VoidCallback onRemoved
  }) {
224 225 226 227
    _InkHighlight highlight = new _InkHighlight(
      renderer: this,
      referenceBox: referenceBox,
      color: color,
228
      shape: shape,
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
      onRemoved: onRemoved
    );
    addInkFeature(highlight);
    return highlight;
  }

  void addInkFeature(InkFeature feature) {
    assert(!feature._debugDisposed);
    assert(feature.renderer == this);
    assert(!_inkFeatures.contains(feature));
    _inkFeatures.add(feature);
    markNeedsPaint();
  }

  void _removeFeature(InkFeature feature) {
    _inkFeatures.remove(feature);
    markNeedsPaint();
  }

  bool hitTestSelf(Point position) => true;

  void paint(PaintingContext context, Offset offset) {
    if (_inkFeatures.isNotEmpty) {
      final Canvas canvas = context.canvas;
      canvas.save();
      canvas.translate(offset.dx, offset.dy);
      canvas.clipRect(Point.origin & size);
      for (InkFeature inkFeature in _inkFeatures)
        inkFeature._paint(canvas);
      canvas.restore();
    }
    super.paint(context, offset);
  }
}

class InkFeatures extends OneChildRenderObjectWidget {
  InkFeatures({ Key key, this.color, Widget child }) : super(key: key, child: child);

  final Color color;

  RenderInkFeatures createRenderObject() => new RenderInkFeatures(color: color);

  void updateRenderObject(RenderInkFeatures renderObject, InkFeatures oldWidget) {
    renderObject.color = color;
  }
}

abstract class InkFeature {
  InkFeature({
    this.renderer,
    this.referenceBox,
    this.onRemoved
  });

  final RenderInkFeatures renderer;
  final RenderBox referenceBox;
  final VoidCallback onRemoved;

  bool _debugDisposed = false;

  void dispose() {
    assert(!_debugDisposed);
    assert(() { _debugDisposed = true; return true; });
    renderer._removeFeature(this);
    if (onRemoved != null)
      onRemoved();
  }

  void _paint(Canvas canvas) {
    assert(referenceBox.attached);
    assert(!_debugDisposed);
    // find the chain of renderers from us to the feature's referenceBox
301
    List<RenderBox> descendants = <RenderBox>[referenceBox];
302 303 304 305
    RenderBox node = referenceBox;
    while (node != renderer) {
      node = node.parent;
      assert(node != null);
306
      descendants.add(node);
307 308 309
    }
    // determine the transform that gets our coordinate system to be like theirs
    Matrix4 transform = new Matrix4.identity();
310 311 312
    assert(descendants.length >= 2);
    for (int index = descendants.length - 1; index > 0; index -= 1)
      descendants[index].applyPaintTransform(descendants[index - 1], transform);
313 314 315 316 317 318 319 320 321 322 323 324 325
    paintFeature(canvas, transform);
  }

  void paintFeature(Canvas canvas, Matrix4 transform);

  String toString() => "$runtimeType@$hashCode";
}

class _InkSplash extends InkFeature implements InkSplash {
  _InkSplash({
    RenderInkFeatures renderer,
    RenderBox referenceBox,
    this.position,
326
    this.color,
327 328
    this.targetRadius,
    this.clipToReferenceBox,
329
    this.repositionToReferenceBox,
330 331 332
    VoidCallback onRemoved
  }) : super(renderer: renderer, referenceBox: referenceBox, onRemoved: onRemoved) {
    _radius = new ValuePerformance<double>(
333 334 335
      variable: new AnimatedValue<double>(_kSplashInitialSize, end: targetRadius),
      duration: _kUnconfirmedSplashDuration
    )..addListener(renderer.markNeedsPaint)
336
     ..play();
337 338 339 340
    _alpha = new ValuePerformance<int>(
      variable: new AnimatedIntValue(color.alpha, end: 0),
      duration: _kHighlightFadeDuration
    )..addListener(_handleAlphaChange);
341
  }
342 343

  final Point position;
344
  final Color color;
345 346
  final double targetRadius;
  final bool clipToReferenceBox;
347
  final bool repositionToReferenceBox;
348 349

  ValuePerformance<double> _radius;
350
  ValuePerformance<int> _alpha;
351 352

  void confirm() {
353 354 355 356
    int duration = (targetRadius / _kSplashConfirmedVelocity).floor();
    _radius.duration = new Duration(milliseconds: duration);
    _radius.play();
    _alpha.play();
357 358 359
  }

  void cancel() {
360
    _alpha.play();
361 362
  }

363 364
  void _handleAlphaChange() {
    if (_alpha.value == _alpha.variable.end)
365 366 367 368 369 370 371
      dispose();
    else
      renderer.markNeedsPaint();
  }

  void dispose() {
    _radius.stop();
372
    _alpha.stop();
373 374 375 376
    super.dispose();
  }

  void paintFeature(Canvas canvas, Matrix4 transform) {
377 378
    Paint paint = new Paint()..color = color.withAlpha(_alpha.value);
    Point center = position;
379 380 381 382 383 384
    Offset originOffset = MatrixUtils.getAsTranslation(transform);
    if (originOffset == null) {
      canvas.save();
      canvas.concat(transform.storage);
      if (clipToReferenceBox)
        canvas.clipRect(Point.origin & referenceBox.size);
385 386 387
      if (repositionToReferenceBox)
        center = Point.lerp(center, Point.origin, _radius.progress);
      canvas.drawCircle(center, _radius.value, paint);
388 389 390 391 392 393
      canvas.restore();
    } else {
      if (clipToReferenceBox) {
        canvas.save();
        canvas.clipRect(originOffset.toPoint() & referenceBox.size);
      }
394 395 396
      if (repositionToReferenceBox)
        center = Point.lerp(center, referenceBox.size.center(Point.origin), _radius.progress);
      canvas.drawCircle(center + originOffset, _radius.value, paint);
397 398 399 400 401 402 403 404 405 406 407
      if (clipToReferenceBox)
        canvas.restore();
    }
  }
}

class _InkHighlight extends InkFeature implements InkHighlight {
  _InkHighlight({
    RenderInkFeatures renderer,
    RenderBox referenceBox,
    Color color,
408
    this.shape,
409 410 411 412
    VoidCallback onRemoved
  }) : _color = color,
       super(renderer: renderer, referenceBox: referenceBox, onRemoved: onRemoved) {
    _alpha = new ValuePerformance<int>(
413
      variable: new AnimatedIntValue(0, end: color.alpha),
414 415 416 417 418 419 420 421 422 423 424 425 426 427
      duration: _kHighlightFadeDuration
    )..addListener(_handleAlphaChange)
     ..play();
  }

  Color get color => _color;
  Color _color;
  void set color(Color value) {
    if (value == _color)
      return;
    _color = value;
    renderer.markNeedsPaint();
  }

428
  final BoxShape shape;
429

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  bool get active => _active;
  bool _active = true;
  ValuePerformance<int> _alpha;

  void activate() {
    _active = true;
    _alpha.forward();
  }

  void deactivate() {
    _active = false;
    _alpha.reverse();
  }

  void _handleAlphaChange() {
    if (_alpha.value == 0.0 && !_active)
      dispose();
    else
      renderer.markNeedsPaint();
  }

  void dispose() {
    _alpha.stop();
    super.dispose();
  }

456
  void _paintHighlight(Canvas canvas, Rect rect, paint) {
457
    if (shape == BoxShape.rectangle)
458 459 460 461 462
      canvas.drawRect(rect, paint);
    else
      canvas.drawCircle(rect.center, _kDefaultSplashRadius, paint);
  }

463 464 465 466 467 468
  void paintFeature(Canvas canvas, Matrix4 transform) {
    Paint paint = new Paint()..color = color.withAlpha(_alpha.value);
    Offset originOffset = MatrixUtils.getAsTranslation(transform);
    if (originOffset == null) {
      canvas.save();
      canvas.concat(transform.storage);
469
      _paintHighlight(canvas, Point.origin & referenceBox.size, paint);
470 471
      canvas.restore();
    } else {
472
      _paintHighlight(canvas, originOffset.toPoint() & referenceBox.size, paint);
473 474 475
    }
  }

476
}