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

import 'package:flutter/foundation.dart';
6
import 'package:flutter/gestures.dart';
7
import 'package:flutter/material.dart';
8
import 'package:flutter/services.dart';
9 10 11
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';

12
typedef PostInvokeCallback = void Function({Action<Intent> action, Intent intent, ActionDispatcher dispatcher});
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27
class TestIntent extends Intent {
  const TestIntent();
}

class SecondTestIntent extends TestIntent {
  const SecondTestIntent();
}

class ThirdTestIntent extends SecondTestIntent {
  const ThirdTestIntent();
}

class TestAction extends CallbackAction<TestIntent> {
  TestAction({
28 29
    @required OnInvokeCallback onInvoke,
  })  : assert(onInvoke != null),
30
        super(onInvoke: onInvoke);
31

32 33 34 35 36 37 38 39 40 41
  @override
  bool get enabled => _enabled;
  bool _enabled = true;
  set enabled(bool value) {
    if (_enabled == value) {
      return;
    }
    _enabled = value;
    notifyActionListeners();
  }
42

43 44 45 46 47 48 49 50 51 52 53 54 55 56
  @override
  void addActionListener(ActionListenerCallback listener) {
    super.addActionListener(listener);
    listeners.add(listener);
  }

  @override
  void removeActionListener(ActionListenerCallback listener) {
    super.removeActionListener(listener);
    listeners.remove(listener);
  }
  List<ActionListenerCallback> listeners = <ActionListenerCallback>[];

  void _testInvoke(TestIntent intent) => invoke(intent);
57 58 59 60 61 62 63 64
}

class TestDispatcher extends ActionDispatcher {
  const TestDispatcher({this.postInvoke});

  final PostInvokeCallback postInvoke;

  @override
65 66 67
  Object invokeAction(Action<Intent> action, Intent intent, [BuildContext context]) {
    final Object result = super.invokeAction(action, intent, context);
    postInvoke?.call(action: action, intent: intent, dispatcher: this);
68 69 70 71 72 73 74 75 76
    return result;
  }
}

class TestDispatcher1 extends TestDispatcher {
  const TestDispatcher1({PostInvokeCallback postInvoke}) : super(postInvoke: postInvoke);
}

