focus_traversal.dart 86.1 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 123 124 125
  /// address bar, escape an `iframe`, or focus on HTML elements other than
  /// those managed by Flutter.
  leaveFlutterView,
}

/// Determines how focusable widgets are traversed within a [FocusTraversalGroup].
126 127
///
/// The focus traversal policy is what determines which widget is "next",
128 129
/// "previous", or in a direction from the widget associated with the currently
/// focused [FocusNode] (usually a [Focus] widget).
130 131 132 133
///
/// One of the pre-defined subclasses may be used, or define a custom policy to
/// create a unique focus order.
///
134 135 136
/// When defining your own, your subclass should implement [sortDescendants] to
/// provide the order in which you would like the descendants to be traversed.
///
137 138
/// See also:
///
139
///  * [FocusNode], for a description of the focus system.
140 141
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
142
///  * [FocusNode], which is affected by the traversal policy.
143
///  * [WidgetOrderTraversalPolicy], a policy that relies on the widget
144 145 146
///    creation order to describe the order of traversal.
///  * [ReadingOrderTraversalPolicy], a policy that describes the order as the
///    natural "reading order" for the current [Directionality].
147 148
///  * [OrderedTraversalPolicy], a policy that describes the order
///    explicitly using [FocusTraversalOrder] widgets.
149 150
///  * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
///    focus traversal in a direction.
151
@immutable
152
abstract class FocusTraversalPolicy with Diagnosticable {
153 154
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  ///
  /// {@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(
      node.context!, alignment: alignment ?? 1.0,
      alignmentPolicy: alignmentPolicy ?? ScrollPositionAlignmentPolicy.explicit,
      duration: duration ?? Duration.zero,
      curve: curve ?? Curves.ease,
    );
  }
188

189 190
  /// Returns the node that should receive focus if focus is traversing
  /// forwards, and there is no current focus.
191
  ///
192 193 194
  /// 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.
195
  ///
196
  /// The `currentNode` argument must not be null.
197
  ///
198 199 200 201 202 203 204 205
  /// 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.
206 207 208
  ///
  /// See also:
  ///
209 210 211 212 213 214 215
  /// * [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);
  }
216 217 218 219 220 221 222 223 224 225

  /// 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.
  ///
  /// The `currentNode` argument must not be null.
  ///
226 227 228 229 230 231 232 233
  /// 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.
234 235 236
  ///
  /// See also:
  ///
237
  ///  * [previous], the function that is called to move the focus to the previous node.
238 239
  ///  * [DirectionalFocusTraversalPolicyMixin.findFirstFocusInDirection], a
  ///    function that finds the first focusable widget in a particular direction.
240 241 242
  FocusNode findLastFocus(FocusNode currentNode, {bool ignoreCurrentFocus = false}) {
    return _findInitialFocus(currentNode, fromEnd: true, ignoreCurrentFocus: ignoreCurrentFocus);
  }
243

244
  FocusNode _findInitialFocus(FocusNode currentNode, {bool fromEnd = false, bool ignoreCurrentFocus = false}) {
245 246
    final FocusScopeNode scope = currentNode.nearestScope!;
    FocusNode? candidate = scope.focusedChild;
247
    if (ignoreCurrentFocus || candidate == null && scope.descendants.isNotEmpty) {
248
      final Iterable<FocusNode> sorted = _sortAllDescendants(scope, currentNode);
249 250 251 252 253
      if (sorted.isEmpty) {
        candidate = null;
      } else {
        candidate = fromEnd ? sorted.last : sorted.first;
      }
254 255 256 257 258 259 260
    }

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

262 263 264
  /// 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.
265 266
  ///
  /// This is typically used by [inDirection] to determine which node to focus
267
  /// if it is called when no node is currently focused.
268 269
  ///
  /// All arguments must not be null.
270
  FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction);
271 272 273 274 275 276 277 278 279 280 281 282

  /// 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) {}

283
  /// This is called whenever the given [node] is re-parented into a new scope,
284 285 286 287 288 289 290
  /// 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
291
  void changedScope({FocusNode? node, FocusScopeNode? oldScope}) {}
292 293 294 295 296 297 298 299 300 301 302

  /// 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.
  ///
  /// The [currentNode] argument must not be null.
303
  bool next(FocusNode currentNode) => _moveFocus(currentNode, forward: true);
304 305 306 307 308 309 310 311 312 313 314

  /// 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.
  ///
  /// The [currentNode] argument must not be null.
315
  bool previous(FocusNode currentNode) => _moveFocus(currentNode, forward: false);
316 317 318 319 320 321 322 323 324 325 326 327 328

  /// 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.
  ///
  /// All arguments must not be null.
  bool inDirection(FocusNode currentNode, TraversalDirection direction);

329 330 331 332 333
  /// 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
334 335 336 337 338 339 340 341 342
  /// 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.
343 344 345 346 347 348 349 350 351 352
  ///
  /// 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
353
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode);
354

