forked from flutter/flutter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
focus_traversal.dart
1851 lines (1708 loc) · 76.4 KB
/
focus_traversal.dart
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.
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;
}
void _focusAndEnsureVisible(
FocusNode node, {
ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit,
}) {
node.requestFocus();
Scrollable.ensureVisible(node.context!, alignment: 1.0, alignmentPolicy: alignmentPolicy);
}
// A class to temporarily hold information about FocusTraversalGroups when
// sorting their contents.
class _FocusTraversalGroupInfo {
_FocusTraversalGroupInfo(
_FocusTraversalGroupMarker? marker, {
FocusTraversalPolicy? defaultPolicy,
List<FocusNode>? members,
}) : groupNode = marker?.focusNode,
policy = marker?.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,
}
/// An object used to specify a focus traversal policy used for configuring a
/// [FocusTraversalGroup] widget.
///
/// 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.
const FocusTraversalPolicy();
/// 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.
///
/// The `currentNode` argument must not be null.
///
/// 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.
///
/// The `currentNode` argument must not be null.
///
/// 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 next 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}) {
assert(currentNode != null);
final FocusScopeNode scope = currentNode.nearestScope!;
FocusNode? candidate = scope.focusedChild;
if (ignoreCurrentFocus || candidate == null && scope.descendants.isNotEmpty) {
final Iterable<FocusNode> sorted = _sortAllDescendants(scope, currentNode);
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.
///
/// All arguments must not be null.
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.
///
/// The [currentNode] argument must not be null.
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.
///
/// The [currentNode] argument must not be null.
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.
///
/// All arguments must not be null.
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);
_FocusTraversalGroupMarker? _getMarker(BuildContext? context) {
return context?.getElementForInheritedWidgetOfExactType<_FocusTraversalGroupMarker>()?.widget as _FocusTraversalGroupMarker?;
}
// 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) {
assert(scope != null);
final _FocusTraversalGroupMarker? scopeGroupMarker = _getMarker(scope.context);
final FocusTraversalPolicy defaultPolicy = scopeGroupMarker?.policy ?? ReadingOrderTraversalPolicy();
// Build the sorting data structure, separating descendants into groups.
final Map<FocusNode?, _FocusTraversalGroupInfo> groups = <FocusNode?, _FocusTraversalGroupInfo>{};
for (final FocusNode node in scope.descendants) {
final _FocusTraversalGroupMarker? groupMarker = _getMarker(node.context);
final FocusNode? groupNode = groupMarker?.focusNode;
// 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 in _FocusTraversalGroupState.build, and start
// looking with that node's parent, since _getMarker will return the
// context it was called on if it matches the type.
final BuildContext? parentContext = _getAncestor(groupNode!.context!, count: 2);
final _FocusTraversalGroupMarker? parentMarker = _getMarker(parentContext);
final FocusNode? parentNode = parentMarker?.focusNode;
groups[parentNode] ??= _FocusTraversalGroupInfo(parentMarker, members: <FocusNode>[], defaultPolicy: defaultPolicy);
assert(!groups[parentNode]!.members.contains(node));
groups[parentNode]!.members.add(groupNode);
continue;
}
// Skip non-focusable and non-traversable nodes in the same way that
// FocusScopeNode.traversalDescendants would.
if (node.canRequestFocus && !node.skipTraversal) {
groups[groupNode] ??= _FocusTraversalGroupInfo(groupMarker, members: <FocusNode>[], defaultPolicy: defaultPolicy);
assert(!groups[groupNode]!.members.contains(node));
groups[groupNode]!.members.add(node);
}
}
// 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 List<FocusNode> 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(scopeGroupMarker?.focusNode)) {
visitGroups(groups[scopeGroupMarker?.focusNode]!);
}
// 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.
assert(
sortedDescendants.length <= scope.traversalDescendants.length && sortedDescendants.toSet().difference(scope.traversalDescendants.toSet()).isEmpty,
'Sorted descendants contains different nodes than FocusScopeNode.traversalDescendants would. '
'These are the different nodes: ${sortedDescendants.toSet().difference(scope.traversalDescendants.toSet())}',
);
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}) {
assert(forward != null);
final FocusScopeNode nearestScope = currentNode.nearestScope!;
invalidateScopeData(nearestScope);
final FocusNode? focusedChild = nearestScope.focusedChild;
if (focusedChild == null) {
final FocusNode? firstFocus = forward ? findFirstFocus(currentNode) : findLastFocus(currentNode);
if (firstFocus != null) {
_focusAndEnsureVisible(
firstFocus,
alignmentPolicy: forward ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
return true;
}
}
final List<FocusNode> sortedNodes = _sortAllDescendants(nearestScope, currentNode);
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;
}
if (forward && focusedChild == sortedNodes.last) {
_focusAndEnsureVisible(sortedNodes.first, alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd);
return true;
}
if (!forward && focusedChild == sortedNodes.first) {
_focusAndEnsureVisible(sortedNodes.last, alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart);
return true;
}
final Iterable<FocusNode> maybeFlipped = forward ? sortedNodes : sortedNodes.reversed;
FocusNode? previousNode;
for (final FocusNode node in maybeFlipped) {
if (previousNode == focusedChild) {
_focusAndEnsureVisible(
node,
alignmentPolicy: forward ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
return true;
}
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})
: assert(direction != null),
assert(node != null);
final TraversalDirection direction;
final FocusNode node;
}
class _DirectionalPolicyData {
const _DirectionalPolicyData({required this.history}) : assert(history != null);
/// 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.
///
/// 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) {
assert(direction != null);
assert(currentNode != null);
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);
}
}
FocusNode? _sortAndFindInitial(FocusNode currentNode, {required bool vertical, required bool first}) {
final Iterable<FocusNode> nodes = currentNode.nearestScope!.traversalDescendants;
final List<FocusNode> sorted = nodes.toList();
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);
}
}
});
if (sorted.isNotEmpty) {
return sorted.first;
}
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;
}
// 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.
Iterable<FocusNode> _sortAndFilterHorizontally(
TraversalDirection direction,
Rect target,
Iterable<FocusNode> nodes,
) {
assert(direction == TraversalDirection.left || direction == TraversalDirection.right);
final Iterable<FocusNode> filtered;
switch (direction) {
case TraversalDirection.left:
filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dx <= target.left);
break;
case TraversalDirection.right:
filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dx >= target.right);
break;
case TraversalDirection.up:
case TraversalDirection.down:
throw ArgumentError('Invalid direction $direction');
}
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;
}
// 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.
Iterable<FocusNode> _sortAndFilterVertically(
TraversalDirection direction,
Rect target,
Iterable<FocusNode> nodes,
) {
assert(direction == TraversalDirection.up || direction == TraversalDirection.down);
final Iterable<FocusNode> filtered;
switch (direction) {
case TraversalDirection.up:
filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dy <= target.top);
break;
case TraversalDirection.down:
filtered = nodes.where((FocusNode node) => node.rect != target && node.rect.center.dy >= target.bottom);
break;
case TraversalDirection.left:
case TraversalDirection.right:
throw ArgumentError('Invalid direction $direction');
}
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;
}
// 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) {
final _DirectionalPolicyData? policyData = _policyData[nearestScope];
if (policyData != null && policyData.history.isNotEmpty && policyData.history.first.direction != direction) {
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
// 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.
invalidateScopeData(nearestScope);
return false;
}
// Returns true if successfully popped the history.
bool popOrInvalidate(TraversalDirection direction) {
final FocusNode lastNode = policyData.history.removeLast().node;
if (Scrollable.maybeOf(lastNode.context!) != Scrollable.maybeOf(primaryFocus!.context!)) {
invalidateScopeData(nearestScope);
return false;
}
final ScrollPositionAlignmentPolicy alignmentPolicy;
switch (direction) {
case TraversalDirection.up:
case TraversalDirection.left:
alignmentPolicy = ScrollPositionAlignmentPolicy.keepVisibleAtStart;
break;
case TraversalDirection.right:
case TraversalDirection.down:
alignmentPolicy = ScrollPositionAlignmentPolicy.keepVisibleAtEnd;
break;
}
_focusAndEnsureVisible(
lastNode,
alignmentPolicy: alignmentPolicy,
);
return true;
}
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);
break;
case TraversalDirection.up:
case TraversalDirection.down:
if (popOrInvalidate(direction)) {
return true;
}
break;
}
break;
case TraversalDirection.left:
case TraversalDirection.right:
switch (policyData.history.first.direction) {
case TraversalDirection.left:
case TraversalDirection.right:
if (popOrInvalidate(direction)) {
return true;
}
break;
case TraversalDirection.up:
case TraversalDirection.down:
// Reset the policy data if we change directions.
invalidateScopeData(nearestScope);
break;
}
}
}
if (policyData != null && policyData.history.isEmpty) {
invalidateScopeData(nearestScope);
}
return false;
}
void _pushPolicyData(TraversalDirection direction, FocusScopeNode nearestScope, FocusNode focusedChild) {
final _DirectionalPolicyData? policyData = _policyData[nearestScope];
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
/// 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.
///
/// 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) {
final FocusScopeNode nearestScope = currentNode.nearestScope!;
final FocusNode? focusedChild = nearestScope.focusedChild;
if (focusedChild == null) {
final FocusNode firstFocus = findFirstFocusInDirection(currentNode, direction) ?? currentNode;
switch (direction) {
case TraversalDirection.up:
case TraversalDirection.left:
_focusAndEnsureVisible(
firstFocus,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
break;
case TraversalDirection.right:
case TraversalDirection.down:
_focusAndEnsureVisible(
firstFocus,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
break;
}
return true;
}
if (_popPolicyDataIfNeeded(direction, nearestScope, focusedChild)) {
return true;
}
FocusNode? found;
final ScrollableState? focusedScrollable = Scrollable.maybeOf(focusedChild.context!);
switch (direction) {
case TraversalDirection.down:
case TraversalDirection.up:
Iterable<FocusNode> eligibleNodes = _sortAndFilterVertically(direction, focusedChild.rect, nearestScope.traversalDescendants);
if (eligibleNodes.isEmpty) {
break;
}
if (focusedScrollable != null && !focusedScrollable.position.atEdge) {
final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where((FocusNode node) => Scrollable.maybeOf(node.context!) == 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 Rect 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) {
found = _sortByDistancePreferVertical(focusedChild.rect.center, inBand).first;
break;
}
// Only out-of-band targets are eligible, so pick the one that is
// closest the to the center line horizontally.
found = _sortByDistancePreferHorizontal(focusedChild.rect.center, eligibleNodes).first;
break;
case TraversalDirection.right:
case TraversalDirection.left:
Iterable<FocusNode> eligibleNodes = _sortAndFilterHorizontally(direction, focusedChild.rect, nearestScope.traversalDescendants);
if (eligibleNodes.isEmpty) {
break;
}
if (focusedScrollable != null && !focusedScrollable.position.atEdge) {
final Iterable<FocusNode> filteredEligibleNodes = eligibleNodes.where((FocusNode node) => Scrollable.maybeOf(node.context!) == 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 Rect 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) {
found = _sortByDistancePreferHorizontal(focusedChild.rect.center, inBand).first;
break;
}
// Only out-of-band targets are eligible, so pick the one that is
// to the center line vertically.
found = _sortByDistancePreferVertical(focusedChild.rect.center, eligibleNodes).first;
break;
}
if (found != null) {
_pushPolicyData(direction, nearestScope, focusedChild);
switch (direction) {
case TraversalDirection.up:
case TraversalDirection.left:
_focusAndEnsureVisible(
found,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
break;
case TraversalDirection.down:
case TraversalDirection.right:
_focusAndEnsureVisible(
found,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
break;
}
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:
///
/// * [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.
/// * [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.
/// * [OrderedTraversalPolicy], a policy that describes the order
/// explicitly using [FocusTraversalOrder] widgets.
class WidgetOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin {
@override
Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) => descendants;
}
// 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.
class _ReadingOrderSortData with Diagnosticable {
_ReadingOrderSortData(this.node)
: assert(node != null),
rect = node.rect,
directionality = _findDirectionality(node.context!);
final TextDirection? directionality;
final Rect rect;
final FocusNode node;
// Find the directionality in force for a build context without creating a
// dependency.
static TextDirection? _findDirectionality(BuildContext context) {
return (context.getElementForInheritedWidgetOfExactType<Directionality>()?.widget as Directionality?)?.textDirection;
}
/// Finds the common Directional ancestor of an entire list of groups.
static TextDirection? commonDirectionalityOf(List<_ReadingOrderSortData> list) {
final Iterable<Set<Directionality>> allAncestors = list.map<Set<Directionality>>((_ReadingOrderSortData member) => member.directionalAncestors.toSet());
Set<Directionality>? common;
for (final Set<Directionality> ancestorSet in allAncestors) {
common ??= ancestorSet;
common = common.intersection(ancestorSet);
}
if (common!.isEmpty) {
// If there is no common ancestor, then arbitrarily pick the
// directionality of the first group, which is the equivalent of the
// "first strongly typed" item in a bidirectional algorithm.
return list.first.directionality;
}
// 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);
}
});
}
/// 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>[];
InheritedElement? directionalityElement = context.getElementForInheritedWidgetOfExactType<Directionality>();
while (directionalityElement != null) {
result.add(directionalityElement.widget as Directionality);
directionalityElement = _getAncestor(directionalityElement)?.getElementForInheritedWidgetOfExactType<Directionality>();
}
return result;
}
_directionalAncestors ??= getDirectionalityAncestors(node.context!);
return _directionalAncestors!;
}
List<Directionality>? _directionalAncestors;
@override
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));
}
}
// A class for containing group data while sorting in reading order while taking
// into account the ambient directionality.
class _ReadingOrderDirectionalGroupData with Diagnosticable {
_ReadingOrderDirectionalGroupData(this.members);
final List<_ReadingOrderSortData> members;
TextDirection? get directionality => members.first.directionality;
Rect? _rect;
Rect get rect {
if (_rect == null) {
for (final Rect rect in members.map<Rect>((_ReadingOrderSortData data) => data.rect)) {
_rect ??= rect;
_rect = _rect!.expandToInclude(rect);
}
}
return _rect!;
}
List<Directionality> get memberAncestors {
if (_memberAncestors == null) {
_memberAncestors = <Directionality>[];
for (final _ReadingOrderSortData member in members) {
_memberAncestors!.addAll(member.directionalAncestors);
}
}
return _memberAncestors!;
}
List<Directionality>? _memberAncestors;
static void sortWithDirectionality(List<_ReadingOrderDirectionalGroupData> list, TextDirection directionality) {