text_selection_toolbar_test.dart 21.1 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8 9
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;

10
import 'package:flutter/cupertino.dart';
11 12
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
13

14
import '../widgets/editable_text_utils.dart' show textOffsetToPosition;
15 16 17 18

// These constants are copied from cupertino/text_selection_toolbar.dart.
const double _kArrowScreenPadding = 26.0;
const double _kToolbarContentDistance = 8.0;
19
const Size _kToolbarArrowSize = Size(14.0, 7.0);
20 21 22 23 24 25 26 27 28 29 30

// A custom text selection menu that just displays a single custom button.
class _CustomCupertinoTextSelectionControls extends CupertinoTextSelectionControls {
  @override
  Widget buildToolbar(
    BuildContext context,
    Rect globalEditableRegion,
    double textLineHeight,
    Offset selectionMidpoint,
    List<TextSelectionPoint> endpoints,
    TextSelectionDelegate delegate,
31
    ValueListenable<ClipboardStatus>? clipboardStatus,
32
    Offset? lastSecondaryTapDownPosition,
33
  ) {
34
    final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
35
    final double anchorX = (selectionMidpoint.dx + globalEditableRegion.left).clamp(
36 37
      _kArrowScreenPadding + mediaQueryPadding.left,
      MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding,
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    );
    final Offset anchorAbove = Offset(
      anchorX,
      endpoints.first.point.dy - textLineHeight + globalEditableRegion.top,
    );
    final Offset anchorBelow = Offset(
      anchorX,
      endpoints.last.point.dy + globalEditableRegion.top,
    );

    return CupertinoTextSelectionToolbar(
      anchorAbove: anchorAbove,
      anchorBelow: anchorBelow,
      children: <Widget>[
        CupertinoTextSelectionToolbarButton(
          onPressed: () {},
          child: const Text('Custom button'),
        ),
      ],
    );
  }
}

61
class TestBox extends SizedBox {
62
  const TestBox({super.key}) : super(width: itemWidth, height: itemHeight);
63 64 65 66 67

  static const double itemHeight = 44.0;
  static const double itemWidth = 100.0;
}

68 69 70
const CupertinoDynamicColor _kToolbarTextColor = CupertinoDynamicColor.withBrightness(
  color: CupertinoColors.black,
  darkColor: CupertinoColors.white,
71 72
);

73 74 75 76
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  // Find by a runtimeType String, including private types.
77
  Finder findPrivate(String type) {
78 79 80 81 82 83 84 85 86
    return find.descendant(
      of: find.byType(CupertinoApp),
      matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == type),
    );
  }

  // Finding CupertinoTextSelectionToolbar won't give you the position as the user sees
  // it because it's a full-sized Stack at the top level. This method finds the
  // visible part of the toolbar for use in measurements.
87
  Finder findToolbar() => findPrivate('_CupertinoTextSelectionToolbarContent');
88

89 90 91 92 93 94 95 96 97 98 99
  // Check if the middle point of the chevron is pointing left or right.
  //
  // Offset.dx: a right or left margin (_kToolbarChevronSize / 4 => 2.5) to center the icon horizontally
  // Offset.dy: always in the exact vertical center (_kToolbarChevronSize / 2 => 5)
  PaintPattern overflowNextPaintPattern() => paints
    ..line(p1: const Offset(2.5, 0), p2: const Offset(7.5, 5))
    ..line(p1: const Offset(7.5, 5), p2: const Offset(2.5, 10));
  PaintPattern overflowBackPaintPattern() => paints
    ..line(p1: const Offset(7.5, 0), p2: const Offset(2.5, 5))
    ..line(p1: const Offset(2.5, 5), p2: const Offset(7.5, 10));

