Skip to main content

waft_winui/primitives/
retained_flyout.rs

1//! Flyout content lifetime adapted to Flutter's retained OverlayEntry mechanism.
2
3use crate::ThemeResources;
4use crate::ThemeScope;
5use std::{fmt, rc::Rc};
6use waft_embedder::{Offset, Rect, TextDirection, ViewId};
7use waft_foundation::{App, Handle, Listener, Ref};
8use waft_painting::transform_rect;
9use waft_scheduler::{FrameCallback, SchedulerBinding};
10use waft_widgets::*;
11
12/// Owns flyout content independently of any widget that opens it.
13///
14/// One root-overlay entry remains mounted between openings. Its child State is
15/// disposed only when this host is disposed or the root overlay is removed.
16pub struct RetainedFlyoutHost {
17    /// Creates the content within the opening target's theme and direction.
18    builder: WidgetBuilder,
19
20    /// Root entry, created on the first opening.
21    entry: Option<Ref<OverlayEntry>>,
22
23    /// Overlay in which the retained entry lives.
24    overlay: Option<Handle<OverlayState>>,
25
26    /// Mounted state that owns the content focus scope.
27    state: Option<Handle<RetainedFlyoutState>>,
28
29    /// Current opening target, cleared when hidden or when that target unmounts.
30    target: Option<Handle<FlyoutTargetState>>,
31
32    /// Theme last supplied by the current target.
33    resources: Option<Rc<ThemeResources>>,
34
35    /// Text direction last supplied by the current target.
36    direction: TextDirection,
37
38    /// Whether the retained content is visible.
39    open: bool,
40
41    /// Whether opening requests keyboard focus for the content.
42    take_focus: bool,
43
44    /// Focus to restore when the flyout closes.
45    previous_focus: Option<AnyFocusNode>,
46
47    /// An explicitly focused menu header takes precedence over earlier queued focus.
48    pub(crate) return_focus: Option<AnyFocusNode>,
49
50    /// Prevents queued work from using a disposed host.
51    disposed: bool,
52
53    /// Coalesces content updates requested while another widget is building.
54    rebuild_pending: bool,
55
56    /// Invalidates focus requests queued before a newer open or close.
57    epoch: u64,
58
59    /// Presenter-loaded callback after the open frame and focus request.
60    pub(crate) opened: Option<Listener>,
61
62    /// Presenter-hidden callback after the close frame.
63    pub(crate) closed: Option<Listener>,
64
65    /// Notifies the owner when root removal disposes retained content.
66    pub(crate) on_dispose: Option<Listener>,
67
68    /// Optional owner close request when the active target is removed.
69    pub(crate) target_removed: Option<Listener>,
70
71    /// Popup key handling also applies when the scope itself has focus.
72    pub(crate) on_key_event: Option<FocusOnKeyEventCallback>,
73}
74
75impl fmt::Debug for RetainedFlyoutHost {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.debug_struct("RetainedFlyoutHost")
78            .field("open", &self.open)
79            .field("disposed", &self.disposed)
80            .finish_non_exhaustive()
81    }
82}
83
84impl RetainedFlyoutHost {
85    /// Creates a host; content is built lazily when first shown.
86    pub fn new(app: &mut App, builder: WidgetBuilder) -> Ref<Self> {
87        app.create(Self {
88            builder,
89            entry: None,
90            overlay: None,
91            state: None,
92            target: None,
93            resources: None,
94            direction: TextDirection::Ltr,
95            open: false,
96            take_focus: true,
97            previous_focus: None,
98            return_focus: None,
99            disposed: false,
100            epoch: 0,
101            rebuild_pending: false,
102            opened: None,
103            closed: None,
104            target_removed: None,
105            on_dispose: None,
106            on_key_event: None,
107        })
108    }
109
110    /// Whether the retained content is currently shown.
111    pub fn is_open(self: Handle<Self>, app: &App) -> bool {
112        app.get(self).open
113    }
114
115    /// Bounds of the current target in the root overlay's coordinate system.
116    pub fn target_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
117        let target = app.get(self).target?;
118        if !target.mounted(app) {
119            return None;
120        }
121        let target_box = target.context(app).find_render_object(app)?.as_box()?;
122        let overlay = app.get(self).overlay?;
123        let root = overlay.context(app).find_render_object(app)?;
124        let transform = target_box.as_object().get_transform_to(app, Some(root));
125        Some(transform_rect(
126            &transform,
127            Offset::ZERO & target_box.size(app),
128        ))
129    }
130
131    /// The view the content is shown in: its overlay's; none before the first opening.
132    fn view(self: Handle<Self>, app: &App) -> Option<ViewId> {
133        let overlay = app.get(self).overlay?;
134        View::maybe_id_of(app, overlay.context(app))
135    }
136
137    /// Rebuilds retained content after a controller property changes.
138    pub fn rebuild(self: Handle<Self>, app: &mut App) {
139        if app.get(self).disposed {
140            return;
141        }
142        if SchedulerBinding::scheduler_phase(app)
143            == waft_scheduler::SchedulerPhase::PersistentCallbacks
144        {
145            if app.get(self).rebuild_pending {
146                return;
147            }
148            app.get_mut(self).rebuild_pending = true;
149            SchedulerBinding::add_post_frame_callback(
150                app,
151                FrameCallback::new(move |app, _| {
152                    if app.contains(self) {
153                        app.get_mut(self).rebuild_pending = false;
154                        self.rebuild(app);
155                    }
156                }),
157                self.view(app),
158            );
159        } else if let Some(state) = app.get(self).state {
160            state.set_state(app, |_| {});
161        }
162    }
163
164    /// Shows the same content from a context beneath a FlyoutTarget.
165    pub fn show_at(self: Handle<Self>, app: &mut App, context: BuildContext, take_focus: bool) {
166        assert!(
167            !app.get(self).disposed,
168            "cannot show a disposed flyout host"
169        );
170        let target = context
171            .find_ancestor_state_of_type::<FlyoutTargetState>(app)
172            .expect("show_at requires a context beneath FlyoutTarget");
173        let overlay = Overlay::of(app, context, true);
174        if let Some(previous_overlay) = app.get(self).overlay {
175            assert_eq!(
176                previous_overlay, overlay,
177                "a retained flyout belongs to one root overlay"
178            );
179        }
180
181        let resources = app
182            .get(target)
183            .resources
184            .clone()
185            .expect("a built target has a theme");
186        let direction = app.get(target).direction;
187        if let Some(previous_target) = app.get(self).target
188            && previous_target != target
189            && app.contains(previous_target)
190        {
191            app.get_mut(previous_target)
192                .hosts
193                .retain(|host| *host != self);
194        }
195        let previous_focus = app.get(self).return_focus.or_else(|| primary_focus(app));
196        let already_owns_focus = app.get(self).state.is_some_and(|state| {
197            app.get(state)
198                .focus
199                .clone()
200                .unwrap()
201                .as_node()
202                .has_focus(app)
203        });
204        let host = app.get_mut(self);
205        host.target = Some(target);
206        host.resources = Some(resources);
207        host.direction = direction;
208        host.open = true;
209        host.take_focus = take_focus;
210        host.epoch += 1;
211        if !already_owns_focus {
212            host.previous_focus = previous_focus;
213        }
214        if !app.get(target).hosts.contains(&self) {
215            app.get_mut(target).hosts.push(self);
216        }
217
218        if let Some(state) = app.get(self).state {
219            let entry = app.get(self).entry.clone().unwrap();
220            // Keep this entry's key while moving all other entries below it.
221            overlay.rearrange(app, vec![entry.clone()], Some(entry.handle()), None);
222            state.set_state(app, |_| {});
223            state.focus_after_frame(app);
224        } else if app.get(self).entry.is_none() {
225            let entry = OverlayEntry::new(
226                app,
227                Rc::new(move |_, _| RetainedFlyoutRoot { host: self }.into_widget()),
228                false,
229                true,
230                false,
231            );
232            app.get_mut(self).entry = Some(entry.clone());
233            app.get_mut(self).overlay = Some(overlay);
234            overlay.insert(app, entry, None, None);
235        }
236    }
237
238    /// Hides the content without removing its entry or disposing child State.
239    pub fn hide(self: Handle<Self>, app: &mut App) {
240        if app.get(self).disposed || !app.get(self).open {
241            return;
242        }
243        if let Some(state) = app.get(self).state {
244            state.restore_focus(app);
245        }
246        if let Some(target) = app.get(self).target
247            && app.contains(target)
248        {
249            app.get_mut(target).hosts.retain(|host| *host != self);
250        }
251        let host = app.get_mut(self);
252        host.open = false;
253        host.target = None;
254        host.previous_focus = None;
255        host.epoch += 1;
256        let epoch = host.epoch;
257        self.rebuild(app);
258        SchedulerBinding::add_post_frame_callback(
259            app,
260            FrameCallback::new(move |app, _| {
261                if app.contains(self)
262                    && !app.get(self).disposed
263                    && !app.get(self).open
264                    && app.get(self).epoch == epoch
265                    && let Some(closed) = app.get(self).closed.clone()
266                {
267                    closed.call(app);
268                }
269            }),
270            self.view(app),
271        );
272    }
273
274    /// Releases the overlay entry; its widget state disposes the focus scope on unmount.
275    pub fn dispose(self: Handle<Self>, app: &mut App) {
276        if app.get(self).disposed {
277            return;
278        }
279        self.hide(app);
280        app.get_mut(self).disposed = true;
281        if let Some(entry) = app.get_mut(self).entry.take() {
282            entry.remove(app);
283            entry.dispose(app);
284        }
285        if let Some(disposed) = app.get(self).on_dispose.clone() {
286            disposed.call(app);
287        }
288    }
289}
290
291/// Supplies an opening target's lifecycle, theme and direction to retained flyouts.
292#[derive(Clone, Debug)]
293pub struct FlyoutTarget {
294    /// Target widget, including any Builder whose context is passed to show_at.
295    pub child: WidgetRef,
296
297    /// Identity of this target across parent rebuilds.
298    pub key: Option<KeyRef>,
299}
300
301impl FlyoutTarget {
302    /// Wraps an opening target without taking ownership of its flyout content.
303    #[cfg_attr(debug_assertions, track_caller)]
304    pub fn new<K>(child: impl IntoWidget<K>) -> Self {
305        Self {
306            child: child.into_widget(),
307            key: None,
308        }
309    }
310
311    /// Sets the target's widget identity.
312    pub fn key(mut self, key: KeyRef) -> Self {
313        self.key = Some(key);
314        self
315    }
316}
317
318/// Tracks only target lifetime and inherited settings, not flyout content State.
319pub struct FlyoutTargetState {
320    /// Native widget state.
321    state: StateData<FlyoutTarget>,
322
323    /// Hosts that have opened from this target.
324    hosts: Vec<Handle<RetainedFlyoutHost>>,
325
326    /// Theme obtained through this target's inherited dependencies.
327    resources: Option<Rc<ThemeResources>>,
328
329    /// Current inherited text direction.
330    direction: TextDirection,
331}
332
333impl StatefulWidget for FlyoutTarget {
334    type State = FlyoutTargetState;
335
336    fn key(&self) -> Option<&KeyRef> {
337        self.key.as_ref()
338    }
339
340    fn create_state(&self) -> Self::State {
341        FlyoutTargetState {
342            state: StateData::new(),
343            hosts: Vec::new(),
344            resources: None,
345            direction: TextDirection::Ltr,
346        }
347    }
348}
349
350impl State for FlyoutTargetState {
351    type Widget = FlyoutTarget;
352    waft_widgets::state_accessors!();
353
354    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
355        let resources = ThemeResources::of(app, self.context(app));
356        let direction = Directionality::of(app, self.context(app));
357        app.get_mut(self).resources = Some(resources.clone());
358        app.get_mut(self).direction = direction;
359        let hosts = app.get(self).hosts.clone();
360        for host in hosts {
361            if app.contains(host) && !app.get(host).disposed && app.get(host).target == Some(self) {
362                app.get_mut(host).resources = Some(resources.clone());
363                app.get_mut(host).direction = direction;
364                SchedulerBinding::add_post_frame_callback(
365                    app,
366                    FrameCallback::new(move |app, _| {
367                        if app.contains(host)
368                            && !app.get(host).disposed
369                            && let Some(state) = app.get(host).state
370                        {
371                            state.set_state(app, |_| {});
372                        }
373                    }),
374                    View::maybe_id_of(app, self.context(app)),
375                );
376            }
377        }
378    }
379
380    fn dispose(self: Handle<Self>, app: &mut App) {
381        let hosts = app.get(self).hosts.clone();
382        for host in hosts {
383            if app.contains(host) && !app.get(host).disposed && app.get(host).target == Some(self) {
384                // Target removal may happen during build, so close after that pass finishes.
385                SchedulerBinding::add_post_frame_callback(
386                    app,
387                    FrameCallback::new(move |app, _| {
388                        if app.contains(host)
389                            && !app.get(host).disposed
390                            && app.get(host).target == Some(self)
391                        {
392                            if let Some(removed) = app.get(host).target_removed.clone() {
393                                removed.call(app);
394                            } else {
395                                host.hide(app);
396                            }
397                        }
398                    }),
399                    // Disposed, the target is in no view any more.
400                    None,
401                );
402            }
403        }
404    }
405
406    fn build(self: Handle<Self>, app: &mut App, _: BuildContext) -> WidgetRef {
407        self.widget(app).child.clone()
408    }
409}
410
411/// Root entry widget whose identity does not change when the opening target changes.
412#[derive(Debug)]
413struct RetainedFlyoutRoot {
414    /// Application-owned host.
415    host: Handle<RetainedFlyoutHost>,
416}
417
418/// Owns focus resources for the root entry, independently of target widget lifetime.
419struct RetainedFlyoutState {
420    /// Native widget state.
421    state: StateData<RetainedFlyoutRoot>,
422
423    /// Focus scope owned by this retained subtree.
424    focus: Option<Ref<FocusScopeNode>>,
425}
426
427impl StatefulWidget for RetainedFlyoutRoot {
428    type State = RetainedFlyoutState;
429
430    fn create_state(&self) -> Self::State {
431        RetainedFlyoutState {
432            state: StateData::new(),
433            focus: None,
434        }
435    }
436}
437
438impl RetainedFlyoutState {
439    /// Requests content focus only if this opening is still current after layout.
440    fn focus_after_frame(self: Handle<Self>, app: &mut App) {
441        let host = self.widget(app).host;
442        let epoch = app.get(host).epoch;
443        SchedulerBinding::add_post_frame_callback(
444            app,
445            FrameCallback::new(move |app, _| {
446                if !self.mounted(app)
447                    || !app.contains(host)
448                    || app.get(host).disposed
449                    || !app.get(host).open
450                    || app.get(host).epoch != epoch
451                {
452                    return;
453                }
454                if app.get(host).take_focus {
455                    let scope = app.get(self).focus.clone().unwrap().as_node();
456                    let first = scope
457                        .traversal_descendants(app)
458                        .into_iter()
459                        .find(|node| node.can_request_focus(app));
460                    first.unwrap_or(scope).request_focus(app, None);
461                }
462                if let Some(opened) = app.get(host).opened.clone() {
463                    opened.call(app);
464                }
465            }),
466            View::maybe_id_of(app, self.context(app)),
467        );
468    }
469
470    /// Returns focus only if this popup still owns it and the previous node survives.
471    fn restore_focus(self: Handle<Self>, app: &mut App) {
472        let host = self.widget(app).host;
473        let previous = app.get(host).previous_focus;
474        if app
475            .get(self)
476            .focus
477            .clone()
478            .unwrap()
479            .as_node()
480            .has_focus(app)
481            && let Some(previous) = previous.filter(|node| {
482                app.contains(node.id())
483                    && !app.is_disposed(node.id())
484                    && node.context(app).is_some()
485                    && node.can_request_focus(app)
486            })
487        {
488            previous.request_focus(app, None);
489        }
490    }
491}
492
493impl State for RetainedFlyoutState {
494    type Widget = RetainedFlyoutRoot;
495    waft_widgets::state_accessors!();
496
497    fn init_state(self: Handle<Self>, app: &mut App) {
498        let host = self.widget(app).host;
499        let focus = FocusScopeNode::new(app);
500        focus.set_traversal_edge_behavior(app, TraversalEdgeBehavior::ClosedLoop);
501        app.get_mut(self).focus = Some(focus);
502        app.get_mut(host).state = Some(self);
503        self.focus_after_frame(app);
504    }
505
506    fn dispose(self: Handle<Self>, app: &mut App) {
507        let focus = app.get(self).focus.clone().unwrap();
508        focus.as_node().dispose(app);
509        let host = self.widget(app).host;
510        if app.contains(host) {
511            app.get_mut(host).state = None;
512            // Root-overlay teardown releases the retained entry even when its application owner survives.
513            host.dispose(app);
514        }
515    }
516
517    fn build(self: Handle<Self>, app: &mut App, _: BuildContext) -> WidgetRef {
518        let host = self.widget(app).host;
519        let data = app.get(host);
520        let open = data.open;
521        let resources = data
522            .resources
523            .clone()
524            .expect("a shown flyout has a target theme");
525        let direction = data.direction;
526        let builder = data.builder.clone();
527        let on_key_event = data.on_key_event.clone();
528        let themed_content = ThemeScope::with_resources(
529            resources,
530            Directionality::new(
531                direction,
532                Builder::new(move |app, context| builder(app, context)),
533            ),
534        );
535        let mut scope = FocusScope::new(themed_content).node(app.get(self).focus.clone().unwrap());
536        if let Some(handler) = on_key_event {
537            scope = scope.on_key_event(handler);
538        }
539        Offstage::new()
540            .offstage(!open)
541            .child(TickerMode::new(
542                open,
543                ExcludeFocus::new(scope).excluding(!open),
544            ))
545            .into_widget()
546    }
547}