355 356
  Map<FocusNode?, _FocusTraversalGroupInfo> _findGroups(FocusScopeNode scope, _FocusTraversalGroupNode? scopeGroupNode) {
    final FocusTraversalPolicy defaultPolicy = scopeGroupNode?.policy ?? ReadingOrderTraversalPolicy();
357
    final Map<FocusNode?, _FocusTraversalGroupInfo> groups = <FocusNode?, _FocusTraversalGroupInfo>{};
358
    for (final FocusNode node in scope.descendants) {
359
      final _FocusTraversalGroupNode? groupNode = FocusTraversalGroup._getGroupNode(node);
360 361 362 363 364 365
      // 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
366 367 368 369 370 371 372
        // 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);
373 374 375 376 377
        continue;
      }
      // Skip non-focusable and non-traversable nodes in the same way that
      // FocusScopeNode.traversalDescendants would.
      if (node.canRequestFocus && !node.skipTraversal) {
378
        groups[groupNode] ??= _FocusTraversalGroupInfo(groupNode, members: <FocusNode>[], defaultPolicy: defaultPolicy);
379 380
        assert(!groups[groupNode]!.members.contains(node));
        groups[groupNode]!.members.add(node);
381 382
      }
    }
383 384 385 386 387 388 389 390 391
    return groups;
  }

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

    // Sort the member lists using the individual policy sorts.
394 395 396 397
    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);
398 399 400 401 402 403 404
    }

    // 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) {
405
        if (groups.containsKey(node)) {
406 407
          // This is a policy group focus node. Replace it with the members of
          // the corresponding policy group.
408
          visitGroups(groups[node]!);
409 410 411 412 413 414
        } else {
          sortedDescendants.add(node);
        }
      }
    }

415
    // Visit the children of the scope, if any.
416 417
    if (groups.isNotEmpty && groups.containsKey(scopeGroupNode)) {
      visitGroups(groups[scopeGroupNode]!);
418
    }
419 420 421 422 423 424 425 426 427 428 429

    // 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) {
      return !node.canRequestFocus || node.skipTraversal;
    });

    // 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.
430
    assert(
431
      sortedDescendants.length <= scope.traversalDescendants.length && sortedDescendants.toSet().difference(scope.traversalDescendants.toSet()).isEmpty,
432
      'Sorted descendants contains different nodes than FocusScopeNode.traversalDescendants would. '
433
      'These are the different nodes: ${sortedDescendants.toSet().difference(scope.traversalDescendants.toSet())}',
434 435 436 437
    );
    return sortedDescendants;
  }

438 439 440 441 442 443 444 445 446 447 448 449 450 451
  /// 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.
452
  @protected
453 454
  bool _moveFocus(FocusNode currentNode, {required bool forward}) {
    final FocusScopeNode nearestScope = currentNode.nearestScope!;
455
    invalidateScopeData(nearestScope);
456
    final FocusNode? focusedChild = nearestScope.focusedChild;
457
    if (focusedChild == null) {
458
      final FocusNode? firstFocus = forward ? findFirstFocus(currentNode) : findLastFocus(currentNode);
459
      if (firstFocus != null) {
460
        requestFocusCallback(
461 462 463 464 465 466
          firstFocus,
          alignmentPolicy: forward ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
        );
        return true;
      }
    }
467
    final List<FocusNode> sortedNodes = _sortAllDescendants(nearestScope, currentNode);
468 469 470 471 472
    if (sortedNodes.isEmpty) {
      // If there are no nodes to traverse to, like when descendantsAreTraversable
      // is false or skipTraversal for all the nodes is true.
      return false;
    }
473
    if (forward && focusedChild == sortedNodes.last) {
474 475 476 477 478
      switch (nearestScope.traversalEdgeBehavior) {
        case TraversalEdgeBehavior.leaveFlutterView:
          focusedChild!.unfocus();
          return false;
        case TraversalEdgeBehavior.closedLoop:
479
          requestFocusCallback(sortedNodes.first, alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd);
480 481
          return true;
      }
482 483
    }
    if (!forward && focusedChild == sortedNodes.first) {
484 485 486 487 488
      switch (nearestScope.traversalEdgeBehavior) {
        case TraversalEdgeBehavior.leaveFlutterView:
          focusedChild!.unfocus();
          return false;
        case TraversalEdgeBehavior.closedLoop:
489
          requestFocusCallback(sortedNodes.last, alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart);
490 491
          return true;
      }
492 493 494
    }

    final Iterable<FocusNode> maybeFlipped = forward ? sortedNodes : sortedNodes.reversed;
495
    FocusNode? previousNode;
496 497
    for (final FocusNode node in maybeFlipped) {
      if (previousNode == focusedChild) {
498
        requestFocusCallback(
499 500 501 502 503 504 505 506 507
          node,
          alignmentPolicy: forward ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
        );
        return true;
      }
      previousNode = node;
    }
    return false;
  }
508 509
}

510 511
// A policy data object for use by the DirectionalFocusTraversalPolicyMixin so
// it can keep track of the traversal history.
512
class _DirectionalPolicyDataEntry {
513
  const _DirectionalPolicyDataEntry({required this.direction, required this.node});
514 515 516 517 518 519

  final TraversalDirection direction;
  final FocusNode node;
}

class _DirectionalPolicyData {
520
  const _DirectionalPolicyData({required this.history});
521 522 523 524 525 526 527 528 529 530 531 532

