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

5
import 'package:flutter/gestures.dart';
6 7
import 'package:flutter/material.dart' show Tooltip;
import 'package:flutter/widgets.dart';
8
import 'package:meta/meta.dart';
9 10 11

import 'all_elements.dart';

12
/// Signature for [CommonFinders.byWidgetPredicate].
13
typedef WidgetPredicate = bool Function(Widget widget);
14

15
/// Signature for [CommonFinders.byElementPredicate].
16
typedef ElementPredicate = bool Function(Element element);
17 18

/// Some frequently used widget [Finder]s.
19
const CommonFinders find = CommonFinders._();
20 21 22 23 24 25 26

/// Provides lightweight syntax for getting frequently used widget [Finder]s.
///
/// This class is instantiated once, as [find].
class CommonFinders {
  const CommonFinders._();

27 28
  /// Finds [Text] and [EditableText] widgets containing string equal to the
  /// `text` argument.
29
  ///
30
  /// ## Sample code
31
  ///
32 33 34
  /// ```dart
  /// expect(find.text('Back'), findsOneWidget);
  /// ```
35
  ///
36 37
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
38
  Finder text(String text, { bool skipOffstage = true }) => _TextFinder(text, skipOffstage: skipOffstage);
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53
  /// Finds [Text] and [EditableText] widgets which contain the given
  /// `pattern` argument.
  ///
  /// ## Sample code
  ///
  /// ```dart
  /// expect(find.textContain('Back'), findsOneWidget);
  /// expect(find.textContain(RegExp(r'(\w+)')), findsOneWidget);
  /// ```
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder textContaining(Pattern pattern, { bool skipOffstage = true }) => _TextContainingFinder(pattern, skipOffstage: skipOffstage);

54 55 56
  /// Looks for widgets that contain a [Text] descendant with `text`
  /// in it.
  ///
57
  /// ## Sample code
58
  ///
59 60 61 62 63
  /// ```dart
  /// // Suppose you have a button with text 'Update' in it:
  /// new Button(
  ///   child: new Text('Update')
  /// )
64
  ///
65 66 67
  /// // You can find and tap on it like this:
  /// tester.tap(find.widgetWithText(Button, 'Update'));
  /// ```
68
  ///
69 70
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
71
  Finder widgetWithText(Type widgetType, String text, { bool skipOffstage = true }) {
72
    return find.ancestor(
73 74
      of: find.text(text, skipOffstage: skipOffstage),
      matching: find.byType(widgetType, skipOffstage: skipOffstage),
75
    );
76 77 78 79
  }

  /// Finds widgets by searching for one with a particular [Key].
  ///
80
  /// ## Sample code
81
  ///
82 83 84
  /// ```dart
  /// expect(find.byKey(backKey), findsOneWidget);
  /// ```
85
  ///
86 87
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
88
  Finder byKey(Key key, { bool skipOffstage = true }) => _KeyFinder(key, skipOffstage: skipOffstage);
89 90 91 92 93 94 95 96 97

  /// Finds widgets by searching for widgets with a particular type.
  ///
  /// This does not do subclass tests, so for example
  /// `byType(StatefulWidget)` will never find anything since that's
  /// an abstract class.
  ///
  /// The `type` argument must be a subclass of [Widget].
  ///
98
  /// ## Sample code
99
  ///
100 101 102
  /// ```dart
  /// expect(find.byType(IconButton), findsOneWidget);
  /// ```
103
  ///
104 105
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
106
  Finder byType(Type type, { bool skipOffstage = true }) => _WidgetTypeFinder(type, skipOffstage: skipOffstage);
107

108 109
  /// Finds [Icon] widgets containing icon data equal to the `icon`
  /// argument.
110
  ///
111
  /// ## Sample code
112
  ///
113 114 115
  /// ```dart
  /// expect(find.byIcon(Icons.inbox), findsOneWidget);
  /// ```
116
  ///
117 118
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
119
  Finder byIcon(IconData icon, { bool skipOffstage = true }) => _WidgetIconFinder(icon, skipOffstage: skipOffstage);
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  /// Looks for widgets that contain an [Icon] descendant displaying [IconData]
  /// `icon` in it.
  ///
  /// ## Sample code
  ///
  /// ```dart
  /// // Suppose you have a button with icon 'arrow_forward' in it:
  /// new Button(
  ///   child: new Icon(Icons.arrow_forward)
  /// )
  ///
  /// // You can find and tap on it like this:
  /// tester.tap(find.widgetWithIcon(Button, Icons.arrow_forward));
  /// ```
  ///
136 137
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
138
  Finder widgetWithIcon(Type widgetType, IconData icon, { bool skipOffstage = true }) {
139 140 141 142 143 144
    return find.ancestor(
      of: find.byIcon(icon),
      matching: find.byType(widgetType),
    );
  }

145 146 147 148 149 150 151 152
  /// Finds widgets by searching for elements with a particular type.
  ///
  /// This does not do subclass tests, so for example
  /// `byElementType(VirtualViewportElement)` will never find anything
  /// since that's an abstract class.
  ///
  /// The `type` argument must be a subclass of [Element].
  ///
153
  /// ## Sample code
154
  ///
155 156 157
  /// ```dart
  /// expect(find.byElementType(SingleChildRenderObjectElement), findsOneWidget);
  /// ```
158
  ///
159 160
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
161
  Finder byElementType(Type type, { bool skipOffstage = true }) => _ElementTypeFinder(type, skipOffstage: skipOffstage);
162 163 164 165

