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

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/rendering.dart';
7
import 'package:flutter/widgets.dart';
8

9
import 'constants.dart';
10
import 'elevation_overlay.dart';
11
import 'theme.dart';
12

13 14
/// Signature for the callback used by ink effects to obtain the rectangle for the effect.
///
15
/// Used by [InkHighlight] and [InkSplash], for example.
16
typedef RectCallback = Rect Function();
17

18
/// The various kinds of material in Material Design. Used to
19
/// configure the default behavior of [Material] widgets.
20 21
///
/// See also:
22
///
23
///  * [Material], in particular [Material.type].
24
///  * [kMaterialEdges]
25
enum MaterialType {
26
  /// Rectangle using default theme canvas color.
27 28 29 30
  canvas,

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

32 33 34
  /// A circle, no color by default (used for floating action buttons).
  circle,

35
  /// Rounded edges, no color by default (used for [MaterialButton] buttons).
36 37 38
  button,

  /// A transparent piece of material that draws ink splashes and highlights.
39 40 41 42 43 44 45 46 47
  ///
  /// While the material metaphor describes child widgets as printed on the
  /// material itself and do not hide ink effects, in practice the [Material]
  /// widget draws child widgets on top of the ink effects.
  /// A [Material] with type transparency can be placed on top of opaque widgets
  /// to show ink effects on top of them.
  ///
  /// Prefer using the [Ink] widget for showing ink effects on top of opaque
  /// widgets.
48
  transparency
49 50
}

51
/// The border radii used by the various kinds of material in Material Design.
52 53 54 55 56
///
/// See also:
///
///  * [MaterialType]
///  * [Material]
57
const Map<MaterialType, BorderRadius?> kMaterialEdges = <MaterialType, BorderRadius?>{
58
  MaterialType.canvas: null,
59
  MaterialType.card: BorderRadius.all(Radius.circular(2.0)),
60
  MaterialType.circle: null,
61
  MaterialType.button: BorderRadius.all(Radius.circular(2.0)),
62
  MaterialType.transparency: null,
63 64
};

65
/// An interface for creating [InkSplash]s and [InkHighlight]s on a [Material].
66 67
///
/// Typically obtained via [Material.of].
68
abstract class MaterialInkController {
69
  /// The color of the material.
70
  Color? get color;
71

72
  /// The ticker provider used by the controller.
73
  ///
74 75 76 77 78
  /// Ink features that are added to this controller with [addInkFeature] should
  /// use this vsync to drive their animations.
  TickerProvider get vsync;

  /// Add an [InkFeature], such as an [InkSplash] or an [InkHighlight].
79
  ///
80
  /// The ink feature will paint as part of this controller.
81
  void addInkFeature(InkFeature feature);
82 83 84

  /// Notifies the controller that one of its ink features needs to repaint.
  void markNeedsPaint();
85 86
}