  /// 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
533 534 535 536 537
/// 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.
538 539 540 541
///
/// 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
542 543
/// follow the same path on the way up as it did on the way down, since changing
/// the axis of motion resets the history.
544
///
545 546 547 548 549 550 551 552 553 554 555 556 557 558
/// 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.
///
559 560
/// See also:
///
561 562 563 564 565 566 567 568 569
/// * [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.
570 571 572 573 574 575 576 577 578 579
mixin DirectionalFocusTraversalPolicyMixin on FocusTraversalPolicy {
  final Map<FocusScopeNode, _DirectionalPolicyData> _policyData = <FocusScopeNode, _DirectionalPolicyData>{};

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

  @override
580
  void changedScope({FocusNode? node, FocusScopeNode? oldScope}) {
581 582
    super.changedScope(node: node, oldScope: oldScope);
    if (oldScope != null) {
583
      _policyData[oldScope]?.history.removeWhere((_DirectionalPolicyDataEntry entry) {
584 585 586 587 588 589
        return entry.node == node;
      });
    }
  }

  @override
590
  FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction) {
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
    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);
    }
  }

607 608
  FocusNode? _sortAndFindInitial(FocusNode currentNode, {required bool vertical, required bool first}) {
    final Iterable<FocusNode> nodes = currentNode.nearestScope!.traversalDescendants;
609
    final List<FocusNode> sorted = nodes.toList();
610
    mergeSort<FocusNode>(sorted, compare: (FocusNode a, FocusNode b) {
611 612 613 614 615 616 617 618 619 620 621 622 623 624
      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);
        }
      }
    });
625

626
    if (sorted.isNotEmpty) {
627
      return sorted.first;
628
    }
629 630

    return null;
631 632
  }

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
  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;
  }

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
  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;
  }

721 722 723 724 725 726 727 728
  // 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.
729
  Iterable<FocusNode> _sortAndFilterHorizontally(
730 731
    TraversalDirection direction,
    Rect target,
732
    Iterable<FocusNode> nodes,
733 734
  ) {
    assert(direction == TraversalDirection.left || direction == TraversalDirection.right);
735
    final Iterable<FocusNode> filtered;
736 737
    switch (direction) {
      case TraversalDirection.left:
738
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dx <= target.left);
739
      case TraversalDirection.right:
740
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dx >= target.right);
741 742
      case TraversalDirection.up:
      case TraversalDirection.down:
743
        throw ArgumentError('Invalid direction $direction');
744
    }
745 746 747 748
    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;
749 750 751 752 753
  }

  // 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.
754
  Iterable<FocusNode> _sortAndFilterVertically(
755 756 757 758
    TraversalDirection direction,
    Rect target,
    Iterable<FocusNode> nodes,
  ) {
759 760
    assert(direction == TraversalDirection.up || direction == TraversalDirection.down);
    final Iterable<FocusNode> filtered;
761 762
    switch (direction) {
      case TraversalDirection.up:
763
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dy <= target.top);
764
      case TraversalDirection.down:
765
        filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dy >= target.bottom);
766 767
      case TraversalDirection.left:
      case TraversalDirection.right:
768
        throw ArgumentError('Invalid direction $direction');
769
    }
770 771 772
    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;
773 774 775 776 777 778 779
  }

  // 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) {
780
    final _DirectionalPolicyData? policyData = _policyData[nearestScope];
781
    if (policyData != null && policyData.history.isNotEmpty && policyData.history.first.direction != direction) {
782 783 784
      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
785 786 787
        // 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.
788 789 790
        invalidateScopeData(nearestScope);
        return false;
      }
791 792 793 794

      // Returns true if successfully popped the history.
      bool popOrInvalidate(TraversalDirection direction) {
        final FocusNode lastNode = policyData.history.removeLast().node;
795
        if (Scrollable.maybeOf(lastNode.context!) != Scrollable.maybeOf(primaryFocus!.context!)) {
796 797 798
          invalidateScopeData(nearestScope);
          return false;
        }
799
        final ScrollPositionAlignmentPolicy alignmentPolicy;
800
        switch (direction) {
801 802 803 804 805
          case TraversalDirection.up:
          case TraversalDirection.left:
            alignmentPolicy = ScrollPositionAlignmentPolicy.keepVisibleAtStart;
          case TraversalDirection.right:
          case TraversalDirection.down:
806
            alignmentPolicy = ScrollPositionAlignmentPolicy.keepVisibleAtEnd;
807
        }
808
        requestFocusCallback(
809 810 811 812 813 814
          lastNode,
          alignmentPolicy: alignmentPolicy,
        );
        return true;
      }

815 816 817 818 819 820 821 822 823 824
      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:
825 826 827
              if (popOrInvalidate(direction)) {
                return true;
              }
