focus_traversal.dart 90.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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';

7
import 'actions.dart';
8 9
import 'basic.dart';
import 'focus_manager.dart';
10
import 'focus_scope.dart';
11
import 'framework.dart';
12 13
import 'scroll_position.dart';
import 'scrollable.dart';
14

15 16 17 18
// Examples can assume:
// late BuildContext context;
// FocusNode focusNode = FocusNode();

19 20 21 22 23 24
// BuildContext/Element doesn't have a parent accessor, but it can be simulated
// with visitAncestorElements. _getAncestor is needed because
// context.getElementForInheritedWidgetOfExactType will return itself if it
// happens to be of the correct type. _getAncestor should be O(count), since we
// always return false at a specific ancestor. By default it returns the parent,
// which is O(1).
25 26
BuildContext? _getAncestor(BuildContext context, {int count = 1}) {
  BuildContext? target;
27 28 29 30 31 32 33 34 35 36 37
  context.visitAncestorElements((Element ancestor) {
    count--;
    if (count == 0) {
      target = ancestor;
      return false;
    }
    return true;
  });
  return target;
}

38 39 40 41 42 43 44 45 46
/// Signature for the callback that's called when a traversal policy
/// requests focus.
typedef TraversalRequestFocusCallback = void Function(
    FocusNode node, {
    ScrollPositionAlignmentPolicy? alignmentPolicy,
    double? alignment,
    Duration? duration,
    Curve? curve,
});
47 48 49 50 51

// A class to temporarily hold information about FocusTraversalGroups when
// sorting their contents.
class _FocusTraversalGroupInfo {
  _FocusTraversalGroupInfo(
52
    _FocusTraversalGroupNode? group, {
53 54
    FocusTraversalPolicy? defaultPolicy,
    List<FocusNode>? members,
55 56
  })  : groupNode = group,
        policy = group?.policy ?? defaultPolicy ?? ReadingOrderTraversalPolicy(),
57 58
        members = members ?? <FocusNode>[];

59
  final FocusNode? groupNode;
60 61 62 63
  final FocusTraversalPolicy policy;
  final List<FocusNode> members;
}

64 65
/// A direction along either the horizontal or vertical axes.
///
66
/// This is used by the [DirectionalFocusTraversalPolicyMixin], and
67 68
/// [FocusNode.focusInDirection] to indicate which direction to look in for the
/// next focus.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
enum TraversalDirection {
  /// Indicates a direction above the currently focused widget.
  up,

  /// Indicates a direction to the right of the currently focused widget.
  ///
  /// This direction is unaffected by the [Directionality] of the current
  /// context.
  right,

  /// Indicates a direction below the currently focused widget.
  down,

  /// Indicates a direction to the left of the currently focused widget.
  ///
  /// This direction is unaffected by the [Directionality] of the current
  /// context.
  left,
}

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
/// Controls the transfer of focus beyond the first and the last items of a
/// [FocusScopeNode].
///
/// This enumeration only controls the traversal behavior performed by
/// [FocusTraversalPolicy]. Other methods of focus transfer, such as direct
/// calls to [FocusNode.requestFocus] and [FocusNode.unfocus], are not affected
/// by this enumeration.
///
/// See also:
///
/// * [FocusTraversalPolicy], which implements the logic behind this enum.
/// * [FocusScopeNode], which is configured by this enum.
enum TraversalEdgeBehavior {
  /// Keeps the focus among the items of the focus scope.
  ///
  /// Requesting the next focus after the last focusable item will transfer the
  /// focus to the first item, and requesting focus previous to the first item
  /// will transfer the focus to the last item, thus forming a closed loop of
  /// focusable items.
  closedLoop,

  /// Allows the focus to leave the [FlutterView].
  ///
  /// Requesting next focus after the last focusable item or previous to the
  /// first item will unfocus any focused nodes. If the focus traversal action
  /// was initiated by the embedder (e.g. the Flutter Engine) the embedder
  /// receives a result indicating that the focus is no longer within the
  /// current [FlutterView]. For example, [NextFocusAction] invoked via keyboard
  /// (typically the TAB key) would receive [KeyEventResult.skipRemainingHandlers]
  /// allowing the embedder handle the shortcut. On the web, typically the
Lioness100's avatar
Lioness100 committed
119
  /// control is transferred to the browser, allowing the user to reach the
120 121 122
  /// address bar, escape an `iframe`, or focus on HTML elements other than
  /// those managed by Flutter.
  leaveFlutterView,
123 124 125 126 127 128 129 130 131 132

  /// Allows focus to traverse up to parent scope.
  ///
  /// When reaching the edge of the current scope, requesting the next focus
  /// will look up to the parent scope of the current scope and focus the focus
  /// node next to the current scope.
  ///
  /// If there is no parent scope above the current scope, fallback to
  /// [closedLoop] behavior.
  parentScope,
133 134 135
}

/// Determines how focusable widgets are traversed within a [FocusTraversalGroup].
136 137
///
/// The focus traversal policy is what determines which widget is "next",
138 139
/// "previous", or in a direction from the widget associated with the currently
/// focused [FocusNode] (usually a [Focus] widget).
140 141 142 143
///
/// One of the pre-defined subclasses may be used, or define a custom policy to
/// create a unique focus order.
///
144 145 146
/// When defining your own, your subclass should implement [sortDescendants] to
/// provide the order in which you would like the descendants to be traversed.
///
147 148
/// See also:
///
149
///  * [FocusNode], for a description of the focus system.
150 151
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
152
///  * [FocusNode], which is affected by the traversal policy.
153
///  * [WidgetOrderTraversalPolicy], a policy that relies on the widget
154 155 156
///    creation order to describe the order of traversal.
///  * [ReadingOrderTraversalPolicy], a policy that describes the order as the
///    natural "reading order" for the current [Directionality].
157 158
///  * [OrderedTraversalPolicy], a policy that describes the order
///    explicitly using [FocusTraversalOrder] widgets.
159 160
///  * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
///    focus traversal in a direction.
161
@immutable
162
abstract class FocusTraversalPolicy with Diagnosticable {
163 164
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  ///
  /// {@template flutter.widgets.FocusTraversalPolicy.requestFocusCallback}
  /// The `requestFocusCallback` can be used to override the default behavior
  /// of the focus requests. If `requestFocusCallback`
  /// is null, it defaults to [FocusTraversalPolicy.defaultTraversalRequestFocusCallback].
  /// {@endtemplate}
  const FocusTraversalPolicy({
    TraversalRequestFocusCallback? requestFocusCallback
  }) : requestFocusCallback = requestFocusCallback ?? defaultTraversalRequestFocusCallback;

  /// The callback used to move the focus from one focus node to another when
  /// traversing them using a keyboard. By default it requests focus on the next
  /// node and ensures the node is visible if it's in a scrollable.
  final TraversalRequestFocusCallback requestFocusCallback;

  /// The default value for [requestFocusCallback].
  /// Requests focus from `node` and ensures the node is visible
  /// by calling [Scrollable.ensureVisible].
  static void defaultTraversalRequestFocusCallback(
    FocusNode node, {
    ScrollPositionAlignmentPolicy? alignmentPolicy,
    double? alignment,
    Duration? duration,
    Curve? curve,
  }) {
    node.requestFocus();
    Scrollable.ensureVisible(
192 193
      node.context!,
      alignment: alignment ?? 1,
194 195 196 197 198
      alignmentPolicy: alignmentPolicy ?? ScrollPositionAlignmentPolicy.explicit,
      duration: duration ?? Duration.zero,
      curve: curve ?? Curves.ease,
    );
  }
199

200 201 202 203 204 205 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
  /// Request focus on a focus node as a result of a tab traversal.
  ///
  /// If the `node` is a [FocusScopeNode], this method will recursively find
  /// the next focus from its descendants until it find a regular [FocusNode].
  ///
  /// Returns true if this method focused a new focus node.
  bool _requestTabTraversalFocus(
    FocusNode node, {
    ScrollPositionAlignmentPolicy? alignmentPolicy,
    double? alignment,
    Duration? duration,
    Curve? curve,
    required bool forward,
  }) {
    if (node is FocusScopeNode) {
      if (node.focusedChild != null) {
        // Can't stop here as the `focusedChild` may be a focus scope node
        // without a first focus. The first focus will be picked in the
        // next iteration.
        return _requestTabTraversalFocus(
          node.focusedChild!,
          alignmentPolicy: alignmentPolicy,
          alignment: alignment,
          duration: duration,
          curve: curve,
          forward: forward,
        );
      }
      final List<FocusNode> sortedChildren = _sortAllDescendants(node, node);
      if (sortedChildren.isNotEmpty) {
        _requestTabTraversalFocus(
          forward ? sortedChildren.first : sortedChildren.last,
          alignmentPolicy: alignmentPolicy,
          alignment: alignment,
          duration: duration,
          curve: curve,
          forward: forward,
        );
        // Regardless if _requestTabTraversalFocus return true or false, a first
        // focus has been picked.
        return true;
      }
    }
    final bool nodeHadPrimaryFocus = node.hasPrimaryFocus;
    requestFocusCallback(
      node,
      alignmentPolicy: alignmentPolicy,
      alignment: alignment,
      duration: duration,
      curve: curve,
    );
    return !nodeHadPrimaryFocus;
  }

254 255
  /// Returns the node that should receive focus if focus is traversing
  /// forwards, and there is no current focus.
256
  ///
257 258 259
  /// The node returned is the node that should receive focus if focus is
  /// traversing forwards (i.e. with [next]), and there is no current focus in
  /// the nearest [FocusScopeNode] that `currentNode` belongs to.
260
  ///
261 262 263 264 265 266 267 268
  /// If `ignoreCurrentFocus` is false or not given, this function returns the
  /// [FocusScopeNode.focusedChild], if set, on the nearest scope of the
  /// `currentNode`, otherwise, returns the first node from [sortDescendants],
  /// or the given `currentNode` if there are no descendants.
  ///
  /// If `ignoreCurrentFocus` is true, then the algorithm returns the first node
  /// from [sortDescendants], or the given `currentNode` if there are no
  /// descendants.
269 270 271
  ///
  /// See also:
  ///
272 273 274 275 276 277 278
  /// * [next], the function that is called to move the focus to the next node.
  /// * [DirectionalFocusTraversalPolicyMixin.findFirstFocusInDirection], a
  ///   function that finds the first focusable widget in a particular
  ///   direction.
  FocusNode? findFirstFocus(FocusNode currentNode, {bool ignoreCurrentFocus = false}) {
    return _findInitialFocus(currentNode, ignoreCurrentFocus: ignoreCurrentFocus);
  }
279 280 281 282 283 284 285 286