87 88
/// A piece of material.
///
89 90
/// The Material widget is responsible for:
///
91 92 93
/// 1. Clipping: If [clipBehavior] is not [Clip.none], Material clips its widget
///    sub-tree to the shape specified by [shape], [type], and [borderRadius].
///    By default, [clipBehavior] is [Clip.none] for performance considerations.
94
///    See [Ink] for an example of how this affects clipping [Ink] widgets.
95 96 97 98 99 100 101
/// 2. Elevation: Material elevates its widget sub-tree on the Z axis by
///    [elevation] pixels, and draws the appropriate shadow.
/// 3. Ink effects: Material shows ink effects implemented by [InkFeature]s
///    like [InkSplash] and [InkHighlight] below its children.
///
/// ## The Material Metaphor
///
102
/// Material is the central metaphor in Material Design. Each piece of material
103 104
/// exists at a given elevation, which influences how that piece of material
/// visually relates to other pieces of material and how that material casts
105
/// shadows.
106 107 108 109 110 111
///
/// Most user interface elements are either conceptually printed on a piece of
/// material or themselves made of material. Material reacts to user input using
/// [InkSplash] and [InkHighlight] effects. To trigger a reaction on the
/// material, use a [MaterialInkController] obtained via [Material.of].
///
112
/// In general, the features of a [Material] should not change over time (e.g. a
113
/// [Material] should not change its [color], [shadowColor] or [type]).
114 115 116 117 118
/// Changes to [elevation], [shadowColor] and [surfaceTintColor] are animated
/// for [animationDuration]. Changes to [shape] are animated if [type] is
/// not [MaterialType.transparency] and [ShapeBorder.lerp] between the previous
/// and next [shape] values is supported. Shape changes are also animated
/// for [animationDuration].
119
///
120 121
/// ## Shape
///
122
/// The shape for material is determined by [shape], [type], and [borderRadius].
123
///
124 125 126 127 128
///  - If [shape] is non null, it determines the shape.
///  - If [shape] is null and [borderRadius] is non null, the shape is a
///    rounded rectangle, with corners specified by [borderRadius].
///  - If [shape] and [borderRadius] are null, [type] determines the
///    shape as follows:
129 130 131 132 133 134 135 136
///    - [MaterialType.canvas]: the default material shape is a rectangle.
///    - [MaterialType.card]: the default material shape is a rectangle with
///      rounded edges. The edge radii is specified by [kMaterialEdges].
///    - [MaterialType.circle]: the default material shape is a circle.
///    - [MaterialType.button]: the default material shape is a rectangle with
///      rounded edges. The edge radii is specified by [kMaterialEdges].
///    - [MaterialType.transparency]: the default material shape is a rectangle.
///
137 138 139 140
/// ## Border
///
/// If [shape] is not null, then its border will also be painted (if any).
///
141
/// ## Layout change notifications
142
///
Ian Hickson's avatar
Ian Hickson committed
143 144 145 146 147 148 149 150
/// If the layout changes (e.g. because there's a list on the material, and it's
/// been scrolled), a [LayoutChangedNotification] must be dispatched at the
/// relevant subtree. This in particular means that transitions (e.g.
/// [SlideTransition]) should not be placed inside [Material] widgets so as to
/// move subtrees that contain [InkResponse]s, [InkWell]s, [Ink]s, or other
/// widgets that use the [InkFeature] mechanism. Otherwise, in-progress ink
/// features (e.g., ink splashes and ink highlights) won't move to account for
/// the new layout.
151
///
152 153 154 155 156 157 158 159 160 161
/// ## Painting over the material
///
/// Material widgets will often trigger reactions on their nearest material
/// ancestor. For example, [ListTile.hoverColor] triggers a reaction on the
/// tile's material when a pointer is hovering over it. These reactions will be
/// obscured if any widget in between them and the material paints in such a
/// way as to obscure the material (such as setting a [BoxDecoration.color] on
/// a [DecoratedBox]). To avoid this behavior, use [InkDecoration] to decorate
/// the material itself.
///
162 163
/// See also:
///
164
///  * [MergeableMaterial], a piece of material that can split and re-merge.
165
///  * [Card], a wrapper for a [Material] of [type] [MaterialType.card].
166
///  * <https://material.io/design/>
167
///  * <https://m3.material.io/styles/color/the-color-system/color-roles>
168
class Material extends StatefulWidget {
169 170
  /// Creates a piece of material.
  ///
171
  /// The [type], [elevation], [borderOnForeground],
172 173
  /// [clipBehavior], and [animationDuration] arguments must not be null.
  /// Additionally, [elevation] must be non-negative.
174
  ///
175
  /// If a [shape] is specified, then the [borderRadius] property must be
176 177 178 179
  /// null and the [type] property must not be [MaterialType.circle]. If the
  /// [borderRadius] is specified, then the [type] property must not be
  /// [MaterialType.circle]. In both cases, these restrictions are intended to
  /// catch likely errors.
180
  const Material({
181
    super.key,
182 183
    this.type = MaterialType.canvas,
    this.elevation = 0.0,
184
    this.color,
185
    this.shadowColor,
186
    this.surfaceTintColor,
187
    this.textStyle,
188
    this.borderRadius,
189
    this.shape,
190
    this.borderOnForeground = true,
191
    this.clipBehavior = Clip.none,
192
    this.animationDuration = kThemeChangeDuration,
193
    this.child,
194
  }) : assert(type != null),
195
       assert(elevation != null && elevation >= 0.0),
196
       assert(!(shape != null && borderRadius != null)),
197
       assert(animationDuration != null),
198
       assert(!(identical(type, MaterialType.circle) && (borderRadius != null || shape != null))),
199
       assert(borderOnForeground != null),
200
       assert(clipBehavior != null);
201

202
  /// The widget below this widget in the tree.
203
  ///
204
  /// {@macro flutter.widgets.ProxyWidget.child}
205
  final Widget? child;
206

207 208 209
  /// The kind of material to show (e.g., card or canvas). This
  /// affects the shape of the widget, the roundness of its corners if
  /// the shape is rectangular, and the default color.
210
  final MaterialType type;
211

212
  /// {@template flutter.material.material.elevation}
213 214
  /// The z-coordinate at which to place this material relative to its parent.
  ///
215 216
  /// This controls the size of the shadow below the material and the opacity
  /// of the elevation overlay color if it is applied.
217
  ///
218
  /// If this is non-zero, the contents of the material are clipped, because the
219 220
  /// widget conceptually defines an independent printed piece of material.
  ///
221
  /// Defaults to 0. Changing this value will cause the shadow and the elevation
222
  /// overlay or surface tint to animate over [Material.animationDuration].
223 224
  ///
  /// The value is non-negative.
225 226 227
  ///
  /// See also:
  ///
228 229
  ///  * [ThemeData.useMaterial3] which defines whether a surface tint or
  ///    elevation overlay is used to indicate elevation.
230 231
  ///  * [ThemeData.applyElevationOverlayColor] which controls the whether
  ///    an overlay color will be applied to indicate elevation.
232
  ///  * [Material.color] which may have an elevation overlay applied.
233 234 235
  ///  * [Material.shadowColor] which will be used for the color of a drop shadow.
  ///  * [Material.surfaceTintColor] which will be used as the overlay tint to
  ///    show elevation.
236
  /// {@endtemplate}
237
  final double elevation;
238

239
  /// The color to paint the material.
240 241 242
  ///
  /// Must be opaque. To create a transparent piece of material, use
  /// [MaterialType.transparency].
243
  ///
244 245 246 247 248 249 250 251
  /// If [ThemeData.useMaterial3] is true then an optional [surfaceTintColor]
  /// overlay may be applied on top of this color to indicate elevation.
  ///
  /// If [ThemeData.useMaterial3] is false and [ThemeData.applyElevationOverlayColor]
  /// is true and [ThemeData.brightness] is [Brightness.dark] then a
  /// semi-transparent overlay color will be composited on top of this
  /// color to indicate the elevation. This is no longer needed for Material
  /// Design 3, which uses [surfaceTintColor].
252
  ///
253
  /// By default, the color is derived from the [type] of material.
254
  final Color? color;
255

256 257
  /// The color to paint the shadow below the material.
  ///
258 259 260
  /// When [ThemeData.useMaterial3] is true, and this is null, then no drop
  /// shadow will be rendered for this material. If it is non-null, then this
  /// color will be used to render a drop shadow below the material.
261
  ///
262 263
  /// When [ThemeData.useMaterial3] is false, and this is null, then
  /// [ThemeData.shadowColor] is used, which defaults to fully opaque black.
264 265
  ///
  /// See also:
266 267
  ///  * [ThemeData.useMaterial3], which determines the default value for this
  ///    property if it is null.
268 269
  ///  * [ThemeData.applyElevationOverlayColor], which turns elevation overlay
  /// on or off for dark themes.
270
  final Color? shadowColor;
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
  /// The color of the surface tint overlay applied to the material color
  /// to indicate elevation.
  ///
  /// Material Design 3 introduced a new way for some components to indicate
  /// their elevation by using a surface tint color overlay on top of the
  /// base material [color]. This overlay is painted with an opacity that is
  /// related to the [elevation] of the material.
  ///
  /// If [ThemeData.useMaterial3] is false, then this property is not used.
  ///
  /// If [ThemeData.useMaterial3] is true and [surfaceTintColor] is not null,
  /// then it will be used to overlay the base [color] with an opacity based
  /// on the [elevation].
  ///
  /// Otherwise, no surface tint will be applied.
  ///
  /// See also:
  ///
  ///   * [ThemeData.useMaterial3], which turns this feature on.
  ///   * [ElevationOverlay.applySurfaceTint], which is used to implement the
  ///     tint.
  ///   * https://m3.material.io/styles/color/the-color-system/color-roles
  ///     which specifies how the overlay is applied.
  final Color? surfaceTintColor;

297
  /// The typographical style to use for text within this material.
298
  final TextStyle? textStyle;
299

300 301 302 303 304 305 306
  /// Defines the material's shape as well its shadow.
  ///
  /// If shape is non null, the [borderRadius] is ignored and the material's
  /// clip boundary and shadow are defined by the shape.
  ///
  /// A shadow is only displayed if the [elevation] is greater than
  /// zero.
307
  final ShapeBorder? shape;
308

309 310 311 312 313 314
  /// Whether to paint the [shape] border in front of the [child].
  ///
  /// The default value is true.
  /// If false, the border will be painted behind the [child].
  final bool borderOnForeground;

315
  /// {@template flutter.material.Material.clipBehavior}
316 317 318 319 320
  /// The content will be clipped (or not) according to this option.
  ///
  /// See the enum [Clip] for details of all possible options and their common
  /// use cases.
  /// {@endtemplate}
321 322
  ///
  /// Defaults to [Clip.none], and must not be null.
323 324
  final Clip clipBehavior;

325
  /// Defines the duration of animated changes for [shape], [elevation],
326
  /// [shadowColor], [surfaceTintColor] and the elevation overlay if it is applied.
327 328 329 330
  ///
  /// The default value is [kThemeChangeDuration].
  final Duration animationDuration;

331 332 333
  /// If non-null, the corners of this box are rounded by this
  /// [BorderRadiusGeometry] value.
  ///
334 335 336
  /// Otherwise, the corners specified for the current [type] of material are
  /// used.
  ///
337 338
  /// If [shape] is non null then the border radius is ignored.
  ///
339
  /// Must be null if [type] is [MaterialType.circle].
340
  final BorderRadiusGeometry? borderRadius;
341

342 343
  /// The ink controller from the closest instance of this class that
  /// encloses the given context.
344 345 346 347 348 349
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// MaterialInkController inkController = Material.of(context);
  /// ```
350 351
  ///
  /// This method can be expensive (it walks the element tree).
352 353
  static MaterialInkController? of(BuildContext context) {
    return context.findAncestorRenderObjectOfType<_RenderInkFeatures>();
354 355
  }

356
  @override
357
  State<Material> createState() => _MaterialState();
358

359
  @override
360 361
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
362 363
    properties.add(EnumProperty<MaterialType>('type', type));
    properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0));