828 829 830 831 832 833
          }
        case TraversalDirection.left:
        case TraversalDirection.right:
          switch (policyData.history.first.direction) {
            case TraversalDirection.left:
            case TraversalDirection.right:
834 835 836
              if (popOrInvalidate(direction)) {
                return true;
              }
837 838 839 840 841 842 843 844 845 846 847 848 849 850
            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) {
851
    final _DirectionalPolicyData? policyData = _policyData[nearestScope];
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    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
870
  /// policy data for the affected [FocusScopeNode]. If the previous direction
871 872 873 874 875 876 877 878 879
  /// 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) {
880 881
    final FocusScopeNode nearestScope = currentNode.nearestScope!;
    final FocusNode? focusedChild = nearestScope.focusedChild;
882
    if (focusedChild == null) {
883 884 885 886
      final FocusNode firstFocus = findFirstFocusInDirection(currentNode, direction) ?? currentNode;
      switch (direction) {
        case TraversalDirection.up:
        case TraversalDirection.left:
887
          requestFocusCallback(
888 889 890 891 892
            firstFocus,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
          );
        case TraversalDirection.right:
        case TraversalDirection.down:
893
          requestFocusCallback(
894 895 896 897
            firstFocus,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
          );
      }
898 899 900 901 902
      return true;
    }
    if (_popPolicyDataIfNeeded(direction, nearestScope, focusedChild)) {
      return true;
    }
903
    FocusNode? found;
904
    final ScrollableState? focusedScrollable = Scrollable.maybeOf(focusedChild.context!);
905 906 907
    switch (direction) {
      case TraversalDirection.down:
      case TraversalDirection.up:
908 909 910 911
        Iterable<FocusNode> eligibleNodes = _sortAndFilterVertically(direction, focusedChild.rect, nearestScope.traversalDescendants);
        if (eligibleNodes.isEmpty) {
          break;
        }
912
        if (focusedScrollable != null && !focusedScrollable.position.atEdge) {
913
          final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where((FocusNode node) => Scrollable.maybeOf(node.context!) == focusedScrollable);
914 915 916 917
          if (filteredEligibleNodes.isNotEmpty) {
            eligibleNodes = filteredEligibleNodes;
          }
        }
918
        if (direction == TraversalDirection.up) {
919
          eligibleNodes = eligibleNodes.toList().reversed;
920 921 922
        }
        // 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);
923
        final Iterable<FocusNode> inBand = eligibleNodes.where((FocusNode node) => !node.rect.intersect(band).isEmpty);
924
        if (inBand.isNotEmpty) {
925
          found = _sortByDistancePreferVertical(focusedChild.rect.center, inBand).first;
926 927
          break;
        }
928
        // Only out-of-band targets are eligible, so pick the one that is
929 930 931
        // 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;
932 933
      case TraversalDirection.right:
      case TraversalDirection.left:
934 935 936 937
        Iterable<FocusNode> eligibleNodes = _sortAndFilterHorizontally(direction, focusedChild.rect, nearestScope.traversalDescendants);
        if (eligibleNodes.isEmpty) {
          break;
        }
938
        if (focusedScrollable != null && !focusedScrollable.position.atEdge) {
939
          final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where((FocusNode node) => Scrollable.maybeOf(node.context!) == focusedScrollable);
940 941 942 943
          if (filteredEligibleNodes.isNotEmpty) {
            eligibleNodes = filteredEligibleNodes;
          }
        }
944
        if (direction == TraversalDirection.left) {
945
          eligibleNodes = eligibleNodes.toList().reversed;
946 947 948
        }
        // 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);
949
        final Iterable<FocusNode> inBand = eligibleNodes.where((FocusNode node) => !node.rect.intersect(band).isEmpty);
950
        if (inBand.isNotEmpty) {
951
          found = _sortByDistancePreferHorizontal(focusedChild.rect.center, inBand).first;
952 953
          break;
        }
954
        // Only out-of-band targets are eligible, so pick the one that is
955 956 957
        // 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;
958 959 960
    }
    if (found != null) {
      _pushPolicyData(direction, nearestScope, focusedChild);
961 962 963
      switch (direction) {
        case TraversalDirection.up:
        case TraversalDirection.left:
964
          requestFocusCallback(
965 966 967 968 969
            found,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
          );
        case TraversalDirection.down:
        case TraversalDirection.right:
970
          requestFocusCallback(
971 972 973
            found,
            alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
          );
974
      }
975 976 977 978 979 980 981 982 983 984 985 986 987 988
      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:
///
989
///  * [FocusNode], for a description of the focus system.
990 991
///  * [FocusTraversalGroup], a widget that groups together and imposes a
///    traversal policy on the [Focus] nodes below it in the widget hierarchy.
992 993 994 995
///  * [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.
996 997 998
///  * [OrderedTraversalPolicy], a policy that describes the order
///    explicitly using [FocusTraversalOrder] widgets.
class WidgetOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
999 1000 1001 1002 1003
  /// Constructs a traversal policy that orders widgets for keyboard traversal
  /// based on the widget hierarchy order.
  ///
  /// {@macro flutter.widgets.FocusTraversalPolicy.requestFocusCallback}
  WidgetOrderTraversalPolicy({super.requestFocusCallback});
1004
  @override
1005
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) => descendants;
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
}

// 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.
1016
class _ReadingOrderSortData with Diagnosticable {
1017
  _ReadingOrderSortData(this.node)
1018
      : rect = node.rect,
1019
        directionality = _findDirectionality(node.context!);
1020

1021
  final TextDirection? directionality;
1022 1023 1024 1025 1026
  final Rect rect;
  final FocusNode node;

