Skip to main content

waft_widgets/widgets/
automatic_keep_alive.rs

1//! Flutter counterpart: `widgets/automatic_keep_alive.dart`.
2
3use std::any::Any;
4use std::collections::HashMap;
5use std::fmt::{self, Debug};
6
7use waft_foundation::{
8    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsProperty,
9    FlagProperty, Handle, Listenable, ListenableObject, Listener,
10};
11use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
12
13use crate::framework::{
14    BuildContext, IntoWidget, KeyRef, Notification, ParentDataElement, State, StateData,
15    StatefulWidget, StatelessWidget, WidgetRef, downcast_widget,
16};
17use crate::view::View;
18use crate::widgets::notification_listener::NotificationListener;
19use crate::widgets::sliver::KeepAlive;
20use waft_foundation::Ref;
21
22/// Allows subtrees to request to be kept alive in lazy lists.
23///
24/// This widget is like [`KeepAlive`] but instead of being explicitly configured,
25/// it listens to [`KeepAliveNotification`] messages from the [`child`](Self::child) and other
26/// descendants.
27///
28/// The subtree is kept alive whenever there is one or more descendant that has
29/// sent a [`KeepAliveNotification`] and not yet triggered its
30/// [`KeepAliveNotification::handle`].
31///
32/// To send these notifications, consider using [`AutomaticKeepAliveClientMixin`].
33///
34/// See also:
35///
36///  * [`AutomaticKeepAliveClientMixin`], which is a mixin with convenience
37///    methods for clients of [`AutomaticKeepAlive`]. Used with
38///    [`State`] subclasses.
39///  * [`KeepAlive`] which marks a child as needing to stay alive even when it's
40///    in a lazy list that would otherwise remove it.
41#[derive(Debug)]
42pub struct AutomaticKeepAlive {
43    /// See [`Widget::key`](crate::Widget::key).
44    pub key: Option<KeyRef>,
45
46    /// The widget below this widget in the tree.
47    pub child: WidgetRef,
48}
49
50impl AutomaticKeepAlive {
51    /// Creates a widget that listens to [`KeepAliveNotification`]s and maintains a
52    /// [`KeepAlive`] widget appropriately.
53    #[cfg_attr(debug_assertions, track_caller)]
54    pub fn new<K>(child: impl IntoWidget<K>) -> AutomaticKeepAlive {
55        AutomaticKeepAlive {
56            key: None,
57            child: child.into_widget(),
58        }
59    }
60
61    /// Dart `AutomaticKeepAlive(key:)`.
62    pub fn key(mut self, key: KeyRef) -> AutomaticKeepAlive {
63        self.key = Some(key);
64        self
65    }
66}
67
68impl StatefulWidget for AutomaticKeepAlive {
69    type State = AutomaticKeepAliveState;
70
71    fn key(&self) -> Option<&KeyRef> {
72        self.key.as_ref()
73    }
74
75    fn create_state(&self) -> AutomaticKeepAliveState {
76        AutomaticKeepAliveState {
77            state: StateData::new(),
78            handles: None,
79            child: None,
80            keeping_alive: false,
81        }
82    }
83}
84
85/// Dart's `_AutomaticKeepAliveState`.
86pub struct AutomaticKeepAliveState {
87    state: StateData<AutomaticKeepAlive>,
88    handles: Option<HashMap<Ref<KeepAliveHandle>, Listener>>,
89    // In order to apply parent data out of turn, the child of the KeepAlive
90    // widget must be the same across frames.
91    child: Option<WidgetRef>,
92    keeping_alive: bool,
93}
94
95impl AutomaticKeepAliveState {
96    fn update_child(self: Handle<Self>, app: &mut App) {
97        let child = self.widget(app).child.clone();
98        let this = self;
99        app.get_mut(self).child = Some(
100            NotificationListener::<KeepAliveNotification>::new(child)
101                .on_notification(move |app, notification| this.add_client(app, notification))
102                .into_widget(),
103        );
104    }
105
106    fn add_client(self: Handle<Self>, app: &mut App, notification: &KeepAliveNotification) -> bool {
107        let handle = notification.handle.clone();
108        let callback = self.create_callback(handle.handle());
109        {
110            let handles = app.get_mut(self).handles.get_or_insert_with(HashMap::new);
111            debug_assert!(
112                !handles.contains_key(&handle),
113                "the same handle cannot be used in two KeepAliveNotifications without triggering it first"
114            );
115            handles.insert(handle.clone(), callback.clone());
116        }
117        Listenable::add_listener(&handle, app, callback);
118        if !app.get(self).keeping_alive {
119            app.get_mut(self).keeping_alive = true;
120            if let Some(child_element) = self.get_child_element(app) {
121                // If the child already exists, update it synchronously.
122                self.update_parent_data_of_child(app, child_element);
123            } else {
124                // If the child doesn't exist yet, we got called during the very first
125                // build of this subtree. Wait until the end of the frame to update
126                // the child when the child is guaranteed to be present.
127                SchedulerBinding::add_post_frame_callback(
128                    app,
129                    FrameCallback::new(move |app, _time_stamp| {
130                        if !self.mounted(app) {
131                            return;
132                        }
133                        let child_element = self.get_child_element(app);
134                        debug_assert!(child_element.is_some());
135                        self.update_parent_data_of_child(
136                            app,
137                            child_element
138                                .expect("the KeepAlive child exists after the first build"),
139                        );
140                    }),
141                    View::maybe_id_of(app, self.context(app)),
142                );
143            }
144        }
145        false
146    }
147
148    /// Get the [`Element`] for the only [`KeepAlive`] child.
149    ///
150    /// While this widget is guaranteed to have a child, this may return null if
151    /// the first build of that child has not completed yet.
152    fn get_child_element(self: Handle<Self>, app: &App) -> Option<Handle<ParentDataElement>> {
153        debug_assert!(self.mounted(app));
154        let element = self.context(app);
155        let mut child_element = None;
156        // We use Element.visitChildren rather than context.visitChildElements
157        // because we might be called during build, and context.visitChildElements
158        // verifies that it is not called during build. Element.visitChildren does
159        // not, instead it assumes that the caller will be careful. (See the
160        // documentation for these methods for more details.)
161        //
162        // Here we know it's safe (with the exception outlined below) because we
163        // just received a notification, which we wouldn't be able to do if we
164        // hadn't built our child and its child -- our build method always builds
165        // the same subtree and it always includes the node we're looking for
166        // (KeepAlive) as the parent of the node that reports the notifications
167        // (NotificationListener).
168        //
169        // If we are called during the first build of this subtree the links to the
170        // children will not be hooked up yet. In that case this method returns
171        // null despite the fact that we will have a child after the build
172        // completes. It's the caller's responsibility to deal with this case.
173        //
174        // (We're only going down one level, to get our direct child.)
175        element.visit_children(app, &mut |child| {
176            child_element = Some(child);
177        });
178        let child_element = child_element?;
179        debug_assert!(child_element.is_parent_data_element());
180        Some(
181            child_element
182                .downcast::<ParentDataElement>(app)
183                .filter(|_| downcast_widget::<KeepAlive>(&**child_element.widget(app)).is_some())
184                .expect("the only child is the KeepAlive ParentDataElement"),
185        )
186    }
187
188    fn update_parent_data_of_child(
189        self: Handle<Self>,
190        app: &mut App,
191        child_element: Handle<ParentDataElement>,
192    ) {
193        let context = self.context(app);
194        let widget = self.build(app, context);
195        let keep_alive =
196            downcast_widget::<KeepAlive>(&*widget).expect("AutomaticKeepAlive builds a KeepAlive");
197        child_element.apply_widget_out_of_turn(app, keep_alive);
198    }
199
200    fn create_callback(self: Handle<Self>, handle: Handle<KeepAliveHandle>) -> Listener {
201        Listener::new(move |app| {
202            if cfg!(debug_assertions) && !self.mounted(app) {
203                panic!(
204                    "AutomaticKeepAlive handle triggered after AutomaticKeepAlive was disposed.\n\
205                     Widgets should always trigger their KeepAliveNotification handle when they are \
206                     deactivated, so that they (or their handle) do not send spurious events later \
207                     when they are no longer in the tree."
208                );
209            }
210            let callback = app
211                .get_mut(self)
212                .handles
213                .as_mut()
214                .expect("a client was registered")
215                .remove(&handle)
216                .expect("the firing handle is still registered");
217            ListenableObject::remove_listener(handle, app, &callback);
218            if app
219                .get(self)
220                .handles
221                .as_ref()
222                .expect("a client was registered")
223                .is_empty()
224            {
225                if SchedulerBinding::scheduler_phase(app) < SchedulerPhase::PersistentCallbacks {
226                    // Build/layout haven't started yet so let's just schedule this for
227                    // the next frame.
228                    self.set_state(app, |state| {
229                        state.keeping_alive = false;
230                    });
231                } else {
232                    // We were probably notified by a descendant when they were yanked out
233                    // of our subtree somehow. We're probably in the middle of build or
234                    // layout, so there's really nothing we can do to clean up this mess
235                    // short of just scheduling another build to do the cleanup. This is
236                    // very unfortunate, and means (for instance) that garbage collection
237                    // of these resources won't happen for another 16ms.
238                    //
239                    // The problem is there's really no way for us to distinguish these
240                    // cases:
241                    //
242                    //  * We haven't built yet (or missed out chance to build), but
243                    //    someone above us notified our descendant and our descendant is
244                    //    disconnecting from us. If we could mark ourselves dirty we would
245                    //    be able to clean everything this frame. (This is a pretty
246                    //    unlikely scenario in practice. Usually things change before
247                    //    build/layout, not during build/layout.)
248                    //
249                    //  * Our child changed, and as our old child went away, it notified
250                    //    us. We can't setState, since we _just_ built. We can't apply the
251                    //    parent data information to our child because we don't _have_ a
252                    //    child at this instant. We really want to be able to change our
253                    //    mind about how we built, so we can give the KeepAlive widget a
254                    //    new value, but it's too late.
255                    //
256                    //  * A deep descendant in another build scope just got yanked, and in
257                    //    the process notified us. We could apply new parent data
258                    //    information, but it may or may not get applied this frame,
259                    //    depending on whether said child is in the same layout scope.
260                    //
261                    //  * A descendant is being moved from one position under us to
262                    //    another position under us. They just notified us of the removal,
263                    //    at some point in the future they will notify us of the addition.
264                    //    We don't want to do anything. (This is why we check that
265                    //    _handles is still empty below.)
266                    //
267                    //  * We're being notified in the paint phase, or even in a post-frame
268                    //    callback. Either way it is far too late for us to make our
269                    //    parent lay out again this frame, so the garbage won't get
270                    //    collected this frame.
271                    //
272                    //  * We are being torn out of the tree ourselves, as is our
273                    //    descendant, and it notified us while it was being deactivated.
274                    //    We don't need to do anything, but we don't know yet because we
275                    //    haven't been deactivated yet. (This is why we check mounted
276                    //    below before calling setState.)
277                    //
278                    // Long story short, we have to schedule a new frame and request a
279                    // frame there, but this is generally a bad practice, and you should
280                    // avoid it if possible.
281                    app.get_mut(self).keeping_alive = false;
282                    app.schedule_microtask(Listener::new(move |app| {
283                        if self.mounted(app)
284                            && app
285                                .get(self)
286                                .handles
287                                .as_ref()
288                                .expect("a client was registered")
289                                .is_empty()
290                        {
291                            // If mounted is false, we went away as well, so there's nothing to do.
292                            // If _handles is no longer empty, then another client (or the same
293                            // client in a new place) registered itself before we had a chance to
294                            // turn off keepalive, so again there's nothing to do.
295                            self.set_state(app, |state| {
296                                debug_assert!(!state.keeping_alive);
297                            });
298                        }
299                    }));
300                }
301            }
302        })
303    }
304}
305
306impl State for AutomaticKeepAliveState {
307    type Widget = AutomaticKeepAlive;
308    crate::state_accessors!();
309
310    fn debug_fill_properties(
311        self: Handle<Self>,
312        app: &App,
313        properties: &mut DiagnosticPropertiesBuilder,
314    ) {
315        let state = app.get(self);
316        properties.add(
317            FlagProperty::new("_keepingAlive", Some(state.keeping_alive))
318                .if_true("keeping subtree alive"),
319        );
320        properties.add(
321            DiagnosticsProperty::<String>::new(
322                "handles",
323                state.handles.as_ref().map(|handles| {
324                    format!(
325                        "{} active client{}",
326                        handles.len(),
327                        if handles.len() == 1 { "" } else { "s" }
328                    )
329                }),
330            )
331            .if_null("no notifications ever received"),
332        );
333    }
334
335    fn init_state(self: Handle<Self>, app: &mut App) {
336        self.update_child(app);
337    }
338
339    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &AutomaticKeepAlive) {
340        self.update_child(app);
341    }
342
343    fn dispose(self: Handle<Self>, app: &mut App) {
344        if let Some(handles) = app.get_mut(self).handles.take() {
345            for (handle, callback) in handles {
346                Listenable::remove_listener(&handle, app, &callback);
347            }
348        }
349    }
350
351    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
352        let keeping_alive = app.get(self).keeping_alive;
353        let child = app
354            .get(self)
355            .child
356            .clone()
357            .expect("the child is created in init_state");
358        KeepAlive::new(keeping_alive, child).into_widget()
359    }
360}
361
362/// Indicates that the subtree through which this notification bubbles must be
363/// kept alive even if it would normally be discarded as an optimization.
364///
365/// For example, a focused text field might fire this notification to indicate
366/// that it should not be disposed even if the user scrolls the field off
367/// screen.
368///
369/// Each [`KeepAliveNotification`] is configured with a [`handle`](Self::handle) that consists of
370/// a [`Listenable`] that is triggered when the subtree no longer needs to be kept
371/// alive.
372///
373/// The [`handle`](Self::handle) should be triggered any time the sending widget is removed from
374/// the tree (in [`State::deactivate`]). If the widget is then rebuilt and still
375/// needs to be kept alive, it should immediately send a new notification
376/// (possible with the very same [`Listenable`]) during build.
377///
378/// This notification is listened to by the [`AutomaticKeepAlive`] widget, which
379/// is added to the tree automatically by `SliverList` (and `ListView`) and
380/// `SliverGrid` (and `GridView`) widgets.
381///
382/// Failure to trigger the [`handle`](Self::handle) in the manner described above will likely
383/// cause the [`AutomaticKeepAlive`] to lose track of whether the widget should be
384/// kept alive or not, leading to memory leaks or lost data. For example, if the
385/// widget that requested keepalive is removed from the subtree but doesn't
386/// trigger its [`Listenable`] on the way out, then the subtree will continue to
387/// be kept alive until the list itself is disposed. Similarly, if the
388/// [`Listenable`] is triggered while the widget needs to be kept alive, but a new
389/// [`KeepAliveNotification`] is not immediately sent, then the widget risks being
390/// garbage collected while it wants to be kept alive.
391///
392/// It is an error to use the same [`handle`](Self::handle) in two [`KeepAliveNotification`]s
393/// within the same [`AutomaticKeepAlive`] without triggering that [`handle`](Self::handle) before
394/// the second notification is sent.
395///
396/// For a more convenient way to interact with [`AutomaticKeepAlive`] widgets,
397/// consider using [`AutomaticKeepAliveClientMixin`], which uses
398/// [`KeepAliveNotification`] internally.
399#[derive(Debug)]
400pub struct KeepAliveNotification {
401    /// A [`Listenable`] that will inform its clients when the widget that fired the
402    /// notification no longer needs to be kept alive.
403    ///
404    /// [`Handle<KeepAliveHandle>`](KeepAliveHandle) is that listenable. The
405    /// [`Listenable`] should be triggered any time the sending widget is
406    /// removed from the tree (in [`State::deactivate`]). If the widget is then
407    /// rebuilt and still needs to be kept alive, it should immediately send a new
408    /// notification (possible with the very same [`Listenable`]) during build.
409    ///
410    /// See also:
411    ///
412    ///  * [`KeepAliveHandle`], a convenience class for use with this property.
413    pub handle: Ref<KeepAliveHandle>,
414}
415
416impl KeepAliveNotification {
417    /// Creates a notification to indicate that a subtree must be kept alive.
418    pub fn new(handle: Ref<KeepAliveHandle>) -> KeepAliveNotification {
419        KeepAliveNotification { handle }
420    }
421}
422
423impl Notification for KeepAliveNotification {
424    fn as_any(&self) -> &dyn Any {
425        self
426    }
427}
428
429/// A [`Listenable`] which can be manually triggered.
430///
431/// Used with [`KeepAliveNotification`] objects as their
432/// [`KeepAliveNotification::handle`].
433///
434/// For a more convenient way to interact with [`AutomaticKeepAlive`] widgets,
435/// consider using [`AutomaticKeepAliveClientMixin`], which uses a
436/// [`KeepAliveHandle`] internally.
437pub struct KeepAliveHandle {
438    change_notifier: ChangeNotifierData,
439}
440
441impl KeepAliveHandle {
442    /// A handle that has not been triggered.
443    pub fn new(app: &mut App) -> Ref<KeepAliveHandle> {
444        app.create(KeepAliveHandle {
445            change_notifier: ChangeNotifierData::new(),
446        })
447    }
448
449    /// Dart's `KeepAliveHandle.dispose`: notifies, then disposes the notifier.
450    pub fn dispose(self: Handle<Self>, app: &mut App) {
451        self.notify_listeners(app);
452        ChangeNotifierData::dispose(app, self);
453    }
454}
455
456impl ChangeNotifier for KeepAliveHandle {
457    fn change_notifier_data(&self) -> &ChangeNotifierData {
458        &self.change_notifier
459    }
460
461    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
462        &mut self.change_notifier
463    }
464}
465
466impl Debug for KeepAliveHandle {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        f.debug_struct("KeepAliveHandle").finish_non_exhaustive()
469    }
470}
471
472/// The fields of Dart's `AutomaticKeepAliveClientMixin`.
473#[derive(Default)]
474pub struct AutomaticKeepAliveClientMixinData {
475    /// Dart's `_keepAliveHandle`.
476    pub keep_alive_handle: Option<Ref<KeepAliveHandle>>,
477}
478
479impl AutomaticKeepAliveClientMixinData {
480    /// No keep-alive request has been sent.
481    pub fn new() -> AutomaticKeepAliveClientMixinData {
482        AutomaticKeepAliveClientMixinData::default()
483    }
484}
485
486/// A mixin with convenience methods for clients of [`AutomaticKeepAlive`]. It is used
487/// with [`State`] subclasses to manage keep-alive behavior in lazily built lists.
488///
489/// This mixin simplifies interaction with [`AutomaticKeepAlive`] by automatically
490/// sending [`KeepAliveNotification`]s when necessary. Subclasses must implement
491/// [`want_keep_alive`](Self::want_keep_alive) to indicate whether the widget should be
492/// kept alive and call [`update_keep_alive`](Self::update_keep_alive) whenever its value
493/// changes.
494///
495/// The mixin internally manages a [`KeepAliveHandle`], which is used to notify
496/// the nearest [`AutomaticKeepAlive`] ancestor of changes in keep-alive
497/// requirements. [`AutomaticKeepAlive`] listens for [`KeepAliveNotification`]s sent
498/// by this mixin and dynamically wraps the subtree in a [`KeepAlive`] widget to
499/// preserve its state when it is no longer visible in the viewport.
500///
501/// Subclasses must implement [`want_keep_alive`](Self::want_keep_alive), and their
502/// [`build`](Self::build) methods must call [`AutomaticKeepAliveClientMixin::build`]
503/// (though the return value should be ignored).
504///
505/// Then, whenever [`want_keep_alive`](Self::want_keep_alive)'s value changes (or might
506/// change), the subclass should call [`update_keep_alive`](Self::update_keep_alive).
507///
508/// The state holds an [`AutomaticKeepAliveClientMixinData`] under the field
509/// `automatic_keep_alive_client` and implements the accessor pair. Rust cannot
510/// interpose a mixin on [`State`]'s hooks, so the state's own [`State::init_state`],
511/// [`State::deactivate`] and [`State::build`] call the counterparts here, where
512/// Dart's mixin body would run.
513///
514/// See also:
515///
516///  * [`AutomaticKeepAlive`], which listens to messages from this mixin.
517///  * [`KeepAliveNotification`], the notifications sent by this mixin.
518///  * [`KeepAlive`] which marks a child as needing to stay alive even when it's
519///    in a lazy list that would otherwise remove it.
520pub trait AutomaticKeepAliveClientMixin: State {
521    /// Mixin field access.
522    fn automatic_keep_alive_client_data(
523        self: Handle<Self>,
524        app: &App,
525    ) -> &AutomaticKeepAliveClientMixinData;
526
527    /// See [`automatic_keep_alive_client_data`](Self::automatic_keep_alive_client_data).
528    fn automatic_keep_alive_client_data_mut(
529        self: Handle<Self>,
530        app: &mut App,
531    ) -> &mut AutomaticKeepAliveClientMixinData;
532
533    /// Whether the current instance should be kept alive.
534    ///
535    /// Call [`update_keep_alive`](Self::update_keep_alive) whenever this getter's value changes.
536    fn want_keep_alive(self: Handle<Self>, app: &App) -> bool;
537
538    /// Ensures that any [`AutomaticKeepAlive`] ancestors are in a good state, by
539    /// firing a [`KeepAliveNotification`] or triggering the [`KeepAliveHandle`] as
540    /// appropriate.
541    fn update_keep_alive(self: Handle<Self>, app: &mut App) {
542        if self.want_keep_alive(app) {
543            if self
544                .automatic_keep_alive_client_data(app)
545                .keep_alive_handle
546                .is_none()
547            {
548                self.ensure_keep_alive(app);
549            }
550        } else if self
551            .automatic_keep_alive_client_data(app)
552            .keep_alive_handle
553            .is_some()
554        {
555            self.release_keep_alive(app);
556        }
557    }
558
559    /// The mixin's part of [`State::init_state`]; the state calls it where Dart's
560    /// `super.initState()` would reach the mixin.
561    fn init_state(self: Handle<Self>, app: &mut App) {
562        if self.want_keep_alive(app) {
563            self.ensure_keep_alive(app);
564        }
565    }
566
567    /// The mixin's part of [`State::deactivate`]; the state calls it where Dart's
568    /// `super.deactivate()` would reach the mixin.
569    fn deactivate(self: Handle<Self>, app: &mut App) {
570        if self
571            .automatic_keep_alive_client_data(app)
572            .keep_alive_handle
573            .is_some()
574        {
575            self.release_keep_alive(app);
576        }
577    }
578
579    /// The mixin's part of [`State::build`]; the state calls it where Dart's
580    /// `super.build` would reach the mixin. The return value must be ignored.
581    fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
582        if self.want_keep_alive(app)
583            && self
584                .automatic_keep_alive_client_data(app)
585                .keep_alive_handle
586                .is_none()
587        {
588            self.ensure_keep_alive(app);
589            // Whenever wantKeepAlive's value changes (or might change), the
590            // subclass should call [updateKeepAlive].
591            // That will ensure that the keepalive is disabled (or enabled)
592            // without requiring a rebuild.
593        }
594        NullWidget.into_widget()
595    }
596}
597
598/// Dart's private members of `AutomaticKeepAliveClientMixin`.
599trait AutomaticKeepAliveClientMixinPrivate: AutomaticKeepAliveClientMixin {
600    fn ensure_keep_alive(self: Handle<Self>, app: &mut App) {
601        debug_assert!(
602            self.automatic_keep_alive_client_data(app)
603                .keep_alive_handle
604                .is_none()
605        );
606        let handle = KeepAliveHandle::new(app);
607        self.automatic_keep_alive_client_data_mut(app)
608            .keep_alive_handle = Some(handle.clone());
609        KeepAliveNotification::new(handle).dispatch(app, Some(self.context(app)));
610    }
611
612    fn release_keep_alive(self: Handle<Self>, app: &mut App) {
613        let handle = self
614            .automatic_keep_alive_client_data_mut(app)
615            .keep_alive_handle
616            .take()
617            .expect("a keep-alive handle is registered");
618        handle.dispose(app);
619    }
620}
621
622impl<S: AutomaticKeepAliveClientMixin> AutomaticKeepAliveClientMixinPrivate for S {}
623
624/// Dart's `_NullWidget`.
625#[derive(Debug)]
626struct NullWidget;
627
628impl StatelessWidget for NullWidget {
629    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
630        panic!(
631            "Widgets that mix AutomaticKeepAliveClientMixin into their State must \
632             call super.build() but must ignore the return value of the superclass."
633        );
634    }
635}
636
637#[cfg(test)]
638mod tests {
639    use std::cell::Cell;
640    use std::rc::Rc;
641
642    use waft_foundation::{AppCell, ValueKey};
643
644    use super::*;
645    use crate::framework::Element;
646    use crate::test_harness::Harness;
647    use crate::widgets::basic::SizedBox;
648
649    #[derive(Debug)]
650    struct KeepClient {
651        want: bool,
652    }
653
654    impl StatefulWidget for KeepClient {
655        type State = KeepClientState;
656
657        fn create_state(&self) -> KeepClientState {
658            KeepClientState {
659                state: StateData::new(),
660                automatic_keep_alive_client: AutomaticKeepAliveClientMixinData::new(),
661            }
662        }
663    }
664
665    struct KeepClientState {
666        state: StateData<KeepClient>,
667        automatic_keep_alive_client: AutomaticKeepAliveClientMixinData,
668    }
669
670    impl AutomaticKeepAliveClientMixin for KeepClientState {
671        fn automatic_keep_alive_client_data(
672            self: Handle<Self>,
673            app: &App,
674        ) -> &AutomaticKeepAliveClientMixinData {
675            &app.get(self).automatic_keep_alive_client
676        }
677
678        fn automatic_keep_alive_client_data_mut(
679            self: Handle<Self>,
680            app: &mut App,
681        ) -> &mut AutomaticKeepAliveClientMixinData {
682            &mut app.get_mut(self).automatic_keep_alive_client
683        }
684
685        fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
686            self.widget(app).want
687        }
688    }
689
690    impl State for KeepClientState {
691        type Widget = KeepClient;
692        crate::state_accessors!();
693
694        fn init_state(self: Handle<Self>, app: &mut App) {
695            AutomaticKeepAliveClientMixin::init_state(self, app);
696        }
697
698        fn deactivate(self: Handle<Self>, app: &mut App) {
699            AutomaticKeepAliveClientMixin::deactivate(self, app);
700        }
701
702        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
703            let _ = AutomaticKeepAliveClientMixin::build(self, app);
704            SizedBox::shrink().into_widget()
705        }
706    }
707
708    fn host_state(harness: &Harness, app: &App) -> Handle<KeepClientState> {
709        let mut element = harness.root.as_element();
710        loop {
711            if let Some(state) = element.state_handle::<KeepClientState>(app) {
712                return state;
713            }
714            element = element.children(app)[0];
715        }
716    }
717
718    #[test]
719    fn mixin_want_keep_alive_true_dispatches() {
720        let cell = AppCell::new();
721        let mut app = cell.borrow_mut();
722        let harness = Harness::mount(&mut app, KeepClient { want: true }.into_widget());
723        harness.pump(&mut app);
724        let state = host_state(&harness, &app);
725        assert!(
726            app.get(state)
727                .automatic_keep_alive_client
728                .keep_alive_handle
729                .is_some()
730        );
731        AutomaticKeepAliveClientMixin::update_keep_alive(state, &mut app);
732        assert!(
733            app.get(state)
734                .automatic_keep_alive_client
735                .keep_alive_handle
736                .is_some()
737        );
738        let _ = AutomaticKeepAlive::new(SizedBox::shrink()).key(ValueKey::new(1).into());
739    }
740
741    #[test]
742    fn keep_alive_handle_dispose_notifies() {
743        let cell = AppCell::new();
744        let mut app = cell.borrow_mut();
745        let handle = KeepAliveHandle::new(&mut app);
746        let notified = Rc::new(Cell::new(false));
747        Listenable::add_listener(
748            &handle,
749            &mut app,
750            Listener::new({
751                let notified = Rc::clone(&notified);
752                move |_app| notified.set(true)
753            }),
754        );
755        handle.dispose(&mut app);
756        assert!(notified.get());
757    }
758}