364
    properties.add(ColorProperty('color', color, defaultValue: null));
365
    properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null));
366
    properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null));
367
    textStyle?.debugFillProperties(properties, prefix: 'textStyle.');
368
    properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
369
    properties.add(DiagnosticsProperty<bool>('borderOnForeground', borderOnForeground, defaultValue: true));
370
    properties.add(DiagnosticsProperty<BorderRadiusGeometry>('borderRadius', borderRadius, defaultValue: null));
371
  }
372 373 374

  /// The default radius of an ink splash in logical pixels.
  static const double defaultSplashRadius = 35.0;
375 376
}

377
class _MaterialState extends State<Material> with TickerProviderStateMixin {
378
  final GlobalKey _inkFeatureRenderer = GlobalKey(debugLabel: 'ink renderer');
379

380
  Color? _getBackgroundColor(BuildContext context) {
381
    final ThemeData theme = Theme.of(context);
382
    Color? color = widget.color;
383 384 385 386 387 388 389 390
    if (color == null) {
      switch (widget.type) {
        case MaterialType.canvas:
          color = theme.canvasColor;
          break;
        case MaterialType.card:
          color = theme.cardColor;
          break;
391 392 393
        case MaterialType.button:
        case MaterialType.circle:
        case MaterialType.transparency:
394 395
          break;
      }
396
    }
397
    return color;
398 399
  }

400
  @override
401
  Widget build(BuildContext context) {
402
    final ThemeData theme = Theme.of(context);
403
    final Color? backgroundColor = _getBackgroundColor(context);
404 405 406
    final Color? modelShadowColor = widget.shadowColor ?? (theme.useMaterial3 ? null : theme.shadowColor);
    // If no shadow color is specified, use 0 for elevation in the model so a drop shadow won't be painted.
    final double modelElevation = modelShadowColor != null ? widget.elevation : 0;
407 408 409 410 411
    assert(
      backgroundColor != null || widget.type == MaterialType.transparency,
      'If Material type is not MaterialType.transparency, a color must '
      'either be passed in through the `color` property, or be defined '
      'in the theme (ex. canvasColor != null if type is set to '
412
      'MaterialType.canvas)',
413
    );
414
    Widget? contents = widget.child;
415
    if (contents != null) {
416
      contents = AnimatedDefaultTextStyle(
417
        style: widget.textStyle ?? Theme.of(context).textTheme.bodyText2!,
418
        duration: widget.animationDuration,
419
        child: contents,
420 421
      );
    }
422
    contents = NotificationListener<LayoutChangedNotification>(
423
      onNotification: (LayoutChangedNotification notification) {
424
        final _RenderInkFeatures renderer = _inkFeatureRenderer.currentContext!.findRenderObject()! as _RenderInkFeatures;
425
        renderer._didChangeLayout();
426
        return false;
427
      },
428
      child: _InkFeatures(
429
        key: _inkFeatureRenderer,
430
        absorbHitTest: widget.type != MaterialType.transparency,
431
        color: backgroundColor,
432
        vsync: this,
433
        child: contents,
434
      ),
435
    );
436

Josh Soref's avatar
Josh Soref committed
437
    // PhysicalModel has a temporary workaround for a performance issue that
438 439
    // speeds up rectangular non transparent material (the workaround is to
    // skip the call to ui.Canvas.saveLayer if the border radius is 0).
Josh Soref's avatar
Josh Soref committed
440
    // Until the saveLayer performance issue is resolved, we're keeping this
441 442
    // special case here for canvas material type that is using the default
    // shape (rectangle). We could go down this fast path for explicitly
Josh Soref's avatar
Josh Soref committed
443
    // specified rectangles (e.g shape RoundedRectangleBorder with radius 0, but
444 445 446
    // we choose not to as we want the change from the fast-path to the
    // slow-path to be noticeable in the construction site of Material.
    if (widget.type == MaterialType.canvas && widget.shape == null && widget.borderRadius == null) {
447 448 449 450
      final Color color = Theme.of(context).useMaterial3
        ? ElevationOverlay.applySurfaceTint(backgroundColor!, widget.surfaceTintColor, widget.elevation)
        : ElevationOverlay.applyOverlay(context, backgroundColor!, widget.elevation);

451
      return AnimatedPhysicalModel(
452
        curve: Curves.fastOutSlowIn,
453
        duration: widget.animationDuration,
454
        shape: BoxShape.rectangle,
455
        clipBehavior: widget.clipBehavior,
456
        elevation: modelElevation,
457
        color: color,
458
        shadowColor: modelShadowColor ?? const Color(0x00000000),
459 460 461 462 463
        animateColor: false,
        child: contents,
      );
    }

464 465
    final ShapeBorder shape = _getShape();

466 467 468 469 470 471 472 473
    if (widget.type == MaterialType.transparency) {
      return _transparentInterior(
        context: context,
        shape: shape,
        clipBehavior: widget.clipBehavior,
        contents: contents,
      );
    }
474

475
    return _MaterialInterior(
476
      curve: Curves.fastOutSlowIn,
477
      duration: widget.animationDuration,
478
      shape: shape,
479
      borderOnForeground: widget.borderOnForeground,
480
      clipBehavior: widget.clipBehavior,
481
      elevation: widget.elevation,
482
      color: backgroundColor!,
483
      shadowColor: modelShadowColor,
484
      surfaceTintColor: widget.surfaceTintColor,
485 486 487 488
      child: contents,
    );
  }

489
  static Widget _transparentInterior({
490 491 492 493
    required BuildContext context,
    required ShapeBorder shape,
    required Clip clipBehavior,
    required Widget contents,
494
  }) {
495
    final _ShapeBorderPaint child = _ShapeBorderPaint(
496
      shape: shape,
497
      child: contents,
498
    );
499
    return ClipPath(
500 501
      clipper: ShapeBorderClipper(
        shape: shape,
502
        textDirection: Directionality.maybeOf(context),
503
      ),
504
      clipBehavior: clipBehavior,
505
      child: child,
506 507 508 509 510 511 512 513 514 515 516
    );
  }