  /// Finds widgets whose current widget is the instance given by the
  /// argument.
  ///
166
  /// ## Sample code
167
  ///
168 169 170 171 172
  /// ```dart
  /// // Suppose you have a button created like this:
  /// Widget myButton = new Button(
  ///   child: new Text('Update')
  /// );
173
  ///
174 175 176
  /// // You can find and tap on it like this:
  /// tester.tap(find.byWidget(myButton));
  /// ```
177
  ///
178 179
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
180
  Finder byWidget(Widget widget, { bool skipOffstage = true }) => _WidgetFinder(widget, skipOffstage: skipOffstage);
181

182
  /// Finds widgets using a widget [predicate].
183
  ///
184
  /// ## Sample code
185
  ///
186 187 188 189 190 191
  /// ```dart
  /// expect(find.byWidgetPredicate(
  ///   (Widget widget) => widget is Tooltip && widget.message == 'Back',
  ///   description: 'widget with tooltip "Back"',
  /// ), findsOneWidget);
  /// ```
192
  ///
193 194 195 196 197
  /// If [description] is provided, then this uses it as the description of the
  /// [Finder] and appears, for example, in the error message when the finder
  /// fails to locate the desired widget. Otherwise, the description prints the
  /// signature of the predicate function.
  ///
198 199
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
200
  Finder byWidgetPredicate(WidgetPredicate predicate, { String? description, bool skipOffstage = true }) {
201
    return _WidgetPredicateFinder(predicate, description: description, skipOffstage: skipOffstage);
202 203
  }

204 205
  /// Finds Tooltip widgets with the given message.
  ///
206
  /// ## Sample code
207
  ///
208 209 210
  /// ```dart
  /// expect(find.byTooltip('Back'), findsOneWidget);
  /// ```
211
  ///
212 213
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
214
  Finder byTooltip(String message, { bool skipOffstage = true }) {
215 216 217 218 219 220
    return byWidgetPredicate(
      (Widget widget) => widget is Tooltip && widget.message == message,
      skipOffstage: skipOffstage,
    );
  }

221
  /// Finds widgets using an element [predicate].
222
  ///
223
  /// ## Sample code
224
  ///
225 226 227 228 229 230 231 232 233
  /// ```dart
  /// expect(find.byElementPredicate(
  ///   // finds elements of type SingleChildRenderObjectElement, including
  ///   // those that are actually subclasses of that type.
  ///   // (contrast with byElementType, which only returns exact matches)
  ///   (Element element) => element is SingleChildRenderObjectElement,
  ///   description: '$SingleChildRenderObjectElement element',
  /// ), findsOneWidget);
  /// ```
234
  ///
235 236 237 238 239
  /// If [description] is provided, then this uses it as the description of the
  /// [Finder] and appears, for example, in the error message when the finder
  /// fails to locate the desired widget. Otherwise, the description prints the
  /// signature of the predicate function.
  ///
240 241
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
242
  Finder byElementPredicate(ElementPredicate predicate, { String? description, bool skipOffstage = true }) {
243
    return _ElementPredicateFinder(predicate, description: description, skipOffstage: skipOffstage);
244
  }
245

246 247
  /// Finds widgets that are descendants of the [of] parameter and that match
  /// the [matching] parameter.
248
  ///
249
  /// ## Sample code
250
  ///
251 252 253 254 255
  /// ```dart
  /// expect(find.descendant(
  ///   of: find.widgetWithText(Row, 'label_1'), matching: find.text('value_1')
  /// ), findsOneWidget);
  /// ```
256
  ///
257 258 259
  /// If the [matchRoot] argument is true then the widget(s) specified by [of]
  /// will be matched along with the descendants.
  ///
260 261
  /// If the [skipOffstage] argument is true (the default), then nodes that are
  /// [Offstage] or that are from inactive [Route]s are skipped.
Ian Hickson's avatar
Ian Hickson committed
262
  Finder descendant({
263 264
    required Finder of,
    required Finder matching,
Ian Hickson's avatar
Ian Hickson committed
265 266 267
    bool matchRoot = false,
    bool skipOffstage = true,
  }) {
268
    return _DescendantFinder(of, matching, matchRoot: matchRoot, skipOffstage: skipOffstage);
269
  }
270 271 272 273

