semantics_traversal_test.dart 12.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7 8 9 10 11 12 13 14 15 16 17 18
import 'dart:collection';
import 'dart:math' as math;
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';

import 'semantics_tester.dart';

19
typedef TraversalTestFunction = Future<void> Function(TraversalTester tester);
20
const Size tenByTen = Size(10.0, 10.0);
21 22 23 24 25 26 27 28

void main() {
  setUp(() {
    debugResetSemanticsIdCounter();
  });

  void testTraversal(String description, TraversalTestFunction testFunction) {
    testWidgets(description, (WidgetTester tester) async {
29
      final TraversalTester traversalTester = TraversalTester(tester);
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
      await testFunction(traversalTester);
      traversalTester.dispose();
    });
  }

  // ┌───┐ ┌───┐
  // │ A │>│ B │
  // └───┘ └───┘
  testTraversal('Semantics traverses horizontally left-to-right', (TraversalTester tester) async {
    await tester.test(
      textDirection: TextDirection.ltr,
      children: <String, Rect>{
        'A': const Offset(0.0, 0.0) & tenByTen,
        'B': const Offset(20.0, 0.0) & tenByTen,
      },
      expectedTraversal: 'A B',
    );
  });

  // ┌───┐ ┌───┐
  // │ A │<│ B │
  // └───┘ └───┘
  testTraversal('Semantics traverses horizontally right-to-left', (TraversalTester tester) async {
    await tester.test(
      textDirection: TextDirection.rtl,
      children: <String, Rect>{
        'A': const Offset(0.0, 0.0) & tenByTen,
        'B': const Offset(20.0, 0.0) & tenByTen,
      },
      expectedTraversal: 'B A',
    );
  });

  // ┌───┐
  // │ A │
  // └───┘
  //   V
  // ┌───┐
  // │ B │
  // └───┘
  testTraversal('Semantics traverses vertically top-to-bottom', (TraversalTester tester) async {
71
    for (final TextDirection textDirection in TextDirection.values) {
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 153 154 155 156
      await tester.test(
        textDirection: textDirection,
        children: <String, Rect>{
          'A': const Offset(0.0, 0.0) & tenByTen,
          'B': const Offset(0.0, 20.0) & tenByTen,
        },
        expectedTraversal: 'A B',
      );
    }
  });

  // ┌───┐ ┌───┐
  // │ A │>│ B │
  // └───┘ └───┘
  //   ┌─────┘
  //   V
  // ┌───┐ ┌───┐
  // │ C │>│ D │
  // └───┘ └───┘
  testTraversal('Semantics traverses a grid left-to-right', (TraversalTester tester) async {
    await tester.test(
      textDirection: TextDirection.ltr,
      children: <String, Rect>{
        'A': const Offset(0.0, 0.0) & tenByTen,
        'B': const Offset(20.0, 0.0) & tenByTen,
        'C': const Offset(0.0, 20.0) & tenByTen,
        'D': const Offset(20.0, 20.0) & tenByTen,
      },
      expectedTraversal: 'A B C D',
    );
  });

  // ┌───┐ ┌───┐
  // │ A │<│ B │
  // └───┘ └───┘
  //   └─────┐
  //         V
  // ┌───┐ ┌───┐
  // │ C │<│ D │
  // └───┘ └───┘
  testTraversal('Semantics traverses a grid right-to-left', (TraversalTester tester) async {
    await tester.test(
      textDirection: TextDirection.rtl,
      children: <String, Rect>{
        'A': const Offset(0.0, 0.0) & tenByTen,
        'B': const Offset(20.0, 0.0) & tenByTen,
        'C': const Offset(0.0, 20.0) & tenByTen,
        'D': const Offset(20.0, 20.0) & tenByTen,
      },
      expectedTraversal: 'B A D C',
    );
  });

  // ┌───┐           ┌───┐
  // │ A │           │ C │
  // └───┘<->┌───┐<->└───┘
  //         │ B │
  //         └───┘
  testTraversal('Semantics traverses vertically overlapping nodes horizontally', (TraversalTester tester) async {
    final Map<String, Rect> children = <String, Rect>{
      'A': const Offset(0.0, 0.0) & tenByTen,
      'B': const Offset(20.0, 5.0) & tenByTen,
      'C': const Offset(40.0, 0.0) & tenByTen,
    };

    await tester.test(
      textDirection: TextDirection.ltr,
      children: children,
      expectedTraversal: 'A B C',
    );

    await tester.test(
      textDirection: TextDirection.rtl,
      children: children,
      expectedTraversal: 'C B A',
    );
  });

  // LTR:
  // ┌───┐ ┌───┐ ┌───┐ ┌───┐
  // │ A │>│ B │>│ C │>│ D │
  // └───┘ └───┘ └───┘ └───┘
  //   ┌─────────────────┘
  //   V
  // ┌───┐ ┌─────────┐ ┌───┐
157 158 159
  // │ E │>│         │>│ G │
  // └───┘ │    F    │ └───┘
  //   ┌───|─────────|───┘
160
  // ┌───┐ │         │ ┌───┐
161
  // │ H │─|─────────|>│ I │
162 163 164 165 166 167 168 169 170 171 172 173 174 175
  // └───┘ └─────────┘ └───┘
  //   ┌─────────────────┘
  //   V
  // ┌───┐ ┌───┐ ┌───┐ ┌───┐
  // │ J │>│ K │>│ L │>│ M │
  // └───┘ └───┘ └───┘ └───┘
  //
  // RTL:
  // ┌───┐ ┌───┐ ┌───┐ ┌───┐
  // │ A │<│ B │<│ C │<│ D │
  // └───┘ └───┘ └───┘ └───┘
  //   └─────────────────┐
  //                     V
  // ┌───┐ ┌─────────┐ ┌───┐
176 177 178
  // │ E │<│         │<│ G │
  // └───┘ │    F    │ └───┘
  //    └──|─────────|────┐
179
  // ┌───┐ │         │ ┌───┐
180
  // │ H │<|─────────|─│ I │
181 182 183 184 185 186 187 188 189 190 191 192 193
  // └───┘ └─────────┘ └───┘
  //   └─────────────────┐
  //                     V
  // ┌───┐ ┌───┐ ┌───┐ ┌───┐
  // │ J │<│ K │<│ L │<│ M │
  // └───┘ └───┘ └───┘ └───┘
  testTraversal('Semantics traverses vertical groups, then horizontal groups, then knots', (TraversalTester tester) async {
    final Map<String, Rect> children = <String, Rect>{
      'A': const Offset(0.0, 0.0) & tenByTen,
      'B': const Offset(20.0, 0.0) & tenByTen,
      'C': const Offset(40.0, 0.0) & tenByTen,
      'D': const Offset(60.0, 0.0) & tenByTen,
      'E': const Offset(0.0, 20.0) & tenByTen,
194 195 196
      'F': const Offset(20.0, 20.0) & (tenByTen * 2.0),
      'G': const Offset(60.0, 20.0) & tenByTen,
      'H': const Offset(0.0, 40.0) & tenByTen,
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
      'I': const Offset(60.0, 40.0) & tenByTen,
      'J': const Offset(0.0, 60.0) & tenByTen,
      'K': const Offset(20.0, 60.0) & tenByTen,
      'L': const Offset(40.0, 60.0) & tenByTen,
      'M': const Offset(60.0, 60.0) & tenByTen,
    };

    await tester.test(
      textDirection: TextDirection.ltr,
      children: children,
      expectedTraversal: 'A B C D E F G H I J K L M',
    );

    await tester.test(
      textDirection: TextDirection.rtl,
      children: children,
213
      expectedTraversal: 'D C B A G F E I H M L K J',
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
    );
  });

  // The following test tests traversal of the simplest "knot", which is two
  // nodes overlapping both vertically and horizontally. For example:
  //
  // ┌─────────┐
  // │         │
  // │   A     │
  // │     ┌───┼─────┐
  // │     │   │     │
  // └─────┼───┘     │
  //       │     B   │
  //       │         │
  //       └─────────┘
  //
  // The outcome depends on the relative positions of the centers of `Rect`s of
  // their respective boxes, specifically the direction (i.e. angle) of the
  // vector pointing from A to B. We test different angles, one for each octant:
  //
  //  -3π/4 -π/2  -π/4
  //      ╲   │   ╱
  //       ╲ 1│2 ╱
  //        ╲ │ ╱
  //     i=0 ╲│╱ 3
  //  π ──────┼────── 0
  //       7 ╱│╲ 4
  //        ╱ │ ╲
  //       ╱ 6│5 ╲
  //      ╱   │   ╲
  //   3π/4  π/2   π/4
  //
  // For LTR, angles falling into octants 3, 4, 5, and 6, produce A -> B, all
  // others produce B -> A.
  //
  // For RTL, angles falling into octants 5, 6, 7, and 0, produce A -> B, all
  // others produce B -> A.
  testTraversal('Semantics sorts knots', (TraversalTester tester) async {
    const double start = -math.pi + math.pi / 8.0;

    for (int i = 0; i < 8; i += 1) {
      final double angle = start + i.toDouble() * math.pi / 4.0;
256 257 258 259 260
      // These values should be truncated so that double precision rounding
      // issues won't impact the heights/widths and throw off the traversal
      // ordering.
      final double dx = (math.cos(angle) * 15.0) / 10.0;
      final double dy = (math.sin(angle) * 15.0) / 10.0;
261 262 263

      final Map<String, Rect> children = <String, Rect>{
        'A': const Offset(10.0, 10.0) & tenByTen,
264
        'B': Offset(10.0 + dx, 10.0 + dy) & tenByTen,
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
      };

      try {
        await tester.test(
          textDirection: TextDirection.ltr,
          children: children,
          expectedTraversal: 3 <= i && i <= 6 ? 'A B' : 'B A',
        );

        await tester.test(
          textDirection: TextDirection.rtl,
          children: children,
          expectedTraversal: 1 <= i && i <= 4 ? 'B A' : 'A B',
        );
      } catch (error) {
        fail(
          'Test failed with i == $i, angle == ${angle / math.pi}π\n'
          '$error'
        );
      }
    }
  });
}