100 101
  Finder findOverflowNextButton() {
    return find.byWidgetPredicate((Widget widget) =>
102
    widget is CustomPaint &&
103 104 105 106 107 108
        '${widget.painter?.runtimeType}' == '_RightCupertinoChevronPainter',
    );
  }

  Finder findOverflowBackButton() {
    return find.byWidgetPredicate((Widget widget) =>
109
    widget is CustomPaint &&
110 111 112
        '${widget.painter?.runtimeType}' == '_LeftCupertinoChevronPainter',
    );
  }
113

114
  testWidgets('chevrons point to the correct side', (WidgetTester tester) async {
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    // Add enough TestBoxes to need 3 pages.
    final List<Widget> children = List<Widget>.generate(15, (int i) => const TestBox());
    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: CupertinoTextSelectionToolbar(
            anchorAbove: const Offset(50.0, 100.0),
            anchorBelow: const Offset(50.0, 200.0),
            children: children,
          ),
        ),
      ),
    );

    expect(findOverflowBackButton(), findsNothing);
    expect(findOverflowNextButton(), findsOneWidget);

    expect(findOverflowNextButton(), overflowNextPaintPattern());

    // Tap the overflow next button to show the next page of children.
    await tester.tapAt(tester.getCenter(findOverflowNextButton()));
    await tester.pumpAndSettle();

    expect(findOverflowBackButton(), findsOneWidget);
    expect(findOverflowNextButton(), findsOneWidget);

    expect(findOverflowBackButton(), overflowBackPaintPattern());
    expect(findOverflowNextButton(), overflowNextPaintPattern());

    // Tap the overflow next button to show the last page of children.
    await tester.tapAt(tester.getCenter(findOverflowNextButton()));
    await tester.pumpAndSettle();

    expect(findOverflowBackButton(), findsOneWidget);
    expect(findOverflowNextButton(), findsNothing);

    expect(findOverflowBackButton(), overflowBackPaintPattern());
  }, skip: kIsWeb); // Path.combine is not implemented in the HTML backend https://github.com/flutter/flutter/issues/44572
153

154
  testWidgets('paginates children if they overflow', (WidgetTester tester) async {
155
    late StateSetter setState;
156
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
              return CupertinoTextSelectionToolbar(
                anchorAbove: const Offset(50.0, 100.0),
                anchorBelow: const Offset(50.0, 200.0),
                children: children,
              );
            },
          ),
        ),
      ),
    );

    // All children fit on the screen, so they are all rendered.
175
    expect(find.byType(TestBox), findsNWidgets(children.length));
176 177
    expect(findOverflowNextButton(), findsNothing);
    expect(findOverflowBackButton(), findsNothing);
178 179 180 181

    // Adding one more child makes the children overflow.
    setState(() {
      children.add(
182
        const TestBox(),
183 184 185
      );
    });
    await tester.pumpAndSettle();
186
    expect(find.byType(TestBox), findsNWidgets(children.length - 1));
187 188
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
189 190

    // Tap the overflow next button to show the next page of children.
191 192
    // The next button is hidden as there's no next page.
    await tester.tapAt(tester.getCenter(findOverflowNextButton()));
193
    await tester.pumpAndSettle();
194
    expect(find.byType(TestBox), findsNWidgets(1));
195
    expect(findOverflowNextButton(), findsNothing);
196
    expect(findOverflowBackButton(), findsOneWidget);
197 198

    // Tap the overflow back button to go back to the first page.
199
    await tester.tapAt(tester.getCenter(findOverflowBackButton()));
200
    await tester.pumpAndSettle();
201
    expect(find.byType(TestBox), findsNWidgets(7));
202 203
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
204 205 206

    // Adding 7 more children overflows onto a third page.
    setState(() {
207 208 209 210 211 212
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
213 214
    });
    await tester.pumpAndSettle();
215
    expect(find.byType(TestBox), findsNWidgets(7));
216 217
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
218 219

    // Tap the overflow next button to show the second page of children.
220
    await tester.tapAt(tester.getCenter(findOverflowNextButton()));
221 222
    await tester.pumpAndSettle();
    // With the back button, only six children fit on this page.
