modal_barrier_test.dart 37.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
yjbanov's avatar
yjbanov committed
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/foundation.dart';
6
import 'package:flutter/gestures.dart' show PointerDeviceKind, kSecondaryButton;
yjbanov's avatar
yjbanov committed
7
import 'package:flutter/material.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/services.dart';
10
import 'package:flutter_test/flutter_test.dart';
yjbanov's avatar
yjbanov committed
11

12 13
import 'semantics_tester.dart';

yjbanov's avatar
yjbanov committed
14
void main() {
15 16 17 18
  late bool tapped;
  late bool hovered;
  late Widget tapTarget;
  late Widget hoverTarget;
19
  late Animation<Color?> colorAnimation;
yjbanov's avatar
yjbanov committed
20 21 22

  setUp(() {
    tapped = false;
23
    colorAnimation = const AlwaysStoppedAnimation<Color?>(Colors.red);
24
    tapTarget = GestureDetector(
yjbanov's avatar
yjbanov committed
25 26 27
      onTap: () {
        tapped = true;
      },
28
      child: const SizedBox(
yjbanov's avatar
yjbanov committed
29 30
        width: 10.0,
        height: 10.0,
31 32
        child: Text('target', textDirection: TextDirection.ltr),
      ),
yjbanov's avatar
yjbanov committed
33
    );
34 35 36 37 38 39 40 41 42 43 44 45

    hovered = false;
    hoverTarget = MouseRegion(
      onHover: (_) { hovered = true; },
      onEnter: (_) { hovered = true; },
      onExit: (_) { hovered = true; },
      child: const SizedBox(
        width: 10.0,
        height: 10.0,
        child: Text('target', textDirection: TextDirection.ltr),
      ),
    );
yjbanov's avatar
yjbanov committed
46 47
  });

48 49 50 51 52 53 54 55 56
  group('ModalBarrier', () {
    testWidgets('prevents interactions with widgets behind it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          tapTarget,
          const ModalBarrier(dismissible: false),
        ],
      );
yjbanov's avatar
yjbanov committed
57

58 59 60 61 62
      await tester.pumpWidget(subject);
      await tester.tap(find.text('target'), warnIfMissed: false);
      await tester.pumpWidget(subject);
      expect(tapped, isFalse, reason: 'because the tap is not prevented by ModalBarrier');
    });
yjbanov's avatar
yjbanov committed
63

64 65 66 67 68 69 70 71
    testWidgets('prevents hover interactions with widgets behind it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          hoverTarget,
          const ModalBarrier(dismissible: false),
        ],
      );
72

73 74 75
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
      // Start out of hoverTarget
      await gesture.moveTo(const Offset(100, 100));
76

77 78 79 80 81 82
      await tester.pumpWidget(subject);
      // Move into hoverTarget and tap
      await gesture.down(const Offset(5, 5));
      await tester.pumpWidget(subject);
      await gesture.up();
      await tester.pumpWidget(subject);
83

84 85 86
      // Move out
      await gesture.moveTo(const Offset(100, 100));
      await tester.pumpWidget(subject);
87

88 89
      expect(hovered, isFalse, reason: 'because the hover is not prevented by ModalBarrier');
    });
90

91 92 93 94 95 96 97 98
    testWidgets('does not prevent interactions with widgets in front of it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          const ModalBarrier(dismissible: false),
          tapTarget,
        ],
      );
yjbanov's avatar
yjbanov committed
99

100 101 102 103 104
      await tester.pumpWidget(subject);
      await tester.tap(find.text('target'));
      await tester.pumpWidget(subject);
      expect(tapped, isTrue, reason: 'because the tap is prevented by ModalBarrier');
    });
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119
    testWidgets('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async {
      bool dragged = false;
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          const ModalBarrier(dismissible: false),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onHorizontalDragStart: (_) {
              dragged = true;
            },
            child: const Center(
              child: Text('target', textDirection: TextDirection.ltr),
            ),
120
          ),
121 122
        ],
      );
123

