mergeable_material.dart 20.9 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:ui' show lerpDouble;

7
import 'package:flutter/foundation.dart';
8 9 10 11 12 13
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

/// The base type for [MaterialSlice] and [MaterialGap].
///
/// All [MergeableMaterialItem] objects need a [LocalKey].
14
@immutable
15
abstract class MergeableMaterialItem {
16 17 18 19
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  ///
  /// The argument is the [key], which must not be null.
20
  const MergeableMaterialItem(this.key) : assert(key != null);
21 22 23 24 25 26

  /// The key for this item of the list.
  ///
  /// The key is used to match parts of the mergeable material from frame to
  /// frame so that state is maintained appropriately even as slices are added
  /// or removed.
27 28 29 30 31 32 33 34 35 36
  final LocalKey key;
}

/// A class that can be used as a child to [MergeableMaterial]. It is a slice
/// of [Material] that animates merging with other slices.
///
/// All [MaterialSlice] objects need a [LocalKey].
class MaterialSlice extends MergeableMaterialItem {
  /// Creates a slice of [Material] that's mergeable within a
  /// [MergeableMaterial].
37
  const MaterialSlice({
38
    @required LocalKey key,
39
    @required this.child,
40 41
  }) : assert(key != null),
       super(key);
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

  /// The contents of this slice.
  final Widget child;

  @override
  String toString() {
    return 'MergeableSlice(key: $key, child: $child)';
  }
}

/// A class that represents a gap within [MergeableMaterial].
///
/// All [MaterialGap] objects need a [LocalKey].
class MaterialGap extends MergeableMaterialItem {
  /// Creates a Material gap with a given size.
57
  const MaterialGap({
58 59
    @required LocalKey key,
    this.size: 16.0
60 61
  }) : assert(key != null),
       super(key);
62

63
  /// The main axis extent of this gap. For example, if the [MergeableMaterial]
64 65 66 67 68 69 70 71 72 73 74 75
  /// is vertical, then this is the height of the gap.
  final double size;

  @override
  String toString() {
    return 'MaterialGap(key: $key, child: $size)';
  }
}

/// Displays a list of [MergeableMaterialItem] children. The list contains
/// [MaterialSlice] items whose boundaries are either "merged" with adjacent
/// items or separated by a [MaterialGap]. The [children] are distributed along
76
/// the given [mainAxis] in the same way as the children of a [ListBody]. When
77 78 79 80 81 82 83 84 85 86 87 88
/// the list of children changes, gaps are automatically animated open or closed
/// as needed.
///
/// To enable this widget to correlate its list of children with the previous
/// one, each child must specify a key.
///
/// When a new gap is added to the list of children the adjacent items are
/// animated apart. Similarly when a gap is removed the adjacent items are
/// brought back together.
///
/// When a new slice is added or removed, the app is responsible for animating
/// the transition of the slices, while the gaps will be animated automatically.
89 90 91 92 93
///
/// See also:
///
///  * [Card], a piece of material that does not support splitting and merging
///    but otherwise looks the same.
94 95
class MergeableMaterial extends StatefulWidget {
  /// Creates a mergeable Material list of items.
96
  const MergeableMaterial({
97 98 99
    Key key,
    this.mainAxis: Axis.vertical,
    this.elevation: 2,
100
    this.hasDividers: false,
101 102 103 104 105 106 107 108 109
    this.children: const <MergeableMaterialItem>[]
  }) : super(key: key);

  /// The children of the [MergeableMaterial].
  final List<MergeableMaterialItem> children;

  /// The main layout axis.
  final Axis mainAxis;

110 111 112 113 114
  /// The z-coordinate at which to place all the [Material] slices.
  ///
  /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, 16, 24
  ///
  /// Defaults to 2, the appropriate elevation for cards.
115 116
  final int elevation;

117 118 119
  /// Whether connected pieces of [MaterialSlice] have dividers between them.
  final bool hasDividers;

120 121 122
  @override
  String toString() {
    return 'MergeableMaterial('
123
      'key: $key, mainAxis: $mainAxis, elevation: ${elevation.toStringAsFixed(1)}'
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    ')';
  }

  @override
  _MergeableMaterialState createState() => new _MergeableMaterialState();
}

class _AnimationTuple {
  _AnimationTuple({
    this.controller,
    this.startAnimation,
    this.endAnimation,
    this.gapAnimation,
    this.gapStart: 0.0
  });