  /// Returns the node that should receive focus if focus is traversing
  /// backwards, and there is no current focus.
  ///
  /// The node returned is the one that should receive focus if focus is
  /// traversing backwards (i.e. with [previous]), and there is no current focus
  /// in the nearest [FocusScopeNode] that `currentNode` belongs to.
  ///
287 288 289 290 291 292 293 294
  /// If `ignoreCurrentFocus` is false or not given, this function returns the
  /// [FocusScopeNode.focusedChild], if set, on the nearest scope of the
  /// `currentNode`, otherwise, returns the last node from [sortDescendants],
  /// or the given `currentNode` if there are no descendants.
  ///
  /// If `ignoreCurrentFocus` is true, then the algorithm returns the last node
  /// from [sortDescendants], or the given `currentNode` if there are no
  /// descendants.
295 296 297
  ///
  /// See also:
  ///
298
  ///  * [previous], the function that is called to move the focus to the previous node.
299 300
  ///  * [DirectionalFocusTraversalPolicyMixin.findFirstFocusInDirection], a
  ///    function that finds the first focusable widget in a particular direction.
301 302 303
  FocusNode findLastFocus(FocusNode currentNode, {bool ignoreCurrentFocus = false}) {
    return _findInitialFocus(currentNode, fromEnd: true, ignoreCurrentFocus: ignoreCurrentFocus);
  }
304

305
  FocusNode _findInitialFocus(FocusNode currentNode, {bool fromEnd = false, bool ignoreCurrentFocus = false}) {
306 307
    final FocusScopeNode scope = currentNode.nearestScope!;
    FocusNode? candidate = scope.focusedChild;
308
    if (ignoreCurrentFocus || candidate == null && scope.descendants.isNotEmpty) {
309
      final Iterable<FocusNode> sorted = _sortAllDescendants(scope, currentNode).where((FocusNode node) => _canRequestTraversalFocus(node));
310 311 312 313 314
      if (sorted.isEmpty) {
        candidate = null;
      } else {
        candidate = fromEnd ? sorted.last : sorted.first;
      }
315 316 317 318 319 320 321
    }

    // If we still didn't find any candidate, use the current node as a
    // fallback.
    candidate ??= currentNode;
    return candidate;
  }
322

323 324 325
  /// Returns the first node in the given `direction` that should receive focus
  /// if there is no current focus in the scope to which the `currentNode`
  /// belongs.
326 327
  ///
  /// This is typically used by [inDirection] to determine which node to focus
328
  /// if it is called when no node is currently focused.
329
  FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction);
330 331 332 333 334 335 336 337 338 339 340 341

  /// Clears the data associated with the given [FocusScopeNode] for this object.
  ///
  /// This is used to indicate that the focus policy has changed its mode, and
  /// so any cached policy data should be invalidated. For example, changing the
  /// direction in which focus is moving, or changing from directional to
  /// next/previous navigation modes.
  ///
  /// The default implementation does nothing.
  @mustCallSuper
  void invalidateScopeData(FocusScopeNode node) {}

342
  /// This is called whenever the given [node] is re-parented into a new scope,
343 344 345 346 347 348 349
  /// so that the policy has a chance to update or invalidate any cached data
  /// that it maintains per scope about the node.
  ///
  /// The [oldScope] is the previous scope that this node belonged to, if any.
  ///
  /// The default implementation does nothing.
  @mustCallSuper
350
  void changedScope({FocusNode? node, FocusScopeNode? oldScope}) {}
351 352 353 354 355 356 357 358 359

  /// Focuses the next widget in the focus scope that contains the given
  /// [currentNode].
  ///
  /// This should determine what the next node to receive focus should be by
  /// inspecting the node tree, and then calling [FocusNode.requestFocus] on
  /// the node that has been selected.
  ///
  /// Returns true if it successfully found a node and requested focus.
360
  bool next(FocusNode currentNode) => _moveFocus(currentNode, forward: true);
361 362 363 364 365 366 367 368 369

  /// Focuses the previous widget in the focus scope that contains the given
  /// [currentNode].
  ///
  /// This should determine what the previous node to receive focus should be by
  /// inspecting the node tree, and then calling [FocusNode.requestFocus] on
  /// the node that has been selected.
  ///
  /// Returns true if it successfully found a node and requested focus.
370
  bool previous(FocusNode currentNode) => _moveFocus(currentNode, forward: false);
371 372 373 374 375 376 377 378 379 380 381

  /// Focuses the next widget in the given [direction] in the focus scope that
  /// contains the given [currentNode].
  ///
  /// This should determine what the next node to receive focus in the given
  /// [direction] should be by inspecting the node tree, and then calling
  /// [FocusNode.requestFocus] on the node that has been selected.
  ///
  /// Returns true if it successfully found a node and requested focus.
  bool inDirection(FocusNode currentNode, TraversalDirection direction);

382 383 384 385 386
  /// Sorts the given `descendants` into focus order.
  ///
  /// Subclasses should override this to implement a different sort for [next]
  /// and [previous] to use in their ordering. If the returned iterable omits a
  /// node that is a descendant of the given scope, then the user will be unable
387 388 389 390 391 392 393 394 395
  /// to use next/previous keyboard traversal to reach that node.
  ///
  /// The node used to initiate the traversal (the one passed to [next] or
  /// [previous]) is passed as `currentNode`.
  ///
  /// Having the current node in the list is what allows the algorithm to
  /// determine which nodes are adjacent to the current node. If the
  /// `currentNode` is removed from the list, then the focus will be unchanged
  /// when [next] or [previous] are called, and they will return false.
396 397 398 399 400 401 402 403 404 405
  ///
  /// This is not used for directional focus ([inDirection]), only for
  /// determining the focus order for [next] and [previous].
  ///
  /// When implementing an override for this function, be sure to use
  /// [mergeSort] instead of Dart's default list sorting algorithm when sorting
  /// items, since the default algorithm is not stable (items deemed to be equal
  /// can appear in arbitrary order, and change positions between sorts), whereas
  /// [mergeSort] is stable.
  @protected
406
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode);
407

408 409 410 411
  static bool _canRequestTraversalFocus(FocusNode node) {
    return node.canRequestFocus && !node.skipTraversal;
  }

412 413 414
  static Iterable<FocusNode> _getDescendantsWithoutExpandingScope(FocusNode node) {
    final List<FocusNode> result = <FocusNode>[];
    for (final FocusNode child in node.children) {
415
      result.add(child);
416 417 418 419 420 421 422 423
      if (child is! FocusScopeNode) {
        result.addAll(_getDescendantsWithoutExpandingScope(child));
      }
    }
    return result;
  }

  static Map<FocusNode?, _FocusTraversalGroupInfo> _findGroups(FocusScopeNode scope, _FocusTraversalGroupNode? scopeGroupNode, FocusNode currentNode) {
424
    final FocusTraversalPolicy defaultPolicy = scopeGroupNode?.policy ?? ReadingOrderTraversalPolicy();
425
    final Map<FocusNode?, _FocusTraversalGroupInfo> groups = <FocusNode?, _FocusTraversalGroupInfo>{};
426
    for (final FocusNode node in _getDescendantsWithoutExpandingScope(scope)) {
427
      final _FocusTraversalGroupNode? groupNode = FocusTraversalGroup._getGroupNode(node);
428 429 430 431 432 433
      // Group nodes need to be added to their parent's node, or to the "null"
      // node if no parent is found. This creates the hierarchy of group nodes
      // and makes it so the entire group is sorted along with the other members
      // of the parent group.
      if (node == groupNode) {
        // To find the parent of the group node, we need to skip over the parent
434 435 436 437 438 439 440
        // of the Focus node added in _FocusTraversalGroupState.build, and start
        // looking with that node's parent, since _getGroupNode will return the
        // node it was called on if it matches the type.
        final _FocusTraversalGroupNode? parentGroup = FocusTraversalGroup._getGroupNode(groupNode!.parent!);
        groups[parentGroup] ??= _FocusTraversalGroupInfo(parentGroup, members: <FocusNode>[], defaultPolicy: defaultPolicy);
        assert(!groups[parentGroup]!.members.contains(node));
        groups[parentGroup]!.members.add(groupNode);
441 442 443 444
        continue;
      }
      // Skip non-focusable and non-traversable nodes in the same way that
      // FocusScopeNode.traversalDescendants would.
445 446 447 448
      //
      // Current focused node needs to be in the group so that the caller can
      // find the next traversable node from the current focused node.
      if (node == currentNode || (node.canRequestFocus && !node.skipTraversal)) {
449
        groups[groupNode] ??= _FocusTraversalGroupInfo(groupNode, members: <FocusNode>[], defaultPolicy: defaultPolicy);
450 451
        assert(!groups[groupNode]!.members.contains(node));
        groups[groupNode]!.members.add(node);
452 453
      }
    }
454 455 456 457 458
    return groups;
  }

  // Sort all descendants, taking into account the FocusTraversalGroup
  // that they are each in, and filtering out non-traversable/focusable nodes.
459
  static List<FocusNode> _sortAllDescendants(FocusScopeNode scope, FocusNode currentNode) {
460 461
    final _FocusTraversalGroupNode? scopeGroupNode = FocusTraversalGroup._getGroupNode(scope);
    // Build the sorting data structure, separating descendants into groups.
462
    final Map<FocusNode?, _FocusTraversalGroupInfo> groups = _findGroups(scope, scopeGroupNode, currentNode);
463 464

    // Sort the member lists using the individual policy sorts.
465 466 467 468
    for (final FocusNode? key in groups.keys) {
      final List<FocusNode> sortedMembers = groups[key]!.policy.sortDescendants(groups[key]!.members, currentNode).toList();
      groups[key]!.members.clear();
      groups[key]!.members.addAll(sortedMembers);
469 470 471 472 473 474 475
    }

    // Traverse the group tree, adding the children of members in the order they
    // appear in the member lists.
    final List<FocusNode> sortedDescendants = <FocusNode>[];
    void visitGroups(_FocusTraversalGroupInfo info) {
      for (final FocusNode node in info.members) {
476
        if (groups.containsKey(node)) {
477 478
          // This is a policy group focus node. Replace it with the members of
          // the corresponding policy group.
479
          visitGroups(groups[node]!);
480 481 482 483 484 485
        } else {
          sortedDescendants.add(node);
        }
      }
    }

486
    // Visit the children of the scope, if any.
487 488
    if (groups.isNotEmpty && groups.containsKey(scopeGroupNode)) {
      visitGroups(groups[scopeGroupNode]!);
489
    }
490 491 492 493 494

    // Remove the FocusTraversalGroup nodes themselves, which aren't focusable.
    // They were left in above because they were needed to find their members
    // during sorting.
    sortedDescendants.removeWhere((FocusNode node) {
495
      return node != currentNode && !_canRequestTraversalFocus(node);
496 497 498 499 500
    });

    // Sanity check to make sure that the algorithm above doesn't diverge from
    // the one in FocusScopeNode.traversalDescendants in terms of which nodes it
    // finds.
501 502
    assert((){
      final Set<FocusNode> difference = sortedDescendants.toSet().difference(scope.traversalDescendants.toSet());
503
      if (!_canRequestTraversalFocus(currentNode)) {
504 505
        // The scope.traversalDescendants will not contain currentNode if it
        // skips traversal or not focusable.
506
        assert(
507 508 509
         difference.isEmpty || (difference.length == 1 && difference.contains(currentNode)),
         'Difference between sorted descendants and FocusScopeNode.traversalDescendants contains '
         'something other than the current skipped node. This is the difference: $difference',
510 511 512 513 514 515 516 517 518 519
        );
        return true;
      }
      assert(
        difference.isEmpty,
        'Sorted descendants contains different nodes than FocusScopeNode.traversalDescendants would. '
        'These are the different nodes: $difference',
      );
      return true;
    }());
520 521 522
    return sortedDescendants;
  }

523 524 525 526 527 528 529 530 531 532 533 534 535 536
  /// Moves the focus to the next node in the FocusScopeNode nearest to the
  /// currentNode argument, either in a forward or reverse direction, depending
  /// on the value of the forward argument.
  ///
  /// This function is called by the next and previous members to move to the
  /// next or previous node, respectively.
  ///
  /// Uses [findFirstFocus]/[findLastFocus] to find the first/last node if there is
  /// no [FocusScopeNode.focusedChild] set. If there is a focused child for the
  /// scope, then it calls sortDescendants to get a sorted list of descendants,
  /// and then finds the node after the current first focus of the scope if
  /// forward is true, and the node before it if forward is false.
  ///
  /// Returns true if a node requested focus.