124 125 126 127 128 129 130 131
      await tester.pumpWidget(subject);
      await tester.dragFrom(
        tester.getBottomRight(find.byType(GestureDetector)) - const Offset(10, 10),
        const Offset(-20, 0),
      );
      await tester.pumpWidget(subject);
      expect(dragged, isTrue, reason: 'because the drag is prevented by ModalBarrier');
    });
132

133
    testWidgets('does not prevent hover interactions with widgets in front of it', (WidgetTester tester) async {
134 135 136 137
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          const ModalBarrier(dismissible: false),
138
          hoverTarget,
139 140 141
        ],
      );

142 143 144
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
      // Start out of hoverTarget
      await gesture.moveTo(const Offset(100, 100));
145
      await tester.pumpWidget(subject);
146 147 148 149
      expect(hovered, isFalse);

      // Move into hoverTarget
      await gesture.moveTo(const Offset(5, 5));
150
      await tester.pumpWidget(subject);
151 152
      expect(hovered, isTrue, reason: 'because the hover is prevented by ModalBarrier');
      hovered = false;
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 211 212 213 214 215 216 217 218 219 220 221
      // Move out
      await gesture.moveTo(const Offset(100, 100));
      await tester.pumpWidget(subject);
      expect(hovered, isTrue, reason: 'because the hover is prevented by ModalBarrier');
      hovered = false;
    });

    testWidgets('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async {
      final List<String> playedSystemSounds = <String>[];
      try {
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
            SystemChannels.platform, (MethodCall methodCall) async {
          if (methodCall.method == 'SystemSound.play') {
            playedSystemSounds.add(methodCall.arguments as String);
          }
          return null;
        });

        final Widget subject = Stack(
          textDirection: TextDirection.ltr,
          children: <Widget>[
            tapTarget,
            const ModalBarrier(dismissible: false),
          ],
        );

        await tester.pumpWidget(subject);
        await tester.tap(find.text('target'), warnIfMissed: false);
        await tester.pumpWidget(subject);
      } finally {
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
      }
      expect(playedSystemSounds, hasLength(1));
      expect(playedSystemSounds[0], SystemSoundType.alert.toString());
    });

    testWidgets('pops the Navigator when dismissed by primary tap', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => const SecondWidget(),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      // Press the barrier; it shouldn't dismiss yet
      final TestGesture gesture = await tester.press(
        find.byKey(const ValueKey<String>('barrier')),
      );
      await tester.pumpAndSettle(); // begin transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);

      // Release the pointer; the barrier should be dismissed
      await gesture.up();
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should have been dismissed by tapping the barrier.',
      );
    });
yjbanov's avatar
yjbanov committed
222

223 224 225 226 227
    testWidgets('pops the Navigator when dismissed by non-primary tap', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => const SecondWidget(),
      };
yjbanov's avatar
yjbanov committed
228

229
      await tester.pumpWidget(MaterialApp(routes: routes));
yjbanov's avatar
yjbanov committed
230

231 232
      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
yjbanov's avatar
yjbanov committed
233

234 235 236 237
      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
238

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
      // Press the barrier; it shouldn't dismiss yet
      final TestGesture gesture = await tester.press(
        find.byKey(const ValueKey<String>('barrier')),
        buttons: kSecondaryButton,
      );
      await tester.pumpAndSettle(); // begin transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);

      // Release the pointer; the barrier should be dismissed
      await gesture.up();
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should have been dismissed by tapping the barrier.',
      );
    });
256

257 258 259 260 261
    testWidgets('may pop the Navigator when competing with other gestures', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => const SecondWidgetWithCompetence(),
      };
262

263
      await tester.pumpWidget(MaterialApp(routes: routes));
264

265 266
      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
267

