text_selection_toolbar_test.dart 21.3 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
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
14

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

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

// 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,
32
    ValueListenable<ClipboardStatus>? clipboardStatus,
33
    Offset? lastSecondaryTapDownPosition,
34
  ) {
35
    final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
36
    final double anchorX = (selectionMidpoint.dx + globalEditableRegion.left).clamp(
37 38
      _kArrowScreenPadding + mediaQueryPadding.left,
      MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding,
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    );
    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'),
        ),
      ],
    );
  }
}

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

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

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

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

  // Find by a runtimeType String, including private types.
78
  Finder findPrivate(String type) {
79 80 81 82 83 84 85 86 87
    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.
88
  Finder findToolbar() => findPrivate('_CupertinoTextSelectionToolbarContent');
89

90 91 92 93 94 95 96 97 98 99 100
  // 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));

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

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

115
  testWidgetsWithLeakTracking('chevrons point to the correct side', (WidgetTester tester) async {
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 153
    // 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
154

155
  testWidgetsWithLeakTracking('paginates children if they overflow', (WidgetTester tester) async {
156
    late StateSetter setState;
157
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    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.
176
    expect(find.byType(TestBox), findsNWidgets(children.length));
177 178
    expect(findOverflowNextButton(), findsNothing);
    expect(findOverflowBackButton(), findsNothing);
179 180 181 182

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

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

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

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

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

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

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

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

250
  testWidgetsWithLeakTracking('does not paginate if children fit with zero margin', (WidgetTester tester) async {
251
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
252 253
    final double spacerWidth = 1.0 / tester.view.devicePixelRatio;
    final double dividerWidth = 1.0 / tester.view.devicePixelRatio;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    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.

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

    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
              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),
                  ],
                ),
310 311 312 313 314 315 316 317 318
              );
            },
          ),
        ),
      ),
    );

    // When the toolbar doesn't fit above aboveAnchor, it positions itself below
    // belowAnchor.
319
    double toolbarY = tester.getTopLeft(findToolbar()).dy;
320
    expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance));
321 322 323 324
    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);
325 326 327

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

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

343
  testWidgetsWithLeakTracking('can create and use a custom toolbar', (WidgetTester tester) async {
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 373
    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);
374
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
375 376 377

  for (final Brightness? themeBrightness in <Brightness?>[...Brightness.values, null]) {
    for (final Brightness? mediaBrightness in <Brightness?>[...Brightness.values, null]) {
378
      testWidgetsWithLeakTracking('draws dark buttons in dark mode and light button in light mode when theme is $themeBrightness and MediaQuery is $mediaBrightness', (WidgetTester tester) async {
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 408
        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);

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

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

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

476 477 478 479 480 481 482 483
    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),
      ),
484 485 486 487 488 489 490 491
    );

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

    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),
      ),
    );
500
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
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

  testWidgetsWithLeakTracking('Basic golden tests', (WidgetTester tester) async {
    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.
548
}