  // Determines the shape for this Material.
  //
  // If a shape was specified, it will determine the shape.
  // If a borderRadius was specified, the shape is a rounded
  // rectangle.
  // Otherwise, the shape is determined by the widget type as described in the
  // Material class documentation.
  ShapeBorder _getShape() {
517
    if (widget.shape != null) {
518
      return widget.shape!;
519 520
    }
    if (widget.borderRadius != null) {
521
      return RoundedRectangleBorder(borderRadius: widget.borderRadius!);
522
    }
523 524 525
    switch (widget.type) {
      case MaterialType.canvas:
      case MaterialType.transparency:
526
        return const RoundedRectangleBorder();
527 528 529

      case MaterialType.card:
      case MaterialType.button:
530
        return RoundedRectangleBorder(
531
          borderRadius: widget.borderRadius ?? kMaterialEdges[widget.type]!,
532
        );
533

534 535 536
      case MaterialType.circle:
        return const CircleBorder();
    }
537 538 539
  }
}

540
class _RenderInkFeatures extends RenderProxyBox implements MaterialInkController {
541
  _RenderInkFeatures({
542 543 544
    RenderBox? child,
    required this.vsync,
    required this.absorbHitTest,
545 546 547
    this.color,
  }) : assert(vsync != null),
       super(child);
548 549 550 551