537
  @protected
538 539
  bool _moveFocus(FocusNode currentNode, {required bool forward}) {
    final FocusScopeNode nearestScope = currentNode.nearestScope!;
540
    invalidateScopeData(nearestScope);
541
    FocusNode? focusedChild = nearestScope.focusedChild;
542
    if (focusedChild == null) {
543
      final FocusNode? firstFocus = forward ? findFirstFocus(currentNode) : findLastFocus(currentNode);
544
      if (firstFocus != null) {
545
        return _requestTabTraversalFocus(
546 547
          firstFocus,
          alignmentPolicy: forward ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
548
          forward: forward,
549 550 551
        );
      }
    }
552 553
    focusedChild ??= nearestScope;
    final List<FocusNode> sortedNodes = _sortAllDescendants(nearestScope, focusedChild);
554
    assert(sortedNodes.contains(focusedChild));
555

556
    if (forward && focusedChild == sortedNodes.last) {
557 558
      switch (nearestScope.traversalEdgeBehavior) {
        case TraversalEdgeBehavior.leaveFlutterView:
559
          focusedChild.unfocus();
560
          return false;
561 562 563 564 565 566 567 568 569 570 571 572 573 574
        case TraversalEdgeBehavior.parentScope:
          final FocusScopeNode? parentScope = nearestScope.enclosingScope;
          if (parentScope != null && parentScope != FocusManager.instance.rootScope) {
            focusedChild.unfocus();
            parentScope.nextFocus();
            // Verify the focus really has changed.
            return focusedChild.enclosingScope?.focusedChild != focusedChild;
          }
          // No valid parent scope. Fallback to closed loop behavior.
          return _requestTabTraversalFocus(
            sortedNodes.first,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
            forward: forward,
          );
575
        case TraversalEdgeBehavior.closedLoop:
576 577 578 579 580
          return _requestTabTraversalFocus(
            sortedNodes.first,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
            forward: forward,
          );
581
      }
582 583
    }
    if (!forward && focusedChild == sortedNodes.first) {
584 585
      switch (nearestScope.traversalEdgeBehavior) {
        case TraversalEdgeBehavior.leaveFlutterView:
586
          focusedChild.unfocus();
587
          return false;
588 589 590 591 592 593 594 595 596 597 598 599 600 601
        case TraversalEdgeBehavior.parentScope:
          final FocusScopeNode? parentScope = nearestScope.enclosingScope;
          if (parentScope != null && parentScope != FocusManager.instance.rootScope) {
            focusedChild.unfocus();
            parentScope.previousFocus();
            // Verify the focus really has changed.
            return focusedChild.enclosingScope?.focusedChild != focusedChild;
          }
          // No valid parent scope. Fallback to closed loop behavior.
          return _requestTabTraversalFocus(
            sortedNodes.last,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
            forward: forward,
          );
602
        case TraversalEdgeBehavior.closedLoop:
603 604 605 606 607
          return _requestTabTraversalFocus(
            sortedNodes.last,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
            forward: forward,
          );
608
      }
609 610 611
    }

    final Iterable<FocusNode> maybeFlipped = forward ? sortedNodes : sortedNodes.reversed;
612
    FocusNode? previousNode;
613 614
    for (final FocusNode node in maybeFlipped) {
      if (previousNode == focusedChild) {
615
        return _requestTabTraversalFocus(
616 617
          node,
          alignmentPolicy: forward ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
618
          forward: forward,
619 620 621 622 623 624
        );
      }
      previousNode = node;
    }
    return false;
  }
625 626
}

627 628
// A policy data object for use by the DirectionalFocusTraversalPolicyMixin so
// it can keep track of the traversal history.
629
class _DirectionalPolicyDataEntry {
630
  const _DirectionalPolicyDataEntry({required this.direction, required this.node});
631 632 633 634 635 636

  final TraversalDirection direction;
  final FocusNode node;
}

class _DirectionalPolicyData {
637
  const _DirectionalPolicyData({required this.history});
638 639 640 641 642 643 644 645 646 647 648 649

  /// A queue of entries that describe the path taken to the current node.
  final List<_DirectionalPolicyDataEntry> history;
}

/// A mixin class that provides an implementation for finding a node in a
/// particular direction.
///
/// This can be mixed in to other [FocusTraversalPolicy] implementations that
/// only want to implement new next/previous policies.
///
/// Since hysteresis in the navigation order is undesirable, this implementation
650 651 652 653 654
/// maintains a stack of previous locations that have been visited on the policy
/// data for the affected [FocusScopeNode]. If the previous direction was the
/// opposite of the current direction, then the this policy will request focus
/// on the previously focused node. Change to another direction other than the
/// current one or its opposite will clear the stack.
655 656 657 658
///
/// For instance, if the focus moves down, down, down, and then up, up, up, it
/// will follow the same path through the widgets in both directions. However,
/// if it moves down, down, down, left, right, and then up, up, up, it may not
659 660
/// follow the same path on the way up as it did on the way down, since changing
/// the axis of motion resets the history.
661
///
662 663 664 665 666 667 668 669 670 671 672 673 674 675
/// This class implements an algorithm that considers an infinite band extending
/// along the direction of movement, the width or height (depending on
/// direction) of the currently focused widget, and finds the closest widget in
/// that band along the direction of movement. If nothing is found in that band,
/// then it picks the widget with an edge closest to the band in the
/// perpendicular direction. If two out-of-band widgets are the same distance
/// from the band, then it picks the one closest along the direction of
/// movement.
///
/// The goal of this algorithm is to pick a widget that (to the user) doesn't
/// appear to traverse along the wrong axis, as it might if it only sorted
/// widgets by distance along one axis, but also jumps to the next logical
/// widget in a direction without skipping over widgets.
///
676 677
/// See also:
///
678 679 680 681 682 683 684 685 686
/// * [FocusNode], for a description of the focus system.
/// * [FocusTraversalGroup], a widget that groups together and imposes a
///   traversal policy on the [Focus] nodes below it in the widget hierarchy.
/// * [WidgetOrderTraversalPolicy], a policy that relies on the widget creation
///   order to describe the order of traversal.
/// * [ReadingOrderTraversalPolicy], a policy that describes the order as the
///   natural "reading order" for the current [Directionality].
/// * [OrderedTraversalPolicy], a policy that describes the order explicitly
///   using [FocusTraversalOrder] widgets.
687 688 689 690 691 692 693 694 695 696
mixin DirectionalFocusTraversalPolicyMixin on FocusTraversalPolicy {
  final Map<FocusScopeNode, _DirectionalPolicyData> _policyData = <FocusScopeNode, _DirectionalPolicyData>{};

  @override
  void invalidateScopeData(FocusScopeNode node) {
    super.invalidateScopeData(node);
    _policyData.remove(node);
  }

  @override
697
  void changedScope({FocusNode? node, FocusScopeNode? oldScope}) {
698 699
    super.changedScope(node: node, oldScope: oldScope);
    if (oldScope != null) {
700
      _policyData[oldScope]?.history.removeWhere((_DirectionalPolicyDataEntry entry) {
701 702 703 704 705 706
        return entry.node == node;
      });
    }
  }

  @override
707
  FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction) {
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    switch (direction) {
      case TraversalDirection.up:
        // Find the bottom-most node so we can go up from there.
        return _sortAndFindInitial(currentNode, vertical: true, first: false);
      case TraversalDirection.down:
        // Find the top-most node so we can go down from there.
        return _sortAndFindInitial(currentNode, vertical: true, first: true);
      case TraversalDirection.left:
        // Find the right-most node so we can go left from there.
        return _sortAndFindInitial(currentNode, vertical: false, first: false);
      case TraversalDirection.right:
        // Find the left-most node so we can go right from there.
        return _sortAndFindInitial(currentNode, vertical: false, first: true);
    }
  }

724 725
  FocusNode? _sortAndFindInitial(FocusNode currentNode, {required bool vertical, required bool first}) {
    final Iterable<FocusNode> nodes = currentNode.nearestScope!.traversalDescendants;
726
    final List<FocusNode> sorted = nodes.toList();
727
    mergeSort<FocusNode>(sorted, compare: (FocusNode a, FocusNode b) {
728 729 730 731 732 733 734 735 736 737 738 739 740 741
      if (vertical) {
        if (first) {
          return a.rect.top.compareTo(b.rect.top);
        } else {
          return b.rect.bottom.compareTo(a.rect.bottom);
        }
      } else {
        if (first) {
          return a.rect.left.compareTo(b.rect.left);
        } else {
          return b.rect.right.compareTo(a.rect.right);
        }
      }
    });
742

743
    if (sorted.isNotEmpty) {
744
      return sorted.first;
745
    }
746 747

    return null;
748 749
  }

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
  static int _verticalCompare(Offset target, Offset a, Offset b) {
    return (a.dy - target.dy).abs().compareTo((b.dy - target.dy).abs());
  }

  static int _horizontalCompare(Offset target, Offset a, Offset b) {
    return (a.dx - target.dx).abs().compareTo((b.dx - target.dx).abs());
  }

  // Sort the ones that are closest to target vertically first, and if two are
  // the same vertical distance, pick the one that is closest horizontally.
  static Iterable<FocusNode> _sortByDistancePreferVertical(Offset target, Iterable<FocusNode> nodes) {
    final List<FocusNode> sorted = nodes.toList();
    mergeSort<FocusNode>(sorted, compare: (FocusNode nodeA, FocusNode nodeB) {
      final Offset a = nodeA.rect.center;
      final Offset b = nodeB.rect.center;
      final int vertical = _verticalCompare(target, a, b);
      if (vertical == 0) {
        return _horizontalCompare(target, a, b);
      }
      return vertical;
    });
    return sorted;
  }

  // Sort the ones that are closest horizontally first, and if two are the same
  // horizontal distance, pick the one that is closest vertically.
  static Iterable<FocusNode> _sortByDistancePreferHorizontal(Offset target, Iterable<FocusNode> nodes) {
    final List<FocusNode> sorted = nodes.toList();
    mergeSort<FocusNode>(sorted, compare: (FocusNode nodeA, FocusNode nodeB) {
      final Offset a = nodeA.rect.center;
      final Offset b = nodeB.rect.center;
      final int horizontal = _horizontalCompare(target, a, b);
      if (horizontal == 0) {
        return _verticalCompare(target, a, b);
      }
      return horizontal;
    });
    return sorted;
  }

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
  static int _verticalCompareClosestEdge(Offset target, Rect a, Rect b) {
    // Find which edge is closest to the target for each.
    final double aCoord = (a.top - target.dy).abs() < (a.bottom - target.dy).abs() ? a.top : a.bottom;
    final double bCoord = (b.top - target.dy).abs() < (b.bottom - target.dy).abs() ? b.top : b.bottom;
    return (aCoord - target.dy).abs().compareTo((bCoord - target.dy).abs());
  }

  static int _horizontalCompareClosestEdge(Offset target, Rect a, Rect b) {
    // Find which edge is closest to the target for each.
    final double aCoord = (a.left - target.dx).abs() < (a.right - target.dx).abs() ? a.left : a.right;
    final double bCoord = (b.left - target.dx).abs() < (b.right - target.dx).abs() ? b.left : b.right;
    return (aCoord - target.dx).abs().compareTo((bCoord - target.dx).abs());
  }

  // Sort the ones that have edges that are closest horizontally first, and if
  // two are the same horizontal distance, pick the one that is closest
  // vertically.
  static Iterable<FocusNode> _sortClosestEdgesByDistancePreferHorizontal(Offset target, Iterable<FocusNode> nodes) {
    final List<FocusNode> sorted = nodes.toList();
    mergeSort<FocusNode>(sorted, compare: (FocusNode nodeA, FocusNode nodeB) {
      final int horizontal = _horizontalCompareClosestEdge(target, nodeA.rect, nodeB.rect);
      if (horizontal == 0) {
        // If they're the same distance horizontally, pick the closest one
        // vertically.
        return _verticalCompare(target, nodeA.rect.center, nodeB.rect.center);
      }
      return horizontal;
    });
    return sorted;
  }

  // Sort the ones that have edges that are closest vertically first, and if
  // two are the same vertical distance, pick the one that is closest
  // horizontally.
  static Iterable<FocusNode> _sortClosestEdgesByDistancePreferVertical(Offset target, Iterable<FocusNode> nodes) {
    final List<FocusNode> sorted = nodes.toList();
    mergeSort<FocusNode>(sorted, compare: (FocusNode nodeA, FocusNode nodeB) {
      final int vertical = _verticalCompareClosestEdge(target, nodeA.rect, nodeB.rect);
      if (vertical == 0) {
        // If they're the same distance vertically, pick the closest one
        // horizontally.
        return _horizontalCompare(target, nodeA.rect.center, nodeB.rect.center);
      }
      return vertical;
    });
    return sorted;
  }