  /// Finds widgets that are ancestors of the [of] parameter and that match
  /// the [matching] parameter.
  ///
274
  /// ## Sample code
275
  ///
276 277 278 279 280 281 282 283 284 285 286 287 288
  /// ```dart
  /// // Test if a Text widget that contains 'faded' is the
  /// // descendant of an Opacity widget with opacity 0.5:
  /// expect(
  ///   tester.widget<Opacity>(
  ///     find.ancestor(
  ///       of: find.text('faded'),
  ///       matching: find.byType('Opacity'),
  ///     )
  ///   ).opacity,
  ///   0.5
  /// );
  /// ```
289 290 291
  ///
  /// If the [matchRoot] argument is true then the widget(s) specified by [of]
  /// will be matched along with the ancestors.
Ian Hickson's avatar
Ian Hickson committed
292
  Finder ancestor({
293 294
    required Finder of,
    required Finder matching,
Ian Hickson's avatar
Ian Hickson committed
295 296
    bool matchRoot = false,
  }) {
297
    return _AncestorFinder(of, matching, matchRoot: matchRoot);
298
  }
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

  /// Finds [Semantics] widgets matching the given `label`, either by
  /// [RegExp.hasMatch] or string equality.
  ///
  /// The framework may combine semantics labels in certain scenarios, such as
  /// when multiple [Text] widgets are in a [MaterialButton] widget. In such a
  /// case, it may be preferable to match by regular expression. Consumers of
  /// this API __must not__ introduce unsuitable content into the semantics tree
  /// for the purposes of testing; in particular, you should prefer matching by
  /// regular expression rather than by string if the framework has combined
  /// your semantics, and not try to force the framework to break up the
  /// semantics nodes. Breaking up the nodes would have an undesirable effect on
  /// screen readers and other accessibility services.
  ///
  /// ## Sample code
  ///
  /// ```dart
316
  /// expect(find.bySemanticsLabel('Back'), findsOneWidget);
317 318 319 320 321
  /// ```
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder bySemanticsLabel(Pattern label, { bool skipOffstage = true }) {
322
    if (WidgetsBinding.instance!.pipelineOwner.semanticsOwner == null)
323
      throw StateError('Semantics are not enabled. '
324
                       'Make sure to call tester.ensureSemantics() before using '
325 326 327 328 329 330 331 332
                       'this finder, and call dispose on its return value after.');
    return byElementPredicate(
      (Element element) {
        // Multiple elements can have the same renderObject - we want the "owner"
        // of the renderObject, i.e. the RenderObjectElement.
        if (element is! RenderObjectElement) {
          return false;
        }
333
        final String? semanticsLabel = element.renderObject.debugSemantics?.label;
334 335 336 337 338 339 340 341 342 343
        if (semanticsLabel == null) {
          return false;
        }
        return label is RegExp
            ? label.hasMatch(semanticsLabel)
            : label == semanticsLabel;
      },
      skipOffstage: skipOffstage,
    );
  }
344 345 346 347 348
}

/// Searches a widget tree and returns nodes that match a particular
/// pattern.
abstract class Finder {
349
  /// Initializes a Finder. Used by subclasses to initialize the [skipOffstage]
350
  /// property.
351
  Finder({ this.skipOffstage = true });
352

353 354 355 356 357 358 359 360 361 362 363 364 365
  /// Describes what the finder is looking for. The description should be
  /// a brief English noun phrase describing the finder's pattern.
  String get description;