  // This class should exist in a 1:1 relationship with a MaterialState object,
  // since there's no current support for dynamically changing the ticker
  // provider.
552
  @override
553
  final TickerProvider vsync;
554 555 556 557

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

561 562
  bool absorbHitTest;

563 564
  @visibleForTesting
  List<InkFeature>? get debugInkFeatures {
565
    if (kDebugMode) {
566
      return _inkFeatures;
567
    }
568 569
    return null;
  }
570
  List<InkFeature>? _inkFeatures;
571

572
  @override
573 574
  void addInkFeature(InkFeature feature) {
    assert(!feature._debugDisposed);
575
    assert(feature._controller == this);
576
    _inkFeatures ??= <InkFeature>[];
577 578
    assert(!_inkFeatures!.contains(feature));
    _inkFeatures!.add(feature);
579 580 581 582
    markNeedsPaint();
  }

  void _removeFeature(InkFeature feature) {
583
    assert(_inkFeatures != null);
584
    _inkFeatures!.remove(feature);
585 586 587
    markNeedsPaint();
  }

588
  void _didChangeLayout() {
589
    if (_inkFeatures != null && _inkFeatures!.isNotEmpty) {
590
      markNeedsPaint();
591
    }
592 593
  }

594
  @override
595
  bool hitTestSelf(Offset position) => absorbHitTest;
596

597
  @override
598
  void paint(PaintingContext context, Offset offset) {
599
    if (_inkFeatures != null && _inkFeatures!.isNotEmpty) {
600 601 602
      final Canvas canvas = context.canvas;
      canvas.save();
      canvas.translate(offset.dx, offset.dy);
603
      canvas.clipRect(Offset.zero & size);
604
      for (final InkFeature inkFeature in _inkFeatures!) {
605
        inkFeature._paint(canvas);
606
      }
607 608 609 610 611 612
      canvas.restore();
    }
    super.paint(context, offset);
  }
}