223
    expect(find.byType(TestBox), findsNWidgets(6));
224 225
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
226 227

    // Tap the overflow next button again to show the third page of children.
228
    await tester.tapAt(tester.getCenter(findOverflowNextButton()));
229
    await tester.pumpAndSettle();
230
    expect(find.byType(TestBox), findsNWidgets(1));
231
    expect(findOverflowNextButton(), findsNothing);
232
    expect(findOverflowBackButton(), findsOneWidget);
233 234

    // Tap the overflow back button to go back to the second page.
235
    await tester.tapAt(tester.getCenter(findOverflowBackButton()));
236
    await tester.pumpAndSettle();
237
    expect(find.byType(TestBox), findsNWidgets(6));
238 239
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
240 241

    // Tap the overflow back button to go back to the first page.
242
    await tester.tapAt(tester.getCenter(findOverflowBackButton()));
243
    await tester.pumpAndSettle();
244
    expect(find.byType(TestBox), findsNWidgets(7));
245 246
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
247
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
248

249
  testWidgets('does not paginate if children fit with zero margin', (WidgetTester tester) async {
250
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
251 252
    final double spacerWidth = 1.0 / tester.view.devicePixelRatio;
    final double dividerWidth = 1.0 / tester.view.devicePixelRatio;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    const double borderRadius = 8.0; // Should match _kToolbarBorderRadius
    final double width = 7 * TestBox.itemWidth + 6 * (dividerWidth + 2 * spacerWidth) + 2 * borderRadius;
    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: SizedBox(
            width: width,
            child: CupertinoTextSelectionToolbar(
              anchorAbove: const Offset(50.0, 100.0),
              anchorBelow: const Offset(50.0, 200.0),
              children: children,
            ),
          ),
        ),
      ),
    );

    // All children fit on the screen, so they are all rendered.
    expect(find.byType(TestBox), findsNWidgets(children.length));
    expect(findOverflowNextButton(), findsNothing);
    expect(findOverflowBackButton(), findsNothing);
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.

276
  testWidgets('positions itself at anchorAbove if it fits', (WidgetTester tester) async {
277
    late StateSetter setState;
278
    const double height = 50.0;
279 280
    const double anchorBelowY = 500.0;
    double anchorAboveY = 0.0;
281
    const double paddingAbove = 12.0;
282 283 284 285 286 287 288

    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
              final MediaQueryData data = MediaQuery.of(context);
              // Add some custom vertical padding to make this test more strict.
              // By default in the testing environment, _kToolbarContentDistance
              // and the built-in padding from CupertinoApp can end up canceling
              // each other out.
              return MediaQuery(
                data: data.copyWith(
                  padding: data.viewPadding.copyWith(
                    top: paddingAbove,
                  ),
                ),
                child: CupertinoTextSelectionToolbar(
                  anchorAbove: Offset(50.0, anchorAboveY),
                  anchorBelow: const Offset(50.0, anchorBelowY),
                  children: <Widget>[
                    Container(color: const Color(0xffff0000), width: 50.0, height: height),
                    Container(color: const Color(0xff00ff00), width: 50.0, height: height),
                    Container(color: const Color(0xff0000ff), width: 50.0, height: height),
                  ],
                ),
309 310 311 312 313 314 315 316 317
              );
            },
          ),
        ),
      ),
    );

    // When the toolbar doesn't fit above aboveAnchor, it positions itself below
    // belowAnchor.
318
    double toolbarY = tester.getTopLeft(findToolbar()).dy;
319
    expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance));
320 321 322 323
    expect(find.byType(CustomSingleChildLayout), findsOneWidget);
    final CustomSingleChildLayout layout = tester.widget(find.byType(CustomSingleChildLayout));
    final TextSelectionToolbarLayoutDelegate delegate = layout.delegate as TextSelectionToolbarLayoutDelegate;
    expect(delegate.anchorBelow.dy, anchorBelowY - paddingAbove);
