1use std::any::Any;
11use std::cmp::Ordering;
12use std::collections::HashMap;
13use std::fmt::{self, Debug};
14use std::rc::Rc;
15use std::time::Duration;
16
17use waft_animation::{Curve, Curves};
18use waft_embedder::{Offset, Rect, TextDirection};
19use waft_foundation::{
20 App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticableNode,
21 DiagnosticsNode, DiagnosticsProperty, DoubleProperty, EnumProperty, Handle, HandleId,
22 ListenableObject, Listener, OptionRetained, Ref, Retained, StringProperty, ValueChanged,
23 describe_identity,
24};
25use waft_painting::Axis;
26
27use crate::framework::{
28 BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
29 StatelessWidget, WidgetRef, downcast_widget,
30};
31use crate::widgets::actions::{Action, ActionData, Intent};
32use crate::widgets::basic::Directionality;
33use crate::widgets::focus_manager::{
34 AnyFocusNode, FocusManager, FocusNodeData, FocusNodeLeaf, FocusNodeRef, FocusScopeNode,
35 KeyEventResult, TraversalEdgeBehavior, primary_focus,
36};
37use crate::widgets::focus_scope::Focus;
38use crate::widgets::scroll_position::ScrollPositionAlignmentPolicy;
39use crate::widgets::scrollable::Scrollable;
40
41fn get_ancestor(app: &App, context: BuildContext, count: u32) -> Option<BuildContext> {
48 let mut count = count;
49 let mut target = None;
50 context.visit_ancestor_elements(app, &mut |ancestor| {
51 count -= 1;
52 if count == 0 {
53 target = Some(ancestor);
54 return false;
55 }
56 true
57 });
58 target
59}
60
61pub type TraversalRequestFocusCallback = Rc<
66 dyn Fn(
67 &mut App,
68 AnyFocusNode,
69 Option<ScrollPositionAlignmentPolicy>,
70 Option<f64>,
71 Option<Duration>,
72 Option<Rc<dyn Curve>>,
73 ),
74>;
75
76pub fn default_traversal_request_focus_callback(
81 app: &mut App,
82 node: AnyFocusNode,
83 alignment_policy: Option<ScrollPositionAlignmentPolicy>,
84 alignment: Option<f64>,
85 duration: Option<Duration>,
86 curve: Option<Rc<dyn Curve>>,
87) {
88 node.request_focus(app, None);
89 let context = node.context(app).expect("a traversable node has a context");
90 Scrollable::ensure_visible(
91 app,
92 context,
93 alignment.unwrap_or(1.0),
94 duration.unwrap_or(Duration::ZERO),
95 curve.unwrap_or_else(Curves::ease),
96 alignment_policy.unwrap_or(ScrollPositionAlignmentPolicy::Explicit),
97 );
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub enum TraversalDirection {
107 Up,
109
110 Right,
114
115 Down,
117
118 Left,
122}
123
124pub struct FocusTraversalPolicyData {
130 pub request_focus_callback: TraversalRequestFocusCallback,
133}
134
135impl FocusTraversalPolicyData {
136 pub fn new() -> FocusTraversalPolicyData {
138 FocusTraversalPolicyData {
139 request_focus_callback: Rc::new(default_traversal_request_focus_callback),
140 }
141 }
142}
143
144impl Default for FocusTraversalPolicyData {
145 fn default() -> FocusTraversalPolicyData {
146 FocusTraversalPolicyData::new()
147 }
148}
149
150#[macro_export]
153macro_rules! focus_traversal_policy_accessors {
154 () => {
155 fn focus_traversal_policy_data(
156 self: ::waft_foundation::Handle<Self>,
157 app: &::waft_foundation::App,
158 ) -> &$crate::FocusTraversalPolicyData {
159 &app.get(self).policy
160 }
161
162 fn focus_traversal_policy_data_mut(
163 self: ::waft_foundation::Handle<Self>,
164 app: &mut ::waft_foundation::App,
165 ) -> &mut $crate::FocusTraversalPolicyData {
166 &mut app.get_mut(self).policy
167 }
168 };
169}
170
171#[macro_export]
174macro_rules! directional_focus_traversal_policy_overrides {
175 () => {
176 fn invalidate_scope_data(
177 self: ::waft_foundation::Handle<Self>,
178 app: &mut ::waft_foundation::App,
179 node: ::waft_foundation::Handle<$crate::FocusScopeNode>,
180 ) {
181 $crate::DirectionalFocusTraversalPolicyMixin::invalidate_scope_data(self, app, node);
182 }
183
184 fn changed_scope(
185 self: ::waft_foundation::Handle<Self>,
186 app: &mut ::waft_foundation::App,
187 node: Option<$crate::AnyFocusNode>,
188 old_scope: Option<::waft_foundation::Handle<$crate::FocusScopeNode>>,
189 ) {
190 $crate::DirectionalFocusTraversalPolicyMixin::changed_scope(self, app, node, old_scope);
191 }
192
193 fn find_first_focus_in_direction(
194 self: ::waft_foundation::Handle<Self>,
195 app: &mut ::waft_foundation::App,
196 current_node: $crate::AnyFocusNode,
197 direction: $crate::TraversalDirection,
198 ) -> Option<$crate::AnyFocusNode> {
199 $crate::DirectionalFocusTraversalPolicyMixin::find_first_focus_in_direction(
200 self,
201 app,
202 current_node,
203 direction,
204 )
205 }
206
207 fn in_direction(
208 self: ::waft_foundation::Handle<Self>,
209 app: &mut ::waft_foundation::App,
210 current_node: $crate::AnyFocusNode,
211 direction: $crate::TraversalDirection,
212 ) -> bool {
213 $crate::DirectionalFocusTraversalPolicyMixin::in_direction(
214 self,
215 app,
216 current_node,
217 direction,
218 )
219 }
220 };
221}
222
223pub trait FocusTraversalPolicy: Sized + 'static {
249 fn focus_traversal_policy_data(self: Handle<Self>, app: &App) -> &FocusTraversalPolicyData;
252
253 fn focus_traversal_policy_data_mut(
255 self: Handle<Self>,
256 app: &mut App,
257 ) -> &mut FocusTraversalPolicyData;
258
259 fn as_policy(self: Handle<Self>) -> AnyFocusTraversalPolicy {
262 AnyFocusTraversalPolicy {
263 id: self.id(),
264 vtable: const { &FocusTraversalPolicyVTable::of::<Self>() },
265 }
266 }
267
268 fn request_focus_callback(self: Handle<Self>, app: &App) -> TraversalRequestFocusCallback {
270 Rc::clone(&self.focus_traversal_policy_data(app).request_focus_callback)
271 }
272
273 fn set_request_focus_callback(
275 self: Handle<Self>,
276 app: &mut App,
277 value: TraversalRequestFocusCallback,
278 ) {
279 self.focus_traversal_policy_data_mut(app)
280 .request_focus_callback = value;
281 }
282
283 #[expect(
290 clippy::too_many_arguments,
291 reason = "Dart's `_requestTabTraversalFocus` takes these named arguments"
292 )]
293 fn request_tab_traversal_focus(
294 self: Handle<Self>,
295 app: &mut App,
296 node: AnyFocusNode,
297 alignment_policy: Option<ScrollPositionAlignmentPolicy>,
298 alignment: Option<f64>,
299 duration: Option<Duration>,
300 curve: Option<Rc<dyn Curve>>,
301 forward: bool,
302 ) -> bool {
303 if let Some(scope) = node.as_scope() {
304 if let Some(focused_child) = scope.focused_child(app) {
305 return self.request_tab_traversal_focus(
308 app,
309 focused_child,
310 alignment_policy,
311 alignment,
312 duration,
313 curve,
314 forward,
315 );
316 }
317 let sorted_children = sort_all_descendants(app, scope, scope.as_node());
318 if !sorted_children.is_empty() {
319 let child = if forward {
320 sorted_children[0]
321 } else {
322 sorted_children[sorted_children.len() - 1]
323 };
324 self.request_tab_traversal_focus(
325 app,
326 child,
327 alignment_policy,
328 alignment,
329 duration,
330 curve,
331 forward,
332 );
333 return true;
336 }
337 }
338 let node_had_primary_focus = node.has_primary_focus(app);
339 let request_focus_callback = self.request_focus_callback(app);
340 request_focus_callback(app, node, alignment_policy, alignment, duration, curve);
341 !node_had_primary_focus
342 }
343
344 fn find_first_focus(
360 self: Handle<Self>,
361 app: &mut App,
362 current_node: AnyFocusNode,
363 ignore_current_focus: bool,
364 ) -> Option<AnyFocusNode> {
365 Some(self.find_initial_focus(app, current_node, false, ignore_current_focus))
366 }
367
368 fn find_last_focus(
371 self: Handle<Self>,
372 app: &mut App,
373 current_node: AnyFocusNode,
374 ignore_current_focus: bool,
375 ) -> AnyFocusNode {
376 self.find_initial_focus(app, current_node, true, ignore_current_focus)
377 }
378
379 fn find_initial_focus(
381 self: Handle<Self>,
382 app: &mut App,
383 current_node: AnyFocusNode,
384 from_end: bool,
385 ignore_current_focus: bool,
386 ) -> AnyFocusNode {
387 let scope = current_node
388 .nearest_scope(app)
389 .expect("a node in the tree has a nearest scope");
390 let mut candidate = scope.focused_child(app);
391 if ignore_current_focus
392 || (candidate.is_none() && !scope.as_node().descendants(app).is_empty())
393 {
394 let sorted: Vec<AnyFocusNode> = sort_all_descendants(app, scope, current_node)
395 .into_iter()
396 .filter(|node| can_request_traversal_focus(app, *node))
397 .collect();
398 candidate = if sorted.is_empty() {
399 None
400 } else if from_end {
401 Some(sorted[sorted.len() - 1])
402 } else {
403 Some(sorted[0])
404 };
405 }
406
407 candidate.unwrap_or(current_node)
409 }
410
411 fn find_first_focus_in_direction(
417 self: Handle<Self>,
418 app: &mut App,
419 current_node: AnyFocusNode,
420 direction: TraversalDirection,
421 ) -> Option<AnyFocusNode>;
422
423 fn invalidate_scope_data(self: Handle<Self>, app: &mut App, node: Handle<FocusScopeNode>) {
431 let _ = (app, node);
432 }
433
434 fn changed_scope(
442 self: Handle<Self>,
443 app: &mut App,
444 node: Option<AnyFocusNode>,
445 old_scope: Option<Handle<FocusScopeNode>>,
446 ) {
447 let _ = (app, node, old_scope);
448 }
449
450 fn next(self: Handle<Self>, app: &mut App, current_node: AnyFocusNode) -> bool {
458 self.move_focus(app, current_node, true)
459 }
460
461 fn previous(self: Handle<Self>, app: &mut App, current_node: AnyFocusNode) -> bool {
465 self.move_focus(app, current_node, false)
466 }
467
468 fn in_direction(
473 self: Handle<Self>,
474 app: &mut App,
475 current_node: AnyFocusNode,
476 direction: TraversalDirection,
477 ) -> bool;
478
479 fn sort_descendants(
497 self: Handle<Self>,
498 app: &mut App,
499 descendants: Vec<AnyFocusNode>,
500 current_node: AnyFocusNode,
501 ) -> Vec<AnyFocusNode>;
502
503 fn move_focus(
517 self: Handle<Self>,
518 app: &mut App,
519 current_node: AnyFocusNode,
520 forward: bool,
521 ) -> bool {
522 let nearest_scope = current_node
523 .nearest_scope(app)
524 .expect("a node in the tree has a nearest scope");
525 self.invalidate_scope_data(app, nearest_scope);
526 let mut focused_child = nearest_scope.focused_child(app);
527 if focused_child.is_none() {
528 let first_focus = if forward {
529 self.find_first_focus(app, current_node, false)
530 } else {
531 Some(self.find_last_focus(app, current_node, false))
532 };
533 if let Some(first_focus) = first_focus {
534 return self.request_tab_traversal_focus(
535 app,
536 first_focus,
537 Some(if forward {
538 ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
539 } else {
540 ScrollPositionAlignmentPolicy::KeepVisibleAtStart
541 }),
542 None,
543 None,
544 None,
545 forward,
546 );
547 }
548 }
549 let focused_child = *focused_child.get_or_insert(nearest_scope.as_node());
550 let sorted_nodes = sort_all_descendants(app, nearest_scope, focused_child);
551 debug_assert!(sorted_nodes.contains(&focused_child));
552
553 if forward && Some(&focused_child) == sorted_nodes.last() {
554 match nearest_scope.traversal_edge_behavior(app) {
555 TraversalEdgeBehavior::LeaveFlutterView => {
556 focused_child.unfocus(app, Default::default());
557 return false;
558 }
559 TraversalEdgeBehavior::ParentScope => {
560 let parent_scope = nearest_scope.enclosing_scope(app);
561 let root_scope = FocusManager::instance(app).root_scope(app).handle();
562 if let Some(parent_scope) = parent_scope
563 && parent_scope != root_scope
564 {
565 focused_child.unfocus(app, Default::default());
566 parent_scope.as_node().next_focus(app);
567 return focused_child
569 .enclosing_scope(app)
570 .and_then(|scope| scope.focused_child(app))
571 != Some(focused_child);
572 }
573 return self.request_tab_traversal_focus(
575 app,
576 sorted_nodes[0],
577 Some(ScrollPositionAlignmentPolicy::KeepVisibleAtEnd),
578 None,
579 None,
580 None,
581 forward,
582 );
583 }
584 TraversalEdgeBehavior::ClosedLoop => {
585 return self.request_tab_traversal_focus(
586 app,
587 sorted_nodes[0],
588 Some(ScrollPositionAlignmentPolicy::KeepVisibleAtEnd),
589 None,
590 None,
591 None,
592 forward,
593 );
594 }
595 TraversalEdgeBehavior::Stop => return false,
596 }
597 }
598 if !forward && Some(&focused_child) == sorted_nodes.first() {
599 let last = sorted_nodes[sorted_nodes.len() - 1];
600 match nearest_scope.traversal_edge_behavior(app) {
601 TraversalEdgeBehavior::LeaveFlutterView => {
602 focused_child.unfocus(app, Default::default());
603 return false;
604 }
605 TraversalEdgeBehavior::ParentScope => {
606 let parent_scope = nearest_scope.enclosing_scope(app);
607 let root_scope = FocusManager::instance(app).root_scope(app).handle();
608 if let Some(parent_scope) = parent_scope
609 && parent_scope != root_scope
610 {
611 focused_child.unfocus(app, Default::default());
612 parent_scope.as_node().previous_focus(app);
613 return focused_child
615 .enclosing_scope(app)
616 .and_then(|scope| scope.focused_child(app))
617 != Some(focused_child);
618 }
619 return self.request_tab_traversal_focus(
621 app,
622 last,
623 Some(ScrollPositionAlignmentPolicy::KeepVisibleAtStart),
624 None,
625 None,
626 None,
627 forward,
628 );
629 }
630 TraversalEdgeBehavior::ClosedLoop => {
631 return self.request_tab_traversal_focus(
632 app,
633 last,
634 Some(ScrollPositionAlignmentPolicy::KeepVisibleAtStart),
635 None,
636 None,
637 None,
638 forward,
639 );
640 }
641 TraversalEdgeBehavior::Stop => return false,
642 }
643 }
644
645 let maybe_flipped: Vec<AnyFocusNode> = if forward {
646 sorted_nodes
647 } else {
648 sorted_nodes.into_iter().rev().collect()
649 };
650 let mut previous_node: Option<AnyFocusNode> = None;
651 for node in maybe_flipped {
652 if previous_node == Some(focused_child) {
653 return self.request_tab_traversal_focus(
654 app,
655 node,
656 Some(if forward {
657 ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
658 } else {
659 ScrollPositionAlignmentPolicy::KeepVisibleAtStart
660 }),
661 None,
662 None,
663 None,
664 forward,
665 );
666 }
667 previous_node = Some(node);
668 }
669 false
670 }
671}
672
673fn can_request_traversal_focus(app: &mut App, node: AnyFocusNode) -> bool {
675 node.can_request_focus(app) && !node.skip_traversal(app)
676}
677
678fn get_descendants_without_expanding_scope(app: &App, node: AnyFocusNode) -> Vec<AnyFocusNode> {
680 let mut result = Vec::new();
681 for child in node.children(app) {
682 result.push(child);
683 if child.as_scope().is_none() {
684 result.extend(get_descendants_without_expanding_scope(app, child));
685 }
686 }
687 result
688}
689
690struct FocusTraversalGroupInfo {
693 policy: FocusTraversalPolicyRef,
694 members: Vec<AnyFocusNode>,
695}
696
697fn find_groups(
699 app: &mut App,
700 scope: Handle<FocusScopeNode>,
701 scope_group_node: Option<Handle<FocusTraversalGroupNode>>,
702 current_node: AnyFocusNode,
703) -> HashMap<Option<AnyFocusNode>, FocusTraversalGroupInfo> {
704 let default_policy = match scope_group_node {
705 Some(group) => app.get(group).policy.clone(),
706 None => ReadingOrderTraversalPolicy::new(app).into_erased(),
707 };
708 let mut groups: HashMap<Option<AnyFocusNode>, FocusTraversalGroupInfo> = HashMap::new();
709 for node in get_descendants_without_expanding_scope(app, scope.as_node()) {
710 let group_node = FocusTraversalGroup::get_group_node(app, node);
711 if Some(node) == group_node.map(|group| group.as_node()) {
715 let parent = node.parent(app).expect("a group node in the tree has one");
720 let parent_group = FocusTraversalGroup::get_group_node(app, parent);
721 let key = parent_group.map(|group| group.as_node());
722 let info = groups
723 .entry(key)
724 .or_insert_with(|| FocusTraversalGroupInfo {
725 policy: match parent_group {
726 Some(group) => app.get(group).policy.clone(),
727 None => default_policy.clone(),
728 },
729 members: Vec::new(),
730 });
731 debug_assert!(!info.members.contains(&node));
732 info.members.push(node);
733 continue;
734 }
735 if node == current_node || (node.can_request_focus(app) && !node.skip_traversal(app)) {
741 let key = group_node.map(|group| group.as_node());
742 let policy = match group_node {
743 Some(group) => app.get(group).policy.clone(),
744 None => default_policy.clone(),
745 };
746 let info = groups
747 .entry(key)
748 .or_insert_with(|| FocusTraversalGroupInfo {
749 policy,
750 members: Vec::new(),
751 });
752 debug_assert!(!info.members.contains(&node));
753 info.members.push(node);
754 }
755 }
756 groups
757}
758
759fn sort_all_descendants(
762 app: &mut App,
763 scope: Handle<FocusScopeNode>,
764 current_node: AnyFocusNode,
765) -> Vec<AnyFocusNode> {
766 let scope_group_node = FocusTraversalGroup::get_group_node(app, scope.as_node());
767 let mut groups = find_groups(app, scope, scope_group_node, current_node);
769
770 let keys: Vec<Option<AnyFocusNode>> = groups.keys().copied().collect();
772 for key in keys {
773 let (policy, members) = {
774 let info = groups.get(&key).expect("a key of this map");
775 (info.policy.clone(), info.members.clone())
776 };
777 let sorted_members = policy.sort_descendants(app, members, current_node);
778 let info = groups.get_mut(&key).expect("a key of this map");
779 info.members = sorted_members;
780 }
781
782 let mut sorted_descendants = Vec::new();
785 let scope_group_key = scope_group_node.map(|group| group.as_node());
786 if !groups.is_empty() && groups.contains_key(&scope_group_key) {
787 visit_groups(&groups, scope_group_key, &mut sorted_descendants);
788 }
789
790 let mut kept = Vec::with_capacity(sorted_descendants.len());
793 for node in sorted_descendants {
794 if node == current_node || can_request_traversal_focus(app, node) {
795 kept.push(node);
796 }
797 }
798 kept
799}
800
801fn visit_groups(
803 groups: &HashMap<Option<AnyFocusNode>, FocusTraversalGroupInfo>,
804 key: Option<AnyFocusNode>,
805 sorted_descendants: &mut Vec<AnyFocusNode>,
806) {
807 let Some(info) = groups.get(&key) else { return };
808 for node in &info.members {
809 if groups.contains_key(&Some(*node)) {
810 visit_groups(groups, Some(*node), sorted_descendants);
813 } else {
814 sorted_descendants.push(*node);
815 }
816 }
817}
818
819struct FocusTraversalPolicyVTable {
821 type_name: fn() -> &'static str,
822 find_first_focus: fn(&mut App, HandleId, AnyFocusNode, bool) -> Option<AnyFocusNode>,
823 find_last_focus: fn(&mut App, HandleId, AnyFocusNode, bool) -> AnyFocusNode,
824 find_first_focus_in_direction:
825 fn(&mut App, HandleId, AnyFocusNode, TraversalDirection) -> Option<AnyFocusNode>,
826 invalidate_scope_data: fn(&mut App, HandleId, Handle<FocusScopeNode>),
827 changed_scope: fn(&mut App, HandleId, Option<AnyFocusNode>, Option<Handle<FocusScopeNode>>),
828 next: fn(&mut App, HandleId, AnyFocusNode) -> bool,
829 previous: fn(&mut App, HandleId, AnyFocusNode) -> bool,
830 in_direction: fn(&mut App, HandleId, AnyFocusNode, TraversalDirection) -> bool,
831 sort_descendants: fn(&mut App, HandleId, Vec<AnyFocusNode>, AnyFocusNode) -> Vec<AnyFocusNode>,
832}
833
834fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
836 Handle::from_id(id)
837}
838
839impl FocusTraversalPolicyVTable {
840 const fn of<L: FocusTraversalPolicy>() -> FocusTraversalPolicyVTable {
841 FocusTraversalPolicyVTable {
842 type_name: std::any::type_name::<L>,
843 find_first_focus: |app, id, current_node, ignore| {
844 L::find_first_focus(resolve(id), app, current_node, ignore)
845 },
846 find_last_focus: |app, id, current_node, ignore| {
847 L::find_last_focus(resolve(id), app, current_node, ignore)
848 },
849 find_first_focus_in_direction: |app, id, current_node, direction| {
850 L::find_first_focus_in_direction(resolve(id), app, current_node, direction)
851 },
852 invalidate_scope_data: |app, id, node| L::invalidate_scope_data(resolve(id), app, node),
853 changed_scope: |app, id, node, old_scope| {
854 L::changed_scope(resolve(id), app, node, old_scope)
855 },
856 next: |app, id, current_node| L::next(resolve(id), app, current_node),
857 previous: |app, id, current_node| L::previous(resolve(id), app, current_node),
858 in_direction: |app, id, current_node, direction| {
859 L::in_direction(resolve(id), app, current_node, direction)
860 },
861 sort_descendants: |app, id, descendants, current_node| {
862 L::sort_descendants(resolve(id), app, descendants, current_node)
863 },
864 }
865 }
866}
867
868#[derive(Clone, Copy)]
872pub struct AnyFocusTraversalPolicy {
873 id: HandleId,
874 vtable: &'static FocusTraversalPolicyVTable,
875}
876
877pub type FocusTraversalPolicyRef = Retained<AnyFocusTraversalPolicy>;
879
880waft_foundation::erased_handle!(AnyFocusTraversalPolicy: FocusTraversalPolicy => FocusTraversalPolicy::as_policy);
881
882impl fmt::Debug for AnyFocusTraversalPolicy {
883 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884 write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
885 }
886}
887
888impl AnyFocusTraversalPolicy {
889 pub fn to_string_short(self) -> String {
891 describe_identity(
892 waft_foundation::bare_type_name((self.vtable.type_name)()),
893 self.id.identity_hash(),
894 )
895 }
896
897 pub fn id(self) -> HandleId {
899 self.id
900 }
901
902 pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
904 app.handle::<T>(self.id)
905 }
906
907 pub fn find_first_focus(
909 self,
910 app: &mut App,
911 current_node: AnyFocusNode,
912 ignore_current_focus: bool,
913 ) -> Option<AnyFocusNode> {
914 (self.vtable.find_first_focus)(app, self.id, current_node, ignore_current_focus)
915 }
916
917 pub fn find_last_focus(
919 self,
920 app: &mut App,
921 current_node: AnyFocusNode,
922 ignore_current_focus: bool,
923 ) -> AnyFocusNode {
924 (self.vtable.find_last_focus)(app, self.id, current_node, ignore_current_focus)
925 }
926
927 pub fn find_first_focus_in_direction(
929 self,
930 app: &mut App,
931 current_node: AnyFocusNode,
932 direction: TraversalDirection,
933 ) -> Option<AnyFocusNode> {
934 (self.vtable.find_first_focus_in_direction)(app, self.id, current_node, direction)
935 }
936
937 pub fn invalidate_scope_data(self, app: &mut App, node: Handle<FocusScopeNode>) {
939 (self.vtable.invalidate_scope_data)(app, self.id, node);
940 }
941
942 pub fn changed_scope(
944 self,
945 app: &mut App,
946 node: Option<AnyFocusNode>,
947 old_scope: Option<Handle<FocusScopeNode>>,
948 ) {
949 (self.vtable.changed_scope)(app, self.id, node, old_scope);
950 }
951
952 pub fn next(self, app: &mut App, current_node: AnyFocusNode) -> bool {
954 (self.vtable.next)(app, self.id, current_node)
955 }
956
957 pub fn previous(self, app: &mut App, current_node: AnyFocusNode) -> bool {
959 (self.vtable.previous)(app, self.id, current_node)
960 }
961
962 pub fn in_direction(
964 self,
965 app: &mut App,
966 current_node: AnyFocusNode,
967 direction: TraversalDirection,
968 ) -> bool {
969 (self.vtable.in_direction)(app, self.id, current_node, direction)
970 }
971
972 pub fn sort_descendants(
974 self,
975 app: &mut App,
976 descendants: Vec<AnyFocusNode>,
977 current_node: AnyFocusNode,
978 ) -> Vec<AnyFocusNode> {
979 (self.vtable.sort_descendants)(app, self.id, descendants, current_node)
980 }
981}
982
983#[derive(Clone)]
989struct DirectionalPolicyDataEntry {
990 direction: TraversalDirection,
991 node: FocusNodeRef,
992}
993
994struct DirectionalPolicyData {
996 history: Vec<DirectionalPolicyDataEntry>,
997}
998
999pub struct DirectionalFocusTraversalPolicyMixinData {
1002 policy_data: HashMap<Ref<FocusScopeNode>, DirectionalPolicyData>,
1003}
1004
1005impl DirectionalFocusTraversalPolicyMixinData {
1006 pub fn new() -> DirectionalFocusTraversalPolicyMixinData {
1008 DirectionalFocusTraversalPolicyMixinData {
1009 policy_data: HashMap::new(),
1010 }
1011 }
1012}
1013
1014impl Default for DirectionalFocusTraversalPolicyMixinData {
1015 fn default() -> DirectionalFocusTraversalPolicyMixinData {
1016 DirectionalFocusTraversalPolicyMixinData::new()
1017 }
1018}
1019
1020pub trait DirectionalFocusTraversalPolicyMixin: FocusTraversalPolicy {
1045 fn directional_data(self: Handle<Self>, app: &App)
1047 -> &DirectionalFocusTraversalPolicyMixinData;
1048
1049 fn directional_data_mut(
1051 self: Handle<Self>,
1052 app: &mut App,
1053 ) -> &mut DirectionalFocusTraversalPolicyMixinData;
1054
1055 fn invalidate_scope_data(self: Handle<Self>, app: &mut App, node: Handle<FocusScopeNode>) {
1057 self.directional_data_mut(app).policy_data.remove(&node);
1058 }
1059
1060 fn changed_scope(
1062 self: Handle<Self>,
1063 app: &mut App,
1064 node: Option<AnyFocusNode>,
1065 old_scope: Option<Handle<FocusScopeNode>>,
1066 ) {
1067 if let Some(old_scope) = old_scope
1068 && let Some(data) = self
1069 .directional_data_mut(app)
1070 .policy_data
1071 .get_mut(&old_scope)
1072 {
1073 data.history
1074 .retain(|entry| Some(entry.node.handle()) != node);
1075 }
1076 }
1077
1078 fn find_first_focus_in_direction(
1080 self: Handle<Self>,
1081 app: &mut App,
1082 current_node: AnyFocusNode,
1083 direction: TraversalDirection,
1084 ) -> Option<AnyFocusNode> {
1085 let nodes = current_node
1086 .nearest_scope(app)
1087 .expect("a node in the tree has a nearest scope")
1088 .traversal_descendants(app);
1089 let mut sorted = nodes;
1090 let (vertical, first) = match direction {
1091 TraversalDirection::Up => (true, false),
1093 TraversalDirection::Down => (true, true),
1095 TraversalDirection::Left => (false, false),
1097 TraversalDirection::Right => (false, true),
1099 };
1100 let rects = rects_of(app, &sorted);
1101 sorted.sort_by(|a, b| {
1102 let a = rects[a];
1103 let b = rects[b];
1104 if vertical {
1105 if first {
1106 total_cmp(a.top, b.top)
1107 } else {
1108 total_cmp(b.bottom, a.bottom)
1109 }
1110 } else if first {
1111 total_cmp(a.left, b.left)
1112 } else {
1113 total_cmp(b.right, a.right)
1114 }
1115 });
1116 sorted.first().copied()
1117 }
1118
1119 fn find_next_focus_in_direction(
1121 self: Handle<Self>,
1122 app: &mut App,
1123 focused_child: AnyFocusNode,
1124 traversal_descendants: Vec<AnyFocusNode>,
1125 direction: TraversalDirection,
1126 forward: bool,
1127 ) -> Option<AnyFocusNode> {
1128 let target = focused_child.rect(app);
1129 match direction {
1130 TraversalDirection::Down | TraversalDirection::Up => {
1131 let mut eligible_nodes = sort_and_filter_vertically(
1132 app,
1133 direction,
1134 target,
1135 &traversal_descendants,
1136 forward,
1137 );
1138 if eligible_nodes.is_empty() {
1139 return None;
1140 }
1141 filter_to_scrollable(app, focused_child, &mut eligible_nodes, Axis::Vertical);
1142 if direction == TraversalDirection::Up {
1143 eligible_nodes.reverse();
1144 }
1145 let band =
1147 Rect::from_ltrb(target.left, f64::NEG_INFINITY, target.right, f64::INFINITY);
1148 let in_band = nodes_in_band(app, &eligible_nodes, band);
1149 if !in_band.is_empty() {
1150 let sorted = sort_by_distance_prefer_vertical(app, target.center(), &in_band);
1151 return if forward {
1152 sorted.first().copied()
1153 } else {
1154 sorted.last().copied()
1155 };
1156 }
1157 let sorted = sort_closest_edges_by_distance_prefer_horizontal(
1161 app,
1162 target.center(),
1163 &eligible_nodes,
1164 );
1165 if forward {
1166 sorted.first().copied()
1167 } else {
1168 sorted.last().copied()
1169 }
1170 }
1171 TraversalDirection::Right | TraversalDirection::Left => {
1172 let mut eligible_nodes = sort_and_filter_horizontally(
1173 app,
1174 direction,
1175 target,
1176 &traversal_descendants,
1177 forward,
1178 );
1179 if eligible_nodes.is_empty() {
1180 return None;
1181 }
1182 filter_to_scrollable(app, focused_child, &mut eligible_nodes, Axis::Horizontal);
1183 if direction == TraversalDirection::Left {
1184 eligible_nodes.reverse();
1185 }
1186 let band =
1187 Rect::from_ltrb(f64::NEG_INFINITY, target.top, f64::INFINITY, target.bottom);
1188 let in_band = nodes_in_band(app, &eligible_nodes, band);
1189 if !in_band.is_empty() {
1190 let sorted = sort_by_distance_prefer_horizontal(app, target.center(), &in_band);
1191 return if forward {
1192 sorted.first().copied()
1193 } else {
1194 sorted.last().copied()
1195 };
1196 }
1197 let sorted = sort_closest_edges_by_distance_prefer_vertical(
1201 app,
1202 target.center(),
1203 &eligible_nodes,
1204 );
1205 if forward {
1206 sorted.first().copied()
1207 } else {
1208 sorted.last().copied()
1209 }
1210 }
1211 }
1212 }
1213
1214 fn pop_policy_data_if_needed(
1219 self: Handle<Self>,
1220 app: &mut App,
1221 direction: TraversalDirection,
1222 nearest_scope: Handle<FocusScopeNode>,
1223 group_node: Option<Handle<FocusTraversalGroupNode>>,
1224 ) -> bool {
1225 let history_head = self
1226 .directional_data(app)
1227 .policy_data
1228 .get(&nearest_scope)
1229 .and_then(|data| data.history.first().cloned());
1230 if let Some(head) = history_head
1231 && head.direction != direction
1232 {
1233 let last_node = self
1234 .directional_data(app)
1235 .policy_data
1236 .get(&nearest_scope)
1237 .and_then(|data| data.history.last().cloned())
1238 .expect("a non-empty history has a last entry")
1239 .node;
1240 if last_node.parent(app).is_none() {
1241 FocusTraversalPolicy::invalidate_scope_data(self, app, nearest_scope);
1244 return false;
1245 }
1246
1247 let same_axis = matches!(
1248 (direction, head.direction),
1249 (
1250 TraversalDirection::Down | TraversalDirection::Up,
1251 TraversalDirection::Up | TraversalDirection::Down
1252 ) | (
1253 TraversalDirection::Left | TraversalDirection::Right,
1254 TraversalDirection::Left | TraversalDirection::Right
1255 )
1256 );
1257 if same_axis {
1258 if self.pop_or_invalidate(app, direction, nearest_scope, group_node) {
1259 return true;
1260 }
1261 } else {
1262 FocusTraversalPolicy::invalidate_scope_data(self, app, nearest_scope);
1264 }
1265 }
1266 let history_is_empty = self
1267 .directional_data(app)
1268 .policy_data
1269 .get(&nearest_scope)
1270 .is_some_and(|data| data.history.is_empty());
1271 if history_is_empty {
1272 FocusTraversalPolicy::invalidate_scope_data(self, app, nearest_scope);
1273 }
1274 false
1275 }
1276
1277 fn pop_or_invalidate(
1280 self: Handle<Self>,
1281 app: &mut App,
1282 direction: TraversalDirection,
1283 nearest_scope: Handle<FocusScopeNode>,
1284 group_node: Option<Handle<FocusTraversalGroupNode>>,
1285 ) -> bool {
1286 let last_node = self
1287 .directional_data_mut(app)
1288 .policy_data
1289 .get_mut(&nearest_scope)
1290 .and_then(|data| data.history.pop())
1291 .expect("a non-empty history has a last entry")
1292 .node;
1293 let last_context = last_node
1294 .context(app)
1295 .expect("a focused node has a context");
1296 let focused_context = primary_focus(app)
1297 .expect("a directional traversal starts from the primary focus")
1298 .context(app)
1299 .expect("a focused node has a context");
1300 if Scrollable::maybe_of(app, last_context, None)
1301 != Scrollable::maybe_of(app, focused_context, None)
1302 {
1303 FocusTraversalPolicy::invalidate_scope_data(self, app, nearest_scope);
1304 return false;
1305 }
1306 let alignment_policy = match direction {
1307 TraversalDirection::Up | TraversalDirection::Left => {
1308 ScrollPositionAlignmentPolicy::KeepVisibleAtStart
1309 }
1310 TraversalDirection::Right | TraversalDirection::Down => {
1311 ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
1312 }
1313 };
1314 self.request_focus(app, last_node.handle(), Some(alignment_policy), group_node);
1315 true
1316 }
1317
1318 fn push_policy_data(
1320 self: Handle<Self>,
1321 app: &mut App,
1322 direction: TraversalDirection,
1323 nearest_scope: Handle<FocusScopeNode>,
1324 focused_child: AnyFocusNode,
1325 ) {
1326 let new_entry = DirectionalPolicyDataEntry {
1327 node: focused_child.keep(app),
1328 direction,
1329 };
1330 let nearest_scope = nearest_scope.keep(app);
1331 self.directional_data_mut(app)
1332 .policy_data
1333 .entry(nearest_scope)
1334 .or_insert_with(|| DirectionalPolicyData {
1335 history: Vec::new(),
1336 })
1337 .history
1338 .push(new_entry);
1339 }
1340
1341 fn request_traversal_focus_in_direction(
1343 self: Handle<Self>,
1344 app: &mut App,
1345 current_node: AnyFocusNode,
1346 node: AnyFocusNode,
1347 nearest_scope: Handle<FocusScopeNode>,
1348 direction: TraversalDirection,
1349 group_node: Option<Handle<FocusTraversalGroupNode>>,
1350 ) -> bool {
1351 if let Some(scope) = node.as_scope() {
1352 if let Some(focused_child) = scope.focused_child(app) {
1353 return self.request_traversal_focus_in_direction(
1354 app,
1355 current_node,
1356 focused_child,
1357 scope,
1358 direction,
1359 group_node,
1360 );
1361 }
1362 let first_node =
1363 FocusTraversalPolicy::find_first_focus_in_direction(self, app, node, direction)
1364 .unwrap_or(current_node);
1365 let alignment_policy = match direction {
1366 TraversalDirection::Up | TraversalDirection::Left => {
1367 ScrollPositionAlignmentPolicy::KeepVisibleAtStart
1368 }
1369 TraversalDirection::Right | TraversalDirection::Down => {
1370 ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
1371 }
1372 };
1373 self.request_focus(app, first_node, Some(alignment_policy), group_node);
1374 return true;
1375 }
1376 let _ = nearest_scope;
1377 let node_had_primary_focus = node.has_primary_focus(app);
1378 let alignment_policy = match direction {
1379 TraversalDirection::Up | TraversalDirection::Left => {
1380 ScrollPositionAlignmentPolicy::KeepVisibleAtStart
1381 }
1382 TraversalDirection::Right | TraversalDirection::Down => {
1383 ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
1384 }
1385 };
1386 self.request_focus(app, node, Some(alignment_policy), group_node);
1387 !node_had_primary_focus
1388 }
1389
1390 fn request_focus(
1392 self: Handle<Self>,
1393 app: &mut App,
1394 node: AnyFocusNode,
1395 alignment_policy: Option<ScrollPositionAlignmentPolicy>,
1396 group_node: Option<Handle<FocusTraversalGroupNode>>,
1397 ) {
1398 if let Some(group_node) = group_node {
1399 let node = node.keep(app);
1400 app.get_mut(group_node).last_requested_focus = Some(node);
1401 }
1402 let request_focus_callback = self.request_focus_callback(app);
1403 request_focus_callback(app, node, alignment_policy, None, None, None);
1404 }
1405
1406 fn on_edge_for_direction(
1408 self: Handle<Self>,
1409 app: &mut App,
1410 current_node: AnyFocusNode,
1411 focused_child: AnyFocusNode,
1412 group_node: Option<Handle<FocusTraversalGroupNode>>,
1413 direction: TraversalDirection,
1414 scope: Option<Handle<FocusScopeNode>>,
1415 ) -> bool {
1416 let mut nearest_scope = scope.unwrap_or_else(|| {
1417 current_node
1418 .nearest_scope(app)
1419 .expect("a node in the tree has a nearest scope")
1420 });
1421 let found;
1422 match nearest_scope.directional_traversal_edge_behavior(app) {
1423 TraversalEdgeBehavior::LeaveFlutterView => {
1424 focused_child.unfocus(app, Default::default());
1425 return false;
1426 }
1427 TraversalEdgeBehavior::ParentScope => {
1428 let parent_scope = nearest_scope.enclosing_scope(app);
1429 let root_scope = FocusManager::instance(app).root_scope(app).handle();
1430 if let Some(parent_scope) = parent_scope
1431 && parent_scope != root_scope
1432 {
1433 FocusTraversalPolicy::invalidate_scope_data(self, app, nearest_scope);
1434 nearest_scope = parent_scope;
1435 FocusTraversalPolicy::invalidate_scope_data(self, app, nearest_scope);
1436 let descendants = nearest_scope.traversal_descendants(app);
1437 let next = self.find_next_focus_in_direction(
1438 app,
1439 focused_child,
1440 descendants,
1441 direction,
1442 true,
1443 );
1444 match next {
1445 None => {
1446 return self.on_edge_for_direction(
1447 app,
1448 current_node,
1449 focused_child,
1450 group_node,
1451 direction,
1452 Some(nearest_scope),
1453 );
1454 }
1455 Some(next) => found = Some(next),
1456 }
1457 } else {
1458 let descendants = nearest_scope.traversal_descendants(app);
1459 found = self.find_next_focus_in_direction(
1460 app,
1461 focused_child,
1462 descendants,
1463 direction,
1464 false,
1465 );
1466 }
1467 }
1468 TraversalEdgeBehavior::ClosedLoop => {
1469 let descendants = nearest_scope.traversal_descendants(app);
1470 found = self.find_next_focus_in_direction(
1471 app,
1472 focused_child,
1473 descendants,
1474 direction,
1475 false,
1476 );
1477 }
1478 TraversalEdgeBehavior::Stop => return false,
1479 }
1480 if let Some(found) = found {
1481 return self.request_traversal_focus_in_direction(
1482 app,
1483 current_node,
1484 found,
1485 nearest_scope,
1486 direction,
1487 group_node,
1488 );
1489 }
1490 false
1491 }
1492
1493 fn in_direction(
1506 self: Handle<Self>,
1507 app: &mut App,
1508 current_node: AnyFocusNode,
1509 direction: TraversalDirection,
1510 ) -> bool {
1511 let group_node = FocusTraversalGroup::get_group_node(app, current_node);
1512 let nearest_scope = current_node
1513 .nearest_scope(app)
1514 .expect("a node in the tree has a nearest scope");
1515 let focused_child = nearest_scope.focused_child(app);
1516 let Some(focused_child) = focused_child else {
1517 let first_focus = FocusTraversalPolicy::find_first_focus_in_direction(
1518 self,
1519 app,
1520 current_node,
1521 direction,
1522 )
1523 .unwrap_or(current_node);
1524 let alignment_policy = match direction {
1525 TraversalDirection::Up | TraversalDirection::Left => {
1526 ScrollPositionAlignmentPolicy::KeepVisibleAtStart
1527 }
1528 TraversalDirection::Right | TraversalDirection::Down => {
1529 ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
1530 }
1531 };
1532 self.request_focus(app, first_focus, Some(alignment_policy), group_node);
1533 return true;
1534 };
1535 if self.pop_policy_data_if_needed(app, direction, nearest_scope, group_node) {
1536 return true;
1537 }
1538 let descendants = nearest_scope.traversal_descendants(app);
1539 let found =
1540 self.find_next_focus_in_direction(app, focused_child, descendants, direction, true);
1541 if let Some(found) = found {
1542 self.push_policy_data(app, direction, nearest_scope, focused_child);
1543 return self.request_traversal_focus_in_direction(
1544 app,
1545 current_node,
1546 found,
1547 nearest_scope,
1548 direction,
1549 group_node,
1550 );
1551 }
1552 self.on_edge_for_direction(
1553 app,
1554 current_node,
1555 focused_child,
1556 group_node,
1557 direction,
1558 None,
1559 )
1560 }
1561}
1562
1563fn total_cmp(a: f64, b: f64) -> Ordering {
1565 a.total_cmp(&b)
1566}
1567
1568fn rects_of(app: &App, nodes: &[AnyFocusNode]) -> HashMap<AnyFocusNode, Rect> {
1571 nodes.iter().map(|node| (*node, node.rect(app))).collect()
1572}
1573
1574fn vertical_compare(target: Offset, a: Offset, b: Offset) -> Ordering {
1575 total_cmp((a.dy() - target.dy()).abs(), (b.dy() - target.dy()).abs())
1576}
1577
1578fn horizontal_compare(target: Offset, a: Offset, b: Offset) -> Ordering {
1579 total_cmp((a.dx() - target.dx()).abs(), (b.dx() - target.dx()).abs())
1580}
1581
1582fn sort_by_distance_prefer_vertical(
1585 app: &App,
1586 target: Offset,
1587 nodes: &[AnyFocusNode],
1588) -> Vec<AnyFocusNode> {
1589 let rects = rects_of(app, nodes);
1590 let mut sorted = nodes.to_vec();
1591 sorted.sort_by(|node_a, node_b| {
1592 let a = rects[node_a].center();
1593 let b = rects[node_b].center();
1594 match vertical_compare(target, a, b) {
1595 Ordering::Equal => horizontal_compare(target, a, b),
1596 vertical => vertical,
1597 }
1598 });
1599 sorted
1600}
1601
1602fn sort_by_distance_prefer_horizontal(
1605 app: &App,
1606 target: Offset,
1607 nodes: &[AnyFocusNode],
1608) -> Vec<AnyFocusNode> {
1609 let rects = rects_of(app, nodes);
1610 let mut sorted = nodes.to_vec();
1611 sorted.sort_by(|node_a, node_b| {
1612 let a = rects[node_a].center();
1613 let b = rects[node_b].center();
1614 match horizontal_compare(target, a, b) {
1615 Ordering::Equal => vertical_compare(target, a, b),
1616 horizontal => horizontal,
1617 }
1618 });
1619 sorted
1620}
1621
1622fn vertical_compare_closest_edge(target: Offset, a: Rect, b: Rect) -> Ordering {
1623 let a_coord = if (a.top - target.dy()).abs() < (a.bottom - target.dy()).abs() {
1625 a.top
1626 } else {
1627 a.bottom
1628 };
1629 let b_coord = if (b.top - target.dy()).abs() < (b.bottom - target.dy()).abs() {
1630 b.top
1631 } else {
1632 b.bottom
1633 };
1634 total_cmp((a_coord - target.dy()).abs(), (b_coord - target.dy()).abs())
1635}
1636
1637fn horizontal_compare_closest_edge(target: Offset, a: Rect, b: Rect) -> Ordering {
1638 let a_coord = if (a.left - target.dx()).abs() < (a.right - target.dx()).abs() {
1640 a.left
1641 } else {
1642 a.right
1643 };
1644 let b_coord = if (b.left - target.dx()).abs() < (b.right - target.dx()).abs() {
1645 b.left
1646 } else {
1647 b.right
1648 };
1649 total_cmp((a_coord - target.dx()).abs(), (b_coord - target.dx()).abs())
1650}
1651
1652fn sort_closest_edges_by_distance_prefer_horizontal(
1655 app: &App,
1656 target: Offset,
1657 nodes: &[AnyFocusNode],
1658) -> Vec<AnyFocusNode> {
1659 let rects = rects_of(app, nodes);
1660 let mut sorted = nodes.to_vec();
1661 sorted.sort_by(|node_a, node_b| {
1662 let a = rects[node_a];
1663 let b = rects[node_b];
1664 match horizontal_compare_closest_edge(target, a, b) {
1665 Ordering::Equal => vertical_compare(target, a.center(), b.center()),
1667 horizontal => horizontal,
1668 }
1669 });
1670 sorted
1671}
1672
1673fn sort_closest_edges_by_distance_prefer_vertical(
1676 app: &App,
1677 target: Offset,
1678 nodes: &[AnyFocusNode],
1679) -> Vec<AnyFocusNode> {
1680 let rects = rects_of(app, nodes);
1681 let mut sorted = nodes.to_vec();
1682 sorted.sort_by(|node_a, node_b| {
1683 let a = rects[node_a];
1684 let b = rects[node_b];
1685 match vertical_compare_closest_edge(target, a, b) {
1686 Ordering::Equal => horizontal_compare(target, a.center(), b.center()),
1688 vertical => vertical,
1689 }
1690 });
1691 sorted
1692}
1693
1694fn sort_and_filter_horizontally(
1701 app: &App,
1702 direction: TraversalDirection,
1703 target: Rect,
1704 nodes: &[AnyFocusNode],
1705 forward: bool,
1706) -> Vec<AnyFocusNode> {
1707 debug_assert!(direction == TraversalDirection::Left || direction == TraversalDirection::Right);
1708 let rects = rects_of(app, nodes);
1709 let mut sorted: Vec<AnyFocusNode> = nodes
1710 .iter()
1711 .copied()
1712 .filter(|node| {
1713 let rect = rects[node];
1714 rect != target
1715 && match direction {
1716 TraversalDirection::Left => {
1717 if forward {
1718 rect.center().dx() <= target.left
1719 } else {
1720 rect.center().dx() >= target.left
1721 }
1722 }
1723 TraversalDirection::Right => {
1724 if forward {
1725 rect.center().dx() >= target.right
1726 } else {
1727 rect.center().dx() <= target.right
1728 }
1729 }
1730 TraversalDirection::Up | TraversalDirection::Down => {
1731 panic!("Invalid direction {direction:?}")
1732 }
1733 }
1734 })
1735 .collect();
1736 sorted.sort_by(|a, b| total_cmp(rects[a].center().dx(), rects[b].center().dx()));
1738 sorted
1739}
1740
1741fn filter_to_scrollable(
1746 app: &mut App,
1747 focused_child: AnyFocusNode,
1748 eligible_nodes: &mut Vec<AnyFocusNode>,
1749 axis: Axis,
1750) {
1751 let context = focused_child
1752 .context(app)
1753 .expect("a focused node has a context");
1754 let Some(focused_scrollable) = Scrollable::maybe_of(app, context, Some(axis)) else {
1755 return;
1756 };
1757 let mut filtered = Vec::new();
1758 for node in eligible_nodes.iter().copied() {
1759 let context = node.context(app).expect("a traversable node has a context");
1760 if Scrollable::maybe_of(app, context, Some(axis)) == Some(focused_scrollable) {
1761 filtered.push(node);
1762 }
1763 }
1764 if !filtered.is_empty() {
1765 *eligible_nodes = filtered;
1766 }
1767}
1768
1769fn sort_and_filter_vertically(
1773 app: &App,
1774 direction: TraversalDirection,
1775 target: Rect,
1776 nodes: &[AnyFocusNode],
1777 forward: bool,
1778) -> Vec<AnyFocusNode> {
1779 debug_assert!(direction == TraversalDirection::Up || direction == TraversalDirection::Down);
1780 let rects = rects_of(app, nodes);
1781 let mut sorted: Vec<AnyFocusNode> = nodes
1782 .iter()
1783 .copied()
1784 .filter(|node| {
1785 let rect = rects[node];
1786 rect != target
1787 && match direction {
1788 TraversalDirection::Up => {
1789 if forward {
1790 rect.center().dy() <= target.top
1791 } else {
1792 rect.center().dy() >= target.top
1793 }
1794 }
1795 TraversalDirection::Down => {
1796 if forward {
1797 rect.center().dy() >= target.bottom
1798 } else {
1799 rect.center().dy() <= target.bottom
1800 }
1801 }
1802 TraversalDirection::Left | TraversalDirection::Right => {
1803 panic!("Invalid direction {direction:?}")
1804 }
1805 }
1806 })
1807 .collect();
1808 sorted.sort_by(|a, b| total_cmp(rects[a].center().dy(), rects[b].center().dy()));
1809 sorted
1810}
1811
1812fn nodes_in_band(app: &App, nodes: &[AnyFocusNode], band: Rect) -> Vec<AnyFocusNode> {
1814 nodes
1815 .iter()
1816 .copied()
1817 .filter(|node| !node.rect(app).intersect(band).is_empty())
1818 .collect()
1819}
1820
1821pub struct WidgetOrderTraversalPolicy {
1841 policy: FocusTraversalPolicyData,
1842 directional: DirectionalFocusTraversalPolicyMixinData,
1843}
1844
1845impl WidgetOrderTraversalPolicy {
1846 pub fn new(app: &mut App) -> Ref<WidgetOrderTraversalPolicy> {
1852 app.create(WidgetOrderTraversalPolicy {
1853 policy: FocusTraversalPolicyData::new(),
1854 directional: DirectionalFocusTraversalPolicyMixinData::new(),
1855 })
1856 }
1857}
1858
1859impl FocusTraversalPolicy for WidgetOrderTraversalPolicy {
1860 crate::focus_traversal_policy_accessors!();
1861 crate::directional_focus_traversal_policy_overrides!();
1862
1863 fn sort_descendants(
1864 self: Handle<Self>,
1865 _app: &mut App,
1866 descendants: Vec<AnyFocusNode>,
1867 _current_node: AnyFocusNode,
1868 ) -> Vec<AnyFocusNode> {
1869 descendants
1870 }
1871}
1872
1873impl DirectionalFocusTraversalPolicyMixin for WidgetOrderTraversalPolicy {
1874 fn directional_data(
1875 self: Handle<Self>,
1876 app: &App,
1877 ) -> &DirectionalFocusTraversalPolicyMixinData {
1878 &app.get(self).directional
1879 }
1880
1881 fn directional_data_mut(
1882 self: Handle<Self>,
1883 app: &mut App,
1884 ) -> &mut DirectionalFocusTraversalPolicyMixinData {
1885 &mut app.get_mut(self).directional
1886 }
1887}
1888
1889#[derive(Clone)]
1897struct ReadingOrderSortData {
1898 directionality: Option<TextDirection>,
1899 rect: Rect,
1900 node: AnyFocusNode,
1901 directional_ancestors: Vec<BuildContext>,
1904}
1905
1906impl ReadingOrderSortData {
1907 fn new(app: &App, node: AnyFocusNode) -> ReadingOrderSortData {
1908 let context = node.context(app).expect("a traversable node has a context");
1909 ReadingOrderSortData {
1910 directionality: find_directionality(app, context),
1911 rect: node.rect(app),
1912 node,
1913 directional_ancestors: directionality_ancestors(app, context),
1914 }
1915 }
1916
1917 fn common_directionality_of(app: &App, list: &[ReadingOrderSortData]) -> Option<TextDirection> {
1919 let mut common: Option<Vec<BuildContext>> = None;
1920 for member in list {
1921 common = Some(match common {
1922 None => member.directional_ancestors.clone(),
1923 Some(common) => common
1924 .into_iter()
1925 .filter(|ancestor| member.directional_ancestors.contains(ancestor))
1926 .collect(),
1927 });
1928 }
1929 let common = common.expect("the list is never empty");
1930 if common.is_empty() {
1931 return list[0].directionality;
1935 }
1936 let closest = list[0]
1939 .directional_ancestors
1940 .iter()
1941 .find(|ancestor| common.contains(ancestor))
1942 .expect("the intersection is a subset of the first member's ancestors");
1943 Some(text_direction_of(app, *closest))
1944 }
1945
1946 fn sort_with_directionality(list: &mut [ReadingOrderSortData], directionality: TextDirection) {
1947 list.sort_by(|a, b| match directionality {
1948 TextDirection::Ltr => total_cmp(a.rect.left, b.rect.left),
1949 TextDirection::Rtl => total_cmp(b.rect.right, a.rect.right),
1950 });
1951 }
1952}
1953
1954fn find_directionality(app: &App, context: BuildContext) -> Option<TextDirection> {
1956 context
1957 .get_inherited_widget_of_exact_type::<Directionality>(app)
1958 .map(|directionality| directionality.text_direction)
1959}
1960
1961fn text_direction_of(app: &App, element: BuildContext) -> TextDirection {
1963 downcast_widget::<Directionality>(&**element.widget(app))
1964 .expect("the element of a Directionality holds one")
1965 .text_direction
1966}
1967
1968fn directionality_ancestors(app: &App, context: BuildContext) -> Vec<BuildContext> {
1970 let mut result = Vec::new();
1971 let mut directionality_element =
1972 context.get_element_for_inherited_widget_of_exact_type::<Directionality>(app);
1973 while let Some(element) = directionality_element {
1974 result.push(element);
1975 directionality_element = get_ancestor(app, element, 1).and_then(|ancestor| {
1976 ancestor.get_element_for_inherited_widget_of_exact_type::<Directionality>(app)
1977 });
1978 }
1979 result
1980}
1981
1982struct ReadingOrderDirectionalGroupData {
1985 members: Vec<ReadingOrderSortData>,
1986}
1987
1988impl ReadingOrderDirectionalGroupData {
1989 fn directionality(&self) -> Option<TextDirection> {
1990 self.members[0].directionality
1991 }
1992
1993 fn rect(&self) -> Rect {
1994 let mut rect: Option<Rect> = None;
1995 for member in &self.members {
1996 rect = Some(match rect {
1997 None => member.rect,
1998 Some(rect) => rect.expand_to_include(member.rect),
1999 });
2000 }
2001 rect.expect("a group always has a member")
2002 }
2003
2004 fn sort_with_directionality(
2005 list: &mut [ReadingOrderDirectionalGroupData],
2006 directionality: TextDirection,
2007 ) {
2008 list.sort_by(|a, b| match directionality {
2009 TextDirection::Ltr => total_cmp(a.rect().left, b.rect().left),
2010 TextDirection::Rtl => total_cmp(b.rect().right, a.rect().right),
2011 });
2012 }
2013}
2014
2015pub struct ReadingOrderTraversalPolicy {
2029 policy: FocusTraversalPolicyData,
2030 directional: DirectionalFocusTraversalPolicyMixinData,
2031}
2032
2033impl ReadingOrderTraversalPolicy {
2034 pub fn new(app: &mut App) -> Ref<ReadingOrderTraversalPolicy> {
2039 app.create(ReadingOrderTraversalPolicy {
2040 policy: FocusTraversalPolicyData::new(),
2041 directional: DirectionalFocusTraversalPolicyMixinData::new(),
2042 })
2043 }
2044
2045 pub fn sort(app: &App, nodes: Vec<AnyFocusNode>) -> Vec<AnyFocusNode> {
2047 if nodes.len() <= 1 {
2048 return nodes;
2049 }
2050
2051 let mut unplaced: Vec<ReadingOrderSortData> = nodes
2052 .iter()
2053 .map(|node| ReadingOrderSortData::new(app, *node))
2054 .collect();
2055
2056 let mut sorted_list = Vec::new();
2057
2058 while !unplaced.is_empty() {
2065 let current = ReadingOrderTraversalPolicy::pick_next(app, &mut unplaced);
2066 sorted_list.push(unplaced[current].node);
2067 unplaced.remove(current);
2068 }
2069 sorted_list
2070 }
2071
2072 fn collect_directionality_groups(
2076 candidates: &[ReadingOrderSortData],
2077 ) -> Vec<ReadingOrderDirectionalGroupData> {
2078 let mut current_direction = candidates[0].directionality;
2079 let mut current_group: Vec<ReadingOrderSortData> = Vec::new();
2080 let mut result: Vec<ReadingOrderDirectionalGroupData> = Vec::new();
2081 for candidate in candidates {
2083 if candidate.directionality == current_direction {
2084 current_group.push(candidate.clone());
2085 continue;
2086 }
2087 current_direction = candidate.directionality;
2088 result.push(ReadingOrderDirectionalGroupData {
2089 members: std::mem::take(&mut current_group),
2090 });
2091 current_group.push(candidate.clone());
2092 }
2093 if !current_group.is_empty() {
2094 result.push(ReadingOrderDirectionalGroupData {
2095 members: current_group,
2096 });
2097 }
2098 for band_group in result.iter_mut() {
2100 if band_group.members.len() == 1 {
2101 continue; }
2103 let directionality = band_group
2104 .directionality()
2105 .expect("a member with no directionality has no group to sort");
2106 ReadingOrderSortData::sort_with_directionality(&mut band_group.members, directionality);
2107 }
2108 result
2109 }
2110
2111 fn pick_next(app: &App, candidates: &mut [ReadingOrderSortData]) -> usize {
2114 candidates.sort_by(|a, b| total_cmp(a.rect.top, b.rect.top));
2116 let topmost = candidates[0].clone();
2117
2118 let band = Rect::from_ltrb(
2120 f64::NEG_INFINITY,
2121 topmost.rect.top,
2122 f64::INFINITY,
2123 topmost.rect.bottom,
2124 );
2125 let mut in_band_of_top: Vec<ReadingOrderSortData> = candidates
2126 .iter()
2127 .filter(|item| !item.rect.intersect(band).is_empty())
2128 .cloned()
2129 .collect();
2130 debug_assert!(topmost.rect.is_empty() || !in_band_of_top.is_empty());
2132
2133 if in_band_of_top.len() <= 1 {
2135 return 0;
2136 }
2137
2138 let nearest_common_directionality =
2144 ReadingOrderSortData::common_directionality_of(app, &in_band_of_top)
2145 .expect("a node in the tree has a directionality");
2146
2147 ReadingOrderSortData::sort_with_directionality(
2152 &mut in_band_of_top,
2153 nearest_common_directionality,
2154 );
2155
2156 let mut band_groups =
2158 ReadingOrderTraversalPolicy::collect_directionality_groups(&in_band_of_top);
2159 let picked = if band_groups.len() == 1 {
2160 band_groups[0].members[0].node
2163 } else {
2164 ReadingOrderDirectionalGroupData::sort_with_directionality(
2166 &mut band_groups,
2167 nearest_common_directionality,
2168 );
2169 band_groups[0].members[0].node
2170 };
2171 candidates
2172 .iter()
2173 .position(|candidate| candidate.node == picked)
2174 .expect("the picked node came from the candidates")
2175 }
2176}
2177
2178impl FocusTraversalPolicy for ReadingOrderTraversalPolicy {
2179 crate::focus_traversal_policy_accessors!();
2180 crate::directional_focus_traversal_policy_overrides!();
2181
2182 fn sort_descendants(
2185 self: Handle<Self>,
2186 app: &mut App,
2187 descendants: Vec<AnyFocusNode>,
2188 _current_node: AnyFocusNode,
2189 ) -> Vec<AnyFocusNode> {
2190 ReadingOrderTraversalPolicy::sort(app, descendants)
2191 }
2192}
2193
2194impl DirectionalFocusTraversalPolicyMixin for ReadingOrderTraversalPolicy {
2195 fn directional_data(
2196 self: Handle<Self>,
2197 app: &App,
2198 ) -> &DirectionalFocusTraversalPolicyMixinData {
2199 &app.get(self).directional
2200 }
2201
2202 fn directional_data_mut(
2203 self: Handle<Self>,
2204 app: &mut App,
2205 ) -> &mut DirectionalFocusTraversalPolicyMixinData {
2206 &mut app.get_mut(self).directional
2207 }
2208}
2209
2210pub trait FocusOrder: Debug {
2234 fn as_any(&self) -> &dyn Any;
2237
2238 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
2240 let _ = properties;
2241 }
2242
2243 fn to_string_short(&self) -> String {
2245 describe_identity(
2246 waft_foundation::bare_type_name(std::any::type_name::<Self>()),
2247 self as *const Self as *const () as usize as u64,
2248 )
2249 }
2250
2251 fn diagnostics_node(&self, name: Option<String>) -> DiagnosticableNode {
2253 let mut builder = DiagnosticPropertiesBuilder::new();
2254 self.debug_fill_properties(&mut builder);
2255 DiagnosticableNode::from_parts(name, self.to_string_short(), builder)
2256 }
2257
2258 fn diagnostic_string(&self) -> String {
2260 self.diagnostics_node(None)
2261 .with_style(waft_foundation::DiagnosticsTreeStyle::SingleLine)
2262 .to_string_with(None, waft_foundation::DiagnosticLevel::Info)
2263 }
2264
2265 fn compare_to(&self, other: &dyn FocusOrder) -> Ordering {
2275 debug_assert!(
2276 self.as_any().type_id() == other.as_any().type_id(),
2277 "The sorting algorithm must not compare incomparable keys, since they don't know \
2278 how to order themselves relative to each other. Comparing {self:?} with {other:?}"
2279 );
2280 self.do_compare(other)
2281 }
2282
2283 fn do_compare(&self, other: &dyn FocusOrder) -> Ordering;
2292}
2293
2294pub type FocusOrderRef = Rc<dyn FocusOrder>;
2296
2297#[derive(Clone, Copy, Debug, PartialEq)]
2303pub struct NumericFocusOrder {
2304 pub order: f64,
2311}
2312
2313impl NumericFocusOrder {
2314 pub fn new(order: f64) -> NumericFocusOrder {
2316 NumericFocusOrder { order }
2317 }
2318}
2319
2320impl FocusOrder for NumericFocusOrder {
2321 fn as_any(&self) -> &dyn Any {
2322 self
2323 }
2324
2325 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
2326 properties.add(DoubleProperty::new("order", self.order));
2327 }
2328
2329 fn do_compare(&self, other: &dyn FocusOrder) -> Ordering {
2330 let other = other
2331 .as_any()
2332 .downcast_ref::<NumericFocusOrder>()
2333 .expect("compare_to checked the type");
2334 total_cmp(self.order, other.order)
2335 }
2336}
2337
2338#[derive(Clone, Debug, PartialEq, Eq)]
2346pub struct LexicalFocusOrder {
2347 pub order: String,
2355}
2356
2357impl LexicalFocusOrder {
2358 pub fn new(order: impl Into<String>) -> LexicalFocusOrder {
2360 LexicalFocusOrder {
2361 order: order.into(),
2362 }
2363 }
2364}
2365
2366impl FocusOrder for LexicalFocusOrder {
2367 fn as_any(&self) -> &dyn Any {
2368 self
2369 }
2370
2371 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
2372 properties.add(StringProperty::new("order", self.order.clone()));
2373 }
2374
2375 fn do_compare(&self, other: &dyn FocusOrder) -> Ordering {
2376 let other = other
2377 .as_any()
2378 .downcast_ref::<LexicalFocusOrder>()
2379 .expect("compare_to checked the type");
2380 self.order.cmp(&other.order)
2381 }
2382}
2383
2384struct OrderedFocusInfo {
2386 node: AnyFocusNode,
2387 order: FocusOrderRef,
2388}
2389
2390pub struct OrderedTraversalPolicy {
2407 policy: FocusTraversalPolicyData,
2408 directional: DirectionalFocusTraversalPolicyMixinData,
2409 secondary: Option<FocusTraversalPolicyRef>,
2410}
2411
2412impl OrderedTraversalPolicy {
2413 pub fn new(app: &mut App) -> Ref<OrderedTraversalPolicy> {
2418 app.create(OrderedTraversalPolicy {
2419 policy: FocusTraversalPolicyData::new(),
2420 directional: DirectionalFocusTraversalPolicyMixinData::new(),
2421 secondary: None,
2422 })
2423 }
2424
2425 pub fn secondary(self: Handle<Self>, app: &App) -> Option<AnyFocusTraversalPolicy> {
2435 app.get(self).secondary.handle()
2436 }
2437
2438 pub fn set_secondary(self: Handle<Self>, app: &mut App, secondary: FocusTraversalPolicyRef) {
2440 app.get_mut(self).secondary = Some(secondary);
2441 }
2442}
2443
2444impl FocusTraversalPolicy for OrderedTraversalPolicy {
2445 crate::focus_traversal_policy_accessors!();
2446 crate::directional_focus_traversal_policy_overrides!();
2447
2448 fn sort_descendants(
2449 self: Handle<Self>,
2450 app: &mut App,
2451 descendants: Vec<AnyFocusNode>,
2452 current_node: AnyFocusNode,
2453 ) -> Vec<AnyFocusNode> {
2454 let secondary_policy = match app.get(self).secondary.clone() {
2455 Some(secondary) => secondary,
2456 None => ReadingOrderTraversalPolicy::new(app).into_erased(),
2457 };
2458 let sorted_descendants = secondary_policy.sort_descendants(app, descendants, current_node);
2459 let mut unordered: Vec<AnyFocusNode> = Vec::new();
2460 let mut ordered: Vec<OrderedFocusInfo> = Vec::new();
2461 for node in sorted_descendants {
2462 let context = node.context(app).expect("a traversable node has a context");
2463 match FocusTraversalOrder::maybe_of(app, context) {
2464 Some(order) => ordered.push(OrderedFocusInfo { node, order }),
2465 None => unordered.push(node),
2466 }
2467 }
2468 ordered.sort_by(|a, b| {
2469 debug_assert!(
2470 a.order.as_any().type_id() == b.order.as_any().type_id(),
2471 "When sorting nodes for determining focus order, the order ({:?}) of node \
2472 {:?}, isn't the same type as the order ({:?}) of {:?}. Incompatible order \
2473 types can't be compared. Use a FocusTraversalGroup to group similar orders \
2474 together.",
2475 a.order,
2476 a.node,
2477 b.order,
2478 b.node
2479 );
2480 a.order.compare_to(&*b.order)
2481 });
2482 ordered
2483 .into_iter()
2484 .map(|info| info.node)
2485 .chain(unordered)
2486 .collect()
2487 }
2488}
2489
2490impl DirectionalFocusTraversalPolicyMixin for OrderedTraversalPolicy {
2491 fn directional_data(
2492 self: Handle<Self>,
2493 app: &App,
2494 ) -> &DirectionalFocusTraversalPolicyMixinData {
2495 &app.get(self).directional
2496 }
2497
2498 fn directional_data_mut(
2499 self: Handle<Self>,
2500 app: &mut App,
2501 ) -> &mut DirectionalFocusTraversalPolicyMixinData {
2502 &mut app.get_mut(self).directional
2503 }
2504}
2505
2506#[derive(Debug)]
2514pub struct FocusTraversalOrder {
2515 pub key: Option<KeyRef>,
2517
2518 pub order: FocusOrderRef,
2520
2521 pub child: WidgetRef,
2523}
2524
2525impl FocusTraversalOrder {
2526 #[cfg_attr(debug_assertions, track_caller)]
2528 pub fn new<K>(order: FocusOrderRef, child: impl IntoWidget<K>) -> FocusTraversalOrder {
2529 FocusTraversalOrder {
2530 key: None,
2531 order,
2532 child: child.into_widget(),
2533 }
2534 }
2535
2536 pub fn key(mut self, key: KeyRef) -> FocusTraversalOrder {
2538 self.key = Some(key);
2539 self
2540 }
2541
2542 pub fn of(app: &App, context: BuildContext) -> FocusOrderRef {
2549 FocusTraversalOrder::maybe_of(app, context).expect(
2550 "FocusTraversalOrder.of() was called with a context that does not contain a \
2551 FocusTraversalOrder widget.",
2552 )
2553 }
2554
2555 pub fn maybe_of(app: &App, context: BuildContext) -> Option<FocusOrderRef> {
2562 context
2563 .get_inherited_widget_of_exact_type::<FocusTraversalOrder>(app)
2564 .map(|marker| Rc::clone(&marker.order))
2565 }
2566}
2567
2568impl InheritedWidget for FocusTraversalOrder {
2569 fn key(&self) -> Option<&KeyRef> {
2570 self.key.as_ref()
2571 }
2572
2573 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2574 properties.add(DiagnosticsProperty::<String>::new(
2575 "order",
2576 Some(self.order.diagnostic_string()),
2577 ));
2578 }
2579
2580 fn child(&self) -> &WidgetRef {
2581 &self.child
2582 }
2583
2584 fn update_should_notify(&self, _old_widget: &FocusTraversalOrder) -> bool {
2587 false
2588 }
2589}
2590
2591pub struct FocusTraversalGroupNode {
2600 change_notifier: ChangeNotifierData,
2601 focus_node: FocusNodeData,
2602 pub policy: FocusTraversalPolicyRef,
2604 pub last_requested_focus: Option<FocusNodeRef>,
2606}
2607
2608impl FocusTraversalGroupNode {
2609 pub fn new(app: &mut App, policy: FocusTraversalPolicyRef) -> Ref<FocusTraversalGroupNode> {
2611 app.create(FocusTraversalGroupNode {
2612 change_notifier: ChangeNotifierData::new(),
2613 focus_node: FocusNodeData::new(),
2614 policy,
2615 last_requested_focus: None,
2616 })
2617 }
2618}
2619
2620impl ChangeNotifier for FocusTraversalGroupNode {
2621 fn change_notifier_data(&self) -> &ChangeNotifierData {
2622 &self.change_notifier
2623 }
2624
2625 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2626 &mut self.change_notifier
2627 }
2628}
2629
2630impl FocusNodeLeaf for FocusTraversalGroupNode {
2631 crate::focus_node_accessors!();
2632}
2633
2634pub struct FocusTraversalGroup {
2649 pub key: Option<KeyRef>,
2651
2652 pub policy: Option<FocusTraversalPolicyRef>,
2666
2667 pub descendants_are_focusable: bool,
2669
2670 pub descendants_are_traversable: bool,
2672
2673 pub on_focus_node_created: Option<ValueChanged<AnyFocusNode>>,
2675
2676 pub parent_node: Option<FocusNodeRef>,
2688
2689 pub child: WidgetRef,
2691}
2692
2693impl FocusTraversalGroup {
2694 #[cfg_attr(debug_assertions, track_caller)]
2696 pub fn new<K>(child: impl IntoWidget<K>) -> FocusTraversalGroup {
2697 FocusTraversalGroup {
2698 key: None,
2699 policy: None,
2700 descendants_are_focusable: true,
2701 descendants_are_traversable: true,
2702 on_focus_node_created: None,
2703 parent_node: None,
2704 child: child.into_widget(),
2705 }
2706 }
2707
2708 pub fn key(mut self, key: KeyRef) -> FocusTraversalGroup {
2710 self.key = Some(key);
2711 self
2712 }
2713
2714 pub fn policy(mut self, policy: FocusTraversalPolicyRef) -> FocusTraversalGroup {
2716 self.policy = Some(policy);
2717 self
2718 }
2719
2720 pub fn descendants_are_focusable(
2722 mut self,
2723 descendants_are_focusable: bool,
2724 ) -> FocusTraversalGroup {
2725 self.descendants_are_focusable = descendants_are_focusable;
2726 self
2727 }
2728
2729 pub fn descendants_are_traversable(
2731 mut self,
2732 descendants_are_traversable: bool,
2733 ) -> FocusTraversalGroup {
2734 self.descendants_are_traversable = descendants_are_traversable;
2735 self
2736 }
2737
2738 pub fn on_focus_node_created(
2740 mut self,
2741 on_focus_node_created: impl Fn(&mut App, AnyFocusNode) + 'static,
2742 ) -> FocusTraversalGroup {
2743 self.on_focus_node_created = Some(Rc::new(on_focus_node_created));
2744 self
2745 }
2746
2747 pub fn parent_node(mut self, parent_node: FocusNodeRef) -> FocusTraversalGroup {
2749 self.parent_node = Some(parent_node);
2750 self
2751 }
2752
2753 pub fn maybe_of_node(app: &App, node: AnyFocusNode) -> Option<AnyFocusTraversalPolicy> {
2766 FocusTraversalGroup::get_group_node(app, node).map(|group| app.get(group).policy.handle())
2767 }
2768
2769 fn get_group_node(app: &App, node: AnyFocusNode) -> Option<Handle<FocusTraversalGroupNode>> {
2771 let mut node = node;
2772 while node.parent(app).is_some() {
2773 node.context(app)?;
2774 if let Some(group) = node.downcast::<FocusTraversalGroupNode>(app) {
2775 return Some(group);
2776 }
2777 node = node.parent(app).expect("checked by the loop condition");
2778 }
2779 None
2780 }
2781
2782 pub fn of(app: &mut App, context: BuildContext) -> AnyFocusTraversalPolicy {
2803 FocusTraversalGroup::maybe_of(app, context).expect(
2804 "Unable to find a Focus or FocusScope widget in the given context, or the FocusNode \
2805 from the widget that was found is not associated with a FocusTraversalPolicy.\n\
2806 FocusTraversalGroup.of() was called with a context that does not contain a Focus \
2807 or FocusScope widget, or there was no FocusTraversalPolicy in effect.",
2808 )
2809 }
2810
2811 pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<AnyFocusTraversalPolicy> {
2821 let node = Focus::maybe_of(app, context, true, false)?;
2822 FocusTraversalGroup::maybe_of_node(app, node)
2823 }
2824}
2825
2826impl fmt::Debug for FocusTraversalGroup {
2827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2828 f.debug_struct("FocusTraversalGroup")
2829 .field("policy", &self.policy)
2830 .finish_non_exhaustive()
2831 }
2832}
2833
2834impl StatefulWidget for FocusTraversalGroup {
2835 type State = FocusTraversalGroupState;
2836
2837 fn key(&self) -> Option<&KeyRef> {
2838 self.key.as_ref()
2839 }
2840
2841 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2842 properties.add(DiagnosticsProperty::<String>::new(
2843 "policy",
2844 self.policy.as_ref().map(|policy| policy.to_string_short()),
2845 ));
2846 }
2847
2848 fn create_state(&self) -> FocusTraversalGroupState {
2849 FocusTraversalGroupState {
2850 state: StateData::new(),
2851 focus_node: None,
2852 }
2853 }
2854}
2855
2856pub struct FocusTraversalGroupState {
2858 state: StateData<FocusTraversalGroup>,
2859 focus_node: Option<Ref<FocusTraversalGroupNode>>,
2860}
2861
2862impl FocusTraversalGroupState {
2863 pub fn focus_node(self: Handle<Self>, app: &App) -> Handle<FocusTraversalGroupNode> {
2868 app.get(self)
2869 .focus_node
2870 .handle()
2871 .expect("created in init_state")
2872 }
2873
2874 fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
2875 let focus_node = self.focus_node(app);
2876 let primary_focus = FocusManager::instance(app).primary_focus(app);
2877 let Some(last_requested_focus) = app.get(focus_node).last_requested_focus.handle() else {
2878 return;
2879 };
2880
2881 if primary_focus != Some(last_requested_focus) {
2882 let policy = app.get(focus_node).policy.handle();
2883 let mut scope = primary_focus.and_then(|node| node.nearest_scope(app));
2884 while let Some(current) = scope {
2885 policy.invalidate_scope_data(app, current);
2886 scope = current.enclosing_scope(app);
2887 }
2888 app.get_mut(focus_node).last_requested_focus = None;
2889 }
2890 }
2891}
2892
2893impl State for FocusTraversalGroupState {
2894 type Widget = FocusTraversalGroup;
2895 crate::state_accessors!();
2896
2897 fn init_state(self: Handle<Self>, app: &mut App) {
2898 let policy = match self.widget(app).policy.clone() {
2899 Some(policy) => policy,
2900 None => ReadingOrderTraversalPolicy::new(app).into_erased(),
2901 };
2902 let focus_node = FocusTraversalGroupNode::new(app, policy);
2903 focus_node.set_debug_label(app, Some("FocusTraversalGroup".to_string()));
2904 app.get_mut(self).focus_node = Some(focus_node.clone());
2905 let listener =
2906 Listener::handle_method(self, FocusTraversalGroupState::handle_focus_changed);
2907 FocusManager::instance(app).add_listener(app, listener);
2908 if let Some(on_focus_node_created) = self.widget(app).on_focus_node_created.clone() {
2909 on_focus_node_created(app, focus_node.as_node());
2910 }
2911 }
2912
2913 fn dispose(self: Handle<Self>, app: &mut App) {
2914 let listener =
2915 Listener::handle_method(self, FocusTraversalGroupState::handle_focus_changed);
2916 FocusManager::instance(app).remove_listener(app, &listener);
2917 let focus_node = self.focus_node(app);
2918 focus_node.dispose(app);
2919 }
2920
2921 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusTraversalGroup) {
2922 if old_widget.policy != self.widget(app).policy
2923 && let Some(policy) = self.widget(app).policy.clone()
2924 {
2925 let focus_node = self.focus_node(app);
2926 app.get_mut(focus_node).policy = policy;
2927 }
2928 }
2929
2930 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2931 let focus_node: FocusNodeRef = app
2932 .get(self)
2933 .focus_node
2934 .as_ref()
2935 .expect("created in init_state")
2936 .erase();
2937 let widget = self.widget(app);
2938 let (parent_node, descendants_are_focusable, descendants_are_traversable, child) = (
2939 widget.parent_node.clone(),
2940 widget.descendants_are_focusable,
2941 widget.descendants_are_traversable,
2942 widget.child.clone(),
2943 );
2944 let mut focus = Focus::new(child)
2945 .focus_node(focus_node)
2946 .can_request_focus(false)
2947 .skip_traversal(true)
2948 .include_semantics(false)
2949 .descendants_are_focusable(descendants_are_focusable)
2950 .descendants_are_traversable(descendants_are_traversable);
2951 if let Some(parent_node) = parent_node {
2952 focus = focus.parent_node(parent_node);
2953 }
2954 focus.into_widget()
2955 }
2956}
2957
2958pub struct RequestFocusIntent {
2964 pub request_focus_callback: TraversalRequestFocusCallback,
2967
2968 pub focus_node: FocusNodeRef,
2970}
2971
2972impl RequestFocusIntent {
2973 pub fn new(focus_node: FocusNodeRef) -> RequestFocusIntent {
2975 RequestFocusIntent {
2976 request_focus_callback: Rc::new(default_traversal_request_focus_callback),
2977 focus_node,
2978 }
2979 }
2980
2981 pub fn request_focus_callback(
2983 mut self,
2984 request_focus_callback: TraversalRequestFocusCallback,
2985 ) -> RequestFocusIntent {
2986 self.request_focus_callback = request_focus_callback;
2987 self
2988 }
2989}
2990
2991impl fmt::Debug for RequestFocusIntent {
2992 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2993 f.debug_struct("RequestFocusIntent")
2994 .field("focusNode", &self.focus_node)
2995 .finish_non_exhaustive()
2996 }
2997}
2998
2999impl Intent for RequestFocusIntent {
3000 fn as_any(&self) -> &dyn Any {
3001 self
3002 }
3003}
3004
3005pub struct RequestFocusAction {
3016 action: ActionData,
3017}
3018
3019impl RequestFocusAction {
3020 pub fn new(app: &mut App) -> Ref<RequestFocusAction> {
3022 app.create(RequestFocusAction {
3023 action: ActionData::new(),
3024 })
3025 }
3026}
3027
3028impl Action for RequestFocusAction {
3029 type Intent = RequestFocusIntent;
3030 crate::action_accessors!();
3031
3032 fn invoke(
3033 self: Handle<Self>,
3034 app: &mut App,
3035 intent: &RequestFocusIntent,
3036 ) -> Option<Rc<dyn Any>> {
3037 let callback = Rc::clone(&intent.request_focus_callback);
3038 callback(app, intent.focus_node.handle(), None, None, None, None);
3039 None
3040 }
3041}
3042
3043#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3046pub struct NextFocusIntent;
3047
3048impl NextFocusIntent {
3049 pub const fn new() -> NextFocusIntent {
3051 NextFocusIntent
3052 }
3053}
3054
3055impl Intent for NextFocusIntent {
3056 fn as_any(&self) -> &dyn Any {
3057 self
3058 }
3059}
3060
3061pub struct NextFocusAction {
3066 action: ActionData,
3067}
3068
3069impl NextFocusAction {
3070 pub fn new(app: &mut App) -> Ref<NextFocusAction> {
3072 app.create(NextFocusAction {
3073 action: ActionData::new(),
3074 })
3075 }
3076}
3077
3078impl Action for NextFocusAction {
3079 type Intent = NextFocusIntent;
3080 crate::action_accessors!();
3081
3082 fn invoke(self: Handle<Self>, app: &mut App, _intent: &NextFocusIntent) -> Option<Rc<dyn Any>> {
3089 let focused = primary_focus(app)
3090 .expect("an action is invoked with a primary focus")
3091 .next_focus(app);
3092 Some(Rc::new(focused))
3093 }
3094
3095 fn to_key_event_result(
3096 self: Handle<Self>,
3097 _app: &mut App,
3098 _intent: &NextFocusIntent,
3099 invoke_result: Option<&Rc<dyn Any>>,
3100 ) -> KeyEventResult {
3101 if invoke_result_is_true(invoke_result) {
3102 KeyEventResult::Handled
3103 } else {
3104 KeyEventResult::SkipRemainingHandlers
3105 }
3106 }
3107}
3108
3109fn invoke_result_is_true(invoke_result: Option<&Rc<dyn Any>>) -> bool {
3111 invoke_result
3112 .and_then(|result| result.downcast_ref::<bool>())
3113 .copied()
3114 .unwrap_or(false)
3115}
3116
3117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3120pub struct PreviousFocusIntent;
3121
3122impl PreviousFocusIntent {
3123 pub const fn new() -> PreviousFocusIntent {
3125 PreviousFocusIntent
3126 }
3127}
3128
3129impl Intent for PreviousFocusIntent {
3130 fn as_any(&self) -> &dyn Any {
3131 self
3132 }
3133}
3134
3135pub struct PreviousFocusAction {
3140 action: ActionData,
3141}
3142
3143impl PreviousFocusAction {
3144 pub fn new(app: &mut App) -> Ref<PreviousFocusAction> {
3146 app.create(PreviousFocusAction {
3147 action: ActionData::new(),
3148 })
3149 }
3150}
3151
3152impl Action for PreviousFocusAction {
3153 type Intent = PreviousFocusIntent;
3154 crate::action_accessors!();
3155
3156 fn invoke(
3163 self: Handle<Self>,
3164 app: &mut App,
3165 _intent: &PreviousFocusIntent,
3166 ) -> Option<Rc<dyn Any>> {
3167 let focused = primary_focus(app)
3168 .expect("an action is invoked with a primary focus")
3169 .previous_focus(app);
3170 Some(Rc::new(focused))
3171 }
3172
3173 fn to_key_event_result(
3174 self: Handle<Self>,
3175 _app: &mut App,
3176 _intent: &PreviousFocusIntent,
3177 invoke_result: Option<&Rc<dyn Any>>,
3178 ) -> KeyEventResult {
3179 if invoke_result_is_true(invoke_result) {
3180 KeyEventResult::Handled
3181 } else {
3182 KeyEventResult::SkipRemainingHandlers
3183 }
3184 }
3185}
3186
3187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3193pub struct DirectionalFocusIntent {
3194 pub direction: TraversalDirection,
3197
3198 pub ignore_text_fields: bool,
3203}
3204
3205impl DirectionalFocusIntent {
3206 pub fn new(direction: TraversalDirection) -> DirectionalFocusIntent {
3208 DirectionalFocusIntent {
3209 direction,
3210 ignore_text_fields: true,
3211 }
3212 }
3213
3214 pub fn ignore_text_fields(mut self, ignore_text_fields: bool) -> DirectionalFocusIntent {
3216 self.ignore_text_fields = ignore_text_fields;
3217 self
3218 }
3219}
3220
3221impl Intent for DirectionalFocusIntent {
3222 fn as_any(&self) -> &dyn Any {
3223 self
3224 }
3225
3226 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
3227 properties.add(EnumProperty::new("direction", self.direction));
3228 }
3229}
3230
3231pub struct DirectionalFocusAction {
3237 action: ActionData,
3238 is_for_text_field: bool,
3240}
3241
3242impl DirectionalFocusAction {
3243 pub fn new(app: &mut App) -> Ref<DirectionalFocusAction> {
3245 app.create(DirectionalFocusAction {
3246 action: ActionData::new(),
3247 is_for_text_field: false,
3248 })
3249 }
3250
3251 pub fn for_text_field(app: &mut App) -> Ref<DirectionalFocusAction> {
3254 app.create(DirectionalFocusAction {
3255 action: ActionData::new(),
3256 is_for_text_field: true,
3257 })
3258 }
3259}
3260
3261impl Action for DirectionalFocusAction {
3262 type Intent = DirectionalFocusIntent;
3263 crate::action_accessors!();
3264
3265 fn invoke(
3266 self: Handle<Self>,
3267 app: &mut App,
3268 intent: &DirectionalFocusIntent,
3269 ) -> Option<Rc<dyn Any>> {
3270 if !intent.ignore_text_fields || !app.get(self).is_for_text_field {
3271 primary_focus(app)
3272 .expect("an action is invoked with a primary focus")
3273 .focus_in_direction(app, intent.direction);
3274 }
3275 None
3276 }
3277}
3278
3279#[derive(Debug)]
3293pub struct ExcludeFocusTraversal {
3294 pub key: Option<KeyRef>,
3296
3297 pub excluding: bool,
3303
3304 pub child: WidgetRef,
3306}
3307
3308impl ExcludeFocusTraversal {
3309 #[cfg_attr(debug_assertions, track_caller)]
3311 pub fn new<K>(child: impl IntoWidget<K>) -> ExcludeFocusTraversal {
3312 ExcludeFocusTraversal {
3313 key: None,
3314 excluding: true,
3315 child: child.into_widget(),
3316 }
3317 }
3318
3319 pub fn key(mut self, key: KeyRef) -> ExcludeFocusTraversal {
3321 self.key = Some(key);
3322 self
3323 }
3324
3325 pub fn excluding(mut self, excluding: bool) -> ExcludeFocusTraversal {
3327 self.excluding = excluding;
3328 self
3329 }
3330}
3331
3332impl StatelessWidget for ExcludeFocusTraversal {
3333 fn key(&self) -> Option<&KeyRef> {
3334 self.key.as_ref()
3335 }
3336
3337 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
3338 Focus::new(self.child.clone())
3339 .can_request_focus(false)
3340 .skip_traversal(true)
3341 .include_semantics(false)
3342 .descendants_are_traversable(!self.excluding)
3343 .into_widget()
3344 }
3345}
3346
3347#[cfg(test)]
3348mod tests {
3349 use waft_embedder::{Rect, TextDirection};
3350
3351 use super::*;
3352 use crate::testing::{WidgetTester, test_widgets};
3353 use crate::widgets::basic::{Directionality, Positioned, SizedBox, Stack};
3354
3355 fn placed(label: &'static str, rect: Rect) -> WidgetRef {
3357 Positioned::from_rect(rect, Focus::new(SizedBox::expand()).debug_label(label)).into_widget()
3358 }
3359
3360 fn mount_group(
3362 tester: &mut WidgetTester,
3363 policy: FocusTraversalPolicyRef,
3364 children: Vec<WidgetRef>,
3365 ) {
3366 tester.pump_widget(Directionality::new(
3367 TextDirection::Ltr,
3368 FocusTraversalGroup::new(Stack::new().children(children)).policy(policy),
3369 ));
3370 }
3371
3372 fn node(app: &mut App, label: &str) -> AnyFocusNode {
3373 let root = FocusManager::instance(app).root_scope(app).as_node();
3374 root.descendants(app)
3375 .into_iter()
3376 .find(|node| node.debug_label(app).as_deref() == Some(label))
3377 .expect("a node with that label")
3378 }
3379
3380 fn label(app: &App, node: AnyFocusNode) -> String {
3381 node.debug_label(app)
3382 .unwrap_or_else(|| "<unlabelled>".to_string())
3383 }
3384
3385 fn order(app: &mut App, start: &str, steps: usize, forward: bool) -> Vec<String> {
3388 let start = node(app, start);
3389 start.request_focus(app, None);
3390 app.drain_microtasks();
3391 let mut seen = Vec::new();
3392 for _ in 0..steps {
3393 let focus = primary_focus(app).expect("a primary focus");
3394 if forward {
3395 focus.next_focus(app);
3396 } else {
3397 focus.previous_focus(app);
3398 }
3399 app.drain_microtasks();
3400 let focus = primary_focus(app).expect("a primary focus");
3401 seen.push(label(app, focus));
3402 }
3403 seen
3404 }
3405
3406 fn scattered() -> Vec<WidgetRef> {
3409 vec![
3410 placed("x", Rect::from_ltwh(100.0, 0.0, 50.0, 20.0)),
3411 placed("y", Rect::from_ltwh(0.0, 0.0, 50.0, 20.0)),
3412 placed("z", Rect::from_ltwh(0.0, 100.0, 50.0, 20.0)),
3413 ]
3414 }
3415
3416 #[test]
3417 fn widget_order_traverses_in_widget_creation_order() {
3418 test_widgets(|tester| {
3419 let mut app = tester.cell.borrow_mut();
3420 let policy = WidgetOrderTraversalPolicy::new(&mut app).into_erased();
3421 drop(app);
3422 mount_group(tester, policy, scattered());
3423 let mut app = tester.cell.borrow_mut();
3424
3425 assert_eq!(order(&mut app, "x", 3, true), ["y", "z", "x"]);
3426 assert_eq!(order(&mut app, "x", 3, false), ["z", "y", "x"]);
3427 });
3428 }
3429
3430 #[test]
3431 fn reading_order_traverses_top_to_bottom_in_the_reading_direction() {
3432 test_widgets(|tester| {
3433 let mut app = tester.cell.borrow_mut();
3434 let policy = ReadingOrderTraversalPolicy::new(&mut app).into_erased();
3435 drop(app);
3436 mount_group(tester, policy, scattered());
3437 let mut app = tester.cell.borrow_mut();
3438
3439 assert_eq!(order(&mut app, "y", 3, true), ["x", "z", "y"]);
3441 assert_eq!(order(&mut app, "y", 3, false), ["z", "x", "y"]);
3442 });
3443 }
3444
3445 #[test]
3446 fn reading_order_follows_the_directionality_in_force() {
3447 test_widgets(|tester| {
3448 let mut app = tester.cell.borrow_mut();
3449 let policy = ReadingOrderTraversalPolicy::new(&mut app).into_erased();
3450 drop(app);
3451 tester.pump_widget(
3452 Directionality::new(
3453 TextDirection::Rtl,
3454 FocusTraversalGroup::new(Stack::new().children(scattered())).policy(policy),
3455 )
3456 .into_widget(),
3457 );
3458 let mut app = tester.cell.borrow_mut();
3459
3460 assert_eq!(order(&mut app, "x", 3, true), ["y", "z", "x"]);
3462 });
3463 }
3464
3465 #[test]
3466 fn ordered_traversal_follows_the_numeric_order() {
3467 test_widgets(|tester| {
3468 let mut app = tester.cell.borrow_mut();
3469 let policy = OrderedTraversalPolicy::new(&mut app).into_erased();
3470 let ordered = |label: &'static str, rect: Rect, order: f64| -> WidgetRef {
3471 FocusTraversalOrder::new(
3472 Rc::new(NumericFocusOrder::new(order)),
3473 Positioned::from_rect(rect, Focus::new(SizedBox::expand()).debug_label(label)),
3474 )
3475 .into_widget()
3476 };
3477 drop(app);
3478 mount_group(
3479 tester,
3480 policy,
3481 vec![
3482 ordered("x", Rect::from_ltwh(100.0, 0.0, 50.0, 20.0), 3.0),
3483 ordered("y", Rect::from_ltwh(0.0, 0.0, 50.0, 20.0), 1.0),
3484 ordered("z", Rect::from_ltwh(0.0, 100.0, 50.0, 20.0), 2.0),
3485 ],
3486 );
3487 let mut app = tester.cell.borrow_mut();
3488
3489 assert_eq!(order(&mut app, "y", 3, true), ["z", "x", "y"]);
3490 });
3491 }
3492
3493 #[test]
3494 fn ordered_traversal_follows_the_lexical_order() {
3495 test_widgets(|tester| {
3496 let mut app = tester.cell.borrow_mut();
3497 let policy = OrderedTraversalPolicy::new(&mut app).into_erased();
3498 let ordered = |label: &'static str, rect: Rect, order: &'static str| -> WidgetRef {
3499 FocusTraversalOrder::new(
3500 Rc::new(LexicalFocusOrder::new(order)),
3501 Positioned::from_rect(rect, Focus::new(SizedBox::expand()).debug_label(label)),
3502 )
3503 .into_widget()
3504 };
3505 drop(app);
3506 mount_group(
3507 tester,
3508 policy,
3509 vec![
3510 ordered("x", Rect::from_ltwh(100.0, 0.0, 50.0, 20.0), "c"),
3511 ordered("y", Rect::from_ltwh(0.0, 0.0, 50.0, 20.0), "a"),
3512 ordered("z", Rect::from_ltwh(0.0, 100.0, 50.0, 20.0), "b"),
3513 ],
3514 );
3515 let mut app = tester.cell.borrow_mut();
3516
3517 assert_eq!(order(&mut app, "y", 3, true), ["z", "x", "y"]);
3518 });
3519 }
3520
3521 #[test]
3522 fn the_traversal_edge_behavior_decides_what_happens_at_the_last_node() {
3523 test_widgets(|tester| {
3524 let mut app = tester.cell.borrow_mut();
3525 let policy = WidgetOrderTraversalPolicy::new(&mut app).into_erased();
3526 drop(app);
3527 mount_group(tester, policy, scattered());
3528 let mut app = tester.cell.borrow_mut();
3529
3530 assert_eq!(order(&mut app, "z", 1, true), ["x"]);
3532
3533 let scope = node(&mut app, "z")
3534 .nearest_scope(&mut app)
3535 .expect("a node in the tree has a nearest scope");
3536 scope.set_traversal_edge_behavior(&mut app, TraversalEdgeBehavior::Stop);
3537 assert_eq!(order(&mut app, "z", 1, true), ["z"]);
3538 assert_eq!(order(&mut app, "x", 1, false), ["x"]);
3539
3540 scope.set_traversal_edge_behavior(&mut app, TraversalEdgeBehavior::LeaveFlutterView);
3541 let last = node(&mut app, "z");
3542 last.request_focus(&mut app, None);
3543 app.drain_microtasks();
3544 assert!(!last.next_focus(&mut app));
3545 app.drain_microtasks();
3546 assert_eq!(primary_focus(&mut app), Some(scope.as_node()));
3547 });
3548 }
3549
3550 #[test]
3551 fn directional_focus_moves_to_the_neighbour_in_that_direction() {
3552 test_widgets(|tester| {
3553 let mut app = tester.cell.borrow_mut();
3554 let policy = ReadingOrderTraversalPolicy::new(&mut app).into_erased();
3555 drop(app);
3556 mount_group(tester, policy, scattered());
3557 let mut app = tester.cell.borrow_mut();
3558
3559 let y = node(&mut app, "y");
3560 y.request_focus(&mut app, None);
3561 app.drain_microtasks();
3562
3563 assert!(y.focus_in_direction(&mut app, TraversalDirection::Right));
3564 app.drain_microtasks();
3565 let focus = primary_focus(&mut app).expect("a primary focus");
3566 assert_eq!(label(&app, focus), "x");
3567
3568 let x = node(&mut app, "x");
3569 assert!(x.focus_in_direction(&mut app, TraversalDirection::Left));
3570 app.drain_microtasks();
3571 let focus = primary_focus(&mut app).expect("a primary focus");
3572 assert_eq!(label(&app, focus), "y");
3573
3574 let y = node(&mut app, "y");
3575 assert!(y.focus_in_direction(&mut app, TraversalDirection::Down));
3576 app.drain_microtasks();
3577 let focus = primary_focus(&mut app).expect("a primary focus");
3578 assert_eq!(label(&app, focus), "z");
3579 });
3580 }
3581
3582 #[test]
3583 fn a_shortcut_bound_to_next_focus_moves_the_focus() {
3584 test_widgets(|tester| {
3585 use std::any::TypeId;
3586 use std::collections::HashMap;
3587 use std::time::Duration;
3588
3589 use waft_services::{
3590 HardwareKeyboard, KeyDownEvent, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey,
3591 };
3592
3593 use crate::widgets::actions::{ActionRef, Actions};
3594 use crate::widgets::shortcuts::{ShortcutMap, Shortcuts, SingleActivator};
3595
3596 let mut app = tester.cell.borrow_mut();
3597 let policy = WidgetOrderTraversalPolicy::new(&mut app).into_erased();
3598 let action: ActionRef = NextFocusAction::new(&mut app).into_erased();
3599 let shortcuts: ShortcutMap = vec![(
3600 Rc::new(SingleActivator::new(LogicalKeyboardKey::TAB)),
3601 Rc::new(NextFocusIntent::new()),
3602 )];
3603 drop(app);
3604 tester.pump_widget(
3605 Directionality::new(
3606 TextDirection::Ltr,
3607 Shortcuts::new(
3608 shortcuts,
3609 Actions::new(
3610 HashMap::from([(TypeId::of::<NextFocusIntent>(), action)]),
3611 FocusTraversalGroup::new(Stack::new().children(scattered()))
3612 .policy(policy),
3613 ),
3614 ),
3615 )
3616 .into_widget(),
3617 );
3618 let mut app = tester.cell.borrow_mut();
3619
3620 node(&mut app, "x").request_focus(&mut app, None);
3621 app.drain_microtasks();
3622
3623 let tab = KeyEvent::Down(KeyDownEvent::new(
3624 PhysicalKeyboardKey::TAB,
3625 LogicalKeyboardKey::TAB,
3626 Duration::ZERO,
3627 ));
3628 let keyboard = HardwareKeyboard::instance(&mut app);
3629 assert!(keyboard.handle_key_event(&mut app, &tab));
3630 app.drain_microtasks();
3631 let focus = primary_focus(&mut app).expect("a primary focus");
3632 assert_eq!(label(&app, focus), "y");
3633 });
3634 }
3635
3636 #[test]
3637 fn exclude_focus_traversal_keeps_its_descendants_out_of_the_order() {
3638 test_widgets(|tester| {
3639 let mut app = tester.cell.borrow_mut();
3640 let policy = WidgetOrderTraversalPolicy::new(&mut app).into_erased();
3641 drop(app);
3642 mount_group(
3643 tester,
3644 policy,
3645 vec![
3646 placed("x", Rect::from_ltwh(100.0, 0.0, 50.0, 20.0)),
3647 Positioned::from_rect(
3648 Rect::from_ltwh(0.0, 0.0, 50.0, 20.0),
3649 ExcludeFocusTraversal::new(Focus::new(SizedBox::expand()).debug_label("y")),
3650 )
3651 .into_widget(),
3652 placed("z", Rect::from_ltwh(0.0, 100.0, 50.0, 20.0)),
3653 ],
3654 );
3655 let mut app = tester.cell.borrow_mut();
3656
3657 assert_eq!(order(&mut app, "x", 2, true), ["z", "x"]);
3658 });
3659 }
3660}