268 269 270 271 272 273 274 275 276
      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      // Tap on the barrier to dismiss it
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should have been dismissed by tapping the barrier.',
      );
    });

    testWidgets('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async {
      bool willPopCalled = false;
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) =>
            Stack(
              children: <Widget>[
                const SecondWidget(),
                WillPopScope(
                  child: const SizedBox(),
                  onWillPop: () async {
                    willPopCalled = true;
                    return false;
                  },
                ),
              ],
            ),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(willPopCalled, isFalse);

      // Tap on the barrier to attempt to dismiss it
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsOneWidget,
        reason: 'The route should still be present if the pop is vetoed.',
      );
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 359 360 361 362 363 364 365 366 367 368 369 370
      expect(willPopCalled, isTrue);
    });

    testWidgets('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async {
      bool willPopCalled = false;
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) =>
            Stack(
              children: <Widget>[
                const SecondWidget(),
                WillPopScope(
                  child: const SizedBox(),
                  onWillPop: () async {
                    willPopCalled = true;
                    return true;
                  },
                ),
              ],
            ),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(willPopCalled, isFalse);

      // Tap on the barrier to attempt to dismiss it
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should not be present if the pop is permitted.',
      );
371

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
      expect(willPopCalled, isTrue);
    });

    testWidgets('will call onDismiss callback', (WidgetTester tester) async {
      bool dismissCallbackCalled = false;
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) =>
            SecondWidget(onDismiss: () {
              dismissCallbackCalled = true;
            }),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
      expect(dismissCallbackCalled, false);

      // Tap on the barrier
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(dismissCallbackCalled, true);
    });

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    testWidgets('when onDismiss throws, should have correct context', (WidgetTester tester) async {
      final FlutterExceptionHandler? handler = FlutterError.onError;
      FlutterErrorDetails? error;
      FlutterError.onError = (FlutterErrorDetails details) {
        error = details;
      };

      final UniqueKey barrierKey = UniqueKey();
      await tester.pumpWidget(MaterialApp(
        home: Scaffold(
          body: ModalBarrier(
            key: barrierKey,
            onDismiss: () => throw Exception('deliberate'),
          ),
        ),
      ));
      await tester.tap(find.byKey(barrierKey));
      await tester.pump();

      expect(error?.context.toString(), contains('handling a gesture'));
      FlutterError.onError = handler;
    });

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
    testWidgets('will not pop when given an onDismiss callback', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => SecondWidget(onDismiss: () {}),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);

      // Tap on the barrier
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsOneWidget,
        reason: 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.',
      );
    });
452

453 454 455
    testWidgets('Undismissible ModalBarrier hidden in semantic tree', (WidgetTester tester) async {
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(const ModalBarrier(dismissible: false));
456

457 458
      final TestSemantics expectedSemantics = TestSemantics.root();
      expect(semantics, hasSemantics(expectedSemantics));
459

460 461
      semantics.dispose();
    });
462

463
    testWidgets('Dismissible ModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async {
464 465 466 467 468 469 470 471 472 473 474
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(const Directionality(
        textDirection: TextDirection.ltr,
        child: ModalBarrier(
          semanticsLabel: 'Dismiss',
        ),
      ));

      final TestSemantics expectedSemantics = TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics.rootChild(
475
            id: 1,
476 477 478 479
            rect: TestSemantics.fullScreen,
            actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
            label: 'Dismiss',
            textDirection: TextDirection.ltr,
480
          ),
481
        ],
482 483
      );
      expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
484

485
      semantics.dispose();
486
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android}));
487 488 489 490 491 492 493 494 495 496
  });
  group('AnimatedModalBarrier', () {
    testWidgets('prevents interactions with widgets behind it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          tapTarget,
          AnimatedModalBarrier(dismissible: false, color: colorAnimation),
        ],
      );
497

498 499 500 501 502
      await tester.pumpWidget(subject);
      await tester.tap(find.text('target'), warnIfMissed: false);
      await tester.pumpWidget(subject);
      expect(tapped, isFalse, reason: 'because the tap is not prevented by ModalBarrier');
    });
503

504 505 506 507 508 509 510 511
    testWidgets('prevents hover interactions with widgets behind it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          hoverTarget,
          AnimatedModalBarrier(dismissible: false, color: colorAnimation),
        ],
      );
512

513 514 515 516 517 518 519 520 521 522 523 524 525 526
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
      // Start out of hoverTarget
      await gesture.moveTo(const Offset(100, 100));

      await tester.pumpWidget(subject);
      // Move into hoverTarget and tap
      await gesture.down(const Offset(5, 5));
      await tester.pumpWidget(subject);
      await gesture.up();
      await tester.pumpWidget(subject);

      // Move out
      await gesture.moveTo(const Offset(100, 100));
      await tester.pumpWidget(subject);