  // Find the directionality in force for a build context without creating a
  // dependency.
1027
  static TextDirection? _findDirectionality(BuildContext context) {
1028
    return context.getInheritedWidgetOfExactType<Directionality>()?.textDirection;
1029
  }
1030

1031
  /// Finds the common Directional ancestor of an entire list of groups.
1032
  static TextDirection? commonDirectionalityOf(List<_ReadingOrderSortData> list) {
1033
    final Iterable<Set<Directionality>> allAncestors = list.map<Set<Directionality>>((_ReadingOrderSortData member) => member.directionalAncestors.toSet());
1034
    Set<Directionality>? common;
1035 1036 1037
    for (final Set<Directionality> ancestorSet in allAncestors) {
      common ??= ancestorSet;
      common = common.intersection(ancestorSet);
1038
    }
1039
    if (common!.isEmpty) {
1040
      // If there is no common ancestor, then arbitrarily pick the
1041 1042
      // directionality of the first group, which is the equivalent of the
      // "first strongly typed" item in a bidirectional algorithm.
1043
      return list.first.directionality;
1044
    }
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    // 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);
1059
      }
1060 1061
    });
  }
1062

1063 1064 1065 1066 1067
  /// 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>[];
1068
      InheritedElement? directionalityElement = context.getElementForInheritedWidgetOfExactType<Directionality>();
1069 1070 1071
      while (directionalityElement != null) {
        result.add(directionalityElement.widget as Directionality);
        directionalityElement = _getAncestor(directionalityElement)?.getElementForInheritedWidgetOfExactType<Directionality>();
1072
      }
1073
      return result;
1074
    }
1075

1076 1077
    _directionalAncestors ??= getDirectionalityAncestors(node.context!);
    return _directionalAncestors!;
1078 1079
  }

1080
  List<Directionality>? _directionalAncestors;
1081 1082

  @override
1083 1084 1085 1086 1087 1088
  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));
  }
1089 1090
}

1091 1092
// A class for containing group data while sorting in reading order while taking
// into account the ambient directionality.
1093
class _ReadingOrderDirectionalGroupData with Diagnosticable {
1094
  _ReadingOrderDirectionalGroupData(this.members);
1095

1096 1097
  final List<_ReadingOrderSortData> members;

1098
  TextDirection? get directionality => members.first.directionality;
1099

1100
  Rect? _rect;
1101 1102 1103 1104
  Rect get rect {
    if (_rect == null) {
      for (final Rect rect in members.map<Rect>((_ReadingOrderSortData data) => data.rect)) {
        _rect ??= rect;
1105
        _rect = _rect!.expandToInclude(rect);
1106 1107
      }
    }
1108
    return _rect!;
1109 1110 1111 1112 1113 1114
  }

  List<Directionality> get memberAncestors {
    if (_memberAncestors == null) {
      _memberAncestors = <Directionality>[];
      for (final _ReadingOrderSortData member in members) {
1115
        _memberAncestors!.addAll(member.directionalAncestors);
1116 1117
      }
    }
1118
    return _memberAncestors!;
1119 1120
  }

1121
  List<Directionality>? _memberAncestors;
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

  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})';
    })));
  }
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
}

/// 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.
///
1156 1157
/// It uses the ambient [Directionality] in the context for the enclosing
/// [FocusTraversalGroup] to determine which direction is "reading order".
1158 1159 1160
///
/// See also:
///
1161
///  * [FocusNode], for a description of the focus system.
1162 1163 1164
///  * [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
1165 1166 1167
///    creation order to describe the order of traversal.
///  * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
///    focus traversal in a direction.
1168 1169
///  * [OrderedTraversalPolicy], a policy that describes the order
///    explicitly using [FocusTraversalOrder] widgets.
1170
class ReadingOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
1171 1172 1173 1174 1175
  /// Constructs a traversal policy that orders the widgets in "reading order".
  ///
  /// {@macro flutter.widgets.FocusTraversalPolicy.requestFocusCallback}
  ReadingOrderTraversalPolicy({super.requestFocusCallback});

1176 1177 1178 1179
  // 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) {
1180
    TextDirection? currentDirection = candidates.first.directionality;
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    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];
1192
    }
1193 1194 1195 1196 1197 1198 1199 1200
    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.
      }
1201
      _ReadingOrderSortData.sortWithDirectionality(bandGroup.members, bandGroup.directionality!);
1202 1203
    }
    return result;
1204 1205
  }

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
  _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();
1217 1218
    }

1219 1220 1221 1222
    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);

1223
    // The topmost rect is in a band by itself, so just return that one.
1224 1225
    if (inBandOfTop.length <= 1) {
      return topmost;
1226 1227
    }

1228 1229 1230 1231 1232 1233
    // 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.
1234
    final TextDirection? nearestCommonDirectionality = _ReadingOrderSortData.commonDirectionalityOf(inBandOfTop);
1235 1236 1237 1238 1239 1240

    // 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.
1241
    _ReadingOrderSortData.sortWithDirectionality(inBandOfTop, nearestCommonDirectionality!);
1242 1243 1244 1245 1246 1247 1248 1249

    // 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;
    }
1250

1251 1252 1253 1254
    // Sort the groups based on the common directionality and bounding boxes.
    _ReadingOrderDirectionalGroupData.sortWithDirectionality(bandGroups, nearestCommonDirectionality);
    return bandGroups.first.members.first;
  }
1255

1256 1257 1258
  // 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
1259
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) {
1260 1261
    if (descendants.length <= 1) {
      return descendants;
1262 1263
    }

1264 1265
    final List<_ReadingOrderSortData> data = <_ReadingOrderSortData>[
      for (final FocusNode node in descendants) _ReadingOrderSortData(node),
1266
    ];
1267

1268 1269 1270 1271 1272 1273 1274
    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);