  /// Returns all the elements in the given list that match this
  /// finder's pattern.
  ///
  /// When implementing your own Finders that inherit directly from
  /// [Finder], this is the main method to override. If your finder
  /// can efficiently be described just in terms of a predicate
  /// function, consider extending [MatchFinder] instead.
  Iterable<Element> apply(Iterable<Element> candidates);

366 367
  /// Whether this finder skips nodes that are offstage.
  ///
368 369 370
  /// If this is true, then the elements are walked using
  /// [Element.debugVisitOnstageChildren]. This skips offstage children of
  /// [Offstage] widgets, as well as children of inactive [Route]s.
371 372
  final bool skipOffstage;

373 374 375
  /// Returns all the [Element]s that will be considered by this finder.
  ///
  /// See [collectAllElementsFrom].
376 377
  @protected
  Iterable<Element> get allCandidates {
378
    return collectAllElementsFrom(
379
      WidgetsBinding.instance!.renderViewElement!,
380
      skipOffstage: skipOffstage,
381 382
    );
  }
383

384
  Iterable<Element>? _cachedResult;
385 386 387 388 389 390 391

  /// Returns the current result. If [precache] was called and returned true, this will
  /// cheaply return the result that was computed then. Otherwise, it creates a new
  /// iterable to compute the answer.
  ///
  /// Calling this clears the cache from [precache].
  Iterable<Element> evaluate() {
392
    final Iterable<Element> result = _cachedResult ?? apply(allCandidates);
393 394 395 396 397 398 399 400 401 402 403
    _cachedResult = null;
    return result;
  }

  /// Attempts to evaluate the finder. Returns whether any elements in the tree
  /// matched the finder. If any did, then the result is cached and can be obtained
  /// from [evaluate].
  ///
  /// If this returns true, you must call [evaluate] before you call [precache] again.
  bool precache() {
    assert(_cachedResult == null);
404
    final Iterable<Element> result = apply(allCandidates);
405 406 407 408 409 410 411 412
    if (result.isNotEmpty) {
      _cachedResult = result;
      return true;
    }
    _cachedResult = null;
    return false;
  }

413 414
  /// Returns a variant of this finder that only matches the first element
  /// matched by this finder.
415
  Finder get first => _FirstFinder(this);
416 417 418

  /// Returns a variant of this finder that only matches the last element
  /// matched by this finder.
419
  Finder get last => _LastFinder(this);
420

421 422
  /// Returns a variant of this finder that only matches the element at the
  /// given index matched by this finder.
423
  Finder at(int index) => _IndexFinder(this, index);
424

425 426 427 428 429
  /// Returns a variant of this finder that only matches elements reachable by
  /// a hit test.
  ///
  /// The [at] parameter specifies the location relative to the size of the
  /// target element where the hit test is performed.
430
  Finder hitTestable({ Alignment at = Alignment.center }) => _HitTestableFinder(this, at);
431

432 433
  @override
  String toString() {
434
    final String additional = skipOffstage ? ' (ignoring offstage widgets)' : '';
435 436 437
    final List<Element> widgets = evaluate().toList();
    final int count = widgets.length;
    if (count == 0)
438
      return 'zero widgets with $description$additional';
439
    if (count == 1)
440
      return 'exactly one widget with $description$additional: ${widgets.single}';
441
    if (count < 4)
442 443
      return '$count widgets with $description$additional: $widgets';
    return '$count widgets with $description$additional: ${widgets[0]}, ${widgets[1]}, ${widgets[2]}, ...';
444 445 446
  }
}

447 448 449 450
/// Applies additional filtering against a [parent] [Finder].
abstract class ChainedFinder extends Finder {
  /// Create a Finder chained against the candidates of another [Finder].
  ChainedFinder(this.parent) : assert(parent != null);
451

452
  /// Another [Finder] that will run first.
453 454
  final Finder parent;

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  /// Return another [Iterable] when given an [Iterable] of candidates from a
  /// parent [Finder].
  ///
  /// This is the method to implement when subclassing [ChainedFinder].
  Iterable<Element> filter(Iterable<Element> parentCandidates);

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return filter(parent.apply(candidates));
  }

  @override
  Iterable<Element> get allCandidates => parent.allCandidates;
}

class _FirstFinder extends ChainedFinder {
  _FirstFinder(Finder parent) : super(parent);

473 474 475 476
  @override
  String get description => '${parent.description} (ignoring all but first)';

