Skip to main content

waft_widgets/widgets/
focus_traversal.rs

1//! Flutter counterpart: `widgets/focus_traversal.dart`.
2//!
3//! The focus traversal policies: [`FocusTraversalPolicy`] and its three implementations,
4//! [`FocusTraversalGroup`], which imposes one on a subtree, and the intents and actions that
5//! move the focus.
6//!
7//! `TraversalEdgeBehavior` is declared in [`focus_manager`](crate::widgets::focus_manager),
8//! where `FocusScopeNode` reads it.
9
10use 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
41/// Returns the ancestor `count` levels above the given `context`.
42///
43/// [`BuildContext`] doesn't have a parent accessor, but it can be simulated with
44/// [`visit_ancestor_elements`](crate::AnyElement::visit_ancestor_elements). This is needed
45/// because `get_element_for_inherited_widget_of_exact_type` will return the context itself if
46/// it happens to be of the correct type.
47fn 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
61/// Signature for the callback that's called when a traversal policy requests focus.
62///
63/// Dart's four named optional arguments (`alignmentPolicy`, `alignment`, `duration`, `curve`)
64/// are positional here.
65pub 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
76/// The default value for [`FocusTraversalPolicyData::request_focus_callback`].
77///
78/// Requests focus from `node` and ensures the node is visible by calling
79/// [`Scrollable::ensure_visible`].
80pub 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/// A direction along either the horizontal or vertical axes.
101///
102/// This is used by [`DirectionalFocusTraversalPolicyMixin`], and
103/// [`AnyFocusNode::focus_in_direction`] to indicate which direction to look in for the next
104/// focus.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub enum TraversalDirection {
107    /// Indicates a direction above the currently focused widget.
108    Up,
109
110    /// Indicates a direction to the right of the currently focused widget.
111    ///
112    /// This direction is unaffected by the [`Directionality`] of the current context.
113    Right,
114
115    /// Indicates a direction below the currently focused widget.
116    Down,
117
118    /// Indicates a direction to the left of the currently focused widget.
119    ///
120    /// This direction is unaffected by the [`Directionality`] of the current context.
121    Left,
122}
123
124// ---------------------------------------------------------------------------------------------
125// FocusTraversalPolicy
126
127/// The fields Dart's `FocusTraversalPolicy` declares; every policy carries this bag under the
128/// field `policy`.
129pub struct FocusTraversalPolicyData {
130    /// The callback used to move the focus from one focus node to another when traversing them
131    /// using a keyboard. By default it requests focus on the next node.
132    pub request_focus_callback: TraversalRequestFocusCallback,
133}
134
135impl FocusTraversalPolicyData {
136    /// The bag of a freshly created policy: Dart's constructor defaults.
137    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/// The accessors [`FocusTraversalPolicy`] asks for, for a struct whose bag is the field
151/// `policy`.
152#[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/// The four members [`DirectionalFocusTraversalPolicyMixin`] overrides, forwarded from a
172/// policy's `impl FocusTraversalPolicy` the way Dart's mixin linearization would.
173#[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
223/// Determines how focusable widgets are traversed within a [`FocusTraversalGroup`].
224///
225/// The focus traversal policy is what determines which widget is "next", "previous", or in a
226/// direction from the widget associated with the currently focused `FocusNode` (usually a
227/// `Focus` widget).
228///
229/// One of the pre-defined implementations may be used, or define a custom policy to create a
230/// unique focus order.
231///
232/// When defining your own, implement [`sort_descendants`](Self::sort_descendants) to provide the
233/// order in which you would like the descendants to be traversed.
234///
235/// See also:
236///
237///  * `FocusNode`, for a description of the focus system.
238///  * [`FocusTraversalGroup`], a widget that groups together and imposes a traversal policy on
239///    the `Focus` nodes below it in the widget hierarchy.
240///  * [`WidgetOrderTraversalPolicy`], a policy that relies on the widget creation order to
241///    describe the order of traversal.
242///  * [`ReadingOrderTraversalPolicy`], a policy that describes the order as the natural "reading
243///    order" for the current [`Directionality`].
244///  * [`OrderedTraversalPolicy`], a policy that describes the order explicitly using
245///    [`FocusTraversalOrder`] widgets.
246///  * [`DirectionalFocusTraversalPolicyMixin`], a trait that implements focus traversal in a
247///    direction.
248pub trait FocusTraversalPolicy: Sized + 'static {
249    /// Dart's `FocusTraversalPolicy` fields, held under the field `policy`
250    /// ([`focus_traversal_policy_accessors!`](crate::focus_traversal_policy_accessors)).
251    fn focus_traversal_policy_data(self: Handle<Self>, app: &App) -> &FocusTraversalPolicyData;
252
253    /// See [`focus_traversal_policy_data`](Self::focus_traversal_policy_data).
254    fn focus_traversal_policy_data_mut(
255        self: Handle<Self>,
256        app: &mut App,
257    ) -> &mut FocusTraversalPolicyData;
258
259    /// This policy as the erased [`AnyFocusTraversalPolicy`] — what to pass where a Dart API
260    /// takes a `FocusTraversalPolicy`.
261    fn as_policy(self: Handle<Self>) -> AnyFocusTraversalPolicy {
262        AnyFocusTraversalPolicy {
263            id: self.id(),
264            vtable: const { &FocusTraversalPolicyVTable::of::<Self>() },
265        }
266    }
267
268    /// See [`FocusTraversalPolicyData::request_focus_callback`].
269    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    /// See [`FocusTraversalPolicyData::request_focus_callback`].
274    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    /// Request focus on a focus node as a result of a tab traversal.
284    ///
285    /// If the `node` is a `FocusScopeNode`, this method will recursively find the next focus
286    /// from its descendants until it finds a regular `FocusNode`.
287    ///
288    /// Returns true if this method focused a new focus node.
289    #[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                // Can't stop here as the `focused_child` may be a focus scope node without a
306                // first focus. The first focus will be picked in the next iteration.
307                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                // Regardless of what `request_tab_traversal_focus` returns, a first focus has
334                // been picked.
335                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    /// Returns the node that should receive focus if focus is traversing forwards, and there is
345    /// no current focus.
346    ///
347    /// The node returned is the node that should receive focus if focus is traversing forwards
348    /// (i.e. with [`next`](Self::next)), and there is no current focus in the nearest
349    /// `FocusScopeNode` that `current_node` belongs to.
350    ///
351    /// If `ignore_current_focus` is false, this function returns the scope's focused child, if
352    /// set, on the nearest scope of the `current_node`, otherwise, returns the first node from
353    /// [`sort_descendants`](Self::sort_descendants), or the given `current_node` if there are no
354    /// descendants.
355    ///
356    /// If `ignore_current_focus` is true, then the algorithm returns the first node from
357    /// [`sort_descendants`](Self::sort_descendants), or the given `current_node` if there are no
358    /// descendants.
359    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    /// Returns the node that should receive focus if focus is traversing backwards, and there
369    /// is no current focus.
370    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    /// Dart's `FocusTraversalPolicy._findInitialFocus`.
380    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        // If we still didn't find any candidate, use the current node as a fallback.
408        candidate.unwrap_or(current_node)
409    }
410
411    /// Returns the first node in the given `direction` that should receive focus if there is no
412    /// current focus in the scope to which the `current_node` belongs.
413    ///
414    /// This is typically used by [`in_direction`](Self::in_direction) to determine which node to
415    /// focus if it is called when no node is currently focused.
416    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    /// Clears the data associated with the given `FocusScopeNode` for this object.
424    ///
425    /// This is used to indicate that the focus policy has changed its mode, and so any cached
426    /// policy data should be invalidated. For example, changing the direction in which focus is
427    /// moving, or changing from directional to next/previous navigation modes.
428    ///
429    /// The default implementation does nothing.
430    fn invalidate_scope_data(self: Handle<Self>, app: &mut App, node: Handle<FocusScopeNode>) {
431        let _ = (app, node);
432    }
433
434    /// This is called whenever the given `node` is re-parented into a new scope, so that the
435    /// policy has a chance to update or invalidate any cached data that it maintains per scope
436    /// about the node.
437    ///
438    /// The `old_scope` is the previous scope that this node belonged to, if any.
439    ///
440    /// The default implementation does nothing.
441    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    /// Focuses the next widget in the focus scope that contains the given `current_node`.
451    ///
452    /// This determines what the next node to receive focus should be by inspecting the node
453    /// tree, and then calling [`AnyFocusNode::request_focus`] on the node that has been
454    /// selected.
455    ///
456    /// Returns true if it successfully found a node and requested focus.
457    fn next(self: Handle<Self>, app: &mut App, current_node: AnyFocusNode) -> bool {
458        self.move_focus(app, current_node, true)
459    }
460
461    /// Focuses the previous widget in the focus scope that contains the given `current_node`.
462    ///
463    /// Returns true if it successfully found a node and requested focus.
464    fn previous(self: Handle<Self>, app: &mut App, current_node: AnyFocusNode) -> bool {
465        self.move_focus(app, current_node, false)
466    }
467
468    /// Focuses the next widget in the given `direction` in the focus scope that contains the
469    /// given `current_node`.
470    ///
471    /// Returns true if it successfully found a node and requested focus.
472    fn in_direction(
473        self: Handle<Self>,
474        app: &mut App,
475        current_node: AnyFocusNode,
476        direction: TraversalDirection,
477    ) -> bool;
478
479    /// Sorts the given `descendants` into focus order.
480    ///
481    /// Implementations override this to implement a different sort for [`next`](Self::next) and
482    /// [`previous`](Self::previous) to use in their ordering. If the returned list omits a node
483    /// that is a descendant of the given scope, then the user will be unable to use
484    /// next/previous keyboard traversal to reach that node.
485    ///
486    /// The node used to initiate the traversal (the one passed to [`next`](Self::next) or
487    /// [`previous`](Self::previous)) is passed as `current_node`.
488    ///
489    /// Having the current node in the list is what allows the algorithm to determine which nodes
490    /// are adjacent to the current node. If the `current_node` is removed from the list, then
491    /// the focus will be unchanged when [`next`](Self::next) or [`previous`](Self::previous) are
492    /// called, and they will return false.
493    ///
494    /// This is not used for directional focus ([`in_direction`](Self::in_direction)), only for
495    /// determining the focus order for [`next`](Self::next) and [`previous`](Self::previous).
496    fn sort_descendants(
497        self: Handle<Self>,
498        app: &mut App,
499        descendants: Vec<AnyFocusNode>,
500        current_node: AnyFocusNode,
501    ) -> Vec<AnyFocusNode>;
502
503    /// Moves the focus to the next node in the `FocusScopeNode` nearest to the `current_node`
504    /// argument, either in a forward or reverse direction, depending on the value of the
505    /// `forward` argument.
506    ///
507    /// This function is called by [`next`](Self::next) and [`previous`](Self::previous).
508    ///
509    /// Uses [`find_first_focus`](Self::find_first_focus) / [`find_last_focus`](Self::find_last_focus)
510    /// to find the first/last node if there is no focused child for the scope. If there is a
511    /// focused child, then it calls [`sort_descendants`](Self::sort_descendants) to get a sorted
512    /// list of descendants, and then finds the node after the current first focus of the scope
513    /// if `forward` is true, and the node before it if `forward` is false.
514    ///
515    /// Returns true if a node requested focus.
516    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                        // Verify the focus really has changed.
568                        return focused_child
569                            .enclosing_scope(app)
570                            .and_then(|scope| scope.focused_child(app))
571                            != Some(focused_child);
572                    }
573                    // No valid parent scope. Fallback to closed loop behavior.
574                    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                        // Verify the focus really has changed.
614                        return focused_child
615                            .enclosing_scope(app)
616                            .and_then(|scope| scope.focused_child(app))
617                            != Some(focused_child);
618                    }
619                    // No valid parent scope. Fallback to closed loop behavior.
620                    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
673/// Dart's `FocusTraversalPolicy._canRequestTraversalFocus`.
674fn can_request_traversal_focus(app: &mut App, node: AnyFocusNode) -> bool {
675    node.can_request_focus(app) && !node.skip_traversal(app)
676}
677
678/// Dart's `FocusTraversalPolicy._getDescendantsWithoutExpandingScope`.
679fn 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
690/// A structure to temporarily hold information about [`FocusTraversalGroup`]s when sorting their
691/// contents.
692struct FocusTraversalGroupInfo {
693    policy: FocusTraversalPolicyRef,
694    members: Vec<AnyFocusNode>,
695}
696
697/// Dart's `FocusTraversalPolicy._findGroups`.
698fn 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        // Group nodes need to be added to their parent's node, or to the `None` node if no
712        // parent is found. This creates the hierarchy of group nodes and makes it so the entire
713        // group is sorted along with the other members of the parent group.
714        if Some(node) == group_node.map(|group| group.as_node()) {
715            // To find the parent of the group node, we need to skip over the parent of the Focus
716            // node added in `FocusTraversalGroupState::build`, and start looking with that
717            // node's parent, since `get_group_node` will return the node it was called on if it
718            // matches the type.
719            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        // Skip non-focusable and non-traversable nodes in the same way that
736        // `FocusScopeNode::traversal_descendants` would.
737        //
738        // The current focused node needs to be in the group so that the caller can find the next
739        // traversable node from the current focused node.
740        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
759/// Sorts all descendants, taking into account the [`FocusTraversalGroup`] that they are each in,
760/// and filtering out non-traversable/focusable nodes.
761fn 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    // Build the sorting data structure, separating descendants into groups.
768    let mut groups = find_groups(app, scope, scope_group_node, current_node);
769
770    // Sort the member lists using the individual policy sorts.
771    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    // Traverse the group tree, adding the children of members in the order they appear in the
783    // member lists.
784    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    // Remove the FocusTraversalGroup nodes themselves, which aren't focusable. They were left in
791    // above because they were needed to find their members during sorting.
792    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
801/// Dart's `visitGroups` closure inside `_sortAllDescendants`.
802fn 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            // This is a policy group focus node. Replace it with the members of the
811            // corresponding policy group.
812            visit_groups(groups, Some(*node), sorted_descendants);
813        } else {
814            sorted_descendants.push(*node);
815        }
816    }
817}
818
819/// The vtable of an erased [`AnyFocusTraversalPolicy`]: one `&'static` table per leaf type.
820struct 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
834/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
835fn 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/// Erased `FocusTraversalPolicy`: one identity and a static vtable.
869///
870/// This is what a field or parameter Dart types as `FocusTraversalPolicy` becomes.
871#[derive(Clone, Copy)]
872pub struct AnyFocusTraversalPolicy {
873    id: HandleId,
874    vtable: &'static FocusTraversalPolicyVTable,
875}
876
877/// A field Dart types as the erased object, kept: AnyFocusTraversalPolicy with its count.
878pub 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    /// Dart's `toStringShort`: the type and the identity.
890    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    /// The arena id behind this handle.
898    pub fn id(self) -> HandleId {
899        self.id
900    }
901
902    /// Dart's `policy as T`: the typed handle when this policy is a `T`, else `None`.
903    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
904        app.handle::<T>(self.id)
905    }
906
907    /// See [`FocusTraversalPolicy::find_first_focus`].
908    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    /// See [`FocusTraversalPolicy::find_last_focus`].
918    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    /// See [`FocusTraversalPolicy::find_first_focus_in_direction`].
928    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    /// See [`FocusTraversalPolicy::invalidate_scope_data`].
938    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    /// See [`FocusTraversalPolicy::changed_scope`].
943    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    /// See [`FocusTraversalPolicy::next`].
953    pub fn next(self, app: &mut App, current_node: AnyFocusNode) -> bool {
954        (self.vtable.next)(app, self.id, current_node)
955    }
956
957    /// See [`FocusTraversalPolicy::previous`].
958    pub fn previous(self, app: &mut App, current_node: AnyFocusNode) -> bool {
959        (self.vtable.previous)(app, self.id, current_node)
960    }
961
962    /// See [`FocusTraversalPolicy::in_direction`].
963    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    /// See [`FocusTraversalPolicy::sort_descendants`].
973    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// ---------------------------------------------------------------------------------------------
984// DirectionalFocusTraversalPolicyMixin
985
986/// A policy data object for use by [`DirectionalFocusTraversalPolicyMixin`] so it can keep track
987/// of the traversal history.
988#[derive(Clone)]
989struct DirectionalPolicyDataEntry {
990    direction: TraversalDirection,
991    node: FocusNodeRef,
992}
993
994/// A queue of entries that describe the path taken to the current node.
995struct DirectionalPolicyData {
996    history: Vec<DirectionalPolicyDataEntry>,
997}
998
999/// The fields Dart's `DirectionalFocusTraversalPolicyMixin` declares; a policy that mixes it in
1000/// carries this bag under the field `directional`.
1001pub struct DirectionalFocusTraversalPolicyMixinData {
1002    policy_data: HashMap<Ref<FocusScopeNode>, DirectionalPolicyData>,
1003}
1004
1005impl DirectionalFocusTraversalPolicyMixinData {
1006    /// The bag of a freshly created policy.
1007    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
1020/// A trait that provides an implementation for finding a node in a particular direction.
1021///
1022/// This can be implemented by other [`FocusTraversalPolicy`] implementations that only want to
1023/// implement new next/previous policies.
1024///
1025/// Since hysteresis in the navigation order is undesirable, this implementation maintains a
1026/// stack of previous locations that have been visited on the policy data for the affected
1027/// `FocusScopeNode`. If the previous direction was the opposite of the current direction, then
1028/// this policy will request focus on the previously focused node. Changing to another direction
1029/// other than the current one or its opposite will clear the stack.
1030///
1031/// For instance, if the focus moves down, down, down, and then up, up, up, it will follow the
1032/// same path through the widgets in both directions. However, if it moves down, down, down,
1033/// left, right, and then up, up, up, it may not follow the same path on the way up as it did on
1034/// the way down, since changing the axis of motion resets the history.
1035///
1036/// This trait implements an algorithm that considers a band extending along the direction of
1037/// movement within the `FocusScope`, the width or height (depending on direction) of the
1038/// currently focused widget, and finds the closest widget in that band along the direction of
1039/// movement. If nothing is found in that band, then it picks the widget with an edge closest to
1040/// the band in the perpendicular direction. If two out-of-band widgets are the same distance
1041/// from the band, then it picks the one closest along the direction of movement. When reaching
1042/// the edge in the direction specified by the `FocusScope`, different behaviors are taken
1043/// according to `FocusScopeNode::directional_traversal_edge_behavior`.
1044pub trait DirectionalFocusTraversalPolicyMixin: FocusTraversalPolicy {
1045    /// Dart's `DirectionalFocusTraversalPolicyMixin` fields, held under the field `directional`.
1046    fn directional_data(self: Handle<Self>, app: &App)
1047    -> &DirectionalFocusTraversalPolicyMixinData;
1048
1049    /// See [`directional_data`](Self::directional_data).
1050    fn directional_data_mut(
1051        self: Handle<Self>,
1052        app: &mut App,
1053    ) -> &mut DirectionalFocusTraversalPolicyMixinData;
1054
1055    /// Dart's `DirectionalFocusTraversalPolicyMixin.invalidateScopeData`.
1056    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    /// Dart's `DirectionalFocusTraversalPolicyMixin.changedScope`.
1061    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    /// Dart's `DirectionalFocusTraversalPolicyMixin.findFirstFocusInDirection`.
1079    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            // Start with the bottom-most node.
1092            TraversalDirection::Up => (true, false),
1093            // Start with the topmost node.
1094            TraversalDirection::Down => (true, true),
1095            // Start with the rightmost node.
1096            TraversalDirection::Left => (false, false),
1097            // Start with the leftmost node.
1098            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    /// Dart's `DirectionalFocusTraversalPolicyMixin._findNextFocusInDirection`.
1120    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                // Find any nodes that intersect the band of the focused child.
1146                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                // Only out-of-band targets are eligible, so pick the one that is closest to the
1158                // center line horizontally, and if any are the same distance horizontally, pick
1159                // the closest one of those vertically.
1160                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                // Only out-of-band targets are eligible, so pick the one that is closest to the
1198                // center line vertically, and if any are the same distance vertically, pick the
1199                // closest one of those horizontally.
1200                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    /// Updates the policy data to keep the previously visited node so that we can avoid
1215    /// hysteresis when we change directions in navigation.
1216    ///
1217    /// Returns true if focus was requested on a previous node.
1218    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                // If a node has been removed from the tree, then we should stop referencing it
1242                // and reset the scope data so that we don't try and request focus on it.
1243                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                // Reset the policy data if we change directions.
1263                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    /// Dart's `popOrInvalidate` closure inside `_popPolicyDataIfNeeded`. Returns true if it
1278    /// successfully popped the history.
1279    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    /// Dart's `DirectionalFocusTraversalPolicyMixin._pushPolicyData`.
1319    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    /// Dart's `DirectionalFocusTraversalPolicyMixin._requestTraversalFocusInDirection`.
1342    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    /// Dart's `DirectionalFocusTraversalPolicyMixin._requestFocus`.
1391    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    /// Dart's `DirectionalFocusTraversalPolicyMixin._onEdgeForDirection`.
1407    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    /// Focuses the next widget in the given `direction` in the `FocusScope` that contains the
1494    /// `current_node`.
1495    ///
1496    /// This determines what the next node to receive focus in the given `direction` will be by
1497    /// inspecting the node tree, and then calling [`AnyFocusNode::request_focus`] on it.
1498    ///
1499    /// Returns true if it successfully found a node and requested focus.
1500    ///
1501    /// Maintains a stack of previous locations that have been visited on the policy data for the
1502    /// affected `FocusScopeNode`. If the previous direction was the opposite of the current
1503    /// direction, then this policy will request focus on the previously focused node. Changing
1504    /// to another direction other than the current one or its opposite will clear the stack.
1505    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
1563/// `f64` has no total order; Dart's `compareTo` on a double does.
1564fn total_cmp(a: f64, b: f64) -> Ordering {
1565    a.total_cmp(&b)
1566}
1567
1568/// The rectangle of every node, read once: `AnyFocusNode::rect` does a coordinate
1569/// transformation each time.
1570fn 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
1582/// Sort the ones that are closest to target vertically first, and if two are the same vertical
1583/// distance, pick the one that is closest horizontally.
1584fn 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
1602/// Sort the ones that are closest horizontally first, and if two are the same horizontal
1603/// distance, pick the one that is closest vertically.
1604fn 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    // Find which edge is closest to the target for each.
1624    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    // Find which edge is closest to the target for each.
1639    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
1652/// Sort the ones that have edges that are closest horizontally first, and if two are the same
1653/// horizontal distance, pick the one that is closest vertically.
1654fn 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            // If they're the same distance horizontally, pick the closest one vertically.
1666            Ordering::Equal => vertical_compare(target, a.center(), b.center()),
1667            horizontal => horizontal,
1668        }
1669    });
1670    sorted
1671}
1672
1673/// Sort the ones that have edges that are closest vertically first, and if two are the same
1674/// vertical distance, pick the one that is closest horizontally.
1675fn 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            // If they're the same distance vertically, pick the closest one horizontally.
1687            Ordering::Equal => horizontal_compare(target, a.center(), b.center()),
1688            vertical => vertical,
1689        }
1690    });
1691    sorted
1692}
1693
1694/// Sorts nodes from left to right horizontally, and removes nodes that are either to the right
1695/// of the left side of the target node if we're going left, or to the left of the right side of
1696/// the target node if we're going right.
1697///
1698/// This doesn't need to take into account directionality because it is typically intending to
1699/// actually go left or right, not in a reading direction.
1700fn 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    // Sort all nodes from left to right.
1737    sorted.sort_by(|a, b| total_cmp(rects[a].center().dx(), rects[b].center().dx()));
1738    sorted
1739}
1740
1741/// Restricts the candidates to the focused node's own `Scrollable` on the given axis, unless none
1742/// of them share it.
1743///
1744/// Dart's `eligibleNodes.where(..)` inside `_findNextFocusInDirection`.
1745fn 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
1769/// Sorts nodes from top to bottom vertically, and removes nodes that are either below the top of
1770/// the target node if we're going up, or above the bottom of the target node if we're going
1771/// down.
1772fn 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
1812/// Dart's `eligibleNodes.where((node) => !node.rect.intersect(band).isEmpty)`.
1813fn 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
1821// ---------------------------------------------------------------------------------------------
1822// WidgetOrderTraversalPolicy
1823
1824/// A [`FocusTraversalPolicy`] that traverses the focus order in widget hierarchy order.
1825///
1826/// This policy is used when the order desired is the order in which widgets are created in the
1827/// widget hierarchy.
1828///
1829/// See also:
1830///
1831///  * `FocusNode`, for a description of the focus system.
1832///  * [`FocusTraversalGroup`], a widget that groups together and imposes a traversal policy on
1833///    the `Focus` nodes below it in the widget hierarchy.
1834///  * [`ReadingOrderTraversalPolicy`], a policy that describes the order as the natural "reading
1835///    order" for the current [`Directionality`].
1836///  * [`DirectionalFocusTraversalPolicyMixin`], a trait that implements focus traversal in a
1837///    direction.
1838///  * [`OrderedTraversalPolicy`], a policy that describes the order explicitly using
1839///    [`FocusTraversalOrder`] widgets.
1840pub struct WidgetOrderTraversalPolicy {
1841    policy: FocusTraversalPolicyData,
1842    directional: DirectionalFocusTraversalPolicyMixinData,
1843}
1844
1845impl WidgetOrderTraversalPolicy {
1846    /// Constructs a traversal policy that orders widgets for keyboard traversal based on the
1847    /// widget hierarchy order.
1848    ///
1849    /// Dart's optional `requestFocusCallback` argument is
1850    /// [`FocusTraversalPolicy::set_request_focus_callback`].
1851    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// ---------------------------------------------------------------------------------------------
1890// ReadingOrderTraversalPolicy
1891
1892/// The rect is copied out of the node, because it will be accessed many times in the reading
1893/// order algorithm, and [`AnyFocusNode::rect`] does coordinate transformation.
1894///
1895/// It's also a convenient place to put some utility functions having to do with the sort data.
1896#[derive(Clone)]
1897struct ReadingOrderSortData {
1898    directionality: Option<TextDirection>,
1899    rect: Rect,
1900    node: AnyFocusNode,
1901    /// The `Directionality` elements above this node, nearest first. Dart holds the widgets and
1902    /// compares them by identity; the element is the same identity within one sort.
1903    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    /// Finds the common directional ancestor of an entire list of groups.
1918    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            // If there is no common ancestor, then arbitrarily pick the directionality of the
1932            // first group, which is the equivalent of the "first strongly typed" item in a
1933            // bidirectional algorithm.
1934            return list[0].directionality;
1935        }
1936        // Find the closest common ancestor. The first member's ancestry was added in order from
1937        // nearest to furthest, so we can still use that to determine the closest one.
1938        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
1954/// Find the directionality in force for a build context without creating a dependency.
1955fn 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
1961/// The `Directionality` widget an element holds.
1962fn 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
1968/// Returns the list of `Directionality` elements, in order from nearest to furthest.
1969fn 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
1982/// A structure for containing group data while sorting in reading order while taking into
1983/// account the ambient directionality.
1984struct 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
2015/// Traverses the focus order in "reading order".
2016///
2017/// By default, reading order traversal goes in the reading direction, and then down, using this
2018/// algorithm:
2019///
2020/// 1. Find the node rectangle that has the highest `top` on the screen.
2021/// 2. Find any other nodes that intersect the infinite horizontal band defined by the highest
2022///    rectangle's top and bottom edges.
2023/// 3. Pick the closest to the beginning of the reading order from among the nodes discovered
2024///    above.
2025///
2026/// It uses the ambient [`Directionality`] in the context for the enclosing
2027/// [`FocusTraversalGroup`] to determine which direction is "reading order".
2028pub struct ReadingOrderTraversalPolicy {
2029    policy: FocusTraversalPolicyData,
2030    directional: DirectionalFocusTraversalPolicyMixinData,
2031}
2032
2033impl ReadingOrderTraversalPolicy {
2034    /// Constructs a traversal policy that orders the widgets in "reading order".
2035    ///
2036    /// Dart's optional `requestFocusCallback` argument is
2037    /// [`FocusTraversalPolicy::set_request_focus_callback`].
2038    pub fn new(app: &mut App) -> Ref<ReadingOrderTraversalPolicy> {
2039        app.create(ReadingOrderTraversalPolicy {
2040            policy: FocusTraversalPolicyData::new(),
2041            directional: DirectionalFocusTraversalPolicyMixinData::new(),
2042        })
2043    }
2044
2045    /// Sorts the input focus nodes into reading order.
2046    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        // Pick the initial widget as the one that is at the beginning of the band of the
2059        // topmost, or the topmost, if there are no others in its band.
2060        //
2061        // Go through each node, picking the next one after eliminating the previous one, since
2062        // removing the previously picked node will expose a new band in which to choose
2063        // candidates.
2064        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    /// Collects the given candidates into groups by directionality. The candidates have already
2073    /// been sorted as if they all had the directionality of the nearest `Directionality`
2074    /// ancestor.
2075    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        // Split candidates into runs of the same directionality.
2082        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        // Sort each group separately. Each group has the same directionality.
2099        for band_group in result.iter_mut() {
2100            if band_group.members.len() == 1 {
2101                continue; // No need to sort one node.
2102            }
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    /// Dart's `ReadingOrderTraversalPolicy._pickNext`: the index of the next node in
2112    /// `candidates`, which this also sorts by their tops.
2113    fn pick_next(app: &App, candidates: &mut [ReadingOrderSortData]) -> usize {
2114        // Find the topmost node by sorting on the top of the rectangles.
2115        candidates.sort_by(|a, b| total_cmp(a.rect.top, b.rect.top));
2116        let topmost = candidates[0].clone();
2117
2118        // Find the candidates that are in the same horizontal band as the current one.
2119        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        // It has to have at least topmost in it if the topmost is not degenerate.
2131        debug_assert!(topmost.rect.is_empty() || !in_band_of_top.is_empty());
2132
2133        // The topmost rect is in a band by itself, so just return that one.
2134        if in_band_of_top.len() <= 1 {
2135            return 0;
2136        }
2137
2138        // Now that we know there are others in the same band as the topmost, then pick the one
2139        // at the beginning, depending on the text direction in force.
2140        //
2141        // Find out the directionality of the nearest common `Directionality` ancestor for all
2142        // nodes. This provides a base directionality to use for the ordering of the groups.
2143        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        // Do an initial common-directionality-based sort to get consistent geometric ordering
2148        // for grouping into directionality groups. It has to use the common directionality to be
2149        // able to group into sane groups for the given directionality, since rectangles can
2150        // overlap and give different results for different directionalities.
2151        ReadingOrderSortData::sort_with_directionality(
2152            &mut in_band_of_top,
2153            nearest_common_directionality,
2154        );
2155
2156        // Collect the top band into internally sorted groups with shared directionality.
2157        let mut band_groups =
2158            ReadingOrderTraversalPolicy::collect_directionality_groups(&in_band_of_top);
2159        let picked = if band_groups.len() == 1 {
2160            // There's only one directionality group, so just send back the first one in that
2161            // group, since it's already sorted.
2162            band_groups[0].members[0].node
2163        } else {
2164            // Sort the groups based on the common directionality and bounding boxes.
2165            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    /// Sorts the list of nodes based on their geometry into the desired reading order based on
2183    /// the directionality of the context for each node.
2184    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
2210// ---------------------------------------------------------------------------------------------
2211// FocusOrder
2212
2213/// Base trait for all sort orders for [`OrderedTraversalPolicy`] traversal.
2214///
2215/// Only orders of the same type are comparable. If a set of widgets in the same
2216/// [`FocusTraversalGroup`] contains orders that are not comparable with each other, it will
2217/// assert, since the ordering between such keys is undefined. To avoid collisions, use a
2218/// [`FocusTraversalGroup`] to group similarly ordered widgets together.
2219///
2220/// When implementing, [`do_compare`](Self::do_compare) must be implemented instead of
2221/// [`compare_to`](Self::compare_to), which calls [`do_compare`](Self::do_compare) to do the
2222/// actual comparison.
2223///
2224/// See also:
2225///
2226///  * [`FocusTraversalGroup`], a widget that groups together and imposes a traversal policy on
2227///    the `Focus` nodes below it in the widget hierarchy.
2228///  * [`FocusTraversalOrder`], a widget that assigns an order to a widget subtree for the
2229///    [`OrderedTraversalPolicy`] to use.
2230///  * [`NumericFocusOrder`], for a focus order that describes its order with an `f64`.
2231///  * [`LexicalFocusOrder`], a focus order that assigns a string-based lexical traversal order
2232///    to a [`FocusTraversalOrder`] widget.
2233pub trait FocusOrder: Debug {
2234    /// The value behind the erased order, for the downcast [`do_compare`](Self::do_compare)
2235    /// does.
2236    fn as_any(&self) -> &dyn Any;
2237
2238    /// Dart's `FocusOrder.debugFillProperties`, from `Diagnosticable`: a subclass adds its own.
2239    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
2240        let _ = properties;
2241    }
2242
2243    /// Dart's `FocusOrder.toStringShort`: the type and the identity.
2244    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    /// Dart's `FocusOrder.toDiagnosticsNode(name:)`, from `Diagnosticable`.
2252    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    /// Dart's `Diagnosticable.toString`, which a property holding an order prints.
2259    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    /// Compares this object to another [`FocusOrder`].
2266    ///
2267    /// When implementing [`FocusOrder`], implement [`do_compare`](Self::do_compare) instead of
2268    /// this function to do the actual comparison.
2269    ///
2270    /// Returns [`Ordering::Less`] if `self` is ordered before `other`, [`Ordering::Greater`] if
2271    /// `self` is ordered after `other`, and [`Ordering::Equal`] if they are ordered together.
2272    ///
2273    /// The `other` argument must be a value that is comparable to this object.
2274    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    /// The implementation called by [`compare_to`](Self::compare_to) to compare orders.
2284    ///
2285    /// The argument is guaranteed to be of the same type as this object.
2286    ///
2287    /// Returns [`Ordering::Less`] if this object comes earlier in the sort order than the
2288    /// `other` argument, and [`Ordering::Greater`] if it comes later. Returning
2289    /// [`Ordering::Equal`] causes the system to fall back to the secondary sort order defined by
2290    /// [`OrderedTraversalPolicy::secondary`].
2291    fn do_compare(&self, other: &dyn FocusOrder) -> Ordering;
2292}
2293
2294/// The erased [`FocusOrder`]: what [`FocusTraversalOrder::order`] holds.
2295pub type FocusOrderRef = Rc<dyn FocusOrder>;
2296
2297/// Can be given to a [`FocusTraversalOrder`] widget to assign a numerical order to a widget
2298/// subtree that is using an [`OrderedTraversalPolicy`] to define the order in which widgets
2299/// should be traversed with the keyboard.
2300///
2301/// Dart's `FocusOrder.numeric`.
2302#[derive(Clone, Copy, Debug, PartialEq)]
2303pub struct NumericFocusOrder {
2304    /// The numerical order to assign to the widget subtree using [`FocusTraversalOrder`].
2305    ///
2306    /// Determines the placement of this widget in a sequence of widgets that defines the order
2307    /// in which this node is traversed by the focus policy.
2308    ///
2309    /// Lower values will be traversed first.
2310    pub order: f64,
2311}
2312
2313impl NumericFocusOrder {
2314    /// Creates an object that describes a focus traversal order numerically.
2315    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/// Can be given to a [`FocusTraversalOrder`] widget to use a string to assign a lexical order to
2339/// a widget subtree that is using an [`OrderedTraversalPolicy`] to define the order in which
2340/// widgets should be traversed with the keyboard.
2341///
2342/// This sorts strings using Rust's default string comparison, which is not locale-specific.
2343///
2344/// Dart's `FocusOrder.lexical`.
2345#[derive(Clone, Debug, PartialEq, Eq)]
2346pub struct LexicalFocusOrder {
2347    /// The string that defines the lexical order to assign to the widget subtree using
2348    /// [`FocusTraversalOrder`].
2349    ///
2350    /// Determines the placement of this widget in a sequence of widgets that defines the order
2351    /// in which this node is traversed by the focus policy.
2352    ///
2353    /// Lower lexical values will be traversed first (e.g. 'a' comes before 'z').
2354    pub order: String,
2355}
2356
2357impl LexicalFocusOrder {
2358    /// Creates an object that describes a focus traversal order lexically.
2359    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
2384/// Used to help sort the focus nodes in an [`OrderedTraversalPolicy`].
2385struct OrderedFocusInfo {
2386    node: AnyFocusNode,
2387    order: FocusOrderRef,
2388}
2389
2390/// A [`FocusTraversalPolicy`] that orders nodes by an explicit order that resides in the nearest
2391/// [`FocusTraversalOrder`] widget ancestor.
2392///
2393/// See also:
2394///
2395///  * [`FocusTraversalGroup`], a widget that groups together and imposes a traversal policy on
2396///    the `Focus` nodes below it in the widget hierarchy.
2397///  * [`WidgetOrderTraversalPolicy`], a policy that relies on the widget creation order to
2398///    describe the order of traversal.
2399///  * [`ReadingOrderTraversalPolicy`], a policy that describes the order as the natural "reading
2400///    order" for the current [`Directionality`].
2401///  * [`NumericFocusOrder`], a focus order that assigns a numeric traversal order to a
2402///    [`FocusTraversalOrder`] widget.
2403///  * [`LexicalFocusOrder`], a focus order that assigns a string-based lexical traversal order
2404///    to a [`FocusTraversalOrder`] widget.
2405///  * [`FocusOrder`], a base trait for all types of focus traversal orderings.
2406pub struct OrderedTraversalPolicy {
2407    policy: FocusTraversalPolicyData,
2408    directional: DirectionalFocusTraversalPolicyMixinData,
2409    secondary: Option<FocusTraversalPolicyRef>,
2410}
2411
2412impl OrderedTraversalPolicy {
2413    /// Constructs a traversal policy that orders widgets for keyboard traversal based on an
2414    /// explicit order.
2415    ///
2416    /// Dart's optional `secondary` and `requestFocusCallback` arguments are the setters.
2417    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    /// This is the policy that is used when a node doesn't have an order assigned, or when
2426    /// multiple nodes have orders which are identical.
2427    ///
2428    /// If not set, this defaults to [`ReadingOrderTraversalPolicy`].
2429    ///
2430    /// This policy determines the secondary sorting order of nodes which evaluate as having an
2431    /// identical order (including those with no order specified).
2432    ///
2433    /// Nodes with no order specified will be sorted after nodes with an explicit order.
2434    pub fn secondary(self: Handle<Self>, app: &App) -> Option<AnyFocusTraversalPolicy> {
2435        app.get(self).secondary.handle()
2436    }
2437
2438    /// Dart `OrderedTraversalPolicy(secondary:)`.
2439    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// ---------------------------------------------------------------------------------------------
2507// FocusTraversalOrder
2508
2509/// An inherited widget that describes the order in which its child subtree should be traversed.
2510///
2511/// The order for a widget is determined by the [`FocusOrder`] returned by
2512/// [`FocusTraversalOrder::of`] for a particular context.
2513#[derive(Debug)]
2514pub struct FocusTraversalOrder {
2515    /// See [`Widget::key`](crate::Widget::key).
2516    pub key: Option<KeyRef>,
2517
2518    /// The order for the widget descendants of this [`FocusTraversalOrder`].
2519    pub order: FocusOrderRef,
2520
2521    /// The widget below this widget in the tree.
2522    pub child: WidgetRef,
2523}
2524
2525impl FocusTraversalOrder {
2526    /// Creates an inherited widget used to describe the focus order of the `child` subtree.
2527    #[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    /// Dart `FocusTraversalOrder(key:)`.
2537    pub fn key(mut self, key: KeyRef) -> FocusTraversalOrder {
2538        self.key = Some(key);
2539        self
2540    }
2541
2542    /// Finds the [`FocusOrder`] in the nearest ancestor [`FocusTraversalOrder`] widget.
2543    ///
2544    /// It does not create a rebuild dependency because changing the traversal order doesn't
2545    /// change the widget tree, so nothing needs to be rebuilt as a result of an order change.
2546    ///
2547    /// If no [`FocusTraversalOrder`] ancestor exists, this panics.
2548    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    /// Finds the [`FocusOrder`] in the nearest ancestor [`FocusTraversalOrder`] widget.
2556    ///
2557    /// It does not create a rebuild dependency because changing the traversal order doesn't
2558    /// change the widget tree, so nothing needs to be rebuilt as a result of an order change.
2559    ///
2560    /// If no [`FocusTraversalOrder`] ancestor exists, returns `None`.
2561    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    /// Since the order of traversal doesn't affect display of anything, we don't need to force a
2585    /// rebuild of anything that depends upon it.
2586    fn update_should_notify(&self, _old_widget: &FocusTraversalOrder) -> bool {
2587        false
2588    }
2589}
2590
2591// ---------------------------------------------------------------------------------------------
2592// FocusTraversalGroup
2593
2594/// A special focus node that only [`FocusTraversalGroup`] uses so that it can be used to cache
2595/// the following in the focus tree:
2596///  - the focus traversal policy — this allows traversal code to find groups in the focus tree.
2597///  - the last focused node — this allows the policy to be invalidated when a focus change was
2598///    not triggered via a traversal request.
2599pub struct FocusTraversalGroupNode {
2600    change_notifier: ChangeNotifierData,
2601    focus_node: FocusNodeData,
2602    /// The policy this group imposes.
2603    pub policy: FocusTraversalPolicyRef,
2604    /// The node the policy last requested focus for.
2605    pub last_requested_focus: Option<FocusNodeRef>,
2606}
2607
2608impl FocusTraversalGroupNode {
2609    /// Creates a [`FocusTraversalGroupNode`] with the given policy.
2610    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
2634/// A widget that describes the inherited focus policy for focus traversal for its descendants,
2635/// grouping them into a separate traversal group.
2636///
2637/// A traversal group is treated as one entity when sorted by the traversal algorithm, so it can
2638/// be used to segregate different parts of the widget tree that need to be sorted using
2639/// different algorithms and/or sort orders when using an [`OrderedTraversalPolicy`].
2640///
2641/// Within the group, it will use the given [`policy`](Self::policy) to order the elements. The
2642/// group itself will be ordered using the parent group's policy.
2643///
2644/// By default, traverses in reading order using [`ReadingOrderTraversalPolicy`].
2645///
2646/// To prevent the members of the group from being focused, set the
2647/// [`descendants_are_focusable`](Self::descendants_are_focusable) attribute to false.
2648pub struct FocusTraversalGroup {
2649    /// See [`Widget::key`](crate::Widget::key).
2650    pub key: Option<KeyRef>,
2651
2652    /// The policy used to move the focus from one focus node to another when traversing them
2653    /// using a keyboard.
2654    ///
2655    /// If not specified, traverses in reading order using [`ReadingOrderTraversalPolicy`], which
2656    /// the state creates, since a policy is an arena object a widget cannot mint.
2657    ///
2658    /// See also:
2659    ///
2660    ///  * [`FocusTraversalPolicy`] for the API used to impose traversal order policy.
2661    ///  * [`WidgetOrderTraversalPolicy`] for a traversal policy that traverses nodes in the order
2662    ///    they are added to the widget tree.
2663    ///  * [`ReadingOrderTraversalPolicy`] for a traversal policy that traverses nodes in the
2664    ///    reading order defined in the widget tree, and then top to bottom.
2665    pub policy: Option<FocusTraversalPolicyRef>,
2666
2667    /// If false, will make this widget's descendants unfocusable.
2668    pub descendants_are_focusable: bool,
2669
2670    /// If false, will make this widget's descendants untraversable.
2671    pub descendants_are_traversable: bool,
2672
2673    /// Called when the `FocusNode` of this widget is created.
2674    pub on_focus_node_created: Option<ValueChanged<AnyFocusNode>>,
2675
2676    /// The optional parent node to use when reparenting this group's `FocusNode`.
2677    ///
2678    /// If `None`, the enclosing `FocusScope` is used as the parent, which mirrors the widget
2679    /// tree and is typically what is desired.
2680    ///
2681    /// Setting this attaches the group (and the focus subtree below it) to the given node
2682    /// instead of the enclosing `FocusScope`, which is useful to keep a subtree's focus
2683    /// independent from the surrounding focus tree (for example, so each `View` forms its own
2684    /// focus root).
2685    ///
2686    /// Defaults to `None`.
2687    pub parent_node: Option<FocusNodeRef>,
2688
2689    /// The child widget of this [`FocusTraversalGroup`].
2690    pub child: WidgetRef,
2691}
2692
2693impl FocusTraversalGroup {
2694    /// Creates a [`FocusTraversalGroup`].
2695    #[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    /// Dart `FocusTraversalGroup(key:)`.
2709    pub fn key(mut self, key: KeyRef) -> FocusTraversalGroup {
2710        self.key = Some(key);
2711        self
2712    }
2713
2714    /// Dart `FocusTraversalGroup(policy:)`.
2715    pub fn policy(mut self, policy: FocusTraversalPolicyRef) -> FocusTraversalGroup {
2716        self.policy = Some(policy);
2717        self
2718    }
2719
2720    /// Dart `FocusTraversalGroup(descendantsAreFocusable:)`.
2721    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    /// Dart `FocusTraversalGroup(descendantsAreTraversable:)`.
2730    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    /// Dart `FocusTraversalGroup(onFocusNodeCreated:)`.
2739    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    /// Dart `FocusTraversalGroup(parentNode:)`.
2748    pub fn parent_node(mut self, parent_node: FocusNodeRef) -> FocusTraversalGroup {
2749        self.parent_node = Some(parent_node);
2750        self
2751    }
2752
2753    /// Returns the [`FocusTraversalPolicy`] that applies to the nearest ancestor of the given
2754    /// `FocusNode`.
2755    ///
2756    /// Will return `None` if no [`FocusTraversalPolicy`] ancestor applies to the given
2757    /// `FocusNode`.
2758    ///
2759    /// The [`FocusTraversalPolicy`] is set by introducing a [`FocusTraversalGroup`] into the
2760    /// widget tree, which will associate a policy with the focus tree under the nearest ancestor
2761    /// `Focus` widget.
2762    ///
2763    /// This function differs from [`maybe_of`](Self::maybe_of) in that it takes a `FocusNode`
2764    /// and only traverses the focus tree to determine the policy in effect.
2765    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    /// Dart's `FocusTraversalGroup._getGroupNode`.
2770    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    /// Returns the [`FocusTraversalPolicy`] that applies to the `FocusNode` of the nearest
2783    /// ancestor `Focus` widget, given a [`BuildContext`].
2784    ///
2785    /// Panics if no `Focus` ancestor is found, or if no [`FocusTraversalPolicy`] applies to the
2786    /// associated `FocusNode`.
2787    ///
2788    /// This function looks up the nearest ancestor `Focus` (or `FocusScope`) widget, and uses
2789    /// its `FocusNode` to walk up the focus tree to find the applicable
2790    /// [`FocusTraversalPolicy`] for that node.
2791    ///
2792    /// Calling this function does not create a rebuild dependency because changing the traversal
2793    /// order doesn't change the widget tree, so nothing needs to be rebuilt as a result of an
2794    /// order change.
2795    ///
2796    /// See also:
2797    ///
2798    ///  * [`maybe_of`](Self::maybe_of) for a similar function that will return `None` if no
2799    ///    [`FocusTraversalGroup`] ancestor is found.
2800    ///  * [`maybe_of_node`](Self::maybe_of_node) for a function that will look for a policy
2801    ///    using a given `FocusNode`, and return `None` if no policy applies.
2802    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    /// Returns the [`FocusTraversalPolicy`] that applies to the `FocusNode` of the nearest
2812    /// ancestor `Focus` widget, or `None`, given a [`BuildContext`].
2813    ///
2814    /// See also:
2815    ///
2816    ///  * [`maybe_of_node`](Self::maybe_of_node) for a similar function that will look for a
2817    ///    policy using a given `FocusNode`.
2818    ///  * [`of`](Self::of) for a similar function that will panic if no
2819    ///    [`FocusTraversalPolicy`] applies.
2820    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
2856/// Dart's `_FocusTraversalGroupState`.
2857pub struct FocusTraversalGroupState {
2858    state: StateData<FocusTraversalGroup>,
2859    focus_node: Option<Ref<FocusTraversalGroupNode>>,
2860}
2861
2862impl FocusTraversalGroupState {
2863    /// The internal focus node used to collect the children of this node into a group, and to
2864    /// provide a context for the traversal algorithm to sort the group with. It's a special
2865    /// focus node just so that it can be identified when walking the focus tree during
2866    /// traversal, and hold the current policy.
2867    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
2958// ---------------------------------------------------------------------------------------------
2959// The intents and actions
2960
2961/// An intent for use with the [`RequestFocusAction`], which supplies the `FocusNode` that should
2962/// be focused.
2963pub struct RequestFocusIntent {
2964    /// The callback used to move the focus to the node [`focus_node`](Self::focus_node). By
2965    /// default it requests focus on the node.
2966    pub request_focus_callback: TraversalRequestFocusCallback,
2967
2968    /// The `FocusNode` that is to be focused.
2969    pub focus_node: FocusNodeRef,
2970}
2971
2972impl RequestFocusIntent {
2973    /// Creates an intent used with [`RequestFocusAction`].
2974    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    /// Dart `RequestFocusIntent(requestFocusCallback:)`.
2982    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
3005/// An [`Action`] that requests the focus on the node it is given in its [`RequestFocusIntent`].
3006///
3007/// This action can be used to request focus for a particular node, by calling
3008/// `Actions::invoke(app, context, &RequestFocusIntent::new(focus_node))`.
3009///
3010/// The difference between requesting focus in this way versus calling
3011/// [`AnyFocusNode::request_focus`] directly is that it will use the [`Action`] registered in the
3012/// nearest `Actions` widget associated with [`RequestFocusIntent`] to make the request, rather
3013/// than just requesting focus directly. This allows the action to have additional side effects,
3014/// like logging, or undo and redo functionality.
3015pub struct RequestFocusAction {
3016    action: ActionData,
3017}
3018
3019impl RequestFocusAction {
3020    /// Creates a [`RequestFocusAction`].
3021    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/// An [`Intent`] bound to [`NextFocusAction`], which moves the focus to the next focusable node
3044/// in the focus traversal order.
3045#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3046pub struct NextFocusIntent;
3047
3048impl NextFocusIntent {
3049    /// Creates an intent that is used with [`NextFocusAction`].
3050    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
3061/// An [`Action`] that moves the focus to the next focusable node in the focus order.
3062///
3063/// This action is the default action registered for the [`NextFocusIntent`], and by default is
3064/// bound to the tab key in `WidgetsApp`.
3065pub struct NextFocusAction {
3066    action: ActionData,
3067}
3068
3069impl NextFocusAction {
3070    /// Creates a [`NextFocusAction`].
3071    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    /// Attempts to pass the focus to the next widget.
3083    ///
3084    /// Returns true if a widget was focused as a result of invoking this action.
3085    ///
3086    /// Returns false when the traversal reached the end and the engine must pass focus to
3087    /// platform UI.
3088    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
3109/// Dart's `bool invokeResult` parameter, which the erased result carries here.
3110fn 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/// An [`Intent`] bound to [`PreviousFocusAction`], which moves the focus to the previous
3118/// focusable node in the focus traversal order.
3119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3120pub struct PreviousFocusIntent;
3121
3122impl PreviousFocusIntent {
3123    /// Creates an intent that is used with [`PreviousFocusAction`].
3124    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
3135/// An [`Action`] that moves the focus to the previous focusable node in the focus order.
3136///
3137/// This action is the default action registered for the [`PreviousFocusIntent`], and by default
3138/// is bound to a combination of the tab key and the shift key in `WidgetsApp`.
3139pub struct PreviousFocusAction {
3140    action: ActionData,
3141}
3142
3143impl PreviousFocusAction {
3144    /// Creates a [`PreviousFocusAction`].
3145    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    /// Attempts to pass the focus to the previous widget.
3157    ///
3158    /// Returns true if a widget was focused as a result of invoking this action.
3159    ///
3160    /// Returns false when the traversal reached the beginning and the engine must pass focus to
3161    /// platform UI.
3162    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/// An [`Intent`] that represents moving to the next focusable node in the given
3188/// [`direction`](Self::direction).
3189///
3190/// This is the [`Intent`] bound by default to the arrow keys in `WidgetsApp`, with the
3191/// appropriate associated directions.
3192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3193pub struct DirectionalFocusIntent {
3194    /// The direction in which to look for the next focusable node when the associated
3195    /// [`DirectionalFocusAction`] is invoked.
3196    pub direction: TraversalDirection,
3197
3198    /// If true, then directional focus actions that occur within a text field will not happen
3199    /// when the focus node which received the key is a text field.
3200    ///
3201    /// Defaults to true.
3202    pub ignore_text_fields: bool,
3203}
3204
3205impl DirectionalFocusIntent {
3206    /// Creates an intent used to move the focus in the given `direction`.
3207    pub fn new(direction: TraversalDirection) -> DirectionalFocusIntent {
3208        DirectionalFocusIntent {
3209            direction,
3210            ignore_text_fields: true,
3211        }
3212    }
3213
3214    /// Dart `DirectionalFocusIntent(ignoreTextFields:)`.
3215    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
3231/// An [`Action`] that moves the focus to the focusable node in the direction configured by the
3232/// associated [`DirectionalFocusIntent::direction`].
3233///
3234/// This is the [`Action`] associated with [`DirectionalFocusIntent`] and bound by default to the
3235/// arrow keys in `WidgetsApp`, with the appropriate associated directions.
3236pub struct DirectionalFocusAction {
3237    action: ActionData,
3238    /// Whether this action is defined in a text field.
3239    is_for_text_field: bool,
3240}
3241
3242impl DirectionalFocusAction {
3243    /// Creates a [`DirectionalFocusAction`].
3244    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    /// Creates a [`DirectionalFocusAction`] that ignores [`DirectionalFocusIntent`]s whose
3252    /// `ignore_text_fields` field is true.
3253    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// ---------------------------------------------------------------------------------------------
3280// ExcludeFocusTraversal
3281
3282/// A widget that controls whether or not the descendants of this widget are traversable.
3283///
3284/// Does not affect the value of [`AnyFocusNode::skip_traversal`] of the descendants.
3285///
3286/// See also:
3287///
3288///  * `Focus`, a widget for adding and managing a `FocusNode` in the widget tree.
3289///  * `ExcludeFocus`, a widget that excludes its descendants from focusability.
3290///  * [`FocusTraversalGroup`], a widget that groups widgets for focus traversal, and can also be
3291///    used in the same way as this widget by setting its `descendants_are_focusable` attribute.
3292#[derive(Debug)]
3293pub struct ExcludeFocusTraversal {
3294    /// See [`Widget::key`](crate::Widget::key).
3295    pub key: Option<KeyRef>,
3296
3297    /// If true, will make this widget's descendants untraversable.
3298    ///
3299    /// Defaults to true.
3300    ///
3301    /// Does not affect the value of [`AnyFocusNode::skip_traversal`] on the descendants.
3302    pub excluding: bool,
3303
3304    /// The child widget of this [`ExcludeFocusTraversal`].
3305    pub child: WidgetRef,
3306}
3307
3308impl ExcludeFocusTraversal {
3309    /// Creates an [`ExcludeFocusTraversal`] widget.
3310    #[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    /// Dart `ExcludeFocusTraversal(key:)`.
3320    pub fn key(mut self, key: KeyRef) -> ExcludeFocusTraversal {
3321        self.key = Some(key);
3322        self
3323    }
3324
3325    /// Dart `ExcludeFocusTraversal(excluding:)`.
3326    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    /// A `Focus` at a fixed place in a `Stack`, labelled so the traversal order can be read.
3356    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    /// Pumps the given children in a `Stack` under a [`FocusTraversalGroup`] with `policy`.
3361    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    /// Focuses `start`, then moves the focus `steps` times, collecting the label of the primary
3386    /// focus after each step.
3387    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    /// The three nodes: "x" to the right of "y", and "z" below both, in an order that is neither
3407    /// the widget order nor the reading order of the others.
3408    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            // "y" and "x" share the topmost band, left to right; "z" is below them.
3440            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            // Right to left: "x" comes before "y" in the topmost band.
3461            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            // The default is a closed loop: the last node wraps around to the first.
3531            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}