613
class _InkFeatures extends SingleChildRenderObjectWidget {
614
  const _InkFeatures({
615
    super.key,
616
    this.color,
617 618
    required this.vsync,
    required this.absorbHitTest,
619 620
    super.child,
  });
621 622 623

  // This widget must be owned by a MaterialState, which must be provided as the vsync.
  // This relationship must be 1:1 and cannot change for the lifetime of the MaterialState.
624

625
  final Color? color;
626

627 628
  final TickerProvider vsync;

629 630
  final bool absorbHitTest;

631
  @override
632
  _RenderInkFeatures createRenderObject(BuildContext context) {
633
    return _RenderInkFeatures(
634
      color: color,
635
      absorbHitTest: absorbHitTest,
636
      vsync: vsync,
637 638
    );
  }
639

640
  @override
641
  void updateRenderObject(BuildContext context, _RenderInkFeatures renderObject) {
642 643
    renderObject..color = color
                ..absorbHitTest = absorbHitTest;
644
    assert(vsync == renderObject.vsync);
645 646 647
  }
}

648 649
/// A visual reaction on a piece of [Material].
///
650 651 652
/// To add an ink feature to a piece of [Material], obtain the
/// [MaterialInkController] via [Material.of] and call
/// [MaterialInkController.addInkFeature].
653
abstract class InkFeature {
654
  /// Initializes fields for subclasses.
655
  InkFeature({
656 657
    required MaterialInkController controller,
    required this.referenceBox,
658
    this.onRemoved,
659 660
  }) : assert(controller != null),
       assert(referenceBox != null),
661
       _controller = controller as _RenderInkFeatures;
662

663 664 665 666
  /// The [MaterialInkController] associated with this [InkFeature].
  ///
  /// Typically used by subclasses to call
  /// [MaterialInkController.markNeedsPaint] when they need to repaint.
667
  MaterialInkController get controller => _controller;
668
  final _RenderInkFeatures _controller;
669 670

  /// The render box whose visual position defines the frame of reference for this ink feature.
671
  final RenderBox referenceBox;
672 673

  /// Called when the ink feature is no longer visible on the material.
674
  final VoidCallback? onRemoved;
675 676 677

