text_selection_toolbar_test.dart 10.2 KB
Newer Older
1 2 3 4 5 6
// 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/foundation.dart';
import 'package:flutter/material.dart';
7
import 'package:flutter_test/flutter_test.dart';
8
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
9
import '../widgets/editable_text_utils.dart' show textOffsetToPosition;
10

11 12
const double _kToolbarContentDistance = 8.0;

13 14 15 16 17 18 19 20 21 22
// A custom text selection menu that just displays a single custom button.
class _CustomMaterialTextSelectionControls extends MaterialTextSelectionControls {
  @override
  Widget buildToolbar(
    BuildContext context,
    Rect globalEditableRegion,
    double textLineHeight,
    Offset selectionMidpoint,
    List<TextSelectionPoint> endpoints,
    TextSelectionDelegate delegate,
23
    ValueListenable<ClipboardStatus>? clipboardStatus,
24
    Offset? lastSecondaryTapDownPosition,
25 26 27 28 29 30 31
  ) {
    final TextSelectionPoint startTextSelectionPoint = endpoints[0];
    final TextSelectionPoint endTextSelectionPoint = endpoints.length > 1
      ? endpoints[1]
      : endpoints[0];
    final Offset anchorAbove = Offset(
      globalEditableRegion.left + selectionMidpoint.dx,
32
      globalEditableRegion.top + startTextSelectionPoint.point.dy - textLineHeight - _kToolbarContentDistance,
33 34 35
    );
    final Offset anchorBelow = Offset(
      globalEditableRegion.left + selectionMidpoint.dx,
36
      globalEditableRegion.top + endTextSelectionPoint.point.dy + TextSelectionToolbar.kToolbarContentDistanceBelow,
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    );

    return TextSelectionToolbar(
      anchorAbove: anchorAbove,
      anchorBelow: anchorBelow,
      children: <Widget>[
        TextSelectionToolbarTextButton(
          padding: TextSelectionToolbarTextButton.getPadding(0, 1),
          onPressed: () {},
          child: const Text('Custom button'),
        ),
      ],
    );
  }
}

53
class TestBox extends SizedBox {
54
  const TestBox({super.key}) : super(width: itemWidth, height: itemHeight);
55 56 57 58 59

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

60 61 62 63
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  // Find by a runtimeType String, including private types.
64
  Finder findPrivate(String type) {
65 66 67 68 69 70 71 72 73
    return find.descendant(
      of: find.byType(MaterialApp),
      matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == type),
    );
  }

  // Finding TextSelectionToolbar 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.
74
  Finder findToolbar() => findPrivate('_TextSelectionToolbarOverflowable');
75

76
  Finder findOverflowButton() => findPrivate('_TextSelectionToolbarOverflowButton');
77

78
  testWidgetsWithLeakTracking('puts children in an overflow menu if they overflow', (WidgetTester tester) async {
79
    late StateSetter setState;
80
    final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
              return TextSelectionToolbar(
                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.
100
    expect(find.byType(TestBox), findsNWidgets(children.length));
101
    expect(findOverflowButton(), findsNothing);
102 103 104 105

    // Adding one more child makes the children overflow.
    setState(() {
      children.add(
106
        const TestBox(),
107 108 109
      );
    });
    await tester.pumpAndSettle();
110
    expect(find.byType(TestBox), findsNWidgets(children.length - 1));
111
    expect(findOverflowButton(), findsOneWidget);
112 113

    // Tap the overflow button to show the overflow menu.
114
    await tester.tap(findOverflowButton());
115
    await tester.pumpAndSettle();
116
    expect(find.byType(TestBox), findsNWidgets(1));
117
    expect(findOverflowButton(), findsOneWidget);
118 119

    // Tap the overflow button again to hide the overflow menu.
120
    await tester.tap(findOverflowButton());
121
    await tester.pumpAndSettle();
122
    expect(find.byType(TestBox), findsNWidgets(children.length - 1));
123
    expect(findOverflowButton(), findsOneWidget);
124 125
  });

126
  testWidgetsWithLeakTracking('positions itself at anchorAbove if it fits', (WidgetTester tester) async {
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 154
    late StateSetter setState;
    const double height = 44.0;
    const double anchorBelowY = 500.0;
    double anchorAboveY = 0.0;

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: StatefulBuilder(
            builder: (BuildContext context, StateSetter setter) {
              setState = setter;
              return TextSelectionToolbar(
                anchorAbove: Offset(50.0, anchorAboveY),
                anchorBelow: const Offset(50.0, anchorBelowY),
                children: <Widget>[
                  Container(color: Colors.red, width: 50.0, height: height),
                  Container(color: Colors.green, width: 50.0, height: height),
                  Container(color: Colors.blue, width: 50.0, height: height),
                ],
              );
            },
          ),
        ),
      ),
    );

    // When the toolbar doesn't fit above aboveAnchor, it positions itself below
    // belowAnchor.