  final AnimationController controller;
  final CurvedAnimation startAnimation;
  final CurvedAnimation endAnimation;
  final CurvedAnimation gapAnimation;
  double gapStart;
}

147
class _MergeableMaterialState extends State<MergeableMaterial> with TickerProviderStateMixin {
148 149
  List<MergeableMaterialItem> _children;
  final Map<LocalKey, _AnimationTuple> _animationTuples =
150
      <LocalKey, _AnimationTuple>{};
151 152 153 154

  @override
  void initState() {
    super.initState();
155
    _children = new List<MergeableMaterialItem>.from(widget.children);
156 157 158 159 160 161 162 163 164 165 166 167

    for (int i = 0; i < _children.length; i += 1) {
      if (_children[i] is MaterialGap) {
        _initGap(_children[i]);
        _animationTuples[_children[i].key].controller.value = 1.0; // Gaps are initially full-sized.
      }
    }
    assert(_debugGapsAreValid(_children));
  }

  void _initGap(MaterialGap gap) {
    final AnimationController controller = new AnimationController(
168 169
      duration: kThemeAnimationDuration,
      vsync: this,
170 171 172 173
    );

    final CurvedAnimation startAnimation = new CurvedAnimation(
      parent: controller,
174
      curve: Curves.fastOutSlowIn
175 176 177
    );
    final CurvedAnimation endAnimation = new CurvedAnimation(
      parent: controller,
178
      curve: Curves.fastOutSlowIn
179 180 181
    );
    final CurvedAnimation gapAnimation = new CurvedAnimation(
      parent: controller,
182
      curve: Curves.fastOutSlowIn
183 184
    );

185
    controller.addListener(_handleTick);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    _animationTuples[gap.key] = new _AnimationTuple(
      controller: controller,
      startAnimation: startAnimation,
      endAnimation: endAnimation,
      gapAnimation: gapAnimation
    );
  }

  @override
  void dispose() {
    for (MergeableMaterialItem child in _children) {
      if (child is MaterialGap)
        _animationTuples[child.key].controller.dispose();
    }
    super.dispose();
  }

  void _handleTick() {
    setState(() {
      // The animation's state is our build state, and it changed already.
    });
  }

  bool _debugHasConsecutiveGaps(List<MergeableMaterialItem> children) {
211 212 213
    for (int i = 0; i < widget.children.length - 1; i += 1) {
      if (widget.children[i] is MaterialGap &&
          widget.children[i + 1] is MaterialGap)
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        return true;
    }
    return false;
  }

  bool _debugGapsAreValid(List<MergeableMaterialItem> children) {
    // Check for consecutive gaps.
    if (_debugHasConsecutiveGaps(children))
      return false;

    // First and last children must not be gaps.
    if (children.isNotEmpty) {
      if (children.first is MaterialGap || children.last is MaterialGap)
        return false;
    }

    return true;
  }

  void _insertChild(int index, MergeableMaterialItem child) {
    _children.insert(index, child);

    if (child is MaterialGap)
      _initGap(child);
  }