1275 1276
    unplaced.remove(current);

1277 1278 1279
    // 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.
1280
    while (unplaced.isNotEmpty) {
1281
      final _ReadingOrderSortData next = _pickNext(unplaced);
1282
      current = next;
1283
      sortedList.add(current.node);
1284 1285
      unplaced.remove(current);
    }
1286
    return sortedList;
1287
  }
1288
}
1289

1290 1291
/// Base class for all sort orders for [OrderedTraversalPolicy] traversal.
///
1292
/// {@template flutter.widgets.FocusOrder.comparable}
1293
/// Only orders of the same type are comparable. If a set of widgets in the same
1294 1295 1296 1297
/// [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.
1298
///
1299 1300 1301
/// When overriding, [FocusOrder.doCompare] must be overridden instead of
/// [FocusOrder.compareTo], which calls [FocusOrder.doCompare] to do the actual
/// comparison.
1302 1303 1304 1305
/// {@endtemplate}
///
/// See also:
///
1306 1307 1308 1309 1310 1311 1312 1313
/// * [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.
1314
@immutable
1315
abstract class FocusOrder with Diagnosticable implements Comparable<FocusOrder> {
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
  /// 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(
1335 1336 1337 1338
      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',
    );
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    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.
///
1359
/// {@macro flutter.widgets.FocusOrder.comparable}
1360 1361 1362 1363
///
/// See also:
///
///  * [FocusTraversalOrder], a widget that assigns an order to a widget subtree
1364
///    for the [OrderedTraversalPolicy] to use.
1365
class NumericFocusOrder extends FocusOrder {
1366
  /// Creates an object that describes a focus traversal order numerically.
1367
  const NumericFocusOrder(this.order);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393

  /// 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
1394
/// locale-specific.
1395
///
1396
/// {@macro flutter.widgets.FocusOrder.comparable}
1397 1398 1399 1400
///
/// See also:
///
///  * [FocusTraversalOrder], a widget that assigns an order to a widget subtree
1401
///    for the [OrderedTraversalPolicy] to use.
1402
class LexicalFocusOrder extends FocusOrder {
1403
  /// Creates an object that describes a focus traversal order lexically.
1404
  const LexicalFocusOrder(this.order);
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

  /// 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 {
1427
  const _OrderedFocusInfo({required this.node, required this.order});
1428 1429 1430 1431 1432 1433 1434 1435

  final FocusNode node;
  final FocusOrder order;
}

/// A [FocusTraversalPolicy] that orders nodes by an explicit order that resides
/// in the nearest [FocusTraversalOrder] widget ancestor.
///
1436
/// {@macro flutter.widgets.FocusOrder.comparable}
1437
///
1438
/// {@tool dartpad}
1439 1440 1441 1442
/// 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).
///
1443
/// ** See code in examples/api/lib/widgets/focus_traversal/ordered_traversal_policy.0.dart **
1444 1445 1446 1447
/// {@end-tool}
///
/// See also:
///
1448 1449 1450
///  * [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
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
///    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].
1465
  OrderedTraversalPolicy({this.secondary, super.requestFocusCallback});
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476

  /// 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.
1477
  final FocusTraversalPolicy? secondary;
1478 1479

  @override
1480
  Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) {
1481
    final FocusTraversalPolicy secondaryPolicy = secondary ?? ReadingOrderTraversalPolicy();
1482
    final Iterable<FocusNode> sortedDescendants = secondaryPolicy.sortDescendants(descendants, currentNode);
1483 1484 1485
    final List<FocusNode> unordered = <FocusNode>[];
    final List<_OrderedFocusInfo> ordered = <_OrderedFocusInfo>[];
    for (final FocusNode node in sortedDescendants) {
1486
      final FocusOrder? order = FocusTraversalOrder.maybeOf(node.context!);
1487 1488 1489 1490
      if (order != null) {
        ordered.add(_OrderedFocusInfo(node: node, order: order));
      } else {
        unordered.add(node);
1491
      }
1492
    }
1493 1494 1495 1496 1497
    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}. "
1498
        "Incompatible order types can't be compared. Use a FocusTraversalGroup to group "
1499 1500 1501 1502 1503 1504 1505
        'similar orders together.',
      );
      return a.order.compareTo(b.order);
    });
    return ordered.map<FocusNode>((_OrderedFocusInfo info) => info.node).followedBy(unordered);
  }
}
1506

1507 1508 1509
/// An inherited widget that describes the order in which its child subtree
/// should be traversed.
///
1510
/// {@macro flutter.widgets.FocusOrder.comparable}
1511 1512 1513 1514
///
/// The order for a widget is determined by the [FocusOrder] returned by
/// [FocusTraversalOrder.of] for a particular context.
class FocusTraversalOrder extends InheritedWidget {
1515 1516
  /// Creates an inherited widget used to describe the focus order of
  /// the [child] subtree.
1517
  const FocusTraversalOrder({super.key, required this.order, required super.child});
1518 1519

  /// The order for the widget descendants of this [FocusTraversalOrder].
1520
  final FocusOrder order;
1521 1522 1523 1524 1525 1526

