-
Notifications
You must be signed in to change notification settings - Fork 30.5k
Expand file tree
/
Copy pathfocus_traversal.dart
More file actions
2474 lines (2307 loc) · 97.1 KB
/
Copy pathfocus_traversal.dart
File metadata and controls
2474 lines (2307 loc) · 97.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'dart:ui';
/// @docImport 'package:flutter/services.dart';
///
/// @docImport 'app.dart';
library;
import 'package:flutter/foundation.dart';
import 'actions.dart';
import 'basic.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'scroll_position.dart';
import 'scrollable.dart';
// Examples can assume:
// late BuildContext context;
// FocusNode focusNode = FocusNode();
// 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).
BuildContext? _getAncestor(BuildContext context, {int count = 1}) {
BuildContext? target;
context.visitAncestorElements((Element ancestor) {
count--;
if (count == 0) {
target = ancestor;
return false;
}
return true;
});
return target;
}
/// 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,
});
// A class to temporarily hold information about FocusTraversalGroups when
// sorting their contents.
class _FocusTraversalGroupInfo {
_FocusTraversalGroupInfo(
_FocusTraversalGroupNode? group, {
FocusTraversalPolicy? defaultPolicy,
List<FocusNode>? members,
}) : groupNode = group,
policy = group?.policy ?? defaultPolicy ?? ReadingOrderTraversalPolicy(),
members = members ?? <FocusNode>[];
final FocusNode? groupNode;
final FocusTraversalPolicy policy;
final List<FocusNode> members;
}
/// A direction along either the horizontal or vertical axes.
///
/// This is used by the [DirectionalFocusTraversalPolicyMixin], and
/// [FocusNode.focusInDirection] to indicate which direction to look in for the
/// next focus.
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,
}
/// Controls the focus transfer at the edges of a [FocusScopeNode].
/// For movement transfers (previous or next), the edge represents
/// the first or last items. For directional transfers, the edge
/// represents the outermost items of the [FocusScopeNode], For example:
/// for moving downwards, the edge node is the one with the largest bottom
/// coordinate; for moving leftwards, the edge node is the one with the
/// smallest x coordinate.
///
/// 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.
///
/// Transfer focus to the edge node in the opposite direction of [FocusScopeNode]
/// as the edge node continues to move, thus forming a closed loop of focusable items.
///
/// For moving transfers, requesting the next focus after the last focusable item will
/// transfer focus to the first item, and requesting focus before the first item will
/// transfer focus to the last item.
///
/// For directional transfers, continuing to request right focus at the rightmost node
/// will transfer focus to the leftmost node. Continuing to request left focus at the
/// leftmost node will transfer focus to the rightmost node.
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
/// control is transferred to the browser, allowing the user to reach the
/// address bar, escape an `iframe`, or focus on HTML elements other than
/// those managed by Flutter.
leaveFlutterView,
/// Allows focus to traverse up to parent scope.
///
/// When reaching the edge of the current scope, requesting the next focus
/// will look up to the parent scope of the current scope and focus the focus
/// node next to the current scope.
///
/// If there is no parent scope above the current scope, fallback to
/// [closedLoop] behavior.
parentScope,
/// Stops the focus traversal at the edge of the focus scope.
///
/// Keeps the focus in its current position when it reaches the edge of a focus scope.
stop,
}
/// Determines how focusable widgets are traversed within a [FocusTraversalGroup].
///
/// The focus traversal policy is what determines which widget is "next",
/// "previous", or in a direction from the widget associated with the currently
/// focused [FocusNode] (usually a [Focus] widget).
///
/// One of the pre-defined subclasses may be used, or define a custom policy to
/// create a unique focus order.
///
/// When defining your own, your subclass should implement [sortDescendants] to
/// provide the order in which you would like the descendants to be traversed.
///
/// See also:
///
/// * [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.
/// * [FocusNode], which is affected by the traversal policy.
/// * [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.
/// * [DirectionalFocusTraversalPolicyMixin] a mixin class that implements
/// focus traversal in a direction.
@immutable
abstract class FocusTraversalPolicy with Diagnosticable {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
///
/// {@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,
alignmentPolicy: alignmentPolicy ?? ScrollPositionAlignmentPolicy.explicit,
duration: duration ?? Duration.zero,
curve: curve ?? Curves.ease,
);
}
/// Request focus on a focus node as a result of a tab traversal.
///
/// If the `node` is a [FocusScopeNode], this method will recursively find
/// the next focus from its descendants until it find a regular [FocusNode].
///
/// Returns true if this method focused a new focus node.
bool _requestTabTraversalFocus(
FocusNode node, {
ScrollPositionAlignmentPolicy? alignmentPolicy,
double? alignment,
Duration? duration,
Curve? curve,
required bool forward,
}) {
if (node is FocusScopeNode) {
if (node.focusedChild != null) {
// Can't stop here as the `focusedChild` may be a focus scope node
// without a first focus. The first focus will be picked in the
// next iteration.
return _requestTabTraversalFocus(
node.focusedChild!,
alignmentPolicy: alignmentPolicy,
alignment: alignment,
duration: duration,
curve: curve,
forward: forward,
);
}
final List<FocusNode> sortedChildren = _sortAllDescendants(node, node);
if (sortedChildren.isNotEmpty) {
_requestTabTraversalFocus(
forward ? sortedChildren.first : sortedChildren.last,
alignmentPolicy: alignmentPolicy,
alignment: alignment,
duration: duration,
curve: curve,
forward: forward,
);
// Regardless if _requestTabTraversalFocus return true or false, a first
// focus has been picked.
return true;
}
}
final bool nodeHadPrimaryFocus = node.hasPrimaryFocus;
requestFocusCallback(
node,
alignmentPolicy: alignmentPolicy,
alignment: alignment,
duration: duration,
curve: curve,
);
return !nodeHadPrimaryFocus;
}
/// Returns the node that should receive focus if focus is traversing
/// forwards, and there is no current focus.
///
/// 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.
///
/// 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.
///
/// See also:
///
/// * [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);
}
/// 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.
///
/// 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.
///
/// See also:
///
/// * [previous], the function that is called to move the focus to the previous node.
/// * [DirectionalFocusTraversalPolicyMixin.findFirstFocusInDirection], a
/// function that finds the first focusable widget in a particular direction.
FocusNode findLastFocus(FocusNode currentNode, {bool ignoreCurrentFocus = false}) {
return _findInitialFocus(currentNode, fromEnd: true, ignoreCurrentFocus: ignoreCurrentFocus);
}
FocusNode _findInitialFocus(
FocusNode currentNode, {
bool fromEnd = false,
bool ignoreCurrentFocus = false,
}) {
final FocusScopeNode scope = currentNode.nearestScope!;
FocusNode? candidate = scope.focusedChild;
if (ignoreCurrentFocus || candidate == null && scope.descendants.isNotEmpty) {
final Iterable<FocusNode> sorted = _sortAllDescendants(
scope,
currentNode,
).where((FocusNode node) => _canRequestTraversalFocus(node));
if (sorted.isEmpty) {
candidate = null;
} else {
candidate = fromEnd ? sorted.last : sorted.first;
}
}
// If we still didn't find any candidate, use the current node as a
// fallback.
candidate ??= currentNode;
return candidate;
}
/// 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.
///
/// This is typically used by [inDirection] to determine which node to focus
/// if it is called when no node is currently focused.
FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction);
/// 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) {}
/// This is called whenever the given [node] is re-parented into a new scope,
/// 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
void changedScope({FocusNode? node, FocusScopeNode? oldScope}) {}
/// 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.
bool next(FocusNode currentNode) => _moveFocus(currentNode, forward: true);
/// 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.
bool previous(FocusNode currentNode) => _moveFocus(currentNode, forward: false);
/// Focuses the next widget in the given [direction] in the focus scope that
/// contains the given [currentNode].
///
/// This should determine what the next node to receive focus in the given
/// [direction] should be by inspecting the node tree, and then calling
/// [FocusNode.requestFocus] on the node that has been selected.
///
/// Returns true if it successfully found a node and requested focus.
bool inDirection(FocusNode currentNode, TraversalDirection direction);
/// 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
/// 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.
///
/// 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
Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode);
static bool _canRequestTraversalFocus(FocusNode node) {
return node.canRequestFocus && !node.skipTraversal;
}
static Iterable<FocusNode> _getDescendantsWithoutExpandingScope(FocusNode node) {
final result = <FocusNode>[];
for (final FocusNode child in node.children) {
result.add(child);
if (child is! FocusScopeNode) {
result.addAll(_getDescendantsWithoutExpandingScope(child));
}
}
return result;
}
static Map<FocusNode?, _FocusTraversalGroupInfo> _findGroups(
FocusScopeNode scope,
_FocusTraversalGroupNode? scopeGroupNode,
FocusNode currentNode,
) {
final FocusTraversalPolicy defaultPolicy =
scopeGroupNode?.policy ?? ReadingOrderTraversalPolicy();
final groups = <FocusNode?, _FocusTraversalGroupInfo>{};
for (final FocusNode node in _getDescendantsWithoutExpandingScope(scope)) {
final _FocusTraversalGroupNode? groupNode = FocusTraversalGroup._getGroupNode(node);
// 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
// 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);
continue;
}
// Skip non-focusable and non-traversable nodes in the same way that
// FocusScopeNode.traversalDescendants would.
//
// Current focused node needs to be in the group so that the caller can
// find the next traversable node from the current focused node.
if (node == currentNode || (node.canRequestFocus && !node.skipTraversal)) {
groups[groupNode] ??= _FocusTraversalGroupInfo(
groupNode,
members: <FocusNode>[],
defaultPolicy: defaultPolicy,
);
assert(!groups[groupNode]!.members.contains(node));
groups[groupNode]!.members.add(node);
}
}
return groups;
}
// Sort all descendants, taking into account the FocusTraversalGroup
// that they are each in, and filtering out non-traversable/focusable nodes.
static 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,
currentNode,
);
// Sort the member lists using the individual policy sorts.
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);
}
// Traverse the group tree, adding the children of members in the order they
// appear in the member lists.
final sortedDescendants = <FocusNode>[];
void visitGroups(_FocusTraversalGroupInfo info) {
for (final FocusNode node in info.members) {
if (groups.containsKey(node)) {
// This is a policy group focus node. Replace it with the members of
// the corresponding policy group.
visitGroups(groups[node]!);
} else {
sortedDescendants.add(node);
}
}
}
// Visit the children of the scope, if any.
if (groups.isNotEmpty && groups.containsKey(scopeGroupNode)) {
visitGroups(groups[scopeGroupNode]!);
}
// 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 != currentNode && !_canRequestTraversalFocus(node);
});
// 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.
assert(() {
final Set<FocusNode> difference = sortedDescendants.toSet().difference(
scope.traversalDescendants.toSet(),
);
if (!_canRequestTraversalFocus(currentNode)) {
// The scope.traversalDescendants will not contain currentNode if it
// skips traversal or not focusable.
assert(
difference.isEmpty || (difference.length == 1 && difference.contains(currentNode)),
'Difference between sorted descendants and FocusScopeNode.traversalDescendants contains '
'something other than the current skipped node. This is the difference: $difference',
);
return true;
}
assert(
difference.isEmpty,
'Sorted descendants contains different nodes than FocusScopeNode.traversalDescendants would. '
'These are the different nodes: $difference',
);
return true;
}());
return sortedDescendants;
}
/// 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.
@protected
bool _moveFocus(FocusNode currentNode, {required bool forward}) {
final FocusScopeNode nearestScope = currentNode.nearestScope!;
invalidateScopeData(nearestScope);
FocusNode? focusedChild = nearestScope.focusedChild;
if (focusedChild == null) {
final FocusNode? firstFocus = forward
? findFirstFocus(currentNode)
: findLastFocus(currentNode);
if (firstFocus != null) {
return _requestTabTraversalFocus(
firstFocus,
alignmentPolicy: forward
? ScrollPositionAlignmentPolicy.keepVisibleAtEnd
: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
forward: forward,
);
}
}
focusedChild ??= nearestScope;
final List<FocusNode> sortedNodes = _sortAllDescendants(nearestScope, focusedChild);
assert(sortedNodes.contains(focusedChild));
if (forward && focusedChild == sortedNodes.last) {
switch (nearestScope.traversalEdgeBehavior) {
case TraversalEdgeBehavior.leaveFlutterView:
focusedChild.unfocus();
return false;
case TraversalEdgeBehavior.parentScope:
final FocusScopeNode? parentScope = nearestScope.enclosingScope;
if (parentScope != null && parentScope != FocusManager.instance.rootScope) {
focusedChild.unfocus();
parentScope.nextFocus();
// Verify the focus really has changed.
return focusedChild.enclosingScope?.focusedChild != focusedChild;
}
// No valid parent scope. Fallback to closed loop behavior.
return _requestTabTraversalFocus(
sortedNodes.first,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
forward: forward,
);
case TraversalEdgeBehavior.closedLoop:
return _requestTabTraversalFocus(
sortedNodes.first,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
forward: forward,
);
case TraversalEdgeBehavior.stop:
return false;
}
}
if (!forward && focusedChild == sortedNodes.first) {
switch (nearestScope.traversalEdgeBehavior) {
case TraversalEdgeBehavior.leaveFlutterView:
focusedChild.unfocus();
return false;
case TraversalEdgeBehavior.parentScope:
final FocusScopeNode? parentScope = nearestScope.enclosingScope;
if (parentScope != null && parentScope != FocusManager.instance.rootScope) {
focusedChild.unfocus();
parentScope.previousFocus();
// Verify the focus really has changed.
return focusedChild.enclosingScope?.focusedChild != focusedChild;
}
// No valid parent scope. Fallback to closed loop behavior.
return _requestTabTraversalFocus(
sortedNodes.last,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
forward: forward,
);
case TraversalEdgeBehavior.closedLoop:
return _requestTabTraversalFocus(
sortedNodes.last,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
forward: forward,
);
case TraversalEdgeBehavior.stop:
return false;
}
}
final Iterable<FocusNode> maybeFlipped = forward ? sortedNodes : sortedNodes.reversed;
FocusNode? previousNode;
for (final node in maybeFlipped) {
if (previousNode == focusedChild) {
return _requestTabTraversalFocus(
node,
alignmentPolicy: forward
? ScrollPositionAlignmentPolicy.keepVisibleAtEnd
: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
forward: forward,
);
}
previousNode = node;
}
return false;
}
}
// A policy data object for use by the DirectionalFocusTraversalPolicyMixin so
// it can keep track of the traversal history.
class _DirectionalPolicyDataEntry {
const _DirectionalPolicyDataEntry({required this.direction, required this.node});
final TraversalDirection direction;
final FocusNode node;
}
class _DirectionalPolicyData {
const _DirectionalPolicyData({required this.history});
/// 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
/// 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.
///
/// 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
/// follow the same path on the way up as it did on the way down, since changing
/// the axis of motion resets the history.
///
/// This class implements an algorithm that considers an band extending
/// along the direction of movement within the [FocusScope], the width or height
/// (depending on direction) of the currently focused widget, and finds the closest
/// widget inthat 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. When reaching the edge in the direction specified by [FocusScope],
/// different behaviors are taken according to [FocusScopeNode.directionalTraversalEdgeBehavior].
/// For [TraversalEdgeBehavior.closedLoop], the algorithm will reselect
/// the farthest node in the opposite direction within the band. For
/// [TraversalEdgeBehavior.parentScope], the band will extend to the parent
/// [FocusScopeNode],and if it is still an edge node in the parent, it will continue
/// to search according to the parent's [FocusScopeNode.directionalTraversalEdgeBehavior],
/// If there is no parent scope above the current scope, fallback to
/// [TraversalEdgeBehavior.closedLoop] behavior. For [TraversalEdgeBehavior.leaveFlutterView],
/// the focus will be lost. For [TraversalEdgeBehavior.stop], the current focused
/// element will remain.
///
/// 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.
///
/// See also:
///
/// * [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.
mixin DirectionalFocusTraversalPolicyMixin on FocusTraversalPolicy {
final Map<FocusScopeNode, _DirectionalPolicyData> _policyData =
<FocusScopeNode, _DirectionalPolicyData>{};
@override
void invalidateScopeData(FocusScopeNode node) {
super.invalidateScopeData(node);
_policyData.remove(node);
}
@override
void changedScope({FocusNode? node, FocusScopeNode? oldScope}) {
super.changedScope(node: node, oldScope: oldScope);
if (oldScope != null) {
_policyData[oldScope]?.history.removeWhere((_DirectionalPolicyDataEntry entry) {
return entry.node == node;
});
}
}
@override
FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction) {
final Iterable<FocusNode> nodes = currentNode.nearestScope!.traversalDescendants;
final List<FocusNode> sorted = nodes.toList();
final (bool vertical, bool first) = switch (direction) {
TraversalDirection.up => (true, false), // Start with the bottom-most node.
TraversalDirection.down => (true, true), // Start with the topmost node.
TraversalDirection.left => (false, false), // Start with the rightmost node.
TraversalDirection.right => (false, true), // Start with the leftmost node.
};
mergeSort<FocusNode>(
sorted,
compare: (FocusNode a, FocusNode b) {
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);
}
}
},
);
return sorted.firstOrNull;
}
FocusNode? _findNextFocusInDirection(
FocusNode focusedChild,
Iterable<FocusNode> traversalDescendants,
TraversalDirection direction, {
bool forward = true,
}) {
switch (direction) {
case TraversalDirection.down:
case TraversalDirection.up:
Iterable<FocusNode> eligibleNodes = _sortAndFilterVertically(
direction,
focusedChild.rect,
traversalDescendants,
forward: forward,
);
if (eligibleNodes.isEmpty) {
break;
}
final ScrollableState? focusedScrollable = Scrollable.maybeOf(
focusedChild.context!,
axis: Axis.vertical,
);
if (focusedScrollable != null) {
final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where(
(FocusNode node) =>
Scrollable.maybeOf(node.context!, axis: Axis.vertical) == focusedScrollable,
);
if (filteredEligibleNodes.isNotEmpty) {
eligibleNodes = filteredEligibleNodes;
}
}
if (direction == TraversalDirection.up) {
eligibleNodes = eligibleNodes.toList().reversed;
}
// Find any nodes that intersect the band of the focused child.
final band = Rect.fromLTRB(
focusedChild.rect.left,
-double.infinity,
focusedChild.rect.right,
double.infinity,
);
final Iterable<FocusNode> inBand = eligibleNodes.where(
(FocusNode node) => !node.rect.intersect(band).isEmpty,
);
if (inBand.isNotEmpty) {
if (forward) {
return _sortByDistancePreferVertical(focusedChild.rect.center, inBand).first;
}
return _sortByDistancePreferVertical(focusedChild.rect.center, inBand).last;
}
// Only out-of-band targets are eligible, so pick the one that is
// closest to the center line horizontally, and if any are the same
// distance horizontally, pick the closest one of those vertically.
if (forward) {
return _sortClosestEdgesByDistancePreferHorizontal(
focusedChild.rect.center,
eligibleNodes,
).first;
}
return _sortClosestEdgesByDistancePreferHorizontal(
focusedChild.rect.center,
eligibleNodes,
).last;
case TraversalDirection.right:
case TraversalDirection.left:
Iterable<FocusNode> eligibleNodes = _sortAndFilterHorizontally(
direction,
focusedChild.rect,
traversalDescendants,
forward: forward,
);
if (eligibleNodes.isEmpty) {
break;
}
final ScrollableState? focusedScrollable = Scrollable.maybeOf(
focusedChild.context!,
axis: Axis.horizontal,
);
if (focusedScrollable != null) {
final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where(
(FocusNode node) =>
Scrollable.maybeOf(node.context!, axis: Axis.horizontal) == focusedScrollable,
);
if (filteredEligibleNodes.isNotEmpty) {
eligibleNodes = filteredEligibleNodes;
}
}
if (direction == TraversalDirection.left) {
eligibleNodes = eligibleNodes.toList().reversed;
}
// Find any nodes that intersect the band of the focused child.
final band = Rect.fromLTRB(
-double.infinity,
focusedChild.rect.top,
double.infinity,
focusedChild.rect.bottom,
);
final Iterable<FocusNode> inBand = eligibleNodes.where(
(FocusNode node) => !node.rect.intersect(band).isEmpty,
);
if (inBand.isNotEmpty) {
if (forward) {
return _sortByDistancePreferHorizontal(focusedChild.rect.center, inBand).first;
}
return _sortByDistancePreferHorizontal(focusedChild.rect.center, inBand).last;
}
// Only out-of-band targets are eligible, so pick the one that is
// closest to the center line vertically, and if any are the same
// distance vertically, pick the closest one of those horizontally.
if (forward) {
return _sortClosestEdgesByDistancePreferVertical(
focusedChild.rect.center,
eligibleNodes,
).first;
}
return _sortClosestEdgesByDistancePreferVertical(
focusedChild.rect.center,
eligibleNodes,
).last;
}
return null;
}
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;
}
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