  @override
477 478
  Iterable<Element> filter(Iterable<Element> parentCandidates) sync* {
    yield parentCandidates.first;
479 480 481
  }
}

482 483
class _LastFinder extends ChainedFinder {
  _LastFinder(Finder parent) : super(parent);
484 485 486 487 488

  @override
  String get description => '${parent.description} (ignoring all but last)';

  @override
489 490
  Iterable<Element> filter(Iterable<Element> parentCandidates) sync* {
    yield parentCandidates.last;
491 492 493
  }
}

494 495
class _IndexFinder extends ChainedFinder {
  _IndexFinder(Finder parent, this.index) : super(parent);
496 497 498 499 500 501 502

  final int index;

  @override
  String get description => '${parent.description} (ignoring all but index $index)';

  @override
503 504
  Iterable<Element> filter(Iterable<Element> parentCandidates) sync* {
    yield parentCandidates.elementAt(index);
505 506 507
  }
}

508 509
class _HitTestableFinder extends ChainedFinder {
  _HitTestableFinder(Finder parent, this.alignment) : super(parent);
510

511
  final Alignment alignment;
512 513 514 515 516

  @override
  String get description => '${parent.description} (considering only hit-testable ones)';

  @override
517 518
  Iterable<Element> filter(Iterable<Element> parentCandidates) sync* {
    for (final Element candidate in parentCandidates) {
519
      final RenderBox box = candidate.renderObject! as RenderBox;
520
      final Offset absoluteOffset = box.localToGlobal(alignment.alongSize(box.size));
521
      final HitTestResult hitResult = HitTestResult();
522
      WidgetsBinding.instance!.hitTest(hitResult, absoluteOffset);
523 524 525 526 527 528 529 530 531 532
      for (final HitTestEntry entry in hitResult.path) {
        if (entry.target == candidate.renderObject) {
          yield candidate;
          break;
        }
      }
    }
  }
}