527

528 529 530 531 532 533
      expect(hovered, isFalse, reason: 'because the hover is not prevented by AnimatedModalBarrier');
    });

    testWidgets('does not prevent interactions with widgets in front of it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
534
        children: <Widget>[
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
          AnimatedModalBarrier(dismissible: false, color: colorAnimation),
          tapTarget,
        ],
      );

      await tester.pumpWidget(subject);
      await tester.tap(find.text('target'));
      await tester.pumpWidget(subject);
      expect(tapped, isTrue, reason: 'because the tap is prevented by AnimatedModalBarrier');
    });

    testWidgets('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async {
      bool dragged = false;
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          AnimatedModalBarrier(dismissible: false, color: colorAnimation),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onHorizontalDragStart: (_) {
              dragged = true;
556
            },
557 558 559
            child: const Center(
              child: Text('target', textDirection: TextDirection.ltr),
            ),
560
          ),
561
        ],
562
      );
563

564 565 566 567 568 569 570 571
      await tester.pumpWidget(subject);
      await tester.dragFrom(
        tester.getBottomRight(find.byType(GestureDetector)) - const Offset(10, 10),
        const Offset(-20, 0),
      );
      await tester.pumpWidget(subject);
      expect(dragged, isTrue, reason: 'because the drag is prevented by AnimatedModalBarrier');
    });
572

573 574 575 576 577 578 579 580
    testWidgets('does not prevent hover interactions with widgets in front of it', (WidgetTester tester) async {
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
        children: <Widget>[
          AnimatedModalBarrier(dismissible: false, color: colorAnimation),
          hoverTarget,
        ],
      );
581

582 583 584 585 586
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
      // Start out of hoverTarget
      await gesture.moveTo(const Offset(100, 100));
      await tester.pumpWidget(subject);
      expect(hovered, isFalse);
587

588 589 590 591 592
      // Move into hoverTarget
      await gesture.moveTo(const Offset(5, 5));
      await tester.pumpWidget(subject);
      expect(hovered, isTrue, reason: 'because the hover is prevented by AnimatedModalBarrier');
      hovered = false;
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
      // Move out
      await gesture.moveTo(const Offset(100, 100));
      await tester.pumpWidget(subject);
      expect(hovered, isTrue, reason: 'because the hover is prevented by AnimatedModalBarrier');
      hovered = false;
    });

    testWidgets('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async {
      final List<String> playedSystemSounds = <String>[];
      try {
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
            SystemChannels.platform, (MethodCall methodCall) async {
          if (methodCall.method == 'SystemSound.play') {
            playedSystemSounds.add(methodCall.arguments as String);
          }
          return null;
        });

        final Widget subject = Stack(
          textDirection: TextDirection.ltr,
          children: <Widget>[
            tapTarget,
            AnimatedModalBarrier(dismissible: false, color: colorAnimation),
          ],
        );

        await tester.pumpWidget(subject);
        await tester.tap(find.text('target'), warnIfMissed: false);
        await tester.pumpWidget(subject);
      } finally {
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
      }
      expect(playedSystemSounds, hasLength(1));
      expect(playedSystemSounds[0], SystemSoundType.alert.toString());
    });

    testWidgets('pops the Navigator when dismissed by primary tap', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => const AnimatedSecondWidget(),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      // Press the barrier; it shouldn't dismiss yet
      final TestGesture gesture = await tester.press(
        find.byKey(const ValueKey<String>('barrier')),
      );
      await tester.pumpAndSettle(); // begin transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);

      // Release the pointer; the barrier should be dismissed
      await gesture.up();
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should have been dismissed by tapping the barrier.',
      );
    });
662

663 664 665 666 667
    testWidgets('pops the Navigator when dismissed by non-primary tap', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => const AnimatedSecondWidget(),
      };
668

669
      await tester.pumpWidget(MaterialApp(routes: routes));
670

671 672
      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
673