838 839 840 841 842 843 844 845
  // Sorts nodes from left to right horizontally, and removes nodes that are
  // either to the right of the left side of the target node if we're going
  // left, or to the left of the right side of the target node if we're going
  // right.
  //
  // This doesn't need to take into account directionality because it is
  // typically intending to actually go left or right, not in a reading
  // direction.
846
  Iterable<FocusNode> _sortAndFilterHorizontally(
847 848
    TraversalDirection direction,
    Rect target,
849
    Iterable<FocusNode> nodes,
850 851
  ) {
    assert(direction == TraversalDirection.left || direction == TraversalDirection.right);
852
    final Iterable<FocusNode> filtered;
853 854
    switch (direction) {
      case TraversalDirection.left:
855
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dx <= target.left);
856
      case TraversalDirection.right:
857
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dx >= target.right);
858 859
      case TraversalDirection.up:
      case TraversalDirection.down:
860
        throw ArgumentError('Invalid direction $direction');
861
    }
862 863 864 865
    final List<FocusNode> sorted = filtered.toList();
    // Sort all nodes from left to right.
    mergeSort<FocusNode>(sorted, compare: (FocusNode a, FocusNode b) => a.rect.center.dx.compareTo(b.rect.center.dx));
    return sorted;
866 867 868 869 870
  }

  // Sorts nodes from top to bottom vertically, and removes nodes that are
  // either below the top of the target node if we're going up, or above the
  // bottom of the target node if we're going down.
871
  Iterable<FocusNode> _sortAndFilterVertically(
872 873 874 875
    TraversalDirection direction,
    Rect target,
    Iterable<FocusNode> nodes,
  ) {
876 877
    assert(direction == TraversalDirection.up || direction == TraversalDirection.down);
    final Iterable<FocusNode> filtered;
878 879
    switch (direction) {
      case TraversalDirection.up:
880
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dy <= target.top);
881
      case TraversalDirection.down:
882
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dy >= target.bottom);
883 884
      case TraversalDirection.left:
      case TraversalDirection.right:
885
        throw ArgumentError('Invalid direction $direction');
886
    }
887 888 889
    final List<FocusNode> sorted = filtered.toList();
    mergeSort<FocusNode>(sorted, compare: (FocusNode a, FocusNode b) => a.rect.center.dy.compareTo(b.rect.center.dy));
    return sorted;
890 891 892 893 894 895 896
  }

  // Updates the policy data to keep the previously visited node so that we can
  // avoid hysteresis when we change directions in navigation.
  //
  // Returns true if focus was requested on a previous node.
  bool _popPolicyDataIfNeeded(TraversalDirection direction, FocusScopeNode nearestScope, FocusNode focusedChild) {
897
    final _DirectionalPolicyData? policyData = _policyData[nearestScope];
898
    if (policyData != null && policyData.history.isNotEmpty && policyData.history.first.direction != direction) {
899 900 901
      if (policyData.history.last.node.parent == null) {
        // If a node has been removed from the tree, then we should stop
        // referencing it and reset the scope data so that we don't try and
902 903 904
        // request focus on it. This can happen in slivers where the rendered
        // node has been unmounted. This has the side effect that hysteresis
        // might not be avoided when items that go off screen get unmounted.
905 906 907
        invalidateScopeData(nearestScope);
        return false;
      }
908 909 910 911

      // Returns true if successfully popped the history.
      bool popOrInvalidate(TraversalDirection direction) {
        final FocusNode lastNode = policyData.history.removeLast().node;
912
        if (Scrollable.maybeOf(lastNode.context!) != Scrollable.maybeOf(primaryFocus!.context!)) {
913 914 915
          invalidateScopeData(nearestScope);
          return false;
        }
916
        final ScrollPositionAlignmentPolicy alignmentPolicy;
917
        switch (direction) {
918 919 920 921 922
          case TraversalDirection.up:
          case TraversalDirection.left:
            alignmentPolicy = ScrollPositionAlignmentPolicy.keepVisibleAtStart;
          case TraversalDirection.right:
          case TraversalDirection.down:
923
            alignmentPolicy = ScrollPositionAlignmentPolicy.keepVisibleAtEnd;
924
        }
925
        requestFocusCallback(
926 927 928 929 930 931
          lastNode,
          alignmentPolicy: alignmentPolicy,
        );
        return true;
      }

932 933 934 935 936 937 938 939 940 941
      switch (direction) {
        case TraversalDirection.down:
        case TraversalDirection.up:
          switch (policyData.history.first.direction) {
            case TraversalDirection.left:
            case TraversalDirection.right:
              // Reset the policy data if we change directions.
              invalidateScopeData(nearestScope);
            case TraversalDirection.up:
            case TraversalDirection.down:
942 943 944
              if (popOrInvalidate(direction)) {
                return true;
              }
945 946 947 948 949 950
          }
        case TraversalDirection.left:
        case TraversalDirection.right:
          switch (policyData.history.first.direction) {
            case TraversalDirection.left:
            case TraversalDirection.right:
951 952 953
              if (popOrInvalidate(direction)) {
                return true;
              }
954 955 956 957 958 959 960 961 962 963 964 965 966 967
            case TraversalDirection.up:
            case TraversalDirection.down:
              // Reset the policy data if we change directions.
              invalidateScopeData(nearestScope);
          }
      }
    }
    if (policyData != null && policyData.history.isEmpty) {
      invalidateScopeData(nearestScope);
    }
    return false;
  }

  void _pushPolicyData(TraversalDirection direction, FocusScopeNode nearestScope, FocusNode focusedChild) {
968
    final _DirectionalPolicyData? policyData = _policyData[nearestScope];
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    final _DirectionalPolicyDataEntry newEntry = _DirectionalPolicyDataEntry(node: focusedChild, direction: direction);
    if (policyData != null) {
      policyData.history.add(newEntry);
    } else {
      _policyData[nearestScope] = _DirectionalPolicyData(history: <_DirectionalPolicyDataEntry>[newEntry]);
    }
  }

  /// Focuses the next widget in the given [direction] in the [FocusScope] that
  /// contains the [currentNode].
  ///
  /// This determines what the next node to receive focus in the given
  /// [direction] will be by inspecting the node tree, and then calling
  /// [FocusNode.requestFocus] on it.
  ///
  /// Returns true if it successfully found a node and requested focus.
  ///
  /// Maintains a stack of previous locations that have been visited on the
987
  /// policy data for the affected [FocusScopeNode]. If the previous direction
988 989 990 991 992 993 994 995 996
  /// was the opposite of the current direction, then the this policy will
  /// request focus on the previously focused node. Change to another direction
  /// other than the current one or its opposite will clear the stack.
  ///
  /// If this function returns true when called by a subclass, then the subclass
  /// should return true and not request focus from any node.
  @mustCallSuper
  @override
  bool inDirection(FocusNode currentNode, TraversalDirection direction) {
997 998
    final FocusScopeNode nearestScope = currentNode.nearestScope!;
    final FocusNode? focusedChild = nearestScope.focusedChild;
999
    if (focusedChild == null) {
1000 1001 1002 1003
      final FocusNode firstFocus = findFirstFocusInDirection(currentNode, direction) ?? currentNode;
      switch (direction) {
        case TraversalDirection.up:
        case TraversalDirection.left:
1004
          requestFocusCallback(
1005 1006 1007 1008 1009
            firstFocus,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
          );
        case TraversalDirection.right:
        case TraversalDirection.down:
1010
          requestFocusCallback(
1011 1012 1013 1014
            firstFocus,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
          );
      }
1015 1016 1017 1018 1019
      return true;
    }
    if (_popPolicyDataIfNeeded(direction, nearestScope, focusedChild)) {
      return true;
    }
1020
    FocusNode? found;
1021
    final ScrollableState? focusedScrollable = Scrollable.maybeOf(focusedChild.context!);
1022 1023 1024
    switch (direction) {
      case TraversalDirection.down:
      case TraversalDirection.up:
1025 1026 1027 1028
        Iterable<FocusNode> eligibleNodes = _sortAndFilterVertically(direction, focusedChild.rect, nearestScope.traversalDescendants);
        if (eligibleNodes.isEmpty) {
          break;
        }
1029
        if (focusedScrollable != null && !focusedScrollable.position.atEdge) {
1030
          final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where((FocusNode node) => Scrollable.maybeOf(node.context!) == focusedScrollable);
1031 1032 1033 1034
          if (filteredEligibleNodes.isNotEmpty) {
            eligibleNodes = filteredEligibleNodes;
          }
        }
1035
        if (direction == TraversalDirection.up) {
1036
          eligibleNodes = eligibleNodes.toList().reversed;
1037 1038 1039
        }
        // Find any nodes that intersect the band of the focused child.
        final Rect band = Rect.fromLTRB(focusedChild.rect.left, -double.infinity, focusedChild.rect.right, double.infinity);
1040
        final Iterable<FocusNode> inBand = eligibleNodes.where((FocusNode node) => !node.rect.intersect(band).isEmpty);
1041
        if (inBand.isNotEmpty) {
1042
          found = _sortByDistancePreferVertical(focusedChild.rect.center, inBand).first;
1043 1044
          break;
        }
1045
        // Only out-of-band targets are eligible, so pick the one that is
1046 1047 1048
        // closest to the center line horizontally, and if any are the same
        // distance horizontally, pick the closest one of those vertically.
        found = _sortClosestEdgesByDistancePreferHorizontal(focusedChild.rect.center, eligibleNodes).first;
1049 1050
      case TraversalDirection.right:
      case TraversalDirection.left:
1051 1052 1053 1054
        Iterable<FocusNode> eligibleNodes = _sortAndFilterHorizontally(direction, focusedChild.rect, nearestScope.traversalDescendants);
        if (eligibleNodes.isEmpty) {
          break;
        }
1055
        if (focusedScrollable != null && !focusedScrollable.position.atEdge) {
1056
          final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where((FocusNode node) => Scrollable.maybeOf(node.context!) == focusedScrollable);
1057 1058 1059 1060
          if (filteredEligibleNodes.isNotEmpty) {
            eligibleNodes = filteredEligibleNodes;
          }
        }
1061
        if (direction == TraversalDirection.left) {
1062
          eligibleNodes = eligibleNodes.toList().reversed;
1063 1064 1065
        }
        // Find any nodes that intersect the band of the focused child.
        final Rect band = Rect.fromLTRB(-double.infinity, focusedChild.rect.top, double.infinity, focusedChild.rect.bottom);
1066
        final Iterable<FocusNode> inBand = eligibleNodes.where((FocusNode node) => !node.rect.intersect(band).isEmpty);
1067
        if (inBand.isNotEmpty) {
1068
          found = _sortByDistancePreferHorizontal(focusedChild.rect.center, inBand).first;
1069 1070
          break;
        }
1071
        // Only out-of-band targets are eligible, so pick the one that is
1072 1073 1074
        // closest to the center line vertically, and if any are the same
        // distance vertically, pick the closest one of those horizontally.
        found = _sortClosestEdgesByDistancePreferVertical(focusedChild.rect.center, eligibleNodes).first;
1075 1076 1077
    }
    if (found != null) {
      _pushPolicyData(direction, nearestScope, focusedChild);
1078 1079 1080
      switch (direction) {
        case TraversalDirection.up:
        case TraversalDirection.left:
1081
          requestFocusCallback(
1082 1083 1084 1085 1086
            found,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
          );
        case TraversalDirection.down:
        case TraversalDirection.right:
1087
          requestFocusCallback(
1088 1089 1090
            found,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
          );
1091
      }
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
      return true;
    }
    return false;
  }
}