  void _removeChild(int index) {
241
    final MergeableMaterialItem child = _children.removeAt(index);
242 243 244 245 246

    if (child is MaterialGap)
      _animationTuples[child.key] = null;
  }

247
  bool _isClosingGap(int index) {
248 249 250 251 252 253 254 255
    if (index < _children.length - 1 && _children[index] is MaterialGap) {
      return _animationTuples[_children[index].key].controller.status ==
          AnimationStatus.reverse;
    }

    return false;
  }

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
  void _removeEmptyGaps() {
    int j = 0;

    while (j < _children.length) {
      if (
        _children[j] is MaterialGap &&
        _animationTuples[_children[j].key].controller.status == AnimationStatus.dismissed
      ) {
        _removeChild(j);
      } else {
        j += 1;
      }
    }
  }

271
  @override
272 273
  void didUpdateWidget(MergeableMaterial oldWidget) {
    super.didUpdateWidget(oldWidget);
274

275
    final Set<LocalKey> oldKeys = oldWidget.children.map(
276 277
      (MergeableMaterialItem child) => child.key
    ).toSet();
278
    final Set<LocalKey> newKeys = widget.children.map(
279 280 281 282 283
      (MergeableMaterialItem child) => child.key
    ).toSet();
    final Set<LocalKey> newOnly = newKeys.difference(oldKeys);
    final Set<LocalKey> oldOnly = oldKeys.difference(newKeys);

284
    final List<MergeableMaterialItem> newChildren = widget.children;
285 286 287 288 289
    int i = 0;
    int j = 0;

    assert(_debugGapsAreValid(newChildren));

290
    _removeEmptyGaps();
291 292 293 294 295 296 297 298 299 300 301 302

    while (i < newChildren.length && j < _children.length) {
      if (newOnly.contains(newChildren[i].key) ||
          oldOnly.contains(_children[j].key)) {
        final int startNew = i;
        final int startOld = j;

        // Skip new keys.
        while (newOnly.contains(newChildren[i].key))
          i += 1;

        // Skip old keys.
303
        while (oldOnly.contains(_children[j].key) || _isClosingGap(j))
304 305 306 307 308 309 310 311 312 313 314 315 316 317
          j += 1;

        final int newLength = i - startNew;
        final int oldLength = j - startOld;

        if (newLength > 0) {
          if (oldLength > 1 ||
              oldLength == 1 && _children[startOld] is MaterialSlice) {
            if (newLength == 1 && newChildren[startNew] is MaterialGap) {
              // Shrink all gaps into the size of the new one.
              double gapSizeSum = 0.0;

              while (startOld < j) {
                if (_children[startOld] is MaterialGap) {
318
                  final MaterialGap gap = _children[startOld];
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
                  gapSizeSum += gap.size;
                }

                _removeChild(startOld);
                j -= 1;
              }

              _insertChild(startOld, newChildren[startNew]);
              _animationTuples[newChildren[startNew].key]
                ..gapStart = gapSizeSum
                ..controller.forward();

              j += 1;
            } else {
              // No animation if replaced items are more than one.
              for (int k = 0; k < oldLength; k += 1)
                _removeChild(startOld);
              for (int k = 0; k < newLength; k += 1)
                _insertChild(startOld + k, newChildren[startNew + k]);

              j += newLength - oldLength;
            }
          } else if (oldLength == 1) {
            if (newLength == 1 && newChildren[startNew] is MaterialGap &&
                _children[startOld].key == newChildren[startNew].key) {
              /// Special case: gap added back.
              _animationTuples[newChildren[startNew].key].controller.forward();
            } else {
              final double gapSize = _getGapSize(startOld);

              _removeChild(startOld);

              for (int k = 0; k < newLength; k += 1)
                _insertChild(startOld + k, newChildren[startNew + k]);

              j += newLength - 1;
              double gapSizeSum = 0.0;

              for (int k = startNew; k < i; k += 1) {
                if (newChildren[k] is MaterialGap) {
359
                  final MaterialGap gap = newChildren[k];
360 361 362 363 364 365 366 367
                  gapSizeSum += gap.size;
                }
              }

              // All gaps get proportional sizes of the original gap and they will
              // animate to their actual size.
              for (int k = startNew; k < i; k += 1) {
                if (newChildren[k] is MaterialGap) {
368
                  final MaterialGap gap = newChildren[k];
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

                  _animationTuples[gap.key].gapStart = gapSize * gap.size /
                      gapSizeSum;
                  _animationTuples[gap.key].controller
                    ..value = 0.0
                    ..forward();
                }
              }
            }
          } else {
            // Grow gaps.
            for (int k = 0; k < newLength; k += 1) {
              _insertChild(startOld + k, newChildren[startNew + k]);

              if (newChildren[startNew + k] is MaterialGap) {
384
                final MaterialGap gap = newChildren[startNew + k];
385 386 387 388 389 390 391 392 393 394 395 396 397 398
                _animationTuples[gap.key].controller.forward();
              }
            }

            j += newLength;
          }
        } else {
          // If more than a gap disappeared, just remove slices and shrink gaps.
          if (oldLength > 1 ||
              oldLength == 1 && _children[startOld] is MaterialSlice) {
            double gapSizeSum = 0.0;

            while (startOld < j) {
              if (_children[startOld] is MaterialGap) {
399
                final MaterialGap gap = _children[startOld];
400 401 402 403 404 405 406 407
                gapSizeSum += gap.size;
              }

              _removeChild(startOld);
              j -= 1;
            }

            if (gapSizeSum != 0.0) {
408
              final MaterialGap gap = new MaterialGap(
409 410 411 412 413 414 415 416 417 418 419 420 421
                key: new UniqueKey(),
                size: gapSizeSum
              );
              _insertChild(startOld, gap);
              _animationTuples[gap.key].gapStart = 0.0;
              _animationTuples[gap.key].controller
                ..value = 1.0
                ..reverse();

              j += 1;
            }
          } else if (oldLength == 1) {
            // Shrink gap.
422
            final MaterialGap gap = _children[startOld];
423 424 425 426 427 428 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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
            _animationTuples[gap.key].gapStart = 0.0;
            _animationTuples[gap.key].controller.reverse();
          }
        }
      } else {
        // Check whether the items are the same type. If they are, it means that
        // their places have been swaped.
        if ((_children[j] is MaterialGap) == (newChildren[i] is MaterialGap)) {
          _children[j] = newChildren[i];

          i += 1;
          j += 1;
        } else {
          // This is a closing gap which we need to skip.
          assert(_children[j] is MaterialGap);
          j += 1;
        }
      }
    }

    // Handle remaining items.
    while (j < _children.length)
      _removeChild(j);
    while (i < newChildren.length) {
      _insertChild(j, newChildren[i]);

      i += 1;
      j += 1;
    }
  }