674 675 676 677
      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
      // Press the barrier; it shouldn't dismiss yet
      final TestGesture gesture = await tester.press(
        find.byKey(const ValueKey<String>('barrier')),
        buttons: kSecondaryButton,
      );
      await tester.pumpAndSettle(); // begin transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);

      // Release the pointer; the barrier should be dismissed
      await gesture.up();
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should have been dismissed by tapping the barrier.',
      );
    });
696

697 698 699 700 701
    testWidgets('may pop the Navigator when competing with other gestures', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => const AnimatedSecondWidgetWithCompetence(),
      };
702

703
      await tester.pumpWidget(MaterialApp(routes: routes));
704

705 706
      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);
707

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      // Tap on the barrier to dismiss it
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should have been dismissed by tapping the barrier.',
      );
    });

    testWidgets('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async {
      bool willPopCalled = false;
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) =>
            Stack(
              children: <Widget>[
                const AnimatedSecondWidget(),
                WillPopScope(
                  child: const SizedBox(),
                  onWillPop: () async {
                    willPopCalled = true;
                    return false;
                  },
                ),
              ],
            ),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(willPopCalled, isFalse);

      // Tap on the barrier to attempt to dismiss it
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsOneWidget,
        reason: 'The route should still be present if the pop is vetoed.',
      );

      expect(willPopCalled, isTrue);
    });

    testWidgets('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async {
      bool willPopCalled = false;
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) =>
            Stack(
              children: <Widget>[
                const AnimatedSecondWidget(),
                WillPopScope(
                  child: const SizedBox(),
                  onWillPop: () async {
                    willPopCalled = true;
                    return true;
                  },
                ),
              ],
            ),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(willPopCalled, isFalse);

      // Tap on the barrier to attempt to dismiss it
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition

      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsNothing,
        reason: 'The route should not be present if the pop is permitted.',
      );

      expect(willPopCalled, isTrue);
    });

    testWidgets('will call onDismiss callback', (WidgetTester tester) async {
      bool dismissCallbackCalled = false;
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) =>
            AnimatedSecondWidget(onDismiss: () {
              dismissCallbackCalled = true;
            }),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);
      expect(dismissCallbackCalled, false);

      // Tap on the barrier
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(dismissCallbackCalled, true);
    });

    testWidgets('will not pop when given an onDismiss callback', (WidgetTester tester) async {
      final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
        '/': (BuildContext context) => const FirstWidget(),
        '/modal': (BuildContext context) => AnimatedSecondWidget(onDismiss: () {}),
      };

      await tester.pumpWidget(MaterialApp(routes: routes));

      // Initially the barrier is not visible
      expect(find.byKey(const ValueKey<String>('barrier')), findsNothing);

      // Tapping on X routes to the barrier
      await tester.tap(find.text('X'));
      await tester.pump(); // begin transition
      await tester.pump(const Duration(seconds: 1)); // end transition
      expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget);

      // Tap on the barrier
      await tester.tap(find.byKey(const ValueKey<String>('barrier')));
      await tester.pumpAndSettle(const Duration(seconds: 1)); // end transition
      expect(
        find.byKey(const ValueKey<String>('barrier')),
        findsOneWidget,
        reason: 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.',
      );
    });

    testWidgets('Undismissible AnimatedModalBarrier hidden in semantic tree', (WidgetTester tester) async {
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(AnimatedModalBarrier(dismissible: false, color: colorAnimation));

      final TestSemantics expectedSemantics = TestSemantics.root();
      expect(semantics, hasSemantics(expectedSemantics));

      semantics.dispose();
    });

880
    testWidgets('Dismissible AnimatedModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async {
881 882 883 884 885 886
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(Directionality(
        textDirection: TextDirection.ltr,
        child: AnimatedModalBarrier(
          semanticsLabel: 'Dismiss',
          color: colorAnimation,
887
        ),
888 889 890 891 892 893 894 895 896 897 898 899 900
      ));

      final TestSemantics expectedSemantics = TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics.rootChild(
            rect: TestSemantics.fullScreen,
            actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
            label: 'Dismiss',
            textDirection: TextDirection.ltr,
          ),
        ],
      );
      expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
901

902
      semantics.dispose();
903 904
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android}));
  });
905