324 325 326

    // Even when it barely doesn't fit.
    setState(() {
327
      anchorAboveY = 70.0;
328 329
    });
    await tester.pump();
330
    toolbarY = tester.getTopLeft(findToolbar()).dy;
331 332 333 334
    expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance));

    // When it does fit above aboveAnchor, it positions itself there.
    setState(() {
335
      anchorAboveY = 80.0;
336 337
    });
    await tester.pump();
338
    toolbarY = tester.getTopLeft(findToolbar()).dy;
339
    expect(toolbarY, equals(anchorAboveY - height + _kToolbarArrowSize.height - _kToolbarContentDistance));
340
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
341

342
  testWidgets('can create and use a custom toolbar', (WidgetTester tester) async {
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 372
    final TextEditingController controller = TextEditingController(
      text: 'Select me custom menu',
    );
    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: CupertinoTextField(
            controller: controller,
            selectionControls: _CustomCupertinoTextSelectionControls(),
          ),
        ),
      ),
    );

    // The selection menu is not initially shown.
    expect(find.text('Custom button'), findsNothing);

    // Long press on "custom" to select it.
    final Offset customPos = textOffsetToPosition(tester, 11);
    final TestGesture gesture = await tester.startGesture(customPos, pointer: 7);
    await tester.pump(const Duration(seconds: 2));
    await gesture.up();
    await tester.pump();

    // The custom selection menu is shown.
    expect(find.text('Custom button'), findsOneWidget);
    expect(find.text('Cut'), findsNothing);
    expect(find.text('Copy'), findsNothing);
    expect(find.text('Paste'), findsNothing);
    expect(find.text('Select all'), findsNothing);