  BorderRadius _borderRadius(int index, bool start, bool end) {
    final Radius cardRadius = kMaterialEdges[MaterialType.card].topLeft;

    Radius startRadius = Radius.zero;
    Radius endRadius = Radius.zero;

    if (index > 0 && _children[index - 1] is MaterialGap) {
      startRadius = Radius.lerp(
        Radius.zero,
        cardRadius,
        _animationTuples[_children[index - 1].key].startAnimation.value
      );
    }
    if (index < _children.length - 2 && _children[index + 1] is MaterialGap) {
      endRadius = Radius.lerp(
        Radius.zero,
        cardRadius,
        _animationTuples[_children[index + 1].key].endAnimation.value
      );
    }

475
    if (widget.mainAxis == Axis.vertical) {
476 477 478 479 480 481 482 483 484 485 486 487 488
      return new BorderRadius.vertical(
        top: start ? cardRadius : startRadius,
        bottom: end ? cardRadius : endRadius
      );
    } else {
      return new BorderRadius.horizontal(
        left: start ? cardRadius : startRadius,
        right: end ? cardRadius : endRadius
      );
    }
  }

  double _getGapSize(int index) {
489
    final MaterialGap gap = _children[index];
490 491 492 493 494 495 496 497

    return lerpDouble(
      _animationTuples[gap.key].gapStart,
      gap.size,
      _animationTuples[gap.key].gapAnimation.value
    );
  }

498 499 500 501 502 503
  bool _willNeedDivider(int index) {
    if (index < 0)
      return false;
    if (index >= _children.length)
      return false;
    return _children[index] is MaterialSlice || _isClosingGap(index);
504 505
  }

506 507
  @override
  Widget build(BuildContext context) {
508 509
    _removeEmptyGaps();

510 511 512 513 514 515 516 517 518 519
    final List<Widget> widgets = <Widget>[];
    List<Widget> slices = <Widget>[];
    int i;

    for (i = 0; i < _children.length; i += 1) {
      if (_children[i] is MaterialGap) {
        assert(slices.isNotEmpty);
        widgets.add(
          new Container(
            decoration: new BoxDecoration(
520
              color: Theme.of(context).cardColor,
521 522 523
              borderRadius: _borderRadius(i - 1, widgets.isEmpty, false),
              shape: BoxShape.rectangle
            ),
524
            child: new ListBody(
525
              mainAxis: widget.mainAxis,
526
              children: slices
527 528 529 530 531 532 533
            )
          )
        );
        slices = <Widget>[];

        widgets.add(
          new SizedBox(
534 535
            width: widget.mainAxis == Axis.horizontal ? _getGapSize(i) : null,
            height: widget.mainAxis == Axis.vertical ? _getGapSize(i) : null
536 537 538
          )
        );
      } else {
539
        final MaterialSlice slice = _children[i];
540 541
        Widget child = slice.child;

542
        if (widget.hasDividers) {
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
          final bool hasTopDivider = _willNeedDivider(i - 1);
          final bool hasBottomDivider = _willNeedDivider(i + 1);

          Border border;
          final BorderSide divider = new BorderSide(
            color: Theme.of(context).dividerColor,
            width: 0.5
          );

          if (i == 0) {
            border = new Border(
              bottom: hasBottomDivider ? divider : BorderSide.none
            );
          } else if (i == _children.length - 1) {
            border = new Border(
              top: hasTopDivider ? divider : BorderSide.none
            );
          } else {
            border = new Border(
              top: hasTopDivider ? divider : BorderSide.none,
              bottom: hasBottomDivider ? divider : BorderSide.none
            );
          }

          assert(border != null);

          child = new AnimatedContainer(
            key: new _MergeableMaterialSliceKey(_children[i].key),
            decoration: new BoxDecoration(border: border),
            duration: kThemeAnimationDuration,
            curve: Curves.fastOutSlowIn,
            child: child
          );
        }
577 578 579 580

        slices.add(
          new Material(
            type: MaterialType.transparency,
581
            child: child
582 583 584 585 586 587 588 589 590
          )
        );
      }
    }

    if (slices.isNotEmpty) {
      widgets.add(
        new Container(
          decoration: new BoxDecoration(
591
            color: Theme.of(context).cardColor,
592 593 594
            borderRadius: _borderRadius(i - 1, widgets.isEmpty, true),
            shape: BoxShape.rectangle
          ),
595
          child: new ListBody(
596
            mainAxis: widget.mainAxis,
597
            children: slices
598 599 600 601 602 603
          )
        )
      );
      slices = <Widget>[];
    }

604
    return new _MergeableMaterialListBody(
605 606
      mainAxis: widget.mainAxis,
      boxShadows: kElevationToShadow[widget.elevation],
607 608 609 610 611 612
      items: _children,
      children: widgets
    );
  }
}