  /// 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.
1527 1528 1529 1530
  ///
  /// 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) {
1531
    final FocusTraversalOrder? marker = context.getInheritedWidgetOfExactType<FocusTraversalOrder>();
1532
    assert(() {
1533 1534 1535 1536
      if (marker == null) {
        throw FlutterError(
          'FocusTraversalOrder.of() was called with a context that '
          'does not contain a FocusTraversalOrder widget. No TraversalOrder widget '
1537 1538 1539
          'ancestor could be found starting from the context that was passed to '
          'FocusTraversalOrder.of().\n'
          'The context used was:\n'
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
          '  $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) {
1556
    final FocusTraversalOrder? marker = context.getInheritedWidgetOfExactType<FocusTraversalOrder>();
1557
    return marker?.order;
1558 1559
  }

1560 1561
  // 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.
1562
  @override
1563
  bool updateShouldNotify(InheritedWidget oldWidget) => false;
1564 1565

  @override
1566 1567 1568 1569
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<FocusOrder>('order', order));
  }
1570 1571
}

1572 1573 1574 1575 1576 1577 1578
/// 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].
1579
///
1580 1581 1582 1583
/// 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].
1584
///
1585
/// To prevent the members of the group from being focused, set the
1586
/// [descendantsAreFocusable] attribute to false.
1587
///
1588
/// {@tool dartpad}
1589 1590
/// This sample shows three rows of buttons, each grouped by a
/// [FocusTraversalGroup], each with different traversal order policies. Use tab
1591
/// traversal to see the order they are traversed in. The first row follows a
1592 1593 1594 1595
/// 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.
///
1596
/// ** See code in examples/api/lib/widgets/focus_traversal/focus_traversal_group.0.dart **
1597 1598
/// {@end-tool}
///
1599 1600
/// See also:
///
1601
///  * [FocusNode], for a description of the focus system.
1602
///  * [WidgetOrderTraversalPolicy], a policy that relies on the widget
1603 1604 1605 1606 1607
///    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.
1608 1609 1610
class FocusTraversalGroup extends StatefulWidget {
  /// Creates a [FocusTraversalGroup] object.
  ///
1611
  /// The [child] and [descendantsAreFocusable] arguments must not be null.
1612
  FocusTraversalGroup({
1613
    super.key,
1614
    FocusTraversalPolicy? policy,
1615
    this.descendantsAreFocusable = true,
1616
    this.descendantsAreTraversable = true,
1617
    required this.child,
1618
  }) : policy = policy ?? ReadingOrderTraversalPolicy();
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636

  /// 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;

1637 1638 1639
  /// {@macro flutter.widgets.Focus.descendantsAreFocusable}
  final bool descendantsAreFocusable;

1640 1641 1642
  /// {@macro flutter.widgets.Focus.descendantsAreTraversable}
  final bool descendantsAreTraversable;

1643 1644
  /// The child widget of this [FocusTraversalGroup].
  ///
1645
  /// {@macro flutter.widgets.ProxyWidget.child}
1646 1647
  final Widget child;

1648 1649
  /// Returns the [FocusTraversalPolicy] that applies to the nearest ancestor of
  /// the given [FocusNode].
1650
  ///
1651 1652
  /// Will return null if no [FocusTraversalPolicy] ancestor applies to the
  /// given [FocusNode].
1653
  ///
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
  /// 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}
1701
  ///
1702 1703
  /// See also:
  ///
1704 1705 1706 1707
  /// * [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.
1708
  static FocusTraversalPolicy of(BuildContext context) {
1709
    final FocusTraversalPolicy? policy = maybeOf(context);
1710
    assert(() {
1711
      if (policy == null) {
1712
        throw FlutterError(
1713 1714
          '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'
1715
          'FocusTraversalGroup.of() was called with a context that does not contain a '
1716 1717 1718 1719
          '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'
1720 1721 1722 1723 1724 1725
          'The context used was:\n'
          '  $context',
        );
      }
      return true;
    }());
1726
    return policy!;
1727 1728
  }

1729 1730
  /// Returns the [FocusTraversalPolicy] that applies to the [FocusNode] of the
  /// nearest ancestor [Focus] widget, or null, given a [BuildContext].
1731
  ///
1732 1733
  /// 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.
1734
  ///
1735
  /// {@macro flutter.widgets.focus_traversal.FocusTraversalGroup.of}
1736 1737 1738
  ///
  /// See also:
  ///
1739 1740 1741 1742
  /// * [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.
1743
  static FocusTraversalPolicy? maybeOf(BuildContext context) {
1744 1745 1746 1747 1748
    final FocusNode? node = Focus.maybeOf(context, scopeOk: true, createDependency: false);
    if (node == null) {
      return null;
    }
    return FocusTraversalGroup.maybeOfNode(node);
1749 1750 1751
  }

  @override
1752
  State<FocusTraversalGroup> createState() => _FocusTraversalGroupState();
1753 1754 1755 1756 1757 1758 1759 1760

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

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
// 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,
  });

  FocusTraversalPolicy policy;
}

1773 1774 1775
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
1776 1777 1778 1779 1780 1781 1782
  // 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,
  );
1783 1784 1785

  @override
  void dispose() {
1786
    focusNode.dispose();
1787 1788 1789
    super.dispose();
  }