void main() {
77 78 79 80 81
  testWidgets('CallbackAction passes correct intent when invoked.', (WidgetTester tester) async {
    Intent passedIntent;
    final TestAction action = TestAction(onInvoke: (Intent intent) {
      passedIntent = intent;
      return true;
82
    });
83 84 85
    const TestIntent intent = TestIntent();
    action._testInvoke(intent);
    expect(passedIntent, equals(intent));
86 87
  });
  group(ActionDispatcher, () {
88 89
    testWidgets('ActionDispatcher invokes actions when asked.', (WidgetTester tester) async {
      await tester.pumpWidget(Container());
90 91
      bool invoked = false;
      const ActionDispatcher dispatcher = ActionDispatcher();
92
      final Object result = dispatcher.invokeAction(
93
        TestAction(
94
          onInvoke: (Intent intent) {
95
            invoked = true;
96
            return invoked;
97 98
          },
        ),
99
        const TestIntent(),
100 101 102 103 104 105 106
      );
      expect(result, isTrue);
      expect(invoked, isTrue);
    });
  });
  group(Actions, () {
    Intent invokedIntent;
107
    Action<Intent> invokedAction;
108 109
    ActionDispatcher invokedDispatcher;

110
    void collect({Action<Intent> action, Intent intent, ActionDispatcher dispatcher}) {
111 112 113 114 115 116 117 118 119 120 121 122 123
      invokedIntent = intent;
      invokedAction = action;
      invokedDispatcher = dispatcher;
    }

    void clear() {
      invokedIntent = null;
      invokedAction = null;
      invokedDispatcher = null;
    }

    setUp(clear);

124
    testWidgets('Actions widget can invoke actions with default dispatcher', (WidgetTester tester) async {
125 126 127 128 129
      final GlobalKey containerKey = GlobalKey();
      bool invoked = false;

      await tester.pumpWidget(
        Actions(
130 131 132 133 134 135 136
          actions: <Type, Action<Intent>>{
            TestIntent: TestAction(
              onInvoke: (Intent intent) {
                invoked = true;
                return invoked;
              },
            ),
137 138 139 140 141 142
          },
          child: Container(key: containerKey),
        ),
      );

      await tester.pump();
143
      final Object result = Actions.invoke(
144
        containerKey.currentContext,
145
        const TestIntent(),
146 147 148 149
      );
      expect(result, isTrue);
      expect(invoked, isTrue);
    });
150
    testWidgets('Actions widget can invoke actions with custom dispatcher', (WidgetTester tester) async {
151 152
      final GlobalKey containerKey = GlobalKey();
      bool invoked = false;
153 154 155
      const TestIntent intent = TestIntent();
      final Action<Intent> testAction = TestAction(
        onInvoke: (Intent intent) {
156
          invoked = true;
157
          return invoked;
158 159 160 161 162 163
        },
      );

      await tester.pumpWidget(
        Actions(
          dispatcher: TestDispatcher(postInvoke: collect),
164 165
          actions: <Type, Action<Intent>>{
            TestIntent: testAction,
166 167 168 169 170 171
          },
          child: Container(key: containerKey),
        ),
      );

      await tester.pump();
172
      final Object result = Actions.invoke<TestIntent>(
173 174 175 176 177 178 179
        containerKey.currentContext,
        intent,
      );
      expect(result, isTrue);
      expect(invoked, isTrue);
      expect(invokedIntent, equals(intent));
    });
180
    testWidgets('Actions can invoke actions in ancestor dispatcher', (WidgetTester tester) async {
181 182
      final GlobalKey containerKey = GlobalKey();
      bool invoked = false;
183 184 185
      const TestIntent intent = TestIntent();
      final Action<Intent> testAction = TestAction(
        onInvoke: (Intent intent) {
186
          invoked = true;
187
          return invoked;
188 189 190 191 192 193
        },
      );

      await tester.pumpWidget(
        Actions(
          dispatcher: TestDispatcher1(postInvoke: collect),
194 195
          actions: <Type, Action<Intent>>{
            TestIntent: testAction,
196 197 198
          },
          child: Actions(
            dispatcher: TestDispatcher(postInvoke: collect),
199
            actions: const <Type, Action<Intent>>{},
200 201 202 203 204 205
            child: Container(key: containerKey),
          ),
        ),
      );

      await tester.pump();
206
      final Object result = Actions.invoke<TestIntent>(
207 208 209 210 211 212 213 214 215
        containerKey.currentContext,
        intent,
      );
      expect(result, isTrue);
      expect(invoked, isTrue);
      expect(invokedIntent, equals(intent));
      expect(invokedAction, equals(testAction));
      expect(invokedDispatcher.runtimeType, equals(TestDispatcher1));
    });
216
    testWidgets("Actions can invoke actions in ancestor dispatcher if a lower one isn't specified", (WidgetTester tester) async {
217 218
      final GlobalKey containerKey = GlobalKey();
      bool invoked = false;
219 220 221
      const TestIntent intent = TestIntent();
      final Action<Intent> testAction = TestAction(
        onInvoke: (Intent intent) {
222
          invoked = true;
223
          return invoked;
224 225 226 227 228 229
        },
      );

      await tester.pumpWidget(
        Actions(
          dispatcher: TestDispatcher1(postInvoke: collect),
230 231
          actions: <Type, Action<Intent>>{
            TestIntent: testAction,
232 233
          },
          child: Actions(
234
            actions: const <Type, Action<Intent>>{},
235 236 237 238 239 240
            child: Container(key: containerKey),
          ),
        ),
      );

      await tester.pump();
241
      final Object result = Actions.invoke<TestIntent>(
242 243 244 245 246 247 248 249 250
        containerKey.currentContext,
        intent,
      );
      expect(result, isTrue);
      expect(invoked, isTrue);
      expect(invokedIntent, equals(intent));
      expect(invokedAction, equals(testAction));
      expect(invokedDispatcher.runtimeType, equals(TestDispatcher1));
    });
251
    testWidgets('Actions widget can be found with of', (WidgetTester tester) async {
252 253 254 255 256 257
      final GlobalKey containerKey = GlobalKey();
      final ActionDispatcher testDispatcher = TestDispatcher1(postInvoke: collect);

      await tester.pumpWidget(
        Actions(
          dispatcher: testDispatcher,
258
          actions: const <Type, Action<Intent>>{},
259 260 261 262 263 264
          child: Container(key: containerKey),
        ),
      );

      await tester.pump();
      final ActionDispatcher dispatcher = Actions.of(
265 266
        containerKey.currentContext,
        nullOk: true,
267 268 269
      );
      expect(dispatcher, equals(testDispatcher));
    });
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    testWidgets('Action can be found with find', (WidgetTester tester) async {
      final GlobalKey containerKey = GlobalKey();
      final ActionDispatcher testDispatcher = TestDispatcher1(postInvoke: collect);
      bool invoked = false;
      final TestAction testAction = TestAction(
        onInvoke: (Intent intent) {
          invoked = true;
          return invoked;
        },
      );
      await tester.pumpWidget(
        Actions(
          dispatcher: testDispatcher,
          actions: <Type, Action<Intent>>{
            TestIntent: testAction,
          },
          child: Actions(
            actions: const <Type, Action<Intent>>{},
            child: Container(key: containerKey),
          ),
        ),
      );

      await tester.pump();
      expect(Actions.find<TestIntent>(containerKey.currentContext), equals(testAction));
      expect(() => Actions.find<DoNothingIntent>(containerKey.currentContext), throwsAssertionError);
      expect(Actions.find<DoNothingIntent>(containerKey.currentContext, nullOk: true), isNull);

      await tester.pumpWidget(
        Actions(
          dispatcher: testDispatcher,
          actions: <Type, Action<Intent>>{
            TestIntent: testAction,
          },
          child: Container(
            child: Actions(
              actions: const <Type, Action<Intent>>{},
              child: Container(key: containerKey),
            ),
          ),
        ),
      );

      await tester.pump();
      expect(Actions.find<TestIntent>(containerKey.currentContext), equals(testAction));
      expect(() => Actions.find<DoNothingIntent>(containerKey.currentContext), throwsAssertionError);
      expect(Actions.find<DoNothingIntent>(containerKey.currentContext, nullOk: true), isNull);
    });
318 319 320 321
    testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', (WidgetTester tester) async {
      FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
      final GlobalKey containerKey = GlobalKey();
      bool invoked = false;
322
      const Intent intent = TestIntent();
323
      final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
324 325
      final Action<Intent> testAction = TestAction(
        onInvoke: (Intent intent) {
326
          invoked = true;
327
          return invoked;
328 329 330 331 332 333 334 335 336 337
        },
      );
      bool hovering = false;
      bool focusing = false;

      Future<void> buildTest(bool enabled) async {
        await tester.pumpWidget(
          Center(
            child: Actions(
              dispatcher: TestDispatcher1(postInvoke: collect),
338
              actions: const <Type, Action<Intent>>{},
339 340 341 342 343 344
              child: FocusableActionDetector(
                enabled: enabled,
                focusNode: focusNode,
                shortcuts: <LogicalKeySet, Intent>{
                  LogicalKeySet(LogicalKeyboardKey.enter): intent,
                },
345 346
                actions: <Type, Action<Intent>>{
                  TestIntent: testAction,
347 348 349 350 351 352 353 354 355 356
                },
                onShowHoverHighlight: (bool value) => hovering = value,
                onShowFocusHighlight: (bool value) => focusing = value,
                child: Container(width: 100, height: 100, key: containerKey),
              ),
            ),
          ),
        );
        return tester.pump();
      }
357

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
      await buildTest(true);
      focusNode.requestFocus();
      await tester.pump();
      final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await gesture.moveTo(tester.getCenter(find.byKey(containerKey)));
      await tester.pump();
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      expect(hovering, isTrue);
      expect(focusing, isTrue);
      expect(invoked, isTrue);

      invoked = false;
      await buildTest(false);
      expect(hovering, isFalse);
      expect(focusing, isFalse);
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      await tester.pump();
      expect(invoked, isFalse);
      await buildTest(true);
      expect(focusing, isFalse);
      expect(hovering, isTrue);
      await buildTest(false);
      expect(focusing, isFalse);
      expect(hovering, isFalse);
      await gesture.moveTo(Offset.zero);
      await buildTest(true);
      expect(hovering, isFalse);
      expect(focusing, isFalse);
    });
388
  });
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554

  group('Listening', () {
    testWidgets('can listen to enabled state of Actions', (WidgetTester tester) async {
      final GlobalKey containerKey = GlobalKey();
      bool invoked1 = false;
      bool invoked2 = false;
      bool invoked3 = false;
      final TestAction action1 = TestAction(
        onInvoke: (Intent intent) {
          invoked1 = true;
          return invoked1;
        },
      );
      final TestAction action2 = TestAction(
        onInvoke: (Intent intent) {
          invoked2 = true;
          return invoked2;
        },
      );
      final TestAction action3 = TestAction(
        onInvoke: (Intent intent) {
          invoked3 = true;
          return invoked3;
        },
      );
      bool enabled1 = true;
      action1.addActionListener((Action<Intent> action) => enabled1 = action.enabled);
      action1.enabled = false;
      expect(enabled1, isFalse);

      bool enabled2 = true;
      action2.addActionListener((Action<Intent> action) => enabled2 = action.enabled);
      action2.enabled = false;
      expect(enabled2, isFalse);

      bool enabled3 = true;
      action3.addActionListener((Action<Intent> action) => enabled3 = action.enabled);
      action3.enabled = false;
      expect(enabled3, isFalse);

      await tester.pumpWidget(
        Actions(
          actions: <Type, Action<TestIntent>>{
            TestIntent: action1,
            SecondTestIntent: action2,
          },
          child: Actions(
            actions: <Type, Action<TestIntent>>{
              ThirdTestIntent: action3,
            },
            child: Container(key: containerKey),
          ),
        ),
      );

      Object result = Actions.invoke(
        containerKey.currentContext,
        const TestIntent(),
      );
      expect(enabled1, isFalse);
      expect(result, isFalse);
      expect(invoked1, isFalse);

      action1.enabled = true;
      result = Actions.invoke(
        containerKey.currentContext,
        const TestIntent(),
      );
      expect(enabled1, isTrue);
      expect(result, isTrue);
      expect(invoked1, isTrue);

      bool enabledChanged;
      await tester.pumpWidget(
        Actions(
          actions: <Type, Action<Intent>>{
            TestIntent: action1,
            SecondTestIntent: action2,
          },
          child: ActionListener(
            listener: (Action<Intent> action) => enabledChanged = action.enabled,
            action: action2,
            child: Actions(
              actions: <Type, Action<Intent>>{
                ThirdTestIntent: action3,
              },
              child: Container(key: containerKey),
            ),
          ),
        ),
      );

      await tester.pump();
      result = Actions.invoke<TestIntent>(
        containerKey.currentContext,
        const SecondTestIntent(),
      );
      expect(enabledChanged, isNull);
      expect(enabled2, isFalse);
      expect(result, isFalse);
      expect(invoked2, isFalse);

      action2.enabled = true;
      expect(enabledChanged, isTrue);
      result = Actions.invoke<TestIntent>(
        containerKey.currentContext,
        const SecondTestIntent(),
      );
      expect(enabled2, isTrue);
      expect(result, isTrue);
      expect(invoked2, isTrue);

      await tester.pumpWidget(
        Actions(
          actions: <Type, Action<Intent>>{
            TestIntent: action1,
          },
          child: Actions(
            actions: <Type, Action<Intent>>{
              ThirdTestIntent: action3,
            },
            child: Container(key: containerKey),
          ),
        ),
      );

      expect(action1.listeners.length, equals(2));
      expect(action2.listeners.length, equals(1));
      expect(action3.listeners.length, equals(2));

      await tester.pumpWidget(
        Actions(
          actions: <Type, Action<Intent>>{
            TestIntent: action1,
            ThirdTestIntent: action3,
          },
          child: Container(key: containerKey),
        ),
      );

      expect(action1.listeners.length, equals(2));
      expect(action2.listeners.length, equals(1));
      expect(action3.listeners.length, equals(2));

      await tester.pumpWidget(
        Actions(
          actions: <Type, Action<Intent>>{
            TestIntent: action1,
          },
          child: Container(key: containerKey),
        ),
      );

      expect(action1.listeners.length, equals(2));
      expect(action2.listeners.length, equals(1));
      expect(action3.listeners.length, equals(1));

      await tester.pumpWidget(Container());
      await tester.pump();

      expect(action1.listeners.length, equals(1));
      expect(action2.listeners.length, equals(1));
      expect(action3.listeners.length, equals(1));
    });
  });

