text_selection_toolbar_test.dart 14.5 KB
Newer Older
1 2 3 4 5
// 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.

import 'package:flutter/cupertino.dart';
6 7
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
8

9
import '../widgets/editable_text_utils.dart' show textOffsetToPosition;
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// These constants are copied from cupertino/text_selection_toolbar.dart.
const double _kArrowScreenPadding = 26.0;
const double _kToolbarContentDistance = 8.0;
const double _kToolbarHeight = 43.0;

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

56
class TestBox extends SizedBox {
57
  const TestBox({super.key}) : super(width: itemWidth, height: itemHeight);
58 59 60 61 62

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

63 64 65 66 67
const CupertinoDynamicColor _kToolbarBackgroundColor = CupertinoDynamicColor.withBrightness(
  color: Color(0xEBF7F7F7),
  darkColor: Color(0xEB202020),
);

68 69 70 71
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  // Find by a runtimeType String, including private types.
72
  Finder findPrivate(String type) {
73 74 75 76 77 78 79 80 81
    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.
82
  Finder findToolbar() => findPrivate('_CupertinoTextSelectionToolbarContent');
83

84 85
  Finder findOverflowNextButton() => find.text('▶');
  Finder findOverflowBackButton() => find.text('◀');
86 87 88

  testWidgets('paginates children if they overflow', (WidgetTester tester) async {
    late StateSetter setState;
89
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    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.
108
    expect(find.byType(TestBox), findsNWidgets(children.length));
109 110
    expect(findOverflowNextButton(), findsNothing);
    expect(findOverflowBackButton(), findsNothing);
111 112 113 114

    // Adding one more child makes the children overflow.
    setState(() {
      children.add(
115
        const TestBox(),
116 117 118
      );
    });
    await tester.pumpAndSettle();
119
    expect(find.byType(TestBox), findsNWidgets(children.length - 1));
120 121
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
122 123

    // Tap the overflow next button to show the next page of children.
124
    await tester.tap(findOverflowNextButton());
125
    await tester.pumpAndSettle();
126
    expect(find.byType(TestBox), findsNWidgets(1));
127 128
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
129 130 131

    // Tapping the overflow next button again does nothing because it is
    // disabled and there are no more children to display.
132
    await tester.tap(findOverflowNextButton());
133
    await tester.pumpAndSettle();
134
    expect(find.byType(TestBox), findsNWidgets(1));
135 136
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
137 138

    // Tap the overflow back button to go back to the first page.
139
    await tester.tap(findOverflowBackButton());
140
    await tester.pumpAndSettle();
141
    expect(find.byType(TestBox), findsNWidgets(7));
142 143
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
144 145 146

    // Adding 7 more children overflows onto a third page.
    setState(() {
147 148 149 150 151 152
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
      children.add(const TestBox());
153 154
    });
    await tester.pumpAndSettle();
155
    expect(find.byType(TestBox), findsNWidgets(7));
156 157
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
158 159

    // Tap the overflow next button to show the second page of children.
160
    await tester.tap(findOverflowNextButton());
161 162
    await tester.pumpAndSettle();
    // With the back button, only six children fit on this page.
163
    expect(find.byType(TestBox), findsNWidgets(6));
164 165
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
166 167

    // Tap the overflow next button again to show the third page of children.
168
    await tester.tap(findOverflowNextButton());
169
    await tester.pumpAndSettle();
170
    expect(find.byType(TestBox), findsNWidgets(1));
171 172
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
173 174

    // Tap the overflow back button to go back to the second page.
175
    await tester.tap(findOverflowBackButton());
176
    await tester.pumpAndSettle();
177
    expect(find.byType(TestBox), findsNWidgets(6));
178 179
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsOneWidget);
180 181

    // Tap the overflow back button to go back to the first page.
182
    await tester.tap(findOverflowBackButton());
183
    await tester.pumpAndSettle();
184
    expect(find.byType(TestBox), findsNWidgets(7));
185 186
    expect(findOverflowNextButton(), findsOneWidget);
    expect(findOverflowBackButton(), findsNothing);
187
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
188

189 190
  testWidgets('does not paginate if children fit with zero margin', (WidgetTester tester) async {
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
191 192
    final double spacerWidth = 1.0 / tester.view.devicePixelRatio;
    final double dividerWidth = 1.0 / tester.view.devicePixelRatio;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    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.

216 217 218 219 220
  testWidgets('positions itself at anchorAbove if it fits', (WidgetTester tester) async {
    late StateSetter setState;
    const double height = _kToolbarHeight;
    const double anchorBelowY = 500.0;
    double anchorAboveY = 0.0;
221
    const double paddingAbove = 12.0;
222 223 224 225 226 227 228

    await tester.pumpWidget(
      CupertinoApp(
        home: Center(
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
              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),
                  ],
                ),
249 250 251 252 253 254 255 256 257
              );
            },
          ),
        ),
      ),
    );

    // When the toolbar doesn't fit above aboveAnchor, it positions itself below
    // belowAnchor.
258
    double toolbarY = tester.getTopLeft(findToolbar()).dy;
259
    expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance));
260 261 262 263
    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);
264 265 266

    // Even when it barely doesn't fit.
    setState(() {
267
      anchorAboveY = 70.0;
268 269
    });
    await tester.pump();
270
    toolbarY = tester.getTopLeft(findToolbar()).dy;
271 272 273 274
    expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance));

    // When it does fit above aboveAnchor, it positions itself there.
    setState(() {
275
      anchorAboveY = 80.0;
276 277
    });
    await tester.pump();
278
    toolbarY = tester.getTopLeft(findToolbar()).dy;
279
    expect(toolbarY, equals(anchorAboveY - height - _kToolbarContentDistance));
280
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
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

  testWidgets('can create and use a custom toolbar', (WidgetTester tester) async {
    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);
313
  }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 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 372 373

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

        final Finder decorationFinder = find.descendant(
          of: find.byType(CupertinoButton),
          matching: find.byType(DecoratedBox)
        );
        expect(decorationFinder, findsOneWidget);
        final DecoratedBox decoratedBox = tester.widget(decorationFinder);
        final BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration;

        // 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(
          boxDecoration.color!.value,
          effectiveBrightness == Brightness.dark
              ? _kToolbarBackgroundColor.darkColor.value
              : _kToolbarBackgroundColor.color.value,
        );
      }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
    }
  }
374
}