Skip to main content

waft_widgets/widgets/
focus_scope.rs

1//! Flutter counterpart: `widgets/focus_scope.dart`.
2
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt;
6use std::panic::Location;
7use std::rc::Rc;
8
9use waft_embedder::TargetPlatform;
10use waft_foundation::{
11    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle, Listener,
12    OptionRetained, Ref, StringProperty, ValueChanged,
13};
14
15use crate::framework::{
16    AnyElement, BuildContext, ComponentElement, ComponentElementData, CreationLocation, Element,
17    ElementData, ElementLifecycle, IntoWidget, KeyRef, ProxyElement, Slot, State, StateData,
18    StatefulWidget, Widget, WidgetKind, WidgetRef, component_element_overrides, downcast_widget,
19};
20use crate::widgets::basic::Semantics;
21use crate::widgets::focus_manager::{
22    AnyFocusNode, FocusAttachment, FocusNode, FocusNodeLeaf, FocusNodeRef, FocusOnKeyEventCallback,
23    FocusScopeNode,
24};
25
26/// A widget that manages a [`FocusNode`] to allow keyboard focus to be given to this widget and
27/// its descendants.
28///
29/// When the focus is gained or lost, [`on_focus_change`](Self::on_focus_change) is called.
30///
31/// For key events, [`on_key_event`](Self::on_key_event) is called if
32/// [`AnyFocusNode::has_focus`] is true for this widget's [`focus_node`](Self::focus_node),
33/// unless a focused descendant's `on_key_event` callback returned
34/// `KeyEventResult::Handled` when called.
35///
36/// This widget does not provide any visual indication that the focus has changed. Any desired
37/// visual changes should be made when [`on_focus_change`](Self::on_focus_change) is called.
38///
39/// To access the [`FocusNode`] of the nearest ancestor [`Focus`] widget and establish a
40/// relationship that will rebuild the widget when the focus changes, use the [`Focus::of`] and
41/// [`FocusScope::of`] static methods.
42///
43/// Managing a [`FocusNode`] means managing its lifecycle, listening for changes in focus, and
44/// re-parenting it when needed to keep the focus hierarchy in sync with the widget hierarchy.
45/// This widget does all of those things for you.
46///
47/// If the [`Focus::new`] constructor is used, then this widget will manage any given
48/// [`focus_node`](Self::focus_node) by overwriting the appropriate values of the node with the
49/// values of this widget whenever the [`Focus`] widget is updated.
50///
51/// If [`Focus::with_external_focus_node`] is used instead, then the values returned by
52/// [`on_key_event`](Self::on_key_event), [`skip_traversal`](Self::skip_traversal),
53/// [`can_request_focus`](Self::can_request_focus), and
54/// [`descendants_are_focusable`](Self::descendants_are_focusable) will be the values in the
55/// external focus node, and the external focus node's values will not be overwritten when the
56/// widget is updated.
57///
58/// To collect a sub-tree of nodes into an exclusive group that restricts focus traversal to the
59/// group, use a [`FocusScope`].
60pub struct Focus {
61    /// See [`Widget::key`].
62    pub key: Option<KeyRef>,
63
64    /// The optional parent node to use when reparenting the
65    /// [`focus_node`](Self::focus_node) for this [`Focus`] widget.
66    ///
67    /// If [`parent_node`](Self::parent_node) is `None`, then [`Focus::maybe_of`] is used to
68    /// find the parent in the widget tree, which is typically what is desired, since it is
69    /// easier to reason about the focus tree if it mirrors the shape of the widget tree.
70    ///
71    /// Set this property if the focus tree needs to have a different shape than the widget
72    /// tree. This is typically in cases where a dialog is in an `Overlay` (or another part of
73    /// the widget tree), and focus should behave as if the widgets in the overlay are
74    /// descendants of the given [`parent_node`](Self::parent_node) for purposes of focus.
75    ///
76    /// Defaults to `None`.
77    pub parent_node: Option<FocusNodeRef>,
78
79    /// The child widget of this [`Focus`].
80    pub child: WidgetRef,
81
82    /// An optional focus node to use as the focus node for this widget.
83    ///
84    /// If one is not supplied, then one will be automatically allocated, owned, and managed by
85    /// this widget. The widget will be focusable even if a
86    /// [`focus_node`](Self::focus_node) is not supplied. If supplied, the given node will be
87    /// _hosted_ by this widget, but not owned. See [`FocusNode`] for more information on what
88    /// being hosted and/or owned implies.
89    ///
90    /// A non-null [`focus_node`](Self::focus_node) must be supplied if using the
91    /// [`Focus::with_external_focus_node`] constructor.
92    pub focus_node: Option<FocusNodeRef>,
93
94    /// True if this widget will be selected as the initial focus when no other node in its
95    /// scope is currently focused.
96    ///
97    /// Ideally, there is only one widget with autofocus set in each [`FocusScope`]. If there is
98    /// more than one widget with autofocus set, then the first one added to the tree will get
99    /// focus.
100    ///
101    /// Defaults to false.
102    pub autofocus: bool,
103
104    /// Handler called when the focus changes.
105    ///
106    /// Called with true if this widget's node gains focus, and false if it loses focus.
107    pub on_focus_change: Option<ValueChanged<bool>>,
108
109    /// Include semantics information in this widget.
110    ///
111    /// Defaults to true.
112    pub include_semantics: bool,
113
114    /// Dart's `Focus._usingExternalFocus`: whether the widget's focus node attributes should
115    /// have priority when the widget is updated.
116    using_external_focus: bool,
117
118    /// Dart's `Focus._onKeyEvent`.
119    on_key_event: Option<FocusOnKeyEventCallback>,
120
121    /// Dart's `Focus._canRequestFocus`.
122    can_request_focus: Option<bool>,
123
124    /// Dart's `Focus._skipTraversal`.
125    skip_traversal: Option<bool>,
126
127    /// Dart's `Focus._descendantsAreFocusable`.
128    descendants_are_focusable: Option<bool>,
129
130    /// Dart's `Focus._descendantsAreTraversable`.
131    descendants_are_traversable: Option<bool>,
132
133    /// Dart's `Focus._debugLabel`.
134    debug_label: Option<String>,
135}
136
137impl Focus {
138    /// Creates a widget that manages a [`FocusNode`].
139    #[cfg_attr(debug_assertions, track_caller)]
140    pub fn new<K>(child: impl IntoWidget<K>) -> Focus {
141        Focus {
142            key: None,
143            parent_node: None,
144            child: child.into_widget(),
145            focus_node: None,
146            autofocus: false,
147            on_focus_change: None,
148            include_semantics: true,
149            using_external_focus: false,
150            on_key_event: None,
151            can_request_focus: None,
152            skip_traversal: None,
153            descendants_are_focusable: None,
154            descendants_are_traversable: None,
155            debug_label: None,
156        }
157    }
158
159    /// Creates a [`Focus`] widget that uses the given `focus_node` as the source of truth for
160    /// attributes on the node, rather than the attributes of this widget.
161    #[cfg_attr(debug_assertions, track_caller)]
162    pub fn with_external_focus_node<K>(
163        child: impl IntoWidget<K>,
164        focus_node: FocusNodeRef,
165    ) -> Focus {
166        Focus {
167            focus_node: Some(focus_node),
168            using_external_focus: true,
169            ..Focus::new(child)
170        }
171    }
172
173    /// Dart `Focus(key:)`.
174    pub fn key(mut self, key: KeyRef) -> Focus {
175        self.key = Some(key);
176        self
177    }
178
179    /// Dart `Focus(parentNode:)`.
180    pub fn parent_node(mut self, parent_node: FocusNodeRef) -> Focus {
181        self.parent_node = Some(parent_node);
182        self
183    }
184
185    /// Dart `Focus(focusNode:)`.
186    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Focus {
187        self.focus_node = Some(focus_node);
188        self
189    }
190
191    /// Dart `Focus(autofocus:)`.
192    pub fn autofocus(mut self, autofocus: bool) -> Focus {
193        self.autofocus = autofocus;
194        self
195    }
196
197    /// Dart `Focus(onFocusChange:)`.
198    pub fn on_focus_change(mut self, on_focus_change: impl Fn(&mut App, bool) + 'static) -> Focus {
199        self.on_focus_change = Some(Rc::new(on_focus_change));
200        self
201    }
202
203    /// Dart `Focus(onKeyEvent:)`.
204    pub fn on_key_event(mut self, on_key_event: FocusOnKeyEventCallback) -> Focus {
205        self.on_key_event = Some(on_key_event);
206        self
207    }
208
209    /// Dart `Focus(canRequestFocus:)`.
210    pub fn can_request_focus(mut self, can_request_focus: bool) -> Focus {
211        self.can_request_focus = Some(can_request_focus);
212        self
213    }
214
215    /// Dart `Focus(skipTraversal:)`.
216    pub fn skip_traversal(mut self, skip_traversal: bool) -> Focus {
217        self.skip_traversal = Some(skip_traversal);
218        self
219    }
220
221    /// Dart `Focus(descendantsAreFocusable:)`.
222    pub fn descendants_are_focusable(mut self, descendants_are_focusable: bool) -> Focus {
223        self.descendants_are_focusable = Some(descendants_are_focusable);
224        self
225    }
226
227    /// Dart `Focus(descendantsAreTraversable:)`.
228    pub fn descendants_are_traversable(mut self, descendants_are_traversable: bool) -> Focus {
229        self.descendants_are_traversable = Some(descendants_are_traversable);
230        self
231    }
232
233    /// Dart `Focus(includeSemantics:)`.
234    pub fn include_semantics(mut self, include_semantics: bool) -> Focus {
235        self.include_semantics = include_semantics;
236        self
237    }
238
239    /// Dart `Focus(debugLabel:)`.
240    pub fn debug_label(mut self, debug_label: impl Into<String>) -> Focus {
241        self.debug_label = Some(debug_label.into());
242        self
243    }
244
245    // ---- the getters `_FocusState` reads; a `withExternalFocusNode` widget leaves every
246    // private field unset, so the node is already the source of truth ----
247
248    /// A handler for keys that are pressed when this object or one of its children has focus.
249    ///
250    /// Key events are first given to the [`FocusNode`] that has primary focus, and if its
251    /// `on_key_event` returns `KeyEventResult::Ignored`, then they are given to each ancestor
252    /// node up the focus hierarchy in turn. If an event reaches the root of the hierarchy, it
253    /// is discarded.
254    pub fn get_on_key_event(&self, app: &App) -> Option<FocusOnKeyEventCallback> {
255        self.on_key_event.clone().or_else(|| {
256            self.focus_node
257                .handle()
258                .and_then(|node| node.on_key_event(app))
259        })
260    }
261
262    /// If true, this widget may request the primary focus.
263    ///
264    /// Defaults to true. Set to false if you want the [`FocusNode`] this widget manages to do
265    /// nothing when [`AnyFocusNode::request_focus`] is called on it. Does not affect the
266    /// children of this node, and [`AnyFocusNode::has_focus`] can still return true if this
267    /// node is the ancestor of the primary focus.
268    pub fn get_can_request_focus(&self, app: &App) -> bool {
269        let (explicit, node) = (self.can_request_focus, self.focus_node.handle());
270        Focus::resolve_can_request_focus(explicit, node, app)
271    }
272
273    /// The body of [`get_can_request_focus`](Self::get_can_request_focus), over copies of the
274    /// two fields it reads: reading the node needs `&mut App`, which a borrow of the widget
275    /// out of the arena would conflict with.
276    fn resolve_can_request_focus(
277        explicit: Option<bool>,
278        node: Option<AnyFocusNode>,
279        app: &App,
280    ) -> bool {
281        explicit
282            .or_else(|| node.map(|node| node.can_request_focus(app)))
283            .unwrap_or(true)
284    }
285
286    /// Sets the [`AnyFocusNode::skip_traversal`] flag on the focus node so that it won't be
287    /// visited by the `FocusTraversalPolicy`.
288    pub fn get_skip_traversal(&self, app: &mut App) -> bool {
289        let (explicit, node) = (self.skip_traversal, self.focus_node.handle());
290        Focus::resolve_skip_traversal(explicit, node, app)
291    }
292
293    /// The body of [`get_skip_traversal`](Self::get_skip_traversal); see
294    /// [`resolve_can_request_focus`](Self::resolve_can_request_focus).
295    fn resolve_skip_traversal(
296        explicit: Option<bool>,
297        node: Option<AnyFocusNode>,
298        app: &mut App,
299    ) -> bool {
300        explicit
301            .or_else(|| node.map(|node| node.skip_traversal(app)))
302            .unwrap_or(false)
303    }
304
305    /// If false, will make this widget's descendants unfocusable.
306    ///
307    /// Defaults to true. Does not affect focusability of this node (just its descendants): for
308    /// that, use [`AnyFocusNode::can_request_focus`].
309    pub fn get_descendants_are_focusable(&self, app: &App) -> bool {
310        self.descendants_are_focusable
311            .or_else(|| {
312                self.focus_node
313                    .handle()
314                    .map(|node| node.descendants_are_focusable(app))
315            })
316            .unwrap_or(true)
317    }
318
319    /// If false, will make this widget's descendants untraversable.
320    ///
321    /// Defaults to true. Does not affect traversability of this node (just its descendants):
322    /// for that, use [`AnyFocusNode::skip_traversal`].
323    pub fn get_descendants_are_traversable(&self, app: &App) -> bool {
324        self.descendants_are_traversable
325            .or_else(|| {
326                self.focus_node
327                    .handle()
328                    .map(|node| node.descendants_are_traversable(app))
329            })
330            .unwrap_or(true)
331    }
332
333    /// A debug label for this widget.
334    pub fn get_debug_label(&self, app: &App) -> Option<String> {
335        self.debug_label.clone().or_else(|| {
336            self.focus_node
337                .handle()
338                .and_then(|node| node.debug_label(app))
339        })
340    }
341
342    /// Returns the focus node of the [`Focus`] that most tightly encloses the given
343    /// `BuildContext`.
344    ///
345    /// If no [`Focus`] node is found before reaching the nearest [`FocusScope`] widget, or
346    /// there is no [`Focus`] widget in the context, then this method panics.
347    ///
348    /// If `create_dependency` is true, calling this function creates a dependency that will
349    /// rebuild the given context when the focus node gains or loses focus.
350    pub fn of(
351        app: &mut App,
352        context: BuildContext,
353        scope_ok: bool,
354        create_dependency: bool,
355    ) -> AnyFocusNode {
356        let node = Focus::maybe_of(app, context, scope_ok, create_dependency);
357        let node = node.expect(
358            "Focus.of() was called with a context that does not contain a Focus widget.\n\
359             No Focus widget ancestor could be found starting from the context that was passed \
360             to Focus.of(). This can happen because you are using a widget that looks for a \
361             Focus ancestor, and do not have a Focus widget descendant in the nearest \
362             FocusScope.",
363        );
364        debug_assert!(
365            scope_ok || node.as_scope().is_none(),
366            "Focus.of() was called with a context that does not contain a Focus between the \
367             given context and the nearest FocusScope widget."
368        );
369        node
370    }
371
372    /// Returns the focus node of the [`Focus`] that most tightly encloses the given
373    /// `BuildContext`.
374    ///
375    /// If no [`Focus`] node is found before reaching the nearest [`FocusScope`] widget, or
376    /// there is no [`Focus`] widget in scope, then this method returns `None`.
377    ///
378    /// If `create_dependency` is true, calling this function creates a dependency that will
379    /// rebuild the given context when the focus node gains or loses focus.
380    pub fn maybe_of(
381        app: &mut App,
382        context: BuildContext,
383        scope_ok: bool,
384        create_dependency: bool,
385    ) -> Option<AnyFocusNode> {
386        let node = if create_dependency {
387            context
388                .depend_on_inherited_widget_of_exact_type::<FocusInheritedScope>(app)
389                .map(|scope| scope.node.handle())
390        } else {
391            context
392                .get_inherited_widget_of_exact_type::<FocusInheritedScope>(app)
393                .map(|scope| scope.node.handle())
394        }?;
395        match node.as_scope() {
396            Some(_) if !scope_ok => None,
397            _ => Some(node),
398        }
399    }
400
401    /// Returns true if the nearest enclosing [`Focus`] widget's node is focused.
402    ///
403    /// A convenience method to allow build methods to write `Focus::is_at(app, context)` to get
404    /// whether or not the nearest [`Focus`] above them in the widget hierarchy currently has
405    /// the input focus.
406    ///
407    /// Returns false if no [`Focus`] widget is found before reaching the nearest
408    /// [`FocusScope`], or if the root of the focus tree is reached without finding a [`Focus`]
409    /// widget.
410    ///
411    /// Calling this function creates a dependency that will rebuild the given context when the
412    /// focus changes.
413    pub fn is_at(app: &mut App, context: BuildContext) -> bool {
414        match Focus::maybe_of(app, context, false, true) {
415            Some(node) => node.has_focus(app),
416            None => false,
417        }
418    }
419}
420
421impl fmt::Debug for Focus {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        f.debug_struct("Focus")
424            .field("debugLabel", &self.debug_label)
425            .field("autofocus", &self.autofocus)
426            .field("focusNode", &self.focus_node)
427            .finish_non_exhaustive()
428    }
429}
430
431impl StatefulWidget for Focus {
432    type State = FocusState;
433
434    fn key(&self) -> Option<&KeyRef> {
435        self.key.as_ref()
436    }
437
438    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
439        properties.add(StringProperty::new("debugLabel", self.get_debug_label(app)));
440        properties.add(
441            FlagProperty::new("autofocus", Some(self.autofocus))
442                .if_true("AUTOFOCUS")
443                .default_value(Some(false)),
444        );
445        properties.add(
446            FlagProperty::new("canRequestFocus", Some(self.get_can_request_focus(app)))
447                .if_false("NOT FOCUSABLE")
448                .default_value(Some(false)),
449        );
450        properties.add(
451            FlagProperty::new(
452                "descendantsAreFocusable",
453                Some(self.get_descendants_are_focusable(app)),
454            )
455            .if_false("DESCENDANTS UNFOCUSABLE")
456            .default_value(Some(true)),
457        );
458        properties.add(
459            FlagProperty::new(
460                "descendantsAreTraversable",
461                Some(self.get_descendants_are_traversable(app)),
462            )
463            .if_false("DESCENDANTS UNTRAVERSABLE")
464            .default_value(Some(true)),
465        );
466        properties.add(
467            DiagnosticsProperty::<String>::new(
468                "focusNode",
469                self.focus_node.handle().map(|node| node.to_string(app)),
470            )
471            .default_value(None),
472        );
473    }
474
475    fn create_state(&self) -> FocusState {
476        FocusState {
477            state: StateData::new(),
478            focus: FocusStateData::new(),
479        }
480    }
481}
482
483/// Dart's private members of `_FocusState`; both [`FocusState`] and [`FocusScopeState`] carry
484/// this bag under the field `focus`.
485pub struct FocusStateData {
486    internal_node: Option<FocusNodeRef>,
487    had_primary_focus: bool,
488    could_request_focus: bool,
489    descendants_were_focusable: bool,
490    descendants_were_traversable: bool,
491    did_autofocus: bool,
492    focus_attachment: Option<Ref<FocusAttachment>>,
493}
494
495impl FocusStateData {
496    /// A state that has not run `init_state` yet.
497    pub fn new() -> FocusStateData {
498        FocusStateData {
499            internal_node: None,
500            had_primary_focus: false,
501            could_request_focus: false,
502            descendants_were_focusable: false,
503            descendants_were_traversable: false,
504            did_autofocus: false,
505            focus_attachment: None,
506        }
507    }
508}
509
510impl Default for FocusStateData {
511    fn default() -> FocusStateData {
512        FocusStateData::new()
513    }
514}
515
516/// The shared bodies of Dart's `_FocusState`, which `_FocusScopeState` extends.
517///
518/// [`create_node`](Self::create_node) is the only virtual; the rest are Dart's `_FocusState`
519/// members, and each state's `State` hooks call them where Dart's inherited body would run.
520pub trait FocusStateLeaf: State + Sized + 'static {
521    /// Dart's `_FocusState` fields, held under the field `focus`.
522    fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData;
523
524    /// See [`focus_state_data`](Self::focus_state_data).
525    fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData;
526
527    /// The `Focus` fields of this state's widget: the widget itself for [`Focus`], the
528    /// superclass bag for [`FocusScope`].
529    fn focus_widget(self: Handle<Self>, app: &App) -> &Focus;
530
531    /// Dart's `_FocusState._createNode`.
532    fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef;
533
534    /// Dart's `widget.canRequestFocus`.
535    fn widget_can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
536        let widget = self.focus_widget(app);
537        let (explicit, node) = (widget.can_request_focus, widget.focus_node.handle());
538        Focus::resolve_can_request_focus(explicit, node, app)
539    }
540
541    /// Dart's `widget.skipTraversal`.
542    fn widget_skip_traversal(self: Handle<Self>, app: &mut App) -> bool {
543        let widget = self.focus_widget(app);
544        let (explicit, node) = (widget.skip_traversal, widget.focus_node.handle());
545        Focus::resolve_skip_traversal(explicit, node, app)
546    }
547
548    /// Dart's `_FocusState.focusNode`.
549    fn focus_node(self: Handle<Self>, app: &mut App) -> AnyFocusNode {
550        if let Some(node) = self.focus_widget(app).focus_node.handle() {
551            return node;
552        }
553        if let Some(node) = self.focus_state_data(app).internal_node.handle() {
554            return node;
555        }
556        let node = self.create_node(app);
557        let handle = node.handle();
558        self.focus_state_data_mut(app).internal_node = Some(node);
559        handle
560    }
561
562    /// [`focus_node`](Self::focus_node) as the reference a widget built from this state keeps.
563    fn kept_focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
564        let node = self.focus_node(app);
565        node.keep(app)
566    }
567
568    /// Dart's `_FocusState._initNode`.
569    fn init_node(self: Handle<Self>, app: &mut App) {
570        let focus_node = self.focus_node(app);
571        if !self.focus_widget(app).using_external_focus {
572            let descendants_are_focusable =
573                self.focus_widget(app).get_descendants_are_focusable(app);
574            focus_node.set_descendants_are_focusable(app, descendants_are_focusable);
575            let descendants_are_traversable =
576                self.focus_widget(app).get_descendants_are_traversable(app);
577            focus_node.set_descendants_are_traversable(app, descendants_are_traversable);
578            let skip_traversal = self.widget_skip_traversal(app);
579            focus_node.set_skip_traversal(app, skip_traversal);
580            if let Some(can_request_focus) = self.focus_widget(app).can_request_focus {
581                focus_node.set_can_request_focus(app, can_request_focus);
582            }
583        }
584        let could_request_focus = focus_node.can_request_focus(app);
585        let descendants_were_focusable = focus_node.descendants_are_focusable(app);
586        let descendants_were_traversable = focus_node.descendants_are_traversable(app);
587        let had_primary_focus = focus_node.has_primary_focus(app);
588        let data = self.focus_state_data_mut(app);
589        data.could_request_focus = could_request_focus;
590        data.descendants_were_focusable = descendants_were_focusable;
591        data.descendants_were_traversable = descendants_were_traversable;
592        data.had_primary_focus = had_primary_focus;
593        let context = self.context(app);
594        let on_key_event = self.focus_widget(app).get_on_key_event(app);
595        let attachment = focus_node.attach(app, Some(context), on_key_event);
596        self.focus_state_data_mut(app).focus_attachment = Some(attachment);
597
598        // Add listener even if the internal node existed before, since it should not be
599        // listening now if we're re-using a previous one because it should have already
600        // removed its listener.
601        focus_node.add_listener(
602            app,
603            Listener::handle_method(self, Self::handle_focus_changed),
604        );
605    }
606
607    /// Dart's `_FocusState.dispose`.
608    fn dispose_focus(self: Handle<Self>, app: &mut App) {
609        // Regardless of the node owner, we need to remove it from the tree and stop listening
610        // to it.
611        let focus_node = self.focus_node(app);
612        focus_node.remove_listener(
613            app,
614            &Listener::handle_method(self, Self::handle_focus_changed),
615        );
616        self.focus_state_data(app)
617            .focus_attachment
618            .handle()
619            .expect("attached in init_state")
620            .detach(app);
621
622        // Don't manage the lifetime of external nodes given to the widget, just the internal
623        // node.
624        if let Some(internal_node) = self.focus_state_data(app).internal_node.handle() {
625            internal_node.dispose(app);
626        }
627    }
628
629    /// Dart's `_FocusState.didChangeDependencies`.
630    fn did_change_dependencies_focus(self: Handle<Self>, app: &mut App) {
631        if let Some(attachment) = self.focus_state_data(app).focus_attachment.handle() {
632            attachment.reparent(app, None);
633        }
634        self.handle_autofocus(app);
635    }
636
637    /// Dart's `_FocusState._handleAutofocus`.
638    fn handle_autofocus(self: Handle<Self>, app: &mut App) {
639        if !self.focus_state_data(app).did_autofocus && self.focus_widget(app).autofocus {
640            let context = self.context(app);
641            let scope = FocusScope::of(app, context, true);
642            let focus_node = self.focus_node(app);
643            scope.autofocus(app, focus_node);
644            self.focus_state_data_mut(app).did_autofocus = true;
645        }
646    }
647
648    /// Dart's `_FocusState.deactivate`.
649    ///
650    /// The focus node's location in the tree is no longer valid here. But we can't unfocus or
651    /// remove the node from the tree because if the widget is moved to a different part of the
652    /// tree (via global key) it should retain its focus state. That's why we temporarily park
653    /// it on the root focus node (via reparent) until it either gets moved to a different part
654    /// of the tree (via `did_change_dependencies`) or until it is disposed.
655    fn deactivate_focus(self: Handle<Self>, app: &mut App) {
656        if let Some(attachment) = self.focus_state_data(app).focus_attachment.handle() {
657            attachment.reparent(app, None);
658        }
659        self.focus_state_data_mut(app).did_autofocus = false;
660    }
661
662    /// Dart's `_FocusState.didUpdateWidget`.
663    fn did_update_widget_focus(self: Handle<Self>, app: &mut App, old_widget: &Focus) {
664        if cfg!(debug_assertions) {
665            // Only update the debug label in debug builds.
666            let widget_label = self.focus_widget(app).debug_label.clone();
667            if old_widget.focus_node == self.focus_widget(app).focus_node
668                && !self.focus_widget(app).using_external_focus
669                && old_widget.debug_label != widget_label
670            {
671                let focus_node = self.focus_node(app);
672                let label = self.focus_widget(app).get_debug_label(app);
673                focus_node.set_debug_label(app, label);
674            }
675        }
676
677        if old_widget.focus_node == self.focus_widget(app).focus_node {
678            if !self.focus_widget(app).using_external_focus {
679                let focus_node = self.focus_node(app);
680                let on_key_event = self.focus_widget(app).get_on_key_event(app);
681                let same_handler = match (&on_key_event, &focus_node.on_key_event(app)) {
682                    (None, None) => true,
683                    (Some(a), Some(b)) => Rc::ptr_eq(a, b),
684                    _ => false,
685                };
686                if !same_handler {
687                    focus_node.set_on_key_event(app, on_key_event);
688                }
689                let skip_traversal = self.widget_skip_traversal(app);
690                focus_node.set_skip_traversal(app, skip_traversal);
691                if let Some(can_request_focus) = self.focus_widget(app).can_request_focus {
692                    focus_node.set_can_request_focus(app, can_request_focus);
693                }
694                let descendants_are_focusable =
695                    self.focus_widget(app).get_descendants_are_focusable(app);
696                focus_node.set_descendants_are_focusable(app, descendants_are_focusable);
697                let descendants_are_traversable =
698                    self.focus_widget(app).get_descendants_are_traversable(app);
699                focus_node.set_descendants_are_traversable(app, descendants_are_traversable);
700            }
701        } else {
702            self.focus_state_data(app)
703                .focus_attachment
704                .handle()
705                .expect("attached in init_state")
706                .detach(app);
707            if let Some(old_node) = old_widget.focus_node.handle() {
708                old_node.remove_listener(
709                    app,
710                    &Listener::handle_method(self, Self::handle_focus_changed),
711                );
712            }
713            self.init_node(app);
714        }
715
716        if old_widget.autofocus != self.focus_widget(app).autofocus {
717            self.handle_autofocus(app);
718        }
719    }
720
721    /// Dart's `_FocusState._handleFocusChanged`.
722    fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
723        let focus_node = self.focus_node(app);
724        let has_primary_focus = focus_node.has_primary_focus(app);
725        let can_request_focus = focus_node.can_request_focus(app);
726        let descendants_are_focusable = focus_node.descendants_are_focusable(app);
727        let descendants_are_traversable = focus_node.descendants_are_traversable(app);
728        if let Some(on_focus_change) = self.focus_widget(app).on_focus_change.clone() {
729            let has_focus = focus_node.has_focus(app);
730            on_focus_change(app, has_focus);
731        }
732        // Check the cached states that matter here, and call set_state if they have changed.
733        if self.focus_state_data(app).had_primary_focus != has_primary_focus {
734            self.set_state(app, |state| {
735                state.focus_state_data_field().had_primary_focus = has_primary_focus;
736            });
737        }
738        if self.focus_state_data(app).could_request_focus != can_request_focus {
739            self.set_state(app, |state| {
740                state.focus_state_data_field().could_request_focus = can_request_focus;
741            });
742        }
743        if self.focus_state_data(app).descendants_were_focusable != descendants_are_focusable {
744            self.set_state(app, |state| {
745                state.focus_state_data_field().descendants_were_focusable =
746                    descendants_are_focusable;
747            });
748        }
749        if self.focus_state_data(app).descendants_were_traversable != descendants_are_traversable {
750            self.set_state(app, |state| {
751                state.focus_state_data_field().descendants_were_traversable =
752                    descendants_are_traversable;
753            });
754        }
755    }
756
757    /// The bag, reached from `&mut Self` inside a `set_state` callback.
758    fn focus_state_data_field(&mut self) -> &mut FocusStateData;
759}
760
761/// Dart's `_FocusState`.
762pub struct FocusState {
763    state: StateData<Focus>,
764    focus: FocusStateData,
765}
766
767impl FocusStateLeaf for FocusState {
768    fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData {
769        &app.get(self).focus
770    }
771
772    fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData {
773        &mut app.get_mut(self).focus
774    }
775
776    fn focus_state_data_field(&mut self) -> &mut FocusStateData {
777        &mut self.focus
778    }
779
780    fn focus_widget(self: Handle<Self>, app: &App) -> &Focus {
781        self.widget(app)
782    }
783
784    fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
785        let node = FocusNode::new(app);
786        let label = self.widget(app).get_debug_label(app);
787        node.set_debug_label(app, label);
788        let can_request_focus = self.widget_can_request_focus(app);
789        node.set_can_request_focus(app, can_request_focus);
790        let descendants_are_focusable = self.widget(app).get_descendants_are_focusable(app);
791        node.set_descendants_are_focusable(app, descendants_are_focusable);
792        let descendants_are_traversable = self.widget(app).get_descendants_are_traversable(app);
793        node.set_descendants_are_traversable(app, descendants_are_traversable);
794        let skip_traversal = self.widget_skip_traversal(app);
795        node.set_skip_traversal(app, skip_traversal);
796        node.into_erased()
797    }
798}
799
800impl State for FocusState {
801    type Widget = Focus;
802    crate::state_accessors!();
803
804    fn init_state(self: Handle<Self>, app: &mut App) {
805        self.init_node(app);
806    }
807
808    fn dispose(self: Handle<Self>, app: &mut App) {
809        self.dispose_focus(app);
810    }
811
812    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
813        self.did_change_dependencies_focus(app);
814    }
815
816    fn deactivate(self: Handle<Self>, app: &mut App) {
817        self.deactivate_focus(app);
818    }
819
820    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Focus) {
821        self.did_update_widget_focus(app, old_widget);
822    }
823
824    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
825        let parent_node = self.widget(app).parent_node.handle();
826        self.focus_state_data(app)
827            .focus_attachment
828            .handle()
829            .expect("attached in init_state")
830            .reparent(app, parent_node);
831        let mut child = self.widget(app).child.clone();
832        let node = self.kept_focus_node(app);
833        if self.widget(app).include_semantics {
834            let could_request_focus = self.focus_state_data(app).could_request_focus;
835            let had_primary_focus = self.focus_state_data(app).had_primary_focus;
836            let mut semantics = Semantics::new().focusable(could_request_focus);
837            // Automatically request the focus for a focusable widget when it
838            // receives an input focus action from the semantics. Nothing is needed
839            // for losing the focus because if focus is lost, that means another
840            // node will gain focus and take focus from this widget.
841            // TODO(gspencergoog): Allow this to be set on iOS once the issue is
842            // addressed: https://github.com/flutter/flutter/issues/150030
843            if app.platform().target_platform() != TargetPlatform::IOS && could_request_focus {
844                let node = node.clone();
845                semantics =
846                    semantics.on_focus(Rc::new(move |app: &mut App| node.request_focus(app, None)));
847            }
848            if could_request_focus {
849                semantics = semantics.focused(had_primary_focus);
850            }
851            child = semantics.child(child).into_widget();
852        }
853        // Dart wraps the child in a `_DebugFocusBorder` when `debugPaintFocusBoxes` is set;
854        // that waits.
855        FocusInheritedScope {
856            node,
857            child,
858            created: None,
859        }
860        .into_widget()
861    }
862}
863
864// ---------------------------------------------------------------------------------------------
865// FocusScope
866
867/// A [`FocusScope`] is similar to a [`Focus`], but also serves as a scope for its descendants,
868/// restricting focus traversal to the scoped controls.
869///
870/// For example a new [`FocusScope`] is created automatically when a route is pushed, keeping
871/// the focus traversal from moving to a control in a previous route.
872///
873/// Like [`Focus`], [`FocusScope`] provides an `on_focus_change` as a way to be notified when
874/// the focus is given to or removed from this widget.
875///
876/// Managing a [`FocusScopeNode`] means managing its lifecycle, listening for changes in focus,
877/// and re-parenting it when needed to keep the focus hierarchy in sync with the widget
878/// hierarchy. This widget does all of those things for you.
879///
880/// [`FocusScopeNode`]s remember the last [`FocusNode`] that was focused within their
881/// descendants.
882pub struct FocusScope {
883    /// Dart's `class FocusScope extends Focus`: the superclass's fields.
884    focus: Focus,
885}
886
887impl FocusScope {
888    /// Creates a widget that manages a [`FocusScopeNode`].
889    #[cfg_attr(debug_assertions, track_caller)]
890    pub fn new<K>(child: impl IntoWidget<K>) -> FocusScope {
891        FocusScope {
892            focus: Focus::new(child),
893        }
894    }
895
896    /// Creates a [`FocusScope`] widget that uses the given `focus_scope_node` as the source of
897    /// truth for attributes on the node, rather than the attributes of this widget.
898    #[cfg_attr(debug_assertions, track_caller)]
899    pub fn with_external_focus_node<K>(
900        child: impl IntoWidget<K>,
901        focus_scope_node: Ref<FocusScopeNode>,
902    ) -> FocusScope {
903        FocusScope {
904            focus: Focus::with_external_focus_node(child, focus_scope_node.into_erased()),
905        }
906    }
907
908    /// Dart `FocusScope(node:)`.
909    pub fn node(mut self, node: Ref<FocusScopeNode>) -> FocusScope {
910        self.focus.focus_node = Some(node.into_erased());
911        self
912    }
913
914    /// Dart `FocusScope(key:)`.
915    pub fn key(mut self, key: KeyRef) -> FocusScope {
916        self.focus = self.focus.key(key);
917        self
918    }
919
920    /// Dart `FocusScope(parentNode:)`.
921    pub fn parent_node(mut self, parent_node: FocusNodeRef) -> FocusScope {
922        self.focus = self.focus.parent_node(parent_node);
923        self
924    }
925
926    /// Dart `FocusScope(autofocus:)`.
927    pub fn autofocus(mut self, autofocus: bool) -> FocusScope {
928        self.focus = self.focus.autofocus(autofocus);
929        self
930    }
931
932    /// Dart `FocusScope(onFocusChange:)`.
933    pub fn on_focus_change(
934        mut self,
935        on_focus_change: impl Fn(&mut App, bool) + 'static,
936    ) -> FocusScope {
937        self.focus = self.focus.on_focus_change(on_focus_change);
938        self
939    }
940
941    /// Dart `FocusScope(onKeyEvent:)`.
942    pub fn on_key_event(mut self, on_key_event: FocusOnKeyEventCallback) -> FocusScope {
943        self.focus = self.focus.on_key_event(on_key_event);
944        self
945    }
946
947    /// Dart `FocusScope(canRequestFocus:)`.
948    pub fn can_request_focus(mut self, can_request_focus: bool) -> FocusScope {
949        self.focus = self.focus.can_request_focus(can_request_focus);
950        self
951    }
952
953    /// Dart `FocusScope(skipTraversal:)`.
954    pub fn skip_traversal(mut self, skip_traversal: bool) -> FocusScope {
955        self.focus = self.focus.skip_traversal(skip_traversal);
956        self
957    }
958
959    /// Dart `FocusScope(descendantsAreFocusable:)`.
960    pub fn descendants_are_focusable(mut self, descendants_are_focusable: bool) -> FocusScope {
961        self.focus = self
962            .focus
963            .descendants_are_focusable(descendants_are_focusable);
964        self
965    }
966
967    /// Dart `FocusScope(descendantsAreTraversable:)`.
968    pub fn descendants_are_traversable(mut self, descendants_are_traversable: bool) -> FocusScope {
969        self.focus = self
970            .focus
971            .descendants_are_traversable(descendants_are_traversable);
972        self
973    }
974
975    /// Dart `FocusScope(includeSemantics:)`.
976    pub fn include_semantics(mut self, include_semantics: bool) -> FocusScope {
977        self.focus = self.focus.include_semantics(include_semantics);
978        self
979    }
980
981    /// Dart `FocusScope(debugLabel:)`.
982    pub fn debug_label(mut self, debug_label: impl Into<String>) -> FocusScope {
983        self.focus = self.focus.debug_label(debug_label);
984        self
985    }
986
987    /// The `Focus` fields this widget inherits.
988    pub fn focus(&self) -> &Focus {
989        &self.focus
990    }
991
992    /// Returns the [`AnyFocusNode::nearest_scope`] of the [`Focus`] or [`FocusScope`] that most
993    /// tightly encloses the given `context`.
994    ///
995    /// If this node doesn't have a [`Focus`] or [`FocusScope`] widget ancestor, then the
996    /// [`FocusManager`](crate::FocusManager)'s root scope is returned.
997    pub fn of(
998        app: &mut App,
999        context: BuildContext,
1000        create_dependency: bool,
1001    ) -> Handle<FocusScopeNode> {
1002        Focus::maybe_of(app, context, true, create_dependency)
1003            .and_then(|node| node.nearest_scope(app))
1004            .unwrap_or_else(|| {
1005                let owner = context
1006                    .owner(app)
1007                    .expect("a mounted element has a build owner");
1008                let manager = owner.focus_manager(app);
1009                manager.root_scope(app).handle()
1010            })
1011    }
1012}
1013
1014impl fmt::Debug for FocusScope {
1015    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1016        f.debug_struct("FocusScope")
1017            .field("focus", &self.focus)
1018            .finish()
1019    }
1020}
1021
1022impl StatefulWidget for FocusScope {
1023    type State = FocusScopeState;
1024
1025    fn key(&self) -> Option<&KeyRef> {
1026        self.focus.key.as_ref()
1027    }
1028
1029    fn create_state(&self) -> FocusScopeState {
1030        FocusScopeState {
1031            state: StateData::new(),
1032            focus: FocusStateData::new(),
1033        }
1034    }
1035}
1036
1037/// Dart's `_FocusScopeState`.
1038pub struct FocusScopeState {
1039    state: StateData<FocusScope>,
1040    focus: FocusStateData,
1041}
1042
1043impl FocusStateLeaf for FocusScopeState {
1044    fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData {
1045        &app.get(self).focus
1046    }
1047
1048    fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData {
1049        &mut app.get_mut(self).focus
1050    }
1051
1052    fn focus_state_data_field(&mut self) -> &mut FocusStateData {
1053        &mut self.focus
1054    }
1055
1056    fn focus_widget(self: Handle<Self>, app: &App) -> &Focus {
1057        &self.widget(app).focus
1058    }
1059
1060    fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
1061        let node = FocusScopeNode::new(app);
1062        let label = self.focus_widget(app).get_debug_label(app);
1063        node.set_debug_label(app, label);
1064        let can_request_focus = self.widget_can_request_focus(app);
1065        node.set_can_request_focus(app, can_request_focus);
1066        let skip_traversal = self.widget_skip_traversal(app);
1067        node.set_skip_traversal(app, skip_traversal);
1068        node.into_erased()
1069    }
1070}
1071
1072impl State for FocusScopeState {
1073    type Widget = FocusScope;
1074    crate::state_accessors!();
1075
1076    fn init_state(self: Handle<Self>, app: &mut App) {
1077        self.init_node(app);
1078    }
1079
1080    fn dispose(self: Handle<Self>, app: &mut App) {
1081        self.dispose_focus(app);
1082    }
1083
1084    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1085        self.did_change_dependencies_focus(app);
1086    }
1087
1088    fn deactivate(self: Handle<Self>, app: &mut App) {
1089        self.deactivate_focus(app);
1090    }
1091
1092    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusScope) {
1093        self.did_update_widget_focus(app, &old_widget.focus);
1094    }
1095
1096    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1097        let parent_node = self.widget(app).focus.parent_node.handle();
1098        self.focus_state_data(app)
1099            .focus_attachment
1100            .handle()
1101            .expect("attached in init_state")
1102            .reparent(app, parent_node);
1103        let child = self.widget(app).focus.child.clone();
1104        let node = self.kept_focus_node(app);
1105        let result = FocusInheritedScope {
1106            node,
1107            child,
1108            created: None,
1109        }
1110        .into_widget();
1111        if self.widget(app).focus.include_semantics {
1112            return Semantics::new()
1113                .explicit_child_nodes(true)
1114                .child(result)
1115                .into_widget();
1116        }
1117        result
1118    }
1119}
1120
1121// ---------------------------------------------------------------------------------------------
1122// _FocusInheritedScope
1123
1124/// The `InheritedWidget` for [`Focus`] and [`FocusScope`].
1125///
1126/// Dart's `_FocusInheritedScope extends InheritedNotifier<FocusNode>`; the notifier behavior
1127/// lives in [`FocusInheritedScopeElement`] until `inherited_notifier.dart` is ported.
1128struct FocusInheritedScope {
1129    /// The [`AnyFocusNode`] to which to listen. Whenever it sends change notifications, the
1130    /// dependents of this widget are triggered.
1131    node: FocusNodeRef,
1132    child: WidgetRef,
1133    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
1134    created: Option<CreationLocation>,
1135}
1136
1137impl FocusInheritedScope {
1138    /// The tree node: an `InheritedWidget` with its own element, outside the `IntoWidget`
1139    /// kinds.
1140    #[cfg_attr(debug_assertions, track_caller)]
1141    fn into_widget(mut self) -> WidgetRef {
1142        self.created = Some(CreationLocation::of_caller());
1143        Rc::new(self)
1144    }
1145}
1146
1147impl fmt::Debug for FocusInheritedScope {
1148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1149        f.debug_struct("_FocusInheritedScope")
1150            .field("node", &self.node)
1151            .finish_non_exhaustive()
1152    }
1153}
1154
1155/// Dart's `InheritedNotifier.updateShouldNotify`; the trait also names the type
1156/// `Focus::maybe_of` looks up with `depend_on_inherited_widget_of_exact_type`.
1157impl crate::framework::InheritedWidget for FocusInheritedScope {
1158    fn child(&self) -> &WidgetRef {
1159        &self.child
1160    }
1161
1162    fn update_should_notify(&self, old_widget: &FocusInheritedScope) -> bool {
1163        old_widget.node != self.node
1164    }
1165}
1166
1167impl Widget for FocusInheritedScope {
1168    fn key(&self) -> Option<&KeyRef> {
1169        None
1170    }
1171
1172    fn creation_location(&self) -> Option<&'static Location<'static>> {
1173        self.created.and_then(CreationLocation::location)
1174    }
1175
1176    fn record_creation_location(&mut self, location: CreationLocation) {
1177        self.created = Some(location);
1178    }
1179
1180    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
1181        FocusInheritedScopeElement::new(app, this).as_element()
1182    }
1183
1184    fn as_any(&self) -> &dyn Any {
1185        self
1186    }
1187
1188    fn widget_type(&self) -> TypeId {
1189        TypeId::of::<FocusInheritedScope>()
1190    }
1191
1192    fn kind(&self) -> WidgetKind {
1193        WidgetKind::Other
1194    }
1195}
1196
1197/// Dart's `_InheritedNotifierElement<FocusNode>`, specialised to [`FocusInheritedScope`]: an
1198/// `InheritedElement` that marks itself dirty whenever the node notifies, and notifies its
1199/// dependents on the next build.
1200struct FocusInheritedScopeElement {
1201    element: ElementData,
1202    component: ComponentElementData,
1203    dependents: HashMap<AnyElement, Option<Rc<dyn Any>>>,
1204    dirty: bool,
1205}
1206
1207impl FocusInheritedScopeElement {
1208    fn new(app: &mut App, widget: WidgetRef) -> Handle<Self> {
1209        let node = FocusInheritedScopeElement::widget_of(&widget).node.handle();
1210        let this = app
1211            .create(FocusInheritedScopeElement {
1212                element: ElementData::new(widget),
1213                component: ComponentElementData::default(),
1214                dependents: HashMap::new(),
1215                dirty: false,
1216            })
1217            .into_tree_node(app);
1218        node.add_listener(
1219            app,
1220            Listener::handle_method(this, FocusInheritedScopeElement::handle_update),
1221        );
1222        this
1223    }
1224
1225    fn widget_of(widget: &WidgetRef) -> &FocusInheritedScope {
1226        downcast_widget::<FocusInheritedScope>(&**widget)
1227            .expect("a FocusInheritedScopeElement holds its FocusInheritedScope")
1228    }
1229
1230    fn widget(self: Handle<Self>, app: &App) -> &FocusInheritedScope {
1231        FocusInheritedScopeElement::widget_of(self.as_element().widget(app))
1232    }
1233
1234    fn handle_update(self: Handle<Self>, app: &mut App) {
1235        app.get_mut(self).dirty = true;
1236        self.as_element().mark_needs_build(app);
1237    }
1238
1239    /// `InheritedElement.notifyClients`, plus Dart's `_dirty` reset.
1240    fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
1241        let dependents: Vec<AnyElement> = app.get(self).dependents.keys().copied().collect();
1242        for dependent in dependents {
1243            let _ = &old_widget;
1244            dependent.did_change_dependencies(app);
1245        }
1246        app.get_mut(self).dirty = false;
1247    }
1248}
1249
1250impl ComponentElement for FocusInheritedScopeElement {
1251    fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
1252        &app.get(self).component
1253    }
1254
1255    fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
1256        &mut app.get_mut(self).component
1257    }
1258
1259    fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
1260        if app.get(self).dirty {
1261            let widget = self.as_element().widget(app).clone();
1262            FocusInheritedScopeElement::notify_clients(self, app, widget);
1263        }
1264        self.proxied_child(app)
1265    }
1266}
1267
1268impl ProxyElement for FocusInheritedScopeElement {
1269    fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
1270        self.widget(app).child.clone()
1271    }
1272
1273    fn updated(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
1274        // `InheritedNotifier.updateShouldNotify`: the notifier changed.
1275        let old_node = FocusInheritedScopeElement::widget_of(&old_widget)
1276            .node
1277            .handle();
1278        if old_node != self.widget(app).node {
1279            FocusInheritedScopeElement::notify_clients(self, app, old_widget);
1280        }
1281    }
1282
1283    fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
1284        FocusInheritedScopeElement::notify_clients(self, app, old_widget);
1285    }
1286}
1287
1288impl Element for FocusInheritedScopeElement {
1289    crate::element_accessors!();
1290    component_element_overrides!();
1291
1292    const IS_INHERITED_ELEMENT: bool = true;
1293
1294    #[inline(always)]
1295    fn mount(
1296        self: Handle<Self>,
1297        app: &mut App,
1298        parent: Option<AnyElement>,
1299        new_slot: Option<Slot>,
1300    ) {
1301        ComponentElement::mount(self, app, parent, new_slot);
1302    }
1303
1304    #[inline(always)]
1305    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
1306        let old_node = self.widget(app).node.handle();
1307        let new_node = FocusInheritedScopeElement::widget_of(&new_widget)
1308            .node
1309            .handle();
1310        if old_node != new_node {
1311            old_node.remove_listener(
1312                app,
1313                &Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
1314            );
1315            new_node.add_listener(
1316                app,
1317                Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
1318            );
1319        }
1320        ProxyElement::update(self, app, new_widget);
1321    }
1322
1323    #[inline(always)]
1324    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
1325        ComponentElement::perform_rebuild(self, app);
1326    }
1327
1328    fn unmount(self: Handle<Self>, app: &mut App) {
1329        let node = self.widget(app).node.handle();
1330        node.remove_listener(
1331            app,
1332            &Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
1333        );
1334        crate::framework::ElementBase::unmount(self, app);
1335    }
1336
1337    fn update_inheritance(self: Handle<Self>, app: &mut App) {
1338        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Active);
1339        let incoming = self
1340            .as_element()
1341            .parent(app)
1342            .and_then(|parent| parent.inherited_elements(app));
1343        let mut widgets: HashMap<TypeId, AnyElement> = incoming
1344            .map(|incoming| (*incoming).clone())
1345            .unwrap_or_default();
1346        widgets.insert(TypeId::of::<FocusInheritedScope>(), self.as_element());
1347        self.as_element()
1348            .set_inherited_elements(app, Some(Rc::new(widgets)));
1349    }
1350
1351    fn debug_deactivated(self: Handle<Self>, app: &mut App) {
1352        debug_assert!(app.get(self).dependents.is_empty());
1353        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
1354    }
1355
1356    fn update_dependencies(
1357        self: Handle<Self>,
1358        app: &mut App,
1359        dependent: AnyElement,
1360        _aspect: Option<Rc<dyn Any>>,
1361    ) {
1362        app.get_mut(self).dependents.insert(dependent, None);
1363    }
1364
1365    fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
1366        app.get_mut(self).dependents.remove(&dependent);
1367    }
1368}
1369
1370// ---------------------------------------------------------------------------------------------
1371// ExcludeFocus
1372
1373/// A widget that controls whether or not the descendants of this widget are focusable.
1374///
1375/// Does not affect the value of [`Focus::can_request_focus`] on the descendants.
1376#[derive(Debug)]
1377pub struct ExcludeFocus {
1378    /// See [`Widget::key`].
1379    pub key: Option<KeyRef>,
1380
1381    /// If true, will make this widget's descendants unfocusable.
1382    ///
1383    /// Defaults to true.
1384    ///
1385    /// If any descendants are focused when this is set to true, they will be unfocused. When
1386    /// [`excluding`](Self::excluding) is set to false again, they will not be refocused,
1387    /// although they will be able to accept focus again.
1388    ///
1389    /// Does not affect the value of [`AnyFocusNode::can_request_focus`] on the descendants.
1390    pub excluding: bool,
1391
1392    /// The child widget of this [`ExcludeFocus`].
1393    pub child: WidgetRef,
1394}
1395
1396impl ExcludeFocus {
1397    /// Creates an [`ExcludeFocus`] widget.
1398    #[cfg_attr(debug_assertions, track_caller)]
1399    pub fn new<K>(child: impl IntoWidget<K>) -> ExcludeFocus {
1400        ExcludeFocus {
1401            key: None,
1402            excluding: true,
1403            child: child.into_widget(),
1404        }
1405    }
1406
1407    /// Dart `ExcludeFocus(key:)`.
1408    pub fn key(mut self, key: KeyRef) -> ExcludeFocus {
1409        self.key = Some(key);
1410        self
1411    }
1412
1413    /// Dart `ExcludeFocus(excluding:)`.
1414    pub fn excluding(mut self, excluding: bool) -> ExcludeFocus {
1415        self.excluding = excluding;
1416        self
1417    }
1418}
1419
1420impl crate::framework::StatelessWidget for ExcludeFocus {
1421    fn key(&self) -> Option<&KeyRef> {
1422        self.key.as_ref()
1423    }
1424
1425    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1426        Focus::new(self.child.clone())
1427            .can_request_focus(false)
1428            .skip_traversal(true)
1429            .include_semantics(false)
1430            .descendants_are_focusable(!self.excluding)
1431            .into_widget()
1432    }
1433}
1434
1435#[cfg(test)]
1436mod tests {
1437    use std::cell::{Cell, RefCell};
1438
1439    use super::*;
1440    use crate::framework::GlobalKey;
1441    use crate::testing::test_widgets;
1442    use crate::widgets::basic::{Builder, Center, Padding, SizedBox};
1443    use crate::widgets::focus_manager::{FocusManager, FocusNode, KeyEventResult};
1444    use crate::widgets::value_listenable_builder::ValueListenableBuilder;
1445    use waft_foundation::ValueNotifier;
1446
1447    type Captured = Rc<Cell<Option<AnyFocusNode>>>;
1448
1449    /// A `Builder` that records `Focus.of` at its own context.
1450    fn probe(captured: &Captured) -> WidgetRef {
1451        let captured = Rc::clone(captured);
1452        Builder::new(move |app, context| {
1453            captured.set(Focus::maybe_of(app, context, false, true));
1454            SizedBox::shrink().into_widget()
1455        })
1456        .into_widget()
1457    }
1458
1459    /// A node a caller keeps outlives the `Focus` it hung under: `FocusNode._removeChild` clears
1460    /// its parent but leaves its cached ancestors, which the next `Focus` reads through
1461    /// `skipTraversal` before it attaches the node again.
1462    #[test]
1463    fn a_kept_node_remounts_after_the_focus_it_hung_under_is_freed() {
1464        test_widgets(|tester| {
1465            let mut app = tester.cell.borrow_mut();
1466            let node: FocusNodeRef = FocusNode::new(&mut app).into_erased();
1467            let layout = app.create(ValueNotifier::new(0));
1468            drop(app);
1469            let widget = ValueListenableBuilder::new(Rc::new(layout.clone()), {
1470                let node = node.clone();
1471                move |_app, _context, layout: &i32, _child| match layout {
1472                    0 => Focus::new(Focus::new(SizedBox::shrink()).focus_node(node.clone()))
1473                        .debug_label("outer")
1474                        .into_widget(),
1475                    1 => SizedBox::shrink().into_widget(),
1476                    _ => Focus::new(SizedBox::shrink())
1477                        .focus_node(node.clone())
1478                        .into_widget(),
1479                }
1480            });
1481            tester.pump_widget(widget.into_widget());
1482            let mut app = tester.cell.borrow_mut();
1483            let outer = node
1484                .parent(&app)
1485                .expect("the node hangs under the outer Focus");
1486            assert!(node.ancestors(&mut app).contains(&outer));
1487
1488            layout.set_value(&mut app, 1);
1489            drop(app);
1490            tester.pump();
1491            let app = tester.cell.borrow();
1492            assert_eq!(node.parent(&app), None);
1493            drop(app);
1494            tester.cell.checkpoint();
1495            let mut app = tester.cell.borrow_mut();
1496            assert!(!app.contains(outer));
1497
1498            layout.set_value(&mut app, 2);
1499            drop(app);
1500            tester.pump();
1501            let mut app = tester.cell.borrow_mut();
1502            assert!(!node.skip_traversal(&mut app));
1503            assert!(!node.ancestors(&mut app).contains(&outer));
1504        });
1505    }
1506
1507    #[test]
1508    fn autofocus_gives_the_focus_widgets_node_the_primary_focus() {
1509        test_widgets(|tester| {
1510            let app = tester.cell.borrow();
1511            let captured: Captured = Rc::default();
1512            drop(app);
1513            tester.pump_widget(Focus::new(probe(&captured)).autofocus(true).into_widget());
1514            let mut app = tester.cell.borrow_mut();
1515            let node = captured.get().expect("Focus.of found the node");
1516            assert!(node.has_primary_focus(&app));
1517            let manager = FocusManager::instance(&mut app);
1518            assert_eq!(manager.primary_focus(&app), Some(node));
1519        });
1520    }
1521
1522    #[test]
1523    fn focus_of_reports_has_focus_on_the_ancestor_and_primary_focus_on_the_leaf() {
1524        test_widgets(|tester| {
1525            let app = tester.cell.borrow();
1526            let outer: Captured = Rc::default();
1527            let inner: Captured = Rc::default();
1528            let inner_sink = Rc::clone(&inner);
1529            let outer_sink = Rc::clone(&outer);
1530            drop(app);
1531            tester.pump_widget(
1532                Focus::new(Builder::new(move |app, context| {
1533                    outer_sink.set(Focus::maybe_of(app, context, false, true));
1534                    Focus::new(probe(&inner_sink)).autofocus(true).into_widget()
1535                }))
1536                .debug_label("outer")
1537                .into_widget(),
1538            );
1539            let app = tester.cell.borrow_mut();
1540
1541            let outer = outer.get().expect("the outer Focus.of found nothing");
1542            let inner = inner.get().expect("the inner Focus.of found nothing");
1543            assert_ne!(outer, inner);
1544            assert_eq!(inner.parent(&app), Some(outer));
1545            assert!(inner.has_primary_focus(&app));
1546            assert!(inner.has_focus(&app));
1547            assert!(outer.has_focus(&app));
1548            assert!(!outer.has_primary_focus(&app));
1549            assert_eq!(outer.debug_label(&app).as_deref(), Some("outer"));
1550        });
1551    }
1552
1553    #[test]
1554    fn focus_scope_of_returns_the_enclosing_scope() {
1555        test_widgets(|tester| {
1556            // With no FocusScope of its own, the context reaches the one the `View` installs, which
1557            // hangs off the root scope through the view's `FocusTraversalGroup`.
1558            let app = tester.cell.borrow();
1559            let scope_node = Rc::new(Cell::new(None));
1560            let sink = Rc::clone(&scope_node);
1561            drop(app);
1562            tester.pump_widget(
1563                Builder::new(move |app, context| {
1564                    sink.set(Some(FocusScope::of(app, context, true)));
1565                    SizedBox::shrink().into_widget()
1566                })
1567                .into_widget(),
1568            );
1569            let mut app = tester.cell.borrow_mut();
1570            let manager = FocusManager::instance(&mut app);
1571            let view_scope = scope_node.get().expect("FocusScope.of ran");
1572            assert_ne!(view_scope, manager.root_scope(&app).handle());
1573            assert_eq!(view_scope.debug_label(&app).as_deref(), Some("View Scope"));
1574            assert_eq!(
1575                view_scope.enclosing_scope(&mut app),
1576                Some(manager.root_scope(&app).handle())
1577            );
1578        });
1579        test_widgets(|tester| {
1580            // A FocusScope widget below the view scopes its own subtree instead.
1581            let app = tester.cell.borrow();
1582            let scope_node = Rc::new(Cell::new(None));
1583            let sink = Rc::clone(&scope_node);
1584            drop(app);
1585            tester.pump_widget(
1586                FocusScope::new(Builder::new(move |app, context| {
1587                    sink.set(Some(FocusScope::of(app, context, true)));
1588                    SizedBox::shrink().into_widget()
1589                }))
1590                .debug_label("scope")
1591                .into_widget(),
1592            );
1593            let mut app = tester.cell.borrow_mut();
1594            let manager = FocusManager::instance(&mut app);
1595            let scope = scope_node.get().expect("FocusScope.of ran");
1596            assert_ne!(scope, manager.root_scope(&app).handle());
1597            assert_eq!(scope.debug_label(&app).as_deref(), Some("scope"));
1598            assert_eq!(
1599                scope
1600                    .enclosing_scope(&mut app)
1601                    .and_then(|scope| scope.debug_label(&app)),
1602                Some("View Scope".to_string())
1603            );
1604        });
1605    }
1606
1607    #[test]
1608    fn a_focus_widgets_on_key_event_receives_events_addressed_to_its_node() {
1609        test_widgets(|tester| {
1610            use std::time::Duration;
1611
1612            use waft_services::{
1613                HardwareKeyboard, KeyDownEvent, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey,
1614            };
1615
1616            let app = tester.cell.borrow();
1617            let seen: Rc<RefCell<Vec<&'static str>>> = Rc::default();
1618            let inner_seen = Rc::clone(&seen);
1619            let outer_seen = Rc::clone(&seen);
1620            drop(app);
1621            tester.pump_widget(
1622                Focus::new(
1623                    Focus::new(SizedBox::shrink())
1624                        .autofocus(true)
1625                        .on_key_event(Rc::new(move |_app, _node, _event| {
1626                            inner_seen.borrow_mut().push("inner");
1627                            KeyEventResult::Ignored
1628                        })),
1629                )
1630                .on_key_event(Rc::new(move |_app, _node, _event| {
1631                    outer_seen.borrow_mut().push("outer");
1632                    KeyEventResult::Handled
1633                }))
1634                .into_widget(),
1635            );
1636            let mut app = tester.cell.borrow_mut();
1637
1638            let event = KeyEvent::Down(KeyDownEvent::new(
1639                PhysicalKeyboardKey::KEY_A,
1640                LogicalKeyboardKey::KEY_A,
1641                Duration::ZERO,
1642            ));
1643            let handled = HardwareKeyboard::instance(&mut app).handle_key_event(&mut app, &event);
1644            assert!(handled);
1645            assert_eq!(*seen.borrow(), vec!["inner", "outer"]);
1646        });
1647    }
1648
1649    #[test]
1650    fn moving_a_focus_widget_by_global_key_keeps_its_node_and_its_focus() {
1651        test_widgets(|tester| {
1652            let app = tester.cell.borrow();
1653            let captured: Captured = Rc::default();
1654            let key = GlobalKey::new();
1655            drop(app);
1656            tester.pump_widget(
1657                Padding::new(waft_painting::EdgeInsetsGeometry::all(4.0))
1658                    .child(
1659                        Focus::new(probe(&captured))
1660                            .key(key.clone().into())
1661                            .autofocus(true),
1662                    )
1663                    .into_widget(),
1664            );
1665            let app = tester.cell.borrow();
1666            let node = captured.get().expect("Focus.of found the node");
1667            assert!(node.has_primary_focus(&app));
1668
1669            drop(app);
1670            tester.pump_widget(
1671                Center::new()
1672                    .child(Focus::new(probe(&captured)).key(key.clone().into()))
1673                    .into_widget(),
1674            );
1675            let app = tester.cell.borrow();
1676            assert_eq!(captured.get(), Some(node));
1677            assert!(node.has_primary_focus(&app));
1678        });
1679    }
1680
1681    #[test]
1682    fn exclude_focus_blocks_the_descendants() {
1683        test_widgets(|tester| {
1684            let app = tester.cell.borrow();
1685            let captured: Captured = Rc::default();
1686            drop(app);
1687            tester.pump_widget(ExcludeFocus::new(Focus::new(probe(&captured))).into_widget());
1688            let mut app = tester.cell.borrow_mut();
1689            let node = captured.get().expect("Focus.of found the node");
1690            assert!(!node.can_request_focus(&app));
1691
1692            node.request_focus(&mut app, None);
1693            app.drain_microtasks();
1694            assert!(!node.has_primary_focus(&app));
1695        });
1696    }
1697}