modal_barrier_test.dart 37.8 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';
11
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
yjbanov's avatar
yjbanov committed
12

13 14
import 'semantics_tester.dart';

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

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

    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
47 48
  });

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

59 60 61 62 63
      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
64

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

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

78 79 80 81 82 83
      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);
84

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

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

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

101 102 103 104 105
      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');
    });
106

107
    testWidgetsWithLeakTracking('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async {
108 109 110 111 112 113 114 115 116 117 118 119 120
      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),
            ),
121
          ),
122 123
        ],
      );
124

125 126 127 128 129 130 131 132
      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');
    });
133

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

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

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

155 156 157 158 159 160 161
      // 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;
    });

162
    testWidgetsWithLeakTracking('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async {
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
      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());
    });

191
    testWidgetsWithLeakTracking('pops the Navigator when dismissed by primary tap', (WidgetTester tester) async {
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 222
      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
223

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

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

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

235 236 237 238
      // 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
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
      // 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.',
      );
    });
257

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

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

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

269 270 271 272 273 274 275 276 277
      // 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
278

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

286
    testWidgetsWithLeakTracking('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async {
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 326
      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.',
      );
327

328 329 330
      expect(willPopCalled, isTrue);
    });

331
    testWidgetsWithLeakTracking('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async {
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 371
      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.',
      );
372

373 374 375
      expect(willPopCalled, isTrue);
    });

376
    testWidgetsWithLeakTracking('will call onDismiss callback', (WidgetTester tester) async {
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 403
      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);
    });

404
    testWidgetsWithLeakTracking('when onDismiss throws, should have correct context', (WidgetTester tester) async {
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
      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;
    });

427
    testWidgetsWithLeakTracking('will not pop when given an onDismiss callback', (WidgetTester tester) async {
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
      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.',
      );
    });
453

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

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

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

464
    testWidgetsWithLeakTracking('Dismissible ModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async {
465 466 467 468 469 470 471 472 473 474 475
      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(
476
            id: 1,
477 478 479 480
            rect: TestSemantics.fullScreen,
            actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
            label: 'Dismiss',
            textDirection: TextDirection.ltr,
481
          ),
482
        ],
483 484
      );
      expect(semantics, hasSemantics(expectedSemantics, ignoreId: true));
485

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

499 500 501 502 503
      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');
    });
504

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

514 515 516 517 518 519 520 521 522 523 524 525 526 527
      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);
528

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

532
    testWidgetsWithLeakTracking('does not prevent interactions with widgets in front of it', (WidgetTester tester) async {
533 534
      final Widget subject = Stack(
        textDirection: TextDirection.ltr,
535
        children: <Widget>[
536 537 538 539 540 541 542 543 544 545 546
          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');
    });

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

565 566 567 568 569 570 571 572
      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');
    });
573

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

583 584 585 586 587
      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);
588

589 590 591 592 593
      // 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;
594

595 596 597 598 599 600 601
      // 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;
    });

602
    testWidgetsWithLeakTracking('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async {
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
      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());
    });

631
    testWidgetsWithLeakTracking('pops the Navigator when dismissed by primary tap', (WidgetTester tester) async {
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 662
      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.',
      );
    });
663

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

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

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

675 676 677 678
      // 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
679

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
      // 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.',
      );
    });
697

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

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

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

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
      // 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.',
      );
    });

726
    testWidgetsWithLeakTracking('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async {
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
      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);
    });

771
    testWidgetsWithLeakTracking('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async {
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
      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);
    });

816
    testWidgetsWithLeakTracking('will call onDismiss callback', (WidgetTester tester) async {
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
      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);
    });

844
    testWidgetsWithLeakTracking('will not pop when given an onDismiss callback', (WidgetTester tester) async {
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
      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.',
      );
    });

871
    testWidgetsWithLeakTracking('Undismissible AnimatedModalBarrier hidden in semantic tree', (WidgetTester tester) async {
872 873 874 875 876 877 878 879 880
      final SemanticsTester semantics = SemanticsTester(tester);
      await tester.pumpWidget(AnimatedModalBarrier(dismissible: false, color: colorAnimation));

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

      semantics.dispose();
    });

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

      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));
902

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

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

921 922 923 924 925 926 927 928 929 930 931 932
      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));
933

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

938
  testWidgetsWithLeakTracking('uses default mouse cursor', (WidgetTester tester) async {
939
    await tester.pumpWidget(const Stack(
940
      textDirection: TextDirection.ltr,
941
      children: <Widget>[
942 943 944 945 946 947 948 949 950 951
        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();

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

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

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

  final VoidCallback? onDismiss;

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

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

  final VoidCallback? onDismiss;

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

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