555
  group('Diagnostics', () {
556
    testWidgets('default Intent debugFillProperties', (WidgetTester tester) async {
557 558
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();

559 560
      // ignore: invalid_use_of_protected_member
      const TestIntent().debugFillProperties(builder);
561 562

      final List<String> description = builder.properties
563 564 565 566 567
        .where((DiagnosticsNode node) {
          return !node.isFiltered(DiagnosticLevel.info);
        })
        .map((DiagnosticsNode node) => node.toString())
        .toList();
568

569
      expect(description, isEmpty);
570
    });
571
    testWidgets('default Actions debugFillProperties', (WidgetTester tester) async {
572 573
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();

574
      Actions(
575
        actions: const <Type, Action<Intent>>{},
576 577 578
        dispatcher: const ActionDispatcher(),
        child: Container(),
      ).debugFillProperties(builder);
579 580

      final List<String> description = builder.properties
581 582 583 584 585
        .where((DiagnosticsNode node) {
          return !node.isFiltered(DiagnosticLevel.info);
        })
        .map((DiagnosticsNode node) => node.toString())
        .toList();
586

587
      expect(description.length, equals(2));
588 589 590
      expect(description[0], equalsIgnoringHashCodes('dispatcher: ActionDispatcher#00000'));
      expect(description[1], equals('actions: {}'));
    });
591
    testWidgets('Actions implements debugFillProperties', (WidgetTester tester) async {
592 593 594 595
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();

      Actions(
        key: const ValueKey<String>('foo'),
596
        dispatcher: const ActionDispatcher(),
597 598
        actions: <Type, Action<Intent>>{
          TestIntent: TestAction(onInvoke: (Intent intent) => null),
599 600 601 602 603
        },
        child: Container(key: const ValueKey<String>('baz')),
      ).debugFillProperties(builder);

      final List<String> description = builder.properties
604 605 606 607 608
          .where((DiagnosticsNode node) {
            return !node.isFiltered(DiagnosticLevel.info);
          })
          .map((DiagnosticsNode node) => node.toString())
          .toList();
609

610
      expect(description.length, equals(2));
611
      expect(description[0], equalsIgnoringHashCodes('dispatcher: ActionDispatcher#00000'));
612
      expect(description[1], equalsIgnoringHashCodes('actions: {TestIntent: TestAction#00000}'));
613
    }, skip: isBrowser);
614 615
  });
}