613
// The parent hierarchy can change and lead to the slice being
614
// rebuilt. Using a global key solves the issue.
615
class _MergeableMaterialSliceKey extends GlobalKey {
616
  _MergeableMaterialSliceKey(this.value) : super.constructor();
617 618 619 620 621 622 623 624 625 626 627 628 629

  final LocalKey value;

  @override
  bool operator ==(dynamic other) {
    if (other is! _MergeableMaterialSliceKey)
      return false;
    final _MergeableMaterialSliceKey typedOther = other;
    return value == typedOther.value;
  }

  @override
  int get hashCode => value.hashCode;
630 631 632 633 634

  @override
  String toString() {
    return '_MergeableMaterialSliceKey($value)';
  }
635 636
}

637 638
class _MergeableMaterialListBody extends ListBody {
  _MergeableMaterialListBody({
639 640 641 642 643 644
    List<Widget> children,
    Axis mainAxis: Axis.vertical,
    this.items,
    this.boxShadows
  }) : super(children: children, mainAxis: mainAxis);

645 646
  final List<MergeableMaterialItem> items;
  final List<BoxShadow> boxShadows;
647 648

  @override
649 650
  RenderListBody createRenderObject(BuildContext context) {
    return new _RenderMergeableMaterialListBody(
651 652 653 654 655 656
      mainAxis: mainAxis,
      boxShadows: boxShadows
    );
  }

  @override
657 658 659
  void updateRenderObject(BuildContext context, RenderListBody renderObject) {
    final _RenderMergeableMaterialListBody materialRenderListBody = renderObject;
    materialRenderListBody
660 661 662 663 664
      ..mainAxis = mainAxis
      ..boxShadows = boxShadows;
  }
}

665 666
class _RenderMergeableMaterialListBody extends RenderListBody {
  _RenderMergeableMaterialListBody({
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    List<RenderBox> children,
    Axis mainAxis: Axis.vertical,
    this.boxShadows
  }) : super(children: children, mainAxis: mainAxis);

  List<BoxShadow> boxShadows;

  void _paintShadows(Canvas canvas, Rect rect) {
    for (BoxShadow boxShadow in boxShadows) {
      final Paint paint = new Paint()
        ..color = boxShadow.color
        ..maskFilter = new MaskFilter.blur(BlurStyle.normal, boxShadow.blurSigma);
      // TODO(dragostis): Right now, we are only interpolating the border radii
      // of the visible Material slices, not the shadows; they are not getting
      // interpolated and always have the same rounded radii. Once shadow
      // performance is better, shadows should be redrawn every single time the
      // slices' radii get interpolated and use those radii not the defaults.
      canvas.drawRRect(kMaterialEdges[MaterialType.card].toRRect(rect), paint);
    }
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    RenderBox child = firstChild;
    int i = 0;

    while (child != null) {
694
      final ListBodyParentData childParentData = child.parentData;
695 696 697 698 699 700 701 702 703 704 705
      final Rect rect = (childParentData.offset + offset) & child.size;
      if (i % 2 == 0)
        _paintShadows(context.canvas, rect);
      child = childParentData.nextSibling;

      i += 1;
    }

    defaultPaint(context, offset);
  }
}