actions_test.dart 19.3 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
  @override
33 34
  bool isEnabled(TestIntent intent) => enabled;

35 36 37 38 39 40 41 42 43
  bool get enabled => _enabled;
  bool _enabled = true;
  set enabled(bool value) {
    if (_enabled == value) {
      return;
    }
    _enabled = value;
    notifyActionListeners();
  }
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58
  @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);
59 60 61 62 63 64 65 66
}

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

  final PostInvokeCallback postInvoke;

  @override
67 68 69
  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);
70 71 72 73 74 75 76 77 78
    return result;
  }
}

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

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

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

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

    setUp(clear);

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

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

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

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

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

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

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

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

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

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

      await tester.pump();
      final ActionDispatcher dispatcher = Actions.of(
267 268
        containerKey.currentContext,
        nullOk: true,
269 270 271
      );
      expect(dispatcher, equals(testDispatcher));
    });
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 318 319
    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);
    });
320 321 322 323
    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;
324
      const Intent intent = TestIntent();
325
      final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
326 327
      final Action<Intent> testAction = TestAction(
        onInvoke: (Intent intent) {
328
          invoked = true;
329
          return invoked;
330 331 332 333 334 335 336 337 338 339
        },
      );
      bool hovering = false;
      bool focusing = false;

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

  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;
417
      action1.addActionListener((Action<Intent> action) => enabled1 = action.isEnabled(const TestIntent()));
418 419 420 421
      action1.enabled = false;
      expect(enabled1, isFalse);

      bool enabled2 = true;
422
      action2.addActionListener((Action<Intent> action) => enabled2 = action.isEnabled(const SecondTestIntent()));
423 424 425 426
      action2.enabled = false;
      expect(enabled2, isFalse);

      bool enabled3 = true;
427
      action3.addActionListener((Action<Intent> action) => enabled3 = action.isEnabled(const ThirdTestIntent()));
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
      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(
471
            listener: (Action<Intent> action) => enabledChanged = action.isEnabled(const ThirdTestIntent()),
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 555 556
            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));
    });
  });

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

561 562
      // ignore: invalid_use_of_protected_member
      const TestIntent().debugFillProperties(builder);
563 564

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

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

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

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

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

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

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

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