906 907
  group('SemanticsClipper', () {
    testWidgets('SemanticsClipper correctly clips Semantics.rect in four directions', (WidgetTester tester) async {
908
      final SemanticsTester semantics = SemanticsTester(tester);
909 910 911 912 913 914 915 916 917
      final ValueNotifier<EdgeInsets> notifier = ValueNotifier<EdgeInsets>(const EdgeInsets.fromLTRB(10, 20, 30, 40));
      const Rect fullScreen = TestSemantics.fullScreen;
      await tester.pumpWidget(Directionality(
        textDirection: TextDirection.ltr,
        child: ModalBarrier(
          semanticsLabel: 'Dismiss',
          clipDetailsNotifier: notifier,
        ),
      ));
918

919 920 921 922 923 924 925 926 927 928 929 930
      final TestSemantics expectedSemantics = TestSemantics.root(
        children: <TestSemantics>[
          TestSemantics.rootChild(
            rect: Rect.fromLTRB(fullScreen.left + 10, fullScreen.top + 20.0, fullScreen.right - 30, fullScreen.bottom - 40),
            actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
            label: 'Dismiss',
            textDirection: TextDirection.ltr,
          ),
        ],

      );
      expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
931

932
      semantics.dispose();
933
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android}));
934
  });
935

936
  testWidgets('uses default mouse cursor', (WidgetTester tester) async {
937
    await tester.pumpWidget(const Stack(
938
      textDirection: TextDirection.ltr,
939
      children: <Widget>[
940 941 942 943 944 945 946 947 948 949
        MouseRegion(cursor: SystemMouseCursors.click),
        ModalBarrier(dismissible: false),
      ],
    ));

    final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
    await gesture.addPointer(location: tester.getCenter(find.byType(ModalBarrier)));

    await tester.pump();

950
    expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
951
  });
yjbanov's avatar
yjbanov committed
952 953
}

954
class FirstWidget extends StatelessWidget {
955
  const FirstWidget({super.key});
956
  @override
yjbanov's avatar
yjbanov committed
957
  Widget build(BuildContext context) {
958 959 960 961
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, '/modal');
      },
962
      child: const Text('X'),
963
    );
yjbanov's avatar
yjbanov committed
964 965 966
  }
}

967
class SecondWidget extends StatelessWidget {
968
  const SecondWidget({super.key, this.onDismiss});
969 970 971

  final VoidCallback? onDismiss;

972
  @override
yjbanov's avatar
yjbanov committed
973
  Widget build(BuildContext context) {
974 975 976
    return ModalBarrier(
      key: const ValueKey<String>('barrier'),
      onDismiss: onDismiss,
977
    );
yjbanov's avatar
yjbanov committed
978 979
  }
}
980

981
class AnimatedSecondWidget extends StatelessWidget {
982
  const AnimatedSecondWidget({super.key, this.onDismiss});
983 984 985 986 987 988 989 990 991 992 993 994 995

  final VoidCallback? onDismiss;

  @override
  Widget build(BuildContext context) {
    return AnimatedModalBarrier(
      key: const ValueKey<String>('barrier'),
      color: const AlwaysStoppedAnimation<Color?>(Colors.red),
      onDismiss: onDismiss,
    );
  }
}

996
class SecondWidgetWithCompetence extends StatelessWidget {
997
  const SecondWidgetWithCompetence({super.key});
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        const ModalBarrier(
          key: ValueKey<String>('barrier'),
        ),
        GestureDetector(
          onVerticalDragStart: (_) {},
          behavior: HitTestBehavior.translucent,
          child: Container(),
1009
        ),
1010 1011 1012 1013
      ],
    );
  }
}
1014
class AnimatedSecondWidgetWithCompetence extends StatelessWidget {
1015
  const AnimatedSecondWidgetWithCompetence({super.key});
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        const AnimatedModalBarrier(
          key: ValueKey<String>('barrier'),
          color: AlwaysStoppedAnimation<Color?>(Colors.red),
        ),
        GestureDetector(
          onVerticalDragStart: (_) {},
          behavior: HitTestBehavior.translucent,
          child: Container(),
        ),
      ],
    );
  }
}