  bool _debugDisposed = false;

678
  /// Free up the resources associated with this ink feature.
679
  @mustCallSuper
680 681
  void dispose() {
    assert(!_debugDisposed);
682 683 684 685
    assert(() {
      _debugDisposed = true;
      return true;
    }());
686
    _controller._removeFeature(this);
687
    onRemoved?.call();
688 689 690 691 692 693
  }

  void _paint(Canvas canvas) {
    assert(referenceBox.attached);
    assert(!_debugDisposed);
    // find the chain of renderers from us to the feature's referenceBox
694 695
    final List<RenderObject> descendants = <RenderObject>[referenceBox];
    RenderObject node = referenceBox;
696
    while (node != _controller) {
697
      final RenderObject childNode = node;
698
      node = node.parent! as RenderObject;
699 700 701 702 703 704 705 706
      if (!node.paintsChild(childNode)) {
        // Some node between the reference box and this would skip painting on
        // the reference box, so bail out early and avoid unnecessary painting.
        // Some cases where this can happen are the reference box being
        // offstage, in a fully transparent opacity node, or in a keep alive
        // bucket.
        return;
      }
707
      descendants.add(node);
708 709
    }
    // determine the transform that gets our coordinate system to be like theirs
710
    final Matrix4 transform = Matrix4.identity();
711
    assert(descendants.length >= 2);
712
    for (int index = descendants.length - 1; index > 0; index -= 1) {
713
      descendants[index].applyPaintTransform(descendants[index - 1], transform);
714
    }
715 716 717
    paintFeature(canvas, transform);
  }

718 719 720
  /// Override this method to paint the ink feature.
  ///
  /// The transform argument gives the coordinate conversion from the coordinate
721
  /// system of the canvas to the coordinate system of the [referenceBox].
722
  @protected
723 724
  void paintFeature(Canvas canvas, Matrix4 transform);

725
  @override
726
  String toString() => describeIdentity(this);
727
}
728 729 730 731

/// An interpolation between two [ShapeBorder]s.
///
/// This class specializes the interpolation of [Tween] to use [ShapeBorder.lerp].
732
class ShapeBorderTween extends Tween<ShapeBorder?> {
733 734 735 736
  /// Creates a [ShapeBorder] tween.
  ///
  /// the [begin] and [end] properties may be null; see [ShapeBorder.lerp] for
  /// the null handling semantics.
737
  ShapeBorderTween({super.begin, super.end});
738 739 740

  /// Returns the value this tween has at the given animation clock value.
  @override
741
  ShapeBorder? lerp(double t) {
742 743 744 745 746 747 748 749
    return ShapeBorder.lerp(begin, end, t);
  }
}

/// The interior of non-transparent material.
///
/// Animates [elevation], [shadowColor], and [shape].
class _MaterialInterior extends ImplicitlyAnimatedWidget {
750 751 752 753 754
  /// Creates a const instance of [_MaterialInterior].
  ///
  /// The [child], [shape], [clipBehavior], [color], and [shadowColor] arguments
  /// must not be null. The [elevation] must be specified and greater than or
  /// equal to zero.
755
  const _MaterialInterior({
756 757
    required this.child,
    required this.shape,
758
    this.borderOnForeground = true,
759
    this.clipBehavior = Clip.none,
760 761 762
    required this.elevation,
    required this.color,
    required this.shadowColor,
763
    required this.surfaceTintColor,
764 765
    super.curve,
    required super.duration,
766 767
  }) : assert(child != null),
       assert(shape != null),
768
       assert(clipBehavior != null),
769
       assert(elevation != null && elevation >= 0.0),
770
       assert(color != null);
771 772 773

  /// The widget below this widget in the tree.
  ///
774
  /// {@macro flutter.widgets.ProxyWidget.child}
775 776 777 778 779 780 781 782
  final Widget child;

  /// The border of the widget.
  ///
  /// This border will be painted, and in addition the outer path of the border
  /// determines the physical shape.
  final ShapeBorder shape;

783 784 785 786 787 788
  /// Whether to paint the border in front of the child.
  ///
  /// The default value is true.
  /// If false, the border will be painted behind the child.
  final bool borderOnForeground;

789
  /// {@macro flutter.material.Material.clipBehavior}
790 791
  ///
  /// Defaults to [Clip.none], and must not be null.
792 793
  final Clip clipBehavior;

794 795 796 797
  /// The target z-coordinate at which to place this physical object relative
  /// to its parent.
  ///
  /// The value is non-negative.
798 799 800 801 802 803
  final double elevation;