/// A [FocusTraversalPolicy] that traverses the focus order in widget hierarchy
/// order.
///
/// This policy is used when the order desired is the order in which widgets are
/// created in the widget hierarchy.
///
/// See also:
///
1106
///  * [FocusNode], for a description of the focus system.
1107 1108
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
1109 1110 1111 1112
///  * [ReadingOrderTraversalPolicy], a policy that describes the order as the
///    natural "reading order" for the current [Directionality].
///  * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
///    focus traversal in a direction.
1113 1114 1115
///  * [OrderedTraversalPolicy], a policy that describes the order
///    explicitly using [FocusTraversalOrder] widgets.
class WidgetOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
1116 1117 1118 1119 1120
  /// Constructs a traversal policy that orders widgets for keyboard traversal
  /// based on the widget hierarchy order.
  ///
  /// {@macro flutter.widgets.FocusTraversalPolicy.requestFocusCallback}
  WidgetOrderTraversalPolicy({super.requestFocusCallback});
1121
  @override
1122
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) => descendants;
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
}

// This class exists mainly for efficiency reasons: the rect is copied out of
// the node, because it will be accessed many times in the reading order
// algorithm, and the FocusNode.rect accessor does coordinate transformation. If
// not for this optimization, it could just be removed, and the node used
// directly.
//
// It's also a convenient place to put some utility functions having to do with
// the sort data.
1133
class _ReadingOrderSortData with Diagnosticable {
1134
  _ReadingOrderSortData(this.node)
1135
      : rect = node.rect,
1136
        directionality = _findDirectionality(node.context!);
1137

1138
  final TextDirection? directionality;
1139 1140 1141 1142 1143
  final Rect rect;
  final FocusNode node;

  // Find the directionality in force for a build context without creating a
  // dependency.
1144
  static TextDirection? _findDirectionality(BuildContext context) {
1145
    return context.getInheritedWidgetOfExactType<Directionality>()?.textDirection;
1146
  }
1147

1148
  /// Finds the common Directional ancestor of an entire list of groups.
1149
  static TextDirection? commonDirectionalityOf(List<_ReadingOrderSortData> list) {
1150
    final Iterable<Set<Directionality>> allAncestors = list.map<Set<Directionality>>((_ReadingOrderSortData member) => member.directionalAncestors.toSet());
1151
    Set<Directionality>? common;
1152 1153 1154
    for (final Set<Directionality> ancestorSet in allAncestors) {
      common ??= ancestorSet;
      common = common.intersection(ancestorSet);
1155
    }
1156
    if (common!.isEmpty) {
1157
      // If there is no common ancestor, then arbitrarily pick the
1158 1159
      // directionality of the first group, which is the equivalent of the
      // "first strongly typed" item in a bidirectional algorithm.
1160
      return list.first.directionality;
1161
    }
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    // Find the closest common ancestor. The memberAncestors list contains the
    // ancestors for all members, but the first member's ancestry was
    // added in order from nearest to furthest, so we can still use that
    // to determine the closest one.
    return list.first.directionalAncestors.firstWhere(common.contains).textDirection;
  }

  static void sortWithDirectionality(List<_ReadingOrderSortData> list, TextDirection directionality) {
    mergeSort<_ReadingOrderSortData>(list, compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) {
      switch (directionality) {
        case TextDirection.ltr:
          return a.rect.left.compareTo(b.rect.left);
        case TextDirection.rtl:
          return b.rect.right.compareTo(a.rect.right);
1176
      }
1177 1178
    });
  }
1179

1180 1181 1182 1183 1184
  /// Returns the list of Directionality ancestors, in order from nearest to
  /// furthest.
  Iterable<Directionality> get directionalAncestors {
    List<Directionality> getDirectionalityAncestors(BuildContext context) {
      final List<Directionality> result = <Directionality>[];
1185
      InheritedElement? directionalityElement = context.getElementForInheritedWidgetOfExactType<Directionality>();
1186 1187 1188
      while (directionalityElement != null) {
        result.add(directionalityElement.widget as Directionality);
        directionalityElement = _getAncestor(directionalityElement)?.getElementForInheritedWidgetOfExactType<Directionality>();
1189
      }
1190
      return result;
1191
    }
1192

1193 1194
    _directionalAncestors ??= getDirectionalityAncestors(node.context!);
    return _directionalAncestors!;
1195 1196
  }

1197
  List<Directionality>? _directionalAncestors;
1198 1199

  @override
1200 1201 1202 1203 1204 1205
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<TextDirection>('directionality', directionality));
    properties.add(StringProperty('name', node.debugLabel, defaultValue: null));
    properties.add(DiagnosticsProperty<Rect>('rect', rect));
  }
1206 1207
}

1208 1209
// A class for containing group data while sorting in reading order while taking
// into account the ambient directionality.
1210
class _ReadingOrderDirectionalGroupData with Diagnosticable {
1211
  _ReadingOrderDirectionalGroupData(this.members);
1212

1213 1214
  final List<_ReadingOrderSortData> members;

1215
  TextDirection? get directionality => members.first.directionality;
1216

1217
  Rect? _rect;
1218 1219 1220 1221
  Rect get rect {
    if (_rect == null) {
      for (final Rect rect in members.map<Rect>((_ReadingOrderSortData data) => data.rect)) {
        _rect ??= rect;
1222
        _rect = _rect!.expandToInclude(rect);
1223 1224
      }
    }
1225
    return _rect!;
1226 1227 1228 1229 1230 1231
  }

  List<Directionality> get memberAncestors {
    if (_memberAncestors == null) {
      _memberAncestors = <Directionality>[];
      for (final _ReadingOrderSortData member in members) {
1232
        _memberAncestors!.addAll(member.directionalAncestors);
1233 1234
      }
    }
1235
    return _memberAncestors!;
1236 1237
  }

1238
  List<Directionality>? _memberAncestors;
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259

  static void sortWithDirectionality(List<_ReadingOrderDirectionalGroupData> list, TextDirection directionality) {
    mergeSort<_ReadingOrderDirectionalGroupData>(list, compare: (_ReadingOrderDirectionalGroupData a, _ReadingOrderDirectionalGroupData b) {
      switch (directionality) {
        case TextDirection.ltr:
          return a.rect.left.compareTo(b.rect.left);
        case TextDirection.rtl:
          return b.rect.right.compareTo(a.rect.right);
      }
    });
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<TextDirection>('directionality', directionality));
    properties.add(DiagnosticsProperty<Rect>('rect', rect));
    properties.add(IterableProperty<String>('members', members.map<String>((_ReadingOrderSortData member) {
      return '"${member.node.debugLabel}"(${member.rect})';
    })));
  }
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
}

/// Traverses the focus order in "reading order".
///
/// By default, reading order traversal goes in the reading direction, and then
/// down, using this algorithm:
///
/// 1. Find the node rectangle that has the highest `top` on the screen.
/// 2. Find any other nodes that intersect the infinite horizontal band defined
///    by the highest rectangle's top and bottom edges.
/// 3. Pick the closest to the beginning of the reading order from among the
///    nodes discovered above.
///
1273 1274
/// It uses the ambient [Directionality] in the context for the enclosing
/// [FocusTraversalGroup] to determine which direction is "reading order".
1275 1276 1277
///
/// See also:
///
1278
///  * [FocusNode], for a description of the focus system.
1279 1280 1281
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
///  * [WidgetOrderTraversalPolicy], a policy that relies on the widget
1282 1283 1284
///    creation order to describe the order of traversal.
///  * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
///    focus traversal in a direction.
1285 1286
///  * [OrderedTraversalPolicy], a policy that describes the order
///    explicitly using [FocusTraversalOrder] widgets.
1287
class ReadingOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
1288 1289 1290 1291 1292
  /// Constructs a traversal policy that orders the widgets in "reading order".
  ///
  /// {@macro flutter.widgets.FocusTraversalPolicy.requestFocusCallback}
  ReadingOrderTraversalPolicy({super.requestFocusCallback});

1293 1294 1295 1296
  // Collects the given candidates into groups by directionality. The candidates
  // have already been sorted as if they all had the directionality of the
  // nearest Directionality ancestor.
  List<_ReadingOrderDirectionalGroupData> _collectDirectionalityGroups(Iterable<_ReadingOrderSortData> candidates) {
1297
    TextDirection? currentDirection = candidates.first.directionality;
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    List<_ReadingOrderSortData> currentGroup = <_ReadingOrderSortData>[];
    final List<_ReadingOrderDirectionalGroupData> result = <_ReadingOrderDirectionalGroupData>[];
    // Split candidates into runs of the same directionality.
    for (final _ReadingOrderSortData candidate in candidates) {
      if (candidate.directionality == currentDirection) {
        currentGroup.add(candidate);
        continue;
      }
      currentDirection = candidate.directionality;
      result.add(_ReadingOrderDirectionalGroupData(currentGroup));
      currentGroup = <_ReadingOrderSortData>[candidate];
1309
    }
1310 1311 1312 1313 1314 1315 1316 1317
    if (currentGroup.isNotEmpty) {
      result.add(_ReadingOrderDirectionalGroupData(currentGroup));
    }
    // Sort each group separately. Each group has the same directionality.
    for (final _ReadingOrderDirectionalGroupData bandGroup in result) {
      if (bandGroup.members.length == 1) {
        continue; // No need to sort one node.
      }
1318
      _ReadingOrderSortData.sortWithDirectionality(bandGroup.members, bandGroup.directionality!);
1319 1320
    }
    return result;
1321 1322
  }

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
  _ReadingOrderSortData _pickNext(List<_ReadingOrderSortData> candidates) {
    // Find the topmost node by sorting on the top of the rectangles.
    mergeSort<_ReadingOrderSortData>(candidates, compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) => a.rect.top.compareTo(b.rect.top));
    final _ReadingOrderSortData topmost = candidates.first;

    // Find the candidates that are in the same horizontal band as the current one.
    List<_ReadingOrderSortData> inBand(_ReadingOrderSortData current, Iterable<_ReadingOrderSortData> candidates) {
      final Rect band = Rect.fromLTRB(double.negativeInfinity, current.rect.top, double.infinity, current.rect.bottom);
      return candidates.where((_ReadingOrderSortData item) {
        return !item.rect.intersect(band).isEmpty;
      }).toList();
1334 1335
    }