533 534 535
/// Searches a widget tree and returns nodes that match a particular
/// pattern.
abstract class MatchFinder extends Finder {
536
  /// Initializes a predicate-based Finder. Used by subclasses to initialize the
537
  /// [skipOffstage] property.
538
  MatchFinder({ bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
539

540 541 542 543 544 545 546 547 548 549 550 551
  /// Returns true if the given element matches the pattern.
  ///
  /// When implementing your own MatchFinder, this is the main method to override.
  bool matches(Element candidate);

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates.where(matches);
  }
}

class _TextFinder extends MatchFinder {
552
  _TextFinder(this.text, { bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
553 554 555 556 557 558 559 560

  final String text;

  @override
  String get description => 'text "$text"';

  @override
  bool matches(Element candidate) {
561 562 563 564
    final Widget widget = candidate.widget;
    if (widget is Text) {
      if (widget.data != null)
        return widget.data == text;
565 566
      assert(widget.textSpan != null);
      return widget.textSpan!.toPlainText() == text;
567 568
    } else if (widget is EditableText) {
      return widget.controller.text == text;
569 570
    }
    return false;
571 572 573
  }
}

574 575 576 577 578 579 580 581 582 583 584 585 586 587
class _TextContainingFinder extends MatchFinder {
  _TextContainingFinder(this.pattern, {bool skipOffstage = true})
      : super(skipOffstage: skipOffstage);

  final Pattern pattern;

  @override
  String get description => 'text containing $pattern';

  @override
  bool matches(Element candidate) {
    final Widget widget = candidate.widget;
    if (widget is Text) {
      if (widget.data != null)
588 589 590
        return widget.data!.contains(pattern);
      assert(widget.textSpan != null);
      return widget.textSpan!.toPlainText().contains(pattern);
591 592 593 594 595 596 597
    } else if (widget is EditableText) {
      return widget.controller.text.contains(pattern);
    }
    return false;
  }
}

598
class _KeyFinder extends MatchFinder {
599
  _KeyFinder(this.key, { bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
600 601 602 603 604 605 606 607 608 609 610 611 612

  final Key key;

  @override
  String get description => 'key $key';

  @override
  bool matches(Element candidate) {
    return candidate.widget.key == key;
  }
}

class _WidgetTypeFinder extends MatchFinder {
613
  _WidgetTypeFinder(this.widgetType, { bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
614 615 616 617 618 619 620 621 622 623 624 625

  final Type widgetType;

  @override
  String get description => 'type "$widgetType"';

  @override
  bool matches(Element candidate) {
    return candidate.widget.runtimeType == widgetType;
  }
}

626
class _WidgetIconFinder extends MatchFinder {
627
  _WidgetIconFinder(this.icon, { bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
628 629 630 631 632 633 634 635 636 637 638 639 640

  final IconData icon;

  @override
  String get description => 'icon "$icon"';

  @override
  bool matches(Element candidate) {
    final Widget widget = candidate.widget;
    return widget is Icon && widget.icon == icon;
  }
}

641
class _ElementTypeFinder extends MatchFinder {
642
  _ElementTypeFinder(this.elementType, { bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
643 644 645 646 647 648 649 650 651 652 653 654

  final Type elementType;

  @override
  String get description => 'type "$elementType"';

  @override
  bool matches(Element candidate) {
    return candidate.runtimeType == elementType;
  }
}

655
class _WidgetFinder extends MatchFinder {
656
  _WidgetFinder(this.widget, { bool skipOffstage = true }) : super(skipOffstage: skipOffstage);
657

658
  final Widget widget;
659 660

  @override
661
  String get description => 'the given widget ($widget)';
662 663 664

  @override
  bool matches(Element candidate) {
665
    return candidate.widget == widget;
666 667 668 669
  }
}

class _WidgetPredicateFinder extends MatchFinder {
670
  _WidgetPredicateFinder(this.predicate, { String? description, bool skipOffstage = true })
671 672
    : _description = description,
      super(skipOffstage: skipOffstage);
673 674

  final WidgetPredicate predicate;
675
  final String? _description;
676 677

  @override
678
  String get description => _description ?? 'widget matching predicate ($predicate)';
679 680 681 682 683 684 685 686

  @override
  bool matches(Element candidate) {
    return predicate(candidate.widget);
  }
}

class _ElementPredicateFinder extends MatchFinder {
687
  _ElementPredicateFinder(this.predicate, { String? description, bool skipOffstage = true })
688 689
    : _description = description,
      super(skipOffstage: skipOffstage);
690 691

  final ElementPredicate predicate;
692
  final String? _description;
693 694

  @override
695
  String get description => _description ?? 'element matching predicate ($predicate)';
696 697 698 699 700 701

  @override
  bool matches(Element candidate) {
    return predicate(candidate);
  }
}
702 703

class _DescendantFinder extends Finder {
704 705 706
  _DescendantFinder(
    this.ancestor,
    this.descendant, {
707 708
    this.matchRoot = false,
    bool skipOffstage = true,
709
  }) : super(skipOffstage: skipOffstage);
710 711 712

  final Finder ancestor;
  final Finder descendant;
713
  final bool matchRoot;
714 715

  @override
716 717 718 719 720
  String get description {
    if (matchRoot)
      return '${descendant.description} in the subtree(s) beginning with ${ancestor.description}';
    return '${descendant.description} that has ancestor(s) with ${ancestor.description}';
  }
721 722 723 724 725 726 727 728

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates.where((Element element) => descendant.evaluate().contains(element));
  }

  @override
  Iterable<Element> get allCandidates {
729
    final Iterable<Element> ancestorElements = ancestor.evaluate();
730
    final List<Element> candidates = ancestorElements.expand<Element>(
731 732
      (Element element) => collectAllElementsFrom(element, skipOffstage: skipOffstage)
    ).toSet().toList();
733 734 735
    if (matchRoot)
      candidates.insertAll(0, ancestorElements);
    return candidates;
736 737
  }
}
738 739

class _AncestorFinder extends Finder {
740
  _AncestorFinder(this.descendant, this.ancestor, { this.matchRoot = false }) : super(skipOffstage: false);
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

  final Finder ancestor;
  final Finder descendant;
  final bool matchRoot;

  @override
  String get description {
    if (matchRoot)
      return 'ancestor ${ancestor.description} beginning with ${descendant.description}';
    return '${ancestor.description} which is an ancestor of ${descendant.description}';
  }

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates.where((Element element) => ancestor.evaluate().contains(element));
  }

  @override
  Iterable<Element> get allCandidates {
    final List<Element> candidates = <Element>[];
761
    for (final Element root in descendant.evaluate()) {
762 763 764 765 766 767 768 769 770 771 772 773
      final List<Element> ancestors = <Element>[];
      if (matchRoot)
        ancestors.add(root);
      root.visitAncestorElements((Element element) {
        ancestors.add(element);
        return true;
      });
      candidates.addAll(ancestors);
    }
    return candidates;
  }
}