155
    double toolbarY = tester.getTopLeft(findToolbar()).dy;
156
    expect(toolbarY, equals(anchorBelowY + TextSelectionToolbar.kToolbarContentDistanceBelow));
157 158 159

    // Even when it barely doesn't fit.
    setState(() {
160
      anchorAboveY = 60.0;
161 162
    });
    await tester.pump();
163
    toolbarY = tester.getTopLeft(findToolbar()).dy;
164
    expect(toolbarY, equals(anchorBelowY + TextSelectionToolbar.kToolbarContentDistanceBelow));
165 166 167

    // When it does fit above aboveAnchor, it positions itself there.
    setState(() {
168
      anchorAboveY = 70.0;
169 170
    });
    await tester.pump();
171
    toolbarY = tester.getTopLeft(findToolbar()).dy;
172
    expect(toolbarY, equals(anchorAboveY - height - _kToolbarContentDistance));
173 174
  });

175
  testWidgetsWithLeakTracking('can create and use a custom toolbar', (WidgetTester tester) async {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Center(
            child: SelectableText(
              'Select me custom menu',
              selectionControls: _CustomMaterialTextSelectionControls(),
            ),
          ),
        ),
      ),
    );

    // 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);
205
  }, skip: kIsWeb); // [intended] We don't show the toolbar on the web.
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 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

  for (final ColorScheme colorScheme in <ColorScheme>[ThemeData.light().colorScheme, ThemeData.dark().colorScheme]) {
    testWidgetsWithLeakTracking('default background color', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          theme: ThemeData(
            colorScheme: colorScheme,
          ),
          home: Scaffold(
            body: Center(
              child: TextSelectionToolbar(
                anchorAbove: Offset.zero,
                anchorBelow: Offset.zero,
                children: <Widget>[
                  TextSelectionToolbarTextButton(
                    padding: TextSelectionToolbarTextButton.getPadding(0, 1),
                    onPressed: () {},
                    child: const Text('Custom button'),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      Finder findToolbarContainer() {
        return find.descendant(
          of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_TextSelectionToolbarContainer'),
          matching: find.byType(Material),
        );
      }
      expect(findToolbarContainer(), findsAtLeastNWidgets(1));

      final Material toolbarContainer = tester.widget(findToolbarContainer().first);
      expect(
        toolbarContainer.color,
        // The default colors are hardcoded and don't take the default value of
        // the theme's surface color.
        switch (colorScheme.brightness) {
          Brightness.light => const Color(0xffffffff),
          Brightness.dark => const Color(0xff424242),
        },
      );
    });

    testWidgetsWithLeakTracking('custom background color', (WidgetTester tester) async {
      const Color customBackgroundColor = Colors.red;

      await tester.pumpWidget(
        MaterialApp(
          theme: ThemeData(
            colorScheme: colorScheme.copyWith(
              surface: customBackgroundColor,
            ),
          ),
          home: Scaffold(
            body: Center(
              child: TextSelectionToolbar(
                anchorAbove: Offset.zero,
                anchorBelow: Offset.zero,
                children: <Widget>[
                  TextSelectionToolbarTextButton(
                    padding: TextSelectionToolbarTextButton.getPadding(0, 1),
                    onPressed: () {},
                    child: const Text('Custom button'),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      Finder findToolbarContainer() {
        return find.descendant(
          of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_TextSelectionToolbarContainer'),
          matching: find.byType(Material),
        );
      }
      expect(findToolbarContainer(), findsAtLeastNWidgets(1));

      final Material toolbarContainer = tester.widget(findToolbarContainer().first);
      expect(
        toolbarContainer.color,
        customBackgroundColor,
      );
    });
  }
295
}