1336 1337 1338 1339
    final List<_ReadingOrderSortData> inBandOfTop = inBand(topmost, candidates);
    // It has to have at least topmost in it if the topmost is not degenerate.
    assert(topmost.rect.isEmpty || inBandOfTop.isNotEmpty);

1340
    // The topmost rect is in a band by itself, so just return that one.
1341 1342
    if (inBandOfTop.length <= 1) {
      return topmost;
1343 1344
    }

1345 1346 1347 1348 1349 1350
    // Now that we know there are others in the same band as the topmost, then pick
    // the one at the beginning, depending on the text direction in force.

    // Find out the directionality of the nearest common Directionality
    // ancestor for all nodes. This provides a base directionality to use for
    // the ordering of the groups.
1351
    final TextDirection? nearestCommonDirectionality = _ReadingOrderSortData.commonDirectionalityOf(inBandOfTop);
1352 1353 1354 1355 1356 1357

    // Do an initial common-directionality-based sort to get consistent geometric
    // ordering for grouping into directionality groups. It has to use the
    // common directionality to be able to group into sane groups for the
    // given directionality, since rectangles can overlap and give different
    // results for different directionalities.
1358
    _ReadingOrderSortData.sortWithDirectionality(inBandOfTop, nearestCommonDirectionality!);
1359 1360 1361 1362 1363 1364 1365 1366

    // Collect the top band into internally sorted groups with shared directionality.
    final List<_ReadingOrderDirectionalGroupData> bandGroups = _collectDirectionalityGroups(inBandOfTop);
    if (bandGroups.length == 1) {
      // There's only one directionality group, so just send back the first
      // one in that group, since it's already sorted.
      return bandGroups.first.members.first;
    }
1367

1368 1369 1370 1371
    // Sort the groups based on the common directionality and bounding boxes.
    _ReadingOrderDirectionalGroupData.sortWithDirectionality(bandGroups, nearestCommonDirectionality);
    return bandGroups.first.members.first;
  }
1372

1373 1374 1375
  // Sorts the list of nodes based on their geometry into the desired reading
  // order based on the directionality of the context for each node.
  @override
1376
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) {
1377 1378
    if (descendants.length <= 1) {
      return descendants;
1379 1380
    }

1381 1382
    final List<_ReadingOrderSortData> data = <_ReadingOrderSortData>[
      for (final FocusNode node in descendants) _ReadingOrderSortData(node),
1383
    ];
1384

1385 1386 1387 1388 1389 1390 1391
    final List<FocusNode> sortedList = <FocusNode>[];
    final List<_ReadingOrderSortData> unplaced = data;

    // Pick the initial widget as the one that is at the beginning of the band
    // of the topmost, or the topmost, if there are no others in its band.
    _ReadingOrderSortData current = _pickNext(unplaced);
    sortedList.add(current.node);
1392 1393
    unplaced.remove(current);

1394 1395 1396
    // Go through each node, picking the next one after eliminating the previous
    // one, since removing the previously picked node will expose a new band in
    // which to choose candidates.
1397
    while (unplaced.isNotEmpty) {
1398
      final _ReadingOrderSortData next = _pickNext(unplaced);
1399
      current = next;
1400
      sortedList.add(current.node);
1401 1402
      unplaced.remove(current);
    }
1403
    return sortedList;
1404
  }
1405
}
1406

1407 1408
/// Base class for all sort orders for [OrderedTraversalPolicy] traversal.
///
1409
/// {@template flutter.widgets.FocusOrder.comparable}
1410
/// Only orders of the same type are comparable. If a set of widgets in the same
1411 1412 1413 1414
/// [FocusTraversalGroup] contains orders that are not comparable with each
/// other, it will assert, since the ordering between such keys is undefined. To
/// avoid collisions, use a [FocusTraversalGroup] to group similarly ordered
/// widgets together.
1415
///
1416 1417 1418
/// When overriding, [FocusOrder.doCompare] must be overridden instead of
/// [FocusOrder.compareTo], which calls [FocusOrder.doCompare] to do the actual
/// comparison.
1419 1420 1421 1422
/// {@endtemplate}
///
/// See also:
///
1423 1424 1425 1426 1427 1428 1429 1430
/// * [FocusTraversalGroup], a widget that groups together and imposes a
///   traversal policy on the [Focus] nodes below it in the widget hierarchy.
/// * [FocusTraversalOrder], a widget that assigns an order to a widget subtree
///   for the [OrderedTraversalPolicy] to use.
/// * [NumericFocusOrder], for a focus order that describes its order with a
///   `double`.
/// * [LexicalFocusOrder], a focus order that assigns a string-based lexical
///   traversal order to a [FocusTraversalOrder] widget.
1431
@immutable
1432
abstract class FocusOrder with Diagnosticable implements Comparable<FocusOrder> {
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const FocusOrder();

  /// Compares this object to another [Comparable].
  ///
  /// When overriding [FocusOrder], implement [doCompare] instead of this
  /// function to do the actual comparison.
  ///
  /// Returns a value like a [Comparator] when comparing `this` to [other].
  /// That is, it returns a negative integer if `this` is ordered before [other],
  /// a positive integer if `this` is ordered after [other],
  /// and zero if `this` and [other] are ordered together.
  ///
  /// The [other] argument must be a value that is comparable to this object.
  @override
  @nonVirtual
  int compareTo(FocusOrder other) {
    assert(
1452 1453 1454 1455
      runtimeType == other.runtimeType,
      "The sorting algorithm must not compare incomparable keys, since they don't "
      'know how to order themselves relative to each other. Comparing $this with $other',
    );
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    return doCompare(other);
  }

  /// The subclass implementation called by [compareTo] to compare orders.
  ///
  /// The argument is guaranteed to be of the same [runtimeType] as this object.
  ///
  /// The method should return a negative number if this object comes earlier in
  /// the sort order than the `other` argument; and a positive number if it
  /// comes later in the sort order than `other`. Returning zero causes the
  /// system to fall back to the secondary sort order defined by
  /// [OrderedTraversalPolicy.secondary]
  @protected
  int doCompare(covariant FocusOrder other);
}

/// Can be given to a [FocusTraversalOrder] widget to assign a numerical order
/// to a widget subtree that is using a [OrderedTraversalPolicy] to define the
/// order in which widgets should be traversed with the keyboard.
///
1476
/// {@macro flutter.widgets.FocusOrder.comparable}
1477 1478 1479 1480
///
/// See also:
///
///  * [FocusTraversalOrder], a widget that assigns an order to a widget subtree
1481
///    for the [OrderedTraversalPolicy] to use.
1482
class NumericFocusOrder extends FocusOrder {
1483
  /// Creates an object that describes a focus traversal order numerically.
1484
  const NumericFocusOrder(this.order);
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510

  /// The numerical order to assign to the widget subtree using
  /// [FocusTraversalOrder].
  ///
  /// Determines the placement of this widget in a sequence of widgets that defines
  /// the order in which this node is traversed by the focus policy.
  ///
  /// Lower values will be traversed first.
  final double order;

  @override
  int doCompare(NumericFocusOrder other) => order.compareTo(other.order);

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DoubleProperty('order', order));
  }
}

/// Can be given to a [FocusTraversalOrder] widget to use a String to assign a
/// lexical order to a widget subtree that is using a
/// [OrderedTraversalPolicy] to define the order in which widgets should be
/// traversed with the keyboard.
///
/// This sorts strings using Dart's default string comparison, which is not
1511
/// locale-specific.
1512
///
1513
/// {@macro flutter.widgets.FocusOrder.comparable}
1514 1515 1516 1517
///
/// See also:
///
///  * [FocusTraversalOrder], a widget that assigns an order to a widget subtree
1518
///    for the [OrderedTraversalPolicy] to use.
1519
class LexicalFocusOrder extends FocusOrder {
1520
  /// Creates an object that describes a focus traversal order lexically.
1521
  const LexicalFocusOrder(this.order);
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

  /// The String that defines the lexical order to assign to the widget subtree
  /// using [FocusTraversalOrder].
  ///
  /// Determines the placement of this widget in a sequence of widgets that defines
  /// the order in which this node is traversed by the focus policy.
  ///
  /// Lower lexical values will be traversed first (e.g. 'a' comes before 'z').
  final String order;

  @override
  int doCompare(LexicalFocusOrder other) => order.compareTo(other.order);

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(StringProperty('order', order));
  }
}

// Used to help sort the focus nodes in an OrderedFocusTraversalPolicy.
class _OrderedFocusInfo {
1544
  const _OrderedFocusInfo({required this.node, required this.order});
1545 1546 1547 1548 1549 1550 1551 1552

  final FocusNode node;
  final FocusOrder order;
}

/// A [FocusTraversalPolicy] that orders nodes by an explicit order that resides
/// in the nearest [FocusTraversalOrder] widget ancestor.
///
1553
/// {@macro flutter.widgets.FocusOrder.comparable}
1554
///
1555
/// {@tool dartpad}
1556 1557 1558 1559
/// This sample shows how to assign a traversal order to a widget. In the
/// example, the focus order goes from bottom right (the "One" button) to top
/// left (the "Six" button).
///
1560
/// ** See code in examples/api/lib/widgets/focus_traversal/ordered_traversal_policy.0.dart **
1561 1562 1563 1564
/// {@end-tool}
///
/// See also:
///
1565 1566 1567
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
///  * [WidgetOrderTraversalPolicy], a policy that relies on the widget
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
///    creation order to describe the order of traversal.
///  * [ReadingOrderTraversalPolicy], a policy that describes the order as the
///    natural "reading order" for the current [Directionality].
///  * [NumericFocusOrder], a focus order that assigns a numeric traversal order
///    to a [FocusTraversalOrder] widget.
///  * [LexicalFocusOrder], a focus order that assigns a string-based lexical
///    traversal order to a [FocusTraversalOrder] widget.
///  * [FocusOrder], an abstract base class for all types of focus traversal
///    orderings.
class OrderedTraversalPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
  /// Constructs a traversal policy that orders widgets for keyboard traversal
  /// based on an explicit order.
  ///
  /// If [secondary] is null, it will default to [ReadingOrderTraversalPolicy].
1582
  OrderedTraversalPolicy({this.secondary, super.requestFocusCallback});
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

  /// This is the policy that is used when a node doesn't have an order
  /// assigned, or when multiple nodes have orders which are identical.
  ///
  /// If not set, this defaults to [ReadingOrderTraversalPolicy].
  ///
  /// This policy determines the secondary sorting order of nodes which evaluate
  /// as having an identical order (including those with no order specified).
  ///
  /// Nodes with no order specified will be sorted after nodes with an explicit
  /// order.
1594
  final FocusTraversalPolicy? secondary;
1595 1596

  @override