373
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
374 375 376

  for (final Brightness? themeBrightness in <Brightness?>[...Brightness.values, null]) {
    for (final Brightness? mediaBrightness in <Brightness?>[...Brightness.values, null]) {
377
      testWidgets('draws dark buttons in dark mode and light button in light mode when theme is $themeBrightness and MediaQuery is $mediaBrightness', (WidgetTester tester) async {
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 404 405 406 407
        await tester.pumpWidget(
          CupertinoApp(
            theme: CupertinoThemeData(
              brightness: themeBrightness,
            ),
            home: Center(
              child: Builder(
                builder: (BuildContext context) {
                  return MediaQuery(
                    data: MediaQuery.of(context).copyWith(platformBrightness: mediaBrightness),
                    child: CupertinoTextSelectionToolbar(
                      anchorAbove: const Offset(100.0, 0.0),
                      anchorBelow: const Offset(100.0, 0.0),
                      children: <Widget>[
                        CupertinoTextSelectionToolbarButton.text(
                          onPressed: () {},
                          text: 'Button',
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ),
        );

        final Finder buttonFinder = find.byType(CupertinoButton);
        expect(buttonFinder, findsOneWidget);

408
        final Finder textFinder = find.descendant(
409
          of: find.byType(CupertinoButton),
410
          matching: find.byType(Text)
411
        );
412 413
        expect(textFinder, findsOneWidget);
        final Text text = tester.widget(textFinder);
414 415 416 417 418 419 420 421 422 423 424

        // Theme brightness is preferred, otherwise MediaQuery brightness is
        // used. If both are null, defaults to light.
        late final Brightness effectiveBrightness;
        if (themeBrightness != null) {
          effectiveBrightness = themeBrightness;
        } else {
          effectiveBrightness = mediaBrightness ?? Brightness.light;
        }

        expect(
425
          text.style!.color!.value,
426
          effectiveBrightness == Brightness.dark
427 428
              ? _kToolbarTextColor.darkColor.value
              : _kToolbarTextColor.color.value,
429 430 431 432
        );
      }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
    }
  }
433

434
  testWidgets('draws a shadow below the toolbar in light mode', (WidgetTester tester) async {
435
    late StateSetter setState;
436
    const double height = 50.0;
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
    double anchorAboveY = 0.0;

    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(
          brightness: Brightness.light,
        ),
        home: Center(
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
              final MediaQueryData data = MediaQuery.of(context);
              // Add some custom vertical padding to make this test more strict.
              // By default in the testing environment, _kToolbarContentDistance
              // and the built-in padding from CupertinoApp can end up canceling
              // each other out.
              return MediaQuery(
                data: data.copyWith(
                  padding: data.viewPadding.copyWith(
                    top: 12.0,
                  ),
                ),
                child: CupertinoTextSelectionToolbar(
                  anchorAbove: Offset(50.0, anchorAboveY),
                  anchorBelow: const Offset(50.0, 500.0),
                  children: <Widget>[
                    Container(color: const Color(0xffff0000), width: 50.0, height: height),
                    Container(color: const Color(0xff00ff00), width: 50.0, height: height),
                    Container(color: const Color(0xff0000ff), width: 50.0, height: height),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );

475 476 477 478 479 480 481 482
    final double dividerWidth = 1.0 / tester.view.devicePixelRatio;

    expect(
      find.byType(CupertinoTextSelectionToolbar),
      paints..rrect(
        rrect: RRect.fromLTRBR(8.0, 515.0, 158.0 + 2 * dividerWidth, 558.0, const Radius.circular(8.0)),
        color: const Color(0x33000000),
      ),
483 484 485 486 487 488 489 490
    );

    // When the toolbar is above the content, the shadow sits around the arrow
    // with no offset.
    setState(() {
      anchorAboveY = 80.0;
    });
    await tester.pump();
491 492 493 494 495 496 497 498

    expect(
      find.byType(CupertinoTextSelectionToolbar),
      paints..rrect(
        rrect: RRect.fromLTRBR(8.0, 29.0, 158.0 + 2 * dividerWidth, 72.0, const Radius.circular(8.0)),
        color: const Color(0x33000000),
      ),
    );
499
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
500

501
  testWidgets('Basic golden tests', (WidgetTester tester) async {
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
    final Key key = UniqueKey();
    Widget buildToolbar(Brightness brightness, Offset offset) {
      final Widget toolbar = CupertinoTextSelectionToolbar(
        anchorAbove: offset,
        anchorBelow: offset,
        children: <Widget>[
          CupertinoTextSelectionToolbarButton.text(onPressed: () {}, text: 'Lorem ipsum'),
          CupertinoTextSelectionToolbarButton.text(onPressed: () {}, text: 'dolor sit amet'),
          CupertinoTextSelectionToolbarButton.text(onPressed: () {}, text: 'Lorem ipsum \ndolor sit amet'),
          CupertinoTextSelectionToolbarButton.buttonItem(buttonItem: ContextMenuButtonItem(onPressed: () {}, type: ContextMenuButtonType.copy)),
        ],
      );
      return CupertinoApp(
        theme: CupertinoThemeData(brightness: brightness),
        home: Center(
          child: SizedBox(
            height: 200,
            child: RepaintBoundary(key: key, child: toolbar),
          ),
        ),
      );
    }

    // The String describes the location of the toolbar in relation to the
    // content the arrow points to.
    const List<(String, Offset)> toolbarLocation = <(String, Offset)>[
      ('BottomRight', Offset.zero),
      ('BottomLeft', Offset(100000, 0)),
      ('TopRight', Offset(0, 100)),
      ('TopLeft', Offset(100000, 100)),
    ];

    debugDisableShadows = false;
    addTearDown(() => debugDisableShadows = true);
    for (final Brightness brightness in Brightness.values) {
      for (final (String location, Offset offset) in toolbarLocation) {
        await tester.pumpWidget(buildToolbar(brightness, offset));
        await expectLater(
          find.byKey(key),
          matchesGoldenFile('cupertino_selection_toolbar.$location.$brightness.png'),
        );
      }
    }
    debugDisableShadows = true;
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
547
}