  /// The target background color.
  final Color color;

  /// The target shadow color.
804
  final Color? shadowColor;
805

806 807 808
  /// The target surface tint color.
  final Color? surfaceTintColor;

809
  @override
810
  _MaterialInteriorState createState() => _MaterialInteriorState();
811 812 813 814

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
    super.debugFillProperties(description);
815 816
    description.add(DiagnosticsProperty<ShapeBorder>('shape', shape));
    description.add(DoubleProperty('elevation', elevation));
817 818
    description.add(ColorProperty('color', color));
    description.add(ColorProperty('shadowColor', shadowColor));
819 820 821 822
  }
}

class _MaterialInteriorState extends AnimatedWidgetBaseState<_MaterialInterior> {
823
  Tween<double>? _elevation;
824
  ColorTween? _surfaceTintColor;
825 826
  ColorTween? _shadowColor;
  ShapeBorderTween? _border;
827 828 829

  @override
  void forEachTween(TweenVisitor<dynamic> visitor) {
830 831 832 833
    _elevation = visitor(
      _elevation,
      widget.elevation,
      (dynamic value) => Tween<double>(begin: value as double),
834
    ) as Tween<double>?;
835 836 837 838 839 840 841
    _shadowColor =  widget.shadowColor != null
      ? visitor(
          _shadowColor,
          widget.shadowColor,
          (dynamic value) => ColorTween(begin: value as Color),
        ) as ColorTween?
      : null;
842 843 844 845 846 847 848
    _surfaceTintColor = widget.surfaceTintColor != null
      ? visitor(
          _surfaceTintColor,
          widget.surfaceTintColor,
              (dynamic value) => ColorTween(begin: value as Color),
        ) as ColorTween?
      : null;
849 850 851 852
    _border = visitor(
      _border,
      widget.shape,
      (dynamic value) => ShapeBorderTween(begin: value as ShapeBorder),
853
    ) as ShapeBorderTween?;
854 855 856 857
  }

  @override
  Widget build(BuildContext context) {
858 859
    final ShapeBorder shape = _border!.evaluate(animation)!;
    final double elevation = _elevation!.evaluate(animation);
860 861 862
    final Color color = Theme.of(context).useMaterial3
      ? ElevationOverlay.applySurfaceTint(widget.color, _surfaceTintColor?.evaluate(animation), elevation)
      : ElevationOverlay.applyOverlay(context, widget.color, elevation);
863 864 865
    // If no shadow color is specified, use 0 for elevation in the model so a drop shadow won't be painted.
    final double modelElevation = widget.shadowColor != null ? elevation : 0;
    final Color shadowColor = _shadowColor?.evaluate(animation) ?? const Color(0x00000000);
866 867
    return PhysicalShape(
      clipper: ShapeBorderClipper(
868
        shape: shape,
869
        textDirection: Directionality.maybeOf(context),
870
      ),
871
      clipBehavior: widget.clipBehavior,
872
      elevation: modelElevation,
873
      color: color,
874
      shadowColor: shadowColor,
875 876 877 878 879
      child: _ShapeBorderPaint(
        shape: shape,
        borderOnForeground: widget.borderOnForeground,
        child: widget.child,
      ),
880 881 882
    );
  }
}
883 884 885

class _ShapeBorderPaint extends StatelessWidget {
  const _ShapeBorderPaint({
886 887
    required this.child,
    required this.shape,
888
    this.borderOnForeground = true,
889 890 891 892
  });

  final Widget child;
  final ShapeBorder shape;
893
  final bool borderOnForeground;
894 895 896

  @override
  Widget build(BuildContext context) {
897
    return CustomPaint(
898 899
      painter: borderOnForeground ? null : _ShapeBorderPainter(shape, Directionality.maybeOf(context)),
      foregroundPainter: borderOnForeground ? _ShapeBorderPainter(shape, Directionality.maybeOf(context)) : null,
900
      child: child,
901 902 903 904 905 906 907
    );
  }
}

class _ShapeBorderPainter extends CustomPainter {
  _ShapeBorderPainter(this.border, this.textDirection);
  final ShapeBorder border;
908
  final TextDirection? textDirection;
909 910 911 912 913 914 915 916 917 918 919

  @override
  void paint(Canvas canvas, Size size) {
    border.paint(canvas, Offset.zero & size, textDirection: textDirection);
  }

  @override
  bool shouldRepaint(_ShapeBorderPainter oldDelegate) {
    return oldDelegate.border != border;
  }
}