1790 1791 1792 1793 1794 1795 1796 1797
  @override
  void didUpdateWidget (FocusTraversalGroup oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.policy != widget.policy) {
      focusNode.policy = widget.policy;
    }
  }

1798 1799
  @override
  Widget build(BuildContext context) {
1800
    return Focus(
1801
      focusNode: focusNode,
1802 1803 1804 1805 1806 1807
      canRequestFocus: false,
      skipTraversal: true,
      includeSemantics: false,
      descendantsAreFocusable: widget.descendantsAreFocusable,
      descendantsAreTraversable: widget.descendantsAreTraversable,
      child: widget.child,
1808 1809 1810 1811
    );
  }
}

1812 1813 1814
/// An intent for use with the [RequestFocusAction], which supplies the
/// [FocusNode] that should be focused.
class RequestFocusIntent extends Intent {
1815 1816
  /// Creates an intent used with [RequestFocusAction].
  ///
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
  /// The [focusNode] argument must not be null.
  /// {@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;
1827

1828 1829
  /// The [FocusNode] that is to be focused.
  final FocusNode focusNode;
1830 1831
}

1832 1833
/// An [Action] that requests the focus on the node it is given in its
/// [RequestFocusIntent].
1834 1835 1836 1837 1838
///
/// This action can be used to request focus for a particular node, by calling
/// [Action.invoke] like so:
///
/// ```dart
1839
/// Actions.invoke(context, RequestFocusIntent(focusNode));
1840 1841
/// ```
///
1842
/// Where the `focusNode` is the node for which the focus will be requested.
1843 1844
///
/// The difference between requesting focus in this way versus calling
1845 1846 1847 1848 1849 1850 1851
/// [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
1852
/// [RequestFocusIntent] in the [WidgetsApp]. It requests focus. You
1853 1854 1855 1856
/// can redefine the associated action with your own [Actions] widget.
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
class RequestFocusAction extends Action<RequestFocusIntent> {
1857

1858
  @override
1859
  void invoke(RequestFocusIntent intent) {
1860
    intent.requestFocusCallback(intent.focusNode);
1861 1862 1863 1864 1865 1866 1867 1868
  }
}

/// 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 {
1869
  /// Creates an intent that is used with [NextFocusAction].
1870
  const NextFocusIntent();
1871 1872 1873 1874 1875
}

/// An [Action] that moves the focus to the next focusable node in the focus
/// order.
///
1876 1877 1878 1879 1880
/// 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> {
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
  /// 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();
  }

1892
  @override
1893 1894
  KeyEventResult toKeyEventResult(NextFocusIntent intent, bool invokeResult) {
    return invokeResult ? KeyEventResult.handled : KeyEventResult.skipRemainingHandlers;
1895 1896 1897 1898 1899 1900 1901 1902
  }
}

/// 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 {
1903
  /// Creates an intent that is used with [PreviousFocusAction].
1904
  const PreviousFocusIntent();
1905 1906 1907 1908 1909
}

/// An [Action] that moves the focus to the previous focusable node in the focus
/// order.
///
1910 1911 1912 1913 1914 1915
/// 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> {
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
  /// 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();
  }

1927
  @override
1928 1929
  KeyEventResult toKeyEventResult(PreviousFocusIntent intent, bool invokeResult) {
    return invokeResult ? KeyEventResult.handled : KeyEventResult.skipRemainingHandlers;
1930
  }
1931 1932 1933 1934 1935 1936 1937 1938 1939
}

/// 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.
1940 1941
///
/// See [FocusTraversalPolicy] for more information about focus traversal.
1942
class DirectionalFocusIntent extends Intent {
1943
  /// Creates an intent used to move the focus in the given [direction].
1944
  const DirectionalFocusIntent(this.direction, {this.ignoreTextFields = true});
1945 1946 1947 1948

  /// The direction in which to look for the next focusable node when the
  /// associated [DirectionalFocusAction] is invoked.
  final TraversalDirection direction;
1949 1950 1951 1952 1953 1954 1955

  /// 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;
1956 1957 1958 1959 1960 1961

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

1964 1965
/// An [Action] that moves the focus to the focusable node in the direction
/// configured by the associated [DirectionalFocusIntent.direction].
1966
///
1967 1968
/// This is the [Action] associated with [DirectionalFocusIntent] and bound by
/// default to the [LogicalKeyboardKey.arrowUp], [LogicalKeyboardKey.arrowDown],
1969 1970
/// [LogicalKeyboardKey.arrowLeft], and [LogicalKeyboardKey.arrowRight] keys in
/// the [WidgetsApp], with the appropriate associated directions.
1971
class DirectionalFocusAction extends Action<DirectionalFocusIntent> {
1972 1973 1974 1975 1976 1977 1978 1979 1980
  /// 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;
1981
  @override
1982
  void invoke(DirectionalFocusIntent intent) {
1983
    if (!intent.ignoreTextFields || !_isForTextField) {
1984
      primaryFocus!.focusInDirection(intent.direction);
1985
    }
1986 1987
  }
}
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007

/// 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.
  ///
  /// The [excluding] argument must not be null.
  ///
  /// The [child] argument is required, and must not be null.
  const ExcludeFocusTraversal({
2008
    super.key,
2009 2010
    this.excluding = true,
    required this.child,
2011
  });
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044

  /// 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,
    );
  }
}