1597
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) {
1598
    final FocusTraversalPolicy secondaryPolicy = secondary ?? ReadingOrderTraversalPolicy();
1599
    final Iterable<FocusNode> sortedDescendants = secondaryPolicy.sortDescendants(descendants, currentNode);
1600 1601 1602
    final List<FocusNode> unordered = <FocusNode>[];
    final List<_OrderedFocusInfo> ordered = <_OrderedFocusInfo>[];
    for (final FocusNode node in sortedDescendants) {
1603
      final FocusOrder? order = FocusTraversalOrder.maybeOf(node.context!);
1604 1605 1606 1607
      if (order != null) {
        ordered.add(_OrderedFocusInfo(node: node, order: order));
      } else {
        unordered.add(node);
1608
      }
1609
    }
1610 1611 1612 1613 1614
    mergeSort<_OrderedFocusInfo>(ordered, compare: (_OrderedFocusInfo a, _OrderedFocusInfo b) {
      assert(
        a.order.runtimeType == b.order.runtimeType,
        'When sorting nodes for determining focus order, the order (${a.order}) of '
        "node ${a.node}, isn't the same type as the order (${b.order}) of ${b.node}. "
1615
        "Incompatible order types can't be compared. Use a FocusTraversalGroup to group "
1616 1617 1618 1619 1620 1621 1622
        'similar orders together.',
      );
      return a.order.compareTo(b.order);
    });
    return ordered.map<FocusNode>((_OrderedFocusInfo info) => info.node).followedBy(unordered);
  }
}
1623

1624 1625 1626
/// An inherited widget that describes the order in which its child subtree
/// should be traversed.
///
1627
/// {@macro flutter.widgets.FocusOrder.comparable}
1628 1629 1630 1631
///
/// The order for a widget is determined by the [FocusOrder] returned by
/// [FocusTraversalOrder.of] for a particular context.
class FocusTraversalOrder extends InheritedWidget {
1632 1633
  /// Creates an inherited widget used to describe the focus order of
  /// the [child] subtree.
1634
  const FocusTraversalOrder({super.key, required this.order, required super.child});
1635 1636

  /// The order for the widget descendants of this [FocusTraversalOrder].
1637
  final FocusOrder order;
1638 1639 1640 1641 1642 1643

  /// Finds the [FocusOrder] in the nearest ancestor [FocusTraversalOrder] widget.
  ///
  /// It does not create a rebuild dependency because changing the traversal
  /// order doesn't change the widget tree, so nothing needs to be rebuilt as a
  /// result of an order change.
1644 1645 1646 1647
  ///
  /// If no [FocusTraversalOrder] ancestor exists, or the order is null, this
  /// will assert in debug mode, and throw an exception in release mode.
  static FocusOrder of(BuildContext context) {
1648
    final FocusTraversalOrder? marker = context.getInheritedWidgetOfExactType<FocusTraversalOrder>();
1649
    assert(() {
1650 1651 1652 1653
      if (marker == null) {
        throw FlutterError(
          'FocusTraversalOrder.of() was called with a context that '
          'does not contain a FocusTraversalOrder widget. No TraversalOrder widget '
1654 1655 1656
          'ancestor could be found starting from the context that was passed to '
          'FocusTraversalOrder.of().\n'
          'The context used was:\n'
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
          '  $context',
        );
      }
      return true;
    }());
    return marker!.order;
  }

  /// Finds the [FocusOrder] in the nearest ancestor [FocusTraversalOrder] widget.
  ///
  /// It does not create a rebuild dependency because changing the traversal
  /// order doesn't change the widget tree, so nothing needs to be rebuilt as a
  /// result of an order change.
  ///
  /// If no [FocusTraversalOrder] ancestor exists, or the order is null, returns null.
  static FocusOrder? maybeOf(BuildContext context) {
1673
    final FocusTraversalOrder? marker = context.getInheritedWidgetOfExactType<FocusTraversalOrder>();
1674
    return marker?.order;
1675 1676
  }

1677 1678
  // Since the order of traversal doesn't affect display of anything, we don't
  // need to force a rebuild of anything that depends upon it.
1679
  @override
1680
  bool updateShouldNotify(InheritedWidget oldWidget) => false;
1681 1682

  @override
1683 1684 1685 1686
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<FocusOrder>('order', order));
  }
1687 1688
}

1689 1690 1691 1692 1693 1694 1695
/// A widget that describes the inherited focus policy for focus traversal for
/// its descendants, grouping them into a separate traversal group.
///
/// A traversal group is treated as one entity when sorted by the traversal
/// algorithm, so it can be used to segregate different parts of the widget tree
/// that need to be sorted using different algorithms and/or sort orders when
/// using an [OrderedTraversalPolicy].
1696
///
1697 1698 1699 1700
/// Within the group, it will use the given [policy] to order the elements. The
/// group itself will be ordered using the parent group's policy.
///
/// By default, traverses in reading order using [ReadingOrderTraversalPolicy].
1701
///
1702
/// To prevent the members of the group from being focused, set the
1703
/// [descendantsAreFocusable] attribute to false.
1704
///
1705
/// {@tool dartpad}
1706 1707
/// This sample shows three rows of buttons, each grouped by a
/// [FocusTraversalGroup], each with different traversal order policies. Use tab
1708
/// traversal to see the order they are traversed in. The first row follows a
1709 1710 1711 1712
/// numerical order, the second follows a lexical order (ordered to traverse
/// right to left), and the third ignores the numerical order assigned to it and
/// traverses in widget order.
///
1713
/// ** See code in examples/api/lib/widgets/focus_traversal/focus_traversal_group.0.dart **
1714 1715
/// {@end-tool}
///
1716 1717
/// See also:
///
1718
///  * [FocusNode], for a description of the focus system.
1719
///  * [WidgetOrderTraversalPolicy], a policy that relies on the widget
1720 1721 1722 1723 1724
///    creation order to describe the order of traversal.
///  * [ReadingOrderTraversalPolicy], a policy that describes the order as the
///    natural "reading order" for the current [Directionality].
///  * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
///    focus traversal in a direction.
1725 1726 1727
class FocusTraversalGroup extends StatefulWidget {
  /// Creates a [FocusTraversalGroup] object.
  FocusTraversalGroup({
1728
    super.key,
1729
    FocusTraversalPolicy? policy,
1730
    this.descendantsAreFocusable = true,
1731
    this.descendantsAreTraversable = true,
1732
    required this.child,
1733
  }) : policy = policy ?? ReadingOrderTraversalPolicy();
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751

  /// The policy used to move the focus from one focus node to another when
  /// traversing them using a keyboard.
  ///
  /// If not specified, traverses in reading order using
  /// [ReadingOrderTraversalPolicy].
  ///
  /// See also:
  ///
  ///  * [FocusTraversalPolicy] for the API used to impose traversal order
  ///    policy.
  ///  * [WidgetOrderTraversalPolicy] for a traversal policy that traverses
  ///    nodes in the order they are added to the widget tree.
  ///  * [ReadingOrderTraversalPolicy] for a traversal policy that traverses
  ///    nodes in the reading order defined in the widget tree, and then top to
  ///    bottom.
  final FocusTraversalPolicy policy;

1752 1753 1754
  /// {@macro flutter.widgets.Focus.descendantsAreFocusable}
  final bool descendantsAreFocusable;

1755 1756 1757
  /// {@macro flutter.widgets.Focus.descendantsAreTraversable}
  final bool descendantsAreTraversable;

1758 1759
  /// The child widget of this [FocusTraversalGroup].
  ///
1760
  /// {@macro flutter.widgets.ProxyWidget.child}
1761 1762
  final Widget child;

1763 1764
  /// Returns the [FocusTraversalPolicy] that applies to the nearest ancestor of
  /// the given [FocusNode].
1765
  ///
1766 1767
  /// Will return null if no [FocusTraversalPolicy] ancestor applies to the
  /// given [FocusNode].
1768
  ///
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
  /// The [FocusTraversalPolicy] is set by introducing a [FocusTraversalGroup]
  /// into the widget tree, which will associate a policy with the focus tree
  /// under the nearest ancestor [Focus] widget.
  ///
  /// This function differs from [maybeOf] in that it takes a [FocusNode] and
  /// only traverses the focus tree to determine the policy in effect. Unlike
  /// this function, the [maybeOf] function takes a [BuildContext] and first
  /// walks up the widget tree to find the nearest ancestor [Focus] or
  /// [FocusScope] widget, and then calls this function with the focus node
  /// associated with that widget to determine the policy in effect.
  static FocusTraversalPolicy? maybeOfNode(FocusNode node) {
    return _getGroupNode(node)?.policy;
  }

  static _FocusTraversalGroupNode? _getGroupNode(FocusNode node) {
    while (node.parent != null) {
      if (node.context == null) {
        return null;
      }
      if (node is _FocusTraversalGroupNode) {
        return node;
      }
      node = node.parent!;
    }
    return null;
  }

  /// Returns the [FocusTraversalPolicy] that applies to the [FocusNode] of the
  /// nearest ancestor [Focus] widget, given a [BuildContext].
  ///
  /// Will throw a [FlutterError] in debug mode, and throw a null check
  /// exception in release mode, if no [Focus] ancestor is found, or if no
  /// [FocusTraversalPolicy] applies to the associated [FocusNode].
  ///
  /// {@template flutter.widgets.focus_traversal.FocusTraversalGroup.of}
  /// This function looks up the nearest ancestor [Focus] (or [FocusScope])
  /// widget, and uses its [FocusNode] (or [FocusScopeNode]) to walk up the
  /// focus tree to find the applicable [FocusTraversalPolicy] for that node.
  ///
  /// Calling this function does not create a rebuild dependency because
  /// changing the traversal order doesn't change the widget tree, so nothing
  /// needs to be rebuilt as a result of an order change.
  ///
  /// The [FocusTraversalPolicy] is set by introducing a [FocusTraversalGroup]
  /// into the widget tree, which will associate a policy with the focus tree
  /// under the nearest ancestor [Focus] widget.
  /// {@endtemplate}
1816
  ///
1817 1818
  /// See also:
  ///
1819 1820 1821 1822
  /// * [maybeOf] for a similar function that will return null if no
  ///   [FocusTraversalGroup] ancestor is found.
  /// * [maybeOfNode] for a function that will look for a policy using a given
  ///   [FocusNode], and return null if no policy applies.
1823
  static FocusTraversalPolicy of(BuildContext context) {
1824
    final FocusTraversalPolicy? policy = maybeOf(context);
1825
    assert(() {
1826
      if (policy == null) {
1827
        throw FlutterError(
1828 1829
          'Unable to find a Focus or FocusScope widget in the given context, or the FocusNode '
          'from with the widget that was found is not associated with a FocusTraversalPolicy.\n'
1830
          'FocusTraversalGroup.of() was called with a context that does not contain a '
1831 1832 1833 1834
          'Focus or FocusScope widget, or there was no FocusTraversalPolicy in effect.\n'
          'This can happen if there is not a FocusTraversalGroup that defines the policy, '
          'or if the context comes from a widget that is above the WidgetsApp, MaterialApp, '
          'or CupertinoApp widget (those widgets introduce an implicit default policy) \n'
1835 1836 1837 1838 1839 1840
          'The context used was:\n'
          '  $context',
        );
      }
      return true;
    }());
1841
    return policy!;
1842 1843
  }

1844 1845
  /// Returns the [FocusTraversalPolicy] that applies to the [FocusNode] of the
  /// nearest ancestor [Focus] widget, or null, given a [BuildContext].
1846
  ///
1847 1848
  /// Will return null if it doesn't find an ancestor [Focus] or [FocusScope]
  /// widget, or doesn't find a [FocusTraversalPolicy] that applies to the node.
1849
  ///
1850
  /// {@macro flutter.widgets.focus_traversal.FocusTraversalGroup.of}
1851 1852 1853
  ///
  /// See also:
  ///
1854 1855 1856 1857
  /// * [maybeOfNode] for a similar function that will look for a policy using a
  ///   given [FocusNode].
  /// * [of] for a similar function that will throw if no [FocusTraversalPolicy]
  ///   applies.
1858
  static FocusTraversalPolicy? maybeOf(BuildContext context) {
1859 1860 1861 1862 1863
    final FocusNode? node = Focus.maybeOf(context, scopeOk: true, createDependency: false);
    if (node == null) {
      return null;
    }
    return FocusTraversalGroup.maybeOfNode(node);
1864 1865 1866
  }