class TraversalTester {
290
  TraversalTester(this.tester) : semantics = SemanticsTester(tester);
291 292 293 294

  final WidgetTester tester;
  final SemanticsTester semantics;

295
  Future<void> test({
296 297 298 299 300 301
    TextDirection textDirection,
    Map<String, Rect> children,
    String expectedTraversal,
  }) async {
    assert(children is LinkedHashMap);
    await tester.pumpWidget(
302 303
        Container(
            child: Directionality(
304
              textDirection: textDirection,
305
              child: Semantics(
306
                textDirection: textDirection,
307 308
                child: CustomMultiChildLayout(
                  delegate: TestLayoutDelegate(children),
309
                  children: children.keys.map<Widget>((String label) {
310
                    return LayoutId(
311
                      id: label,
312
                      child: Semantics(
313 314 315
                        container: true,
                        explicitChildNodes: true,
                        label: label,
316
                        child: SizedBox(
317 318 319 320 321 322 323 324
                          width: children[label].width,
                          height: children[label].height,
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
325
            ),
326
        ),
327 328 329
    );

    expect(semantics, hasSemantics(
330
      TestSemantics.root(
331
        children: <TestSemantics>[
332
          TestSemantics.rootChild(
333 334
            textDirection: textDirection,
            children: expectedTraversal.split(' ').map<TestSemantics>((String label) {
335
              return TestSemantics(
336 337 338
                label: label,
              );
            }).toList(),
339
          ),
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        ],
      ),
      ignoreTransform: true,
      ignoreRect: true,
      ignoreId: true,
      childOrder: DebugSemanticsDumpOrder.traversalOrder,
    ));
  }

  void dispose() {
    semantics.dispose();
  }
}

class TestLayoutDelegate extends MultiChildLayoutDelegate {

  TestLayoutDelegate(this.children);

  final Map<String, Rect> children;

  @override
  void performLayout(Size size) {
    children.forEach((String label, Rect rect) {
363
      layoutChild(label, BoxConstraints.loose(size));
364 365 366 367 368 369 370
      positionChild(label, rect.topLeft);
    });
  }

  @override
  bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => oldDelegate == this;
}