  @override
1867
  State<FocusTraversalGroup> createState() => _FocusTraversalGroupState();
1868 1869 1870 1871 1872 1873 1874 1875

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<FocusTraversalPolicy>('policy', policy));
  }
}

1876 1877 1878 1879 1880 1881 1882
// A special focus node subclass that only FocusTraversalGroup uses so that it
// can be used to cache the policy in the focus tree, and so that the traversal
// code can find groups in the focus tree.
class _FocusTraversalGroupNode extends FocusNode {
  _FocusTraversalGroupNode({
    super.debugLabel,
    required this.policy,
1883 1884
  }) {
    if (kFlutterMemoryAllocationsEnabled) {
1885
      ChangeNotifier.maybeDispatchObjectCreation(this);
1886 1887
    }
  }
1888 1889 1890 1891

  FocusTraversalPolicy policy;
}

1892 1893 1894
class _FocusTraversalGroupState extends State<FocusTraversalGroup> {
  // The internal focus node used to collect the children of this node into a
  // group, and to provide a context for the traversal algorithm to sort the
1895 1896 1897 1898 1899 1900 1901
  // group with. It's a special subclass of FocusNode just so that it can be
  // identified when walking the focus tree during traversal, and hold the
  // current policy.
  late final _FocusTraversalGroupNode focusNode = _FocusTraversalGroupNode(
    debugLabel: 'FocusTraversalGroup',
    policy: widget.policy,
  );
1902 1903 1904

  @override
  void dispose() {
1905
    focusNode.dispose();
1906 1907 1908
    super.dispose();
  }

1909 1910 1911 1912 1913 1914 1915 1916
  @override
  void didUpdateWidget (FocusTraversalGroup oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.policy != widget.policy) {
      focusNode.policy = widget.policy;
    }
  }

1917 1918
  @override
  Widget build(BuildContext context) {
1919
    return Focus(
1920
      focusNode: focusNode,
1921 1922 1923 1924 1925 1926
      canRequestFocus: false,
      skipTraversal: true,
      includeSemantics: false,
      descendantsAreFocusable: widget.descendantsAreFocusable,
      descendantsAreTraversable: widget.descendantsAreTraversable,
      child: widget.child,
1927 1928 1929 1930
    );
  }
}

1931 1932 1933
/// An intent for use with the [RequestFocusAction], which supplies the
/// [FocusNode] that should be focused.
class RequestFocusIntent extends Intent {
1934 1935
  /// Creates an intent used with [RequestFocusAction].
  ///
1936 1937 1938 1939 1940 1941 1942 1943 1944
  /// {@macro flutter.widgets.FocusTraversalPolicy.requestFocusCallback}
  const RequestFocusIntent(this.focusNode, {
    TraversalRequestFocusCallback? requestFocusCallback
  }) : requestFocusCallback = requestFocusCallback ?? FocusTraversalPolicy.defaultTraversalRequestFocusCallback;

  /// The callback used to move the focus to the node [focusNode].
  /// By default it requests focus on the node and ensures the node is visible
  /// if it's in a scrollable.
  final TraversalRequestFocusCallback requestFocusCallback;
1945

1946 1947
  /// The [FocusNode] that is to be focused.
  final FocusNode focusNode;
1948 1949
}

1950 1951
/// An [Action] that requests the focus on the node it is given in its
/// [RequestFocusIntent].
1952 1953 1954 1955 1956
///
/// This action can be used to request focus for a particular node, by calling
/// [Action.invoke] like so:
///
/// ```dart
1957
/// Actions.invoke(context, RequestFocusIntent(focusNode));
1958 1959
/// ```
///
1960
/// Where the `focusNode` is the node for which the focus will be requested.
1961 1962
///
/// The difference between requesting focus in this way versus calling
1963 1964 1965 1966 1967 1968 1969
/// [FocusNode.requestFocus] directly is that it will use the [Action]
/// registered in the nearest [Actions] widget associated with
/// [RequestFocusIntent] to make the request, rather than just requesting focus
/// directly. This allows the action to have additional side effects, like
/// logging, or undo and redo functionality.
///
/// This [RequestFocusAction] class is the default action associated with the
1970
/// [RequestFocusIntent] in the [WidgetsApp]. It requests focus. You
1971 1972 1973 1974
/// can redefine the associated action with your own [Actions] widget.
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
class RequestFocusAction extends Action<RequestFocusIntent> {
1975

1976
  @override
1977
  void invoke(RequestFocusIntent intent) {
1978
    intent.requestFocusCallback(intent.focusNode);
1979 1980 1981 1982 1983 1984 1985 1986
  }
}

/// An [Intent] bound to [NextFocusAction], which moves the focus to the next
/// focusable node in the focus traversal order.
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
class NextFocusIntent extends Intent {
1987
  /// Creates an intent that is used with [NextFocusAction].
1988
  const NextFocusIntent();
1989 1990 1991 1992 1993
}

/// An [Action] that moves the focus to the next focusable node in the focus
/// order.
///
1994 1995 1996 1997 1998
/// This action is the default action registered for the [NextFocusIntent], and
/// by default is bound to the [LogicalKeyboardKey.tab] key in the [WidgetsApp].
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
class NextFocusAction extends Action<NextFocusIntent> {
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
  /// Attempts to pass the focus to the next widget.
  ///
  /// Returns true if a widget was focused as a result of invoking this action.
  ///
  /// Returns false when the traversal reached the end and the engine must pass
  /// focus to platform UI.
  @override
  bool invoke(NextFocusIntent intent) {
    return primaryFocus!.nextFocus();
  }

2010
  @override
2011 2012
  KeyEventResult toKeyEventResult(NextFocusIntent intent, bool invokeResult) {
    return invokeResult ? KeyEventResult.handled : KeyEventResult.skipRemainingHandlers;
2013 2014 2015 2016 2017 2018 2019 2020
  }
}

/// An [Intent] bound to [PreviousFocusAction], which moves the focus to the
/// previous focusable node in the focus traversal order.
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
class PreviousFocusIntent extends Intent {
2021
  /// Creates an intent that is used with [PreviousFocusAction].
2022
  const PreviousFocusIntent();
2023 2024 2025 2026 2027
}

/// An [Action] that moves the focus to the previous focusable node in the focus
/// order.
///
2028 2029 2030 2031 2032 2033
/// This action is the default action registered for the [PreviousFocusIntent],
/// and by default is bound to a combination of the [LogicalKeyboardKey.tab] key
/// and the [LogicalKeyboardKey.shift] key in the [WidgetsApp].
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
class PreviousFocusAction extends Action<PreviousFocusIntent> {
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
  /// Attempts to pass the focus to the previous widget.
  ///
  /// Returns true if a widget was focused as a result of invoking this action.
  ///
  /// Returns false when the traversal reached the beginning and the engine must
  /// pass focus to platform UI.
  @override
  bool invoke(PreviousFocusIntent intent) {
    return primaryFocus!.previousFocus();
  }

2045
  @override
2046 2047
  KeyEventResult toKeyEventResult(PreviousFocusIntent intent, bool invokeResult) {
    return invokeResult ? KeyEventResult.handled : KeyEventResult.skipRemainingHandlers;
2048
  }
2049 2050 2051 2052 2053 2054 2055 2056 2057
}

/// An [Intent] that represents moving to the next focusable node in the given
/// [direction].
///
/// This is the [Intent] bound by default to the [LogicalKeyboardKey.arrowUp],
/// [LogicalKeyboardKey.arrowDown], [LogicalKeyboardKey.arrowLeft], and
/// [LogicalKeyboardKey.arrowRight] keys in the [WidgetsApp], with the
/// appropriate associated directions.
2058 2059
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
2060
class DirectionalFocusIntent extends Intent {
2061
  /// Creates an intent used to move the focus in the given [direction].
2062
  const DirectionalFocusIntent(this.direction, {this.ignoreTextFields = true});
2063 2064 2065 2066

  /// The direction in which to look for the next focusable node when the
  /// associated [DirectionalFocusAction] is invoked.
  final TraversalDirection direction;
2067 2068 2069 2070 2071 2072 2073

  /// If true, then directional focus actions that occur within a text field
  /// will not happen when the focus node which received the key is a text
  /// field.
  ///
  /// Defaults to true.
  final bool ignoreTextFields;
2074 2075 2076 2077 2078 2079

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(EnumProperty<TraversalDirection>('direction', direction));
  }
2080 2081
}

2082 2083
/// An [Action] that moves the focus to the focusable node in the direction
/// configured by the associated [DirectionalFocusIntent.direction].
2084
///
2085 2086
/// This is the [Action] associated with [DirectionalFocusIntent] and bound by
/// default to the [LogicalKeyboardKey.arrowUp], [LogicalKeyboardKey.arrowDown],
2087 2088
/// [LogicalKeyboardKey.arrowLeft], and [LogicalKeyboardKey.arrowRight] keys in
/// the [WidgetsApp], with the appropriate associated directions.
2089
class DirectionalFocusAction extends Action<DirectionalFocusIntent> {
2090 2091 2092 2093 2094 2095 2096 2097 2098
  /// Creates a [DirectionalFocusAction].
  DirectionalFocusAction() : _isForTextField = false;

  /// Creates a [DirectionalFocusAction] that ignores [DirectionalFocusIntent]s
  /// whose `ignoreTextFields` field is true.
  DirectionalFocusAction.forTextField() : _isForTextField = true;

  // Whether this action is defined in a text field.
  final bool _isForTextField;
2099
  @override
2100
  void invoke(DirectionalFocusIntent intent) {
2101
    if (!intent.ignoreTextFields || !_isForTextField) {
2102
      primaryFocus!.focusInDirection(intent.direction);
2103
    }
2104 2105
  }
}
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121

/// A widget that controls whether or not the descendants of this widget are
/// traversable.
///
/// Does not affect the value of [FocusNode.skipTraversal] of the descendants.
///
/// See also:
///
///  * [Focus], a widget for adding and managing a [FocusNode] in the widget tree.
///  * [ExcludeFocus], a widget that excludes its descendants from focusability.
///  * [FocusTraversalGroup], a widget that groups widgets for focus traversal,
///    and can also be used in the same way as this widget by setting its
///    `descendantsAreFocusable` attribute.
class ExcludeFocusTraversal extends StatelessWidget {
  /// Const constructor for [ExcludeFocusTraversal] widget.
  const ExcludeFocusTraversal({
2122
    super.key,
2123 2124
    this.excluding = true,
    required this.child,
2125
  });
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158

  /// If true, will make this widget's descendants untraversable.
  ///
  /// Defaults to true.
  ///
  /// Does not affect the value of [FocusNode.skipTraversal] on the descendants.
  ///
  /// See also:
  ///
  /// * [Focus.descendantsAreTraversable], the attribute of a [Focus] widget that
  ///   controls this same property for focus widgets.
  /// * [FocusTraversalGroup], a widget used to group together and configure the
  ///   focus traversal policy for a widget subtree that has a
  ///   `descendantsAreFocusable` parameter to conditionally block focus for a
  ///   subtree.
  final bool excluding;

  /// The child widget of this [ExcludeFocusTraversal].
  ///
  /// {@macro flutter.widgets.ProxyWidget.child}
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Focus(
      canRequestFocus: false,
      skipTraversal: true,
      includeSemantics: false,
      descendantsAreTraversable: !excluding,
      child: child,
    );
  }
}