Skip to main content

waft_widgets/widgets/
page_storage.rs

1//! Flutter counterpart: `widgets/page_storage.dart`.
2
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::rc::Rc;
8
9use waft_foundation::{App, Handle, Key, LocalKey};
10
11use crate::framework::{
12    AnyElement, BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef, downcast_widget,
13};
14use waft_foundation::Ref;
15
16/// A `Key` that can be used to persist the widget state in storage after the destruction
17/// and will be restored when recreated.
18///
19/// Each key with its value plus the ancestor chain of other [`PageStorageKey`]s need to be
20/// unique within the widget's closest ancestor [`PageStorage`]. To make it possible for a
21/// saved value to be found when a widget is recreated, the key's values must not be objects
22/// whose identity will change each time the widget is created.
23///
24/// Dart's `PageStorageKey<T> extends ValueKey<T>`; the value type is erased inside, as
25/// `GlobalKey`'s is.
26///
27/// See also:
28///
29///  * `RestorationManager`, which manages state restoration.
30pub struct PageStorageKey {
31    value: Rc<dyn Key>,
32}
33
34impl PageStorageKey {
35    /// Creates a [`PageStorageKey`].
36    ///
37    /// The `value` is the value to which this key delegates its equality.
38    pub fn new<T: PartialEq + Hash + fmt::Debug + 'static>(value: T) -> PageStorageKey {
39        PageStorageKey {
40            value: Rc::new(waft_foundation::ValueKey::new(value)),
41        }
42    }
43
44    /// The key as a tree node's key.
45    pub fn into_key(self) -> KeyRef {
46        self.into()
47    }
48}
49
50impl Key for PageStorageKey {
51    fn eq_key(&self, other: &dyn Key) -> bool {
52        (other as &dyn Any)
53            .downcast_ref::<PageStorageKey>()
54            .is_some_and(|other| *other.value == *self.value)
55    }
56
57    fn hash_key(&self, mut state: &mut dyn Hasher) {
58        TypeId::of::<PageStorageKey>().hash(&mut state);
59        self.value.hash_key(state);
60    }
61}
62
63impl LocalKey for PageStorageKey {}
64
65impl fmt::Debug for PageStorageKey {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "[PageStorageKey {:?}]", self.value)
68    }
69}
70
71/// Dart's `_StorageEntryIdentifier`: the [`PageStorageKey`] chain from a context up to its
72/// [`PageStorage`].
73#[derive(Clone)]
74struct StorageEntryIdentifier {
75    keys: Vec<KeyRef>,
76}
77
78impl StorageEntryIdentifier {
79    fn is_not_empty(&self) -> bool {
80        !self.keys.is_empty()
81    }
82}
83
84impl PartialEq for StorageEntryIdentifier {
85    fn eq(&self, other: &StorageEntryIdentifier) -> bool {
86        self.keys.len() == other.keys.len()
87            && self
88                .keys
89                .iter()
90                .zip(&other.keys)
91                .all(|(mine, theirs)| mine == theirs)
92    }
93}
94
95impl Eq for StorageEntryIdentifier {}
96
97impl Hash for StorageEntryIdentifier {
98    fn hash<H: Hasher>(&self, state: &mut H) {
99        for key in &self.keys {
100            key.hash(state);
101        }
102    }
103}
104
105impl fmt::Debug for StorageEntryIdentifier {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        write!(f, "StorageEntryIdentifier(")?;
108        for (index, key) in self.keys.iter().enumerate() {
109            if index > 0 {
110                write!(f, ":")?;
111            }
112            write!(f, "{key:?}")?;
113        }
114        write!(f, ")")
115    }
116}
117
118/// What a bucket entry is filed under: Dart's `Object` map key, either the computed chain or
119/// a caller's identifier.
120#[derive(Clone)]
121enum StorageSlot {
122    Entry(StorageEntryIdentifier),
123    Identifier(KeyRef),
124}
125
126impl PartialEq for StorageSlot {
127    fn eq(&self, other: &StorageSlot) -> bool {
128        match (self, other) {
129            (StorageSlot::Entry(mine), StorageSlot::Entry(theirs)) => mine == theirs,
130            (StorageSlot::Identifier(mine), StorageSlot::Identifier(theirs)) => mine == theirs,
131            _ => false,
132        }
133    }
134}
135
136impl Eq for StorageSlot {}
137
138impl Hash for StorageSlot {
139    fn hash<H: Hasher>(&self, state: &mut H) {
140        match self {
141            StorageSlot::Entry(entry) => {
142                0u8.hash(state);
143                entry.hash(state);
144            }
145            StorageSlot::Identifier(key) => {
146                1u8.hash(state);
147                key.hash(state);
148            }
149        }
150    }
151}
152
153/// A storage bucket associated with a page in an app.
154///
155/// Useful for storing per-page state that persists across navigations from one page to
156/// another.
157///
158/// A bucket has identity, so it is an arena object reached through its `Handle`.
159#[derive(Default)]
160pub struct PageStorageBucket {
161    storage: Option<HashMap<StorageSlot, Rc<dyn Any>>>,
162}
163
164impl PageStorageBucket {
165    /// Creates an empty bucket.
166    pub fn new(app: &mut App) -> Ref<PageStorageBucket> {
167        app.create(PageStorageBucket::default())
168    }
169
170    fn maybe_add_key(app: &App, context: AnyElement, keys: &mut Vec<KeyRef>) -> bool {
171        let widget = context.widget(app);
172        if let Some(key) = widget.key()
173            && (key.key() as &dyn Any).is::<PageStorageKey>()
174        {
175            keys.push(key.clone());
176        }
177        downcast_widget::<PageStorage>(&**widget).is_none()
178    }
179
180    fn all_keys(app: &App, context: BuildContext) -> Vec<KeyRef> {
181        let mut keys = Vec::new();
182        if Self::maybe_add_key(app, context, &mut keys) {
183            context.visit_ancestor_elements(app, &mut |element| {
184                Self::maybe_add_key(app, element, &mut keys)
185            });
186        }
187        keys
188    }
189
190    fn compute_identifier(app: &App, context: BuildContext) -> StorageEntryIdentifier {
191        StorageEntryIdentifier {
192            keys: Self::all_keys(app, context),
193        }
194    }
195
196    /// Write the given data into this page storage bucket using the specified identifier or
197    /// an identifier computed from the given context. The computed identifier is based on
198    /// the [`PageStorageKey`]s found in the path from context to the [`PageStorage`] widget
199    /// that owns this page storage bucket.
200    ///
201    /// If an explicit identifier is not provided and no [`PageStorageKey`]s are found, then
202    /// the `data` is not saved.
203    pub fn write_state(
204        self: Handle<Self>,
205        app: &mut App,
206        context: BuildContext,
207        data: Rc<dyn Any>,
208        identifier: Option<KeyRef>,
209    ) {
210        let slot = match identifier {
211            Some(identifier) => StorageSlot::Identifier(identifier),
212            None => {
213                let context_identifier = Self::compute_identifier(app, context);
214                if !context_identifier.is_not_empty() {
215                    app.get_mut(self).storage.get_or_insert_with(HashMap::new);
216                    return;
217                }
218                StorageSlot::Entry(context_identifier)
219            }
220        };
221        app.get_mut(self)
222            .storage
223            .get_or_insert_with(HashMap::new)
224            .insert(slot, data);
225    }
226
227    /// Read given data from into this page storage bucket using the specified identifier or
228    /// an identifier computed from the given context. The computed identifier is based on
229    /// the [`PageStorageKey`]s found in the path from context to the [`PageStorage`] widget
230    /// that owns this page storage bucket.
231    ///
232    /// If an explicit identifier is not provided and no [`PageStorageKey`]s are found, then
233    /// null is returned.
234    pub fn read_state(
235        self: Handle<Self>,
236        app: &App,
237        context: BuildContext,
238        identifier: Option<KeyRef>,
239    ) -> Option<Rc<dyn Any>> {
240        let storage = app.get(self).storage.as_ref()?;
241        let slot = match identifier {
242            Some(identifier) => StorageSlot::Identifier(identifier),
243            None => {
244                let context_identifier = Self::compute_identifier(app, context);
245                if !context_identifier.is_not_empty() {
246                    return None;
247                }
248                StorageSlot::Entry(context_identifier)
249            }
250        };
251        storage.get(&slot).cloned()
252    }
253}
254
255/// Establish a subtree in which widgets can opt into persisting states after being
256/// destroyed.
257///
258/// [`PageStorage`] is used to save and restore values that can outlive the widget. For
259/// example, when multiple pages are grouped in tabs, when a page is switched out, its widget
260/// is destroyed and its state is lost. By adding a [`PageStorage`] at the root and adding a
261/// [`PageStorageKey`] to each page, some of the page's state (e.g. the scroll position of a
262/// `Scrollable` widget) will be stored automatically in its closest ancestor [`PageStorage`],
263/// and restored when it's switched back.
264///
265/// Usually you don't need to explicitly use a [`PageStorage`], since it's already included
266/// in a `Navigator` (Dart's `MaterialApp` / `CupertinoApp` do it for you).
267#[derive(Debug)]
268pub struct PageStorage {
269    pub key: Option<KeyRef>,
270    /// The page storage bucket to use for this subtree.
271    pub bucket: Ref<PageStorageBucket>,
272    /// The widget below this widget in the tree.
273    pub child: WidgetRef,
274}
275
276impl PageStorage {
277    /// Creates a widget that provides a storage bucket for its descendants.
278    #[cfg_attr(debug_assertions, track_caller)]
279    pub fn new<K>(bucket: Ref<PageStorageBucket>, child: impl IntoWidget<K>) -> PageStorage {
280        PageStorage {
281            key: None,
282            bucket,
283            child: child.into_widget(),
284        }
285    }
286
287    /// Dart `PageStorage(key:)`.
288    pub fn key(mut self, key: KeyRef) -> PageStorage {
289        self.key = Some(key);
290        self
291    }
292
293    /// The [`PageStorageBucket`] from the closest instance of a [`PageStorage`] widget that
294    /// encloses the given context.
295    ///
296    /// Returns null if none exists.
297    ///
298    /// Typical usage is as follows:
299    ///
300    /// ```text
301    /// PageStorage::maybe_of(app, context)
302    /// ```
303    ///
304    /// This method can be expensive (it walks the element tree).
305    pub fn maybe_of(app: &App, context: BuildContext) -> Option<Handle<PageStorageBucket>> {
306        context
307            .find_ancestor_widget_of_exact_type::<PageStorage>(app)
308            .map(|widget| widget.bucket.handle())
309    }
310
311    /// The [`PageStorageBucket`] from the closest instance of a [`PageStorage`] widget that
312    /// encloses the given context.
313    ///
314    /// If no ancestor is found, this method will assert in debug mode, and throw an
315    /// exception in release mode.
316    ///
317    /// This method can be expensive (it walks the element tree).
318    pub fn of(app: &App, context: BuildContext) -> Handle<PageStorageBucket> {
319        PageStorage::maybe_of(app, context).unwrap_or_else(|| {
320            panic!(
321                "PageStorage.of() was called with a context that does not contain a PageStorage \
322                 widget.\nNo PageStorage widget ancestor could be found starting from the \
323                 context that was passed to PageStorage.of(). This can happen because you are \
324                 using a widget that looks for a PageStorage ancestor, but no such ancestor \
325                 exists.\nThe context used was:\n  {}",
326                context.widget(app).type_name()
327            )
328        })
329    }
330}
331
332impl StatelessWidget for PageStorage {
333    fn key(&self) -> Option<&KeyRef> {
334        self.key.as_ref()
335    }
336
337    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
338        self.child.clone()
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use std::cell::RefCell;
345    use waft_foundation::AppCell;
346
347    use super::*;
348    use crate::test_harness::Harness;
349    use crate::widgets::basic::{Builder, Padding, SizedBox};
350    use waft_painting::EdgeInsetsGeometry;
351
352    /// A leaf that writes `value` on its first build and reads it back on the next.
353    fn probe(seen: &Rc<RefCell<Vec<Option<i32>>>>, value: i32) -> WidgetRef {
354        let seen = Rc::clone(seen);
355        Builder::new(move |app, context| {
356            let bucket = PageStorage::of(app, context);
357            let read = bucket
358                .read_state(app, context, None)
359                .and_then(|data| data.downcast_ref::<i32>().copied());
360            seen.borrow_mut().push(read);
361            bucket.write_state(app, context, Rc::new(value), None);
362            SizedBox::shrink().into_widget()
363        })
364        .into_widget()
365    }
366
367    #[test]
368    fn state_is_filed_under_the_page_storage_key_chain() {
369        let cell = AppCell::new();
370        let mut app = cell.borrow_mut();
371        let bucket = PageStorageBucket::new(&mut app);
372        let seen = Rc::new(RefCell::new(Vec::new()));
373        let page = |seen: &Rc<RefCell<Vec<Option<i32>>>>, value: i32| {
374            PageStorage::new(
375                bucket.clone(),
376                Padding::new(EdgeInsetsGeometry::ZERO)
377                    .key(PageStorageKey::new("page").into_key())
378                    .child(probe(seen, value)),
379            )
380            .into_widget()
381        };
382        let harness = Harness::mount(&mut app, page(&seen, 1));
383        harness.pump(&mut app);
384        assert_eq!(*seen.borrow(), vec![None]);
385
386        // A recreated subtree with the same key chain reads the saved value.
387        harness.set_child(&mut app, SizedBox::shrink().into_widget());
388        harness.pump(&mut app);
389        harness.set_child(&mut app, page(&seen, 2));
390        harness.pump(&mut app);
391        assert_eq!(*seen.borrow(), vec![None, Some(1)]);
392    }
393
394    #[test]
395    fn without_keys_nothing_is_saved_and_identifiers_are_direct() {
396        let cell = AppCell::new();
397        let mut app = cell.borrow_mut();
398        let bucket = PageStorageBucket::new(&mut app);
399        let seen = Rc::new(RefCell::new(Vec::new()));
400        let harness = Harness::mount(
401            &mut app,
402            PageStorage::new(bucket.clone(), probe(&seen, 1)).into_widget(),
403        );
404        harness.pump(&mut app);
405        harness.set_child(
406            &mut app,
407            PageStorage::new(bucket.clone(), probe(&seen, 2)).into_widget(),
408        );
409        harness.pump(&mut app);
410        assert_eq!(*seen.borrow(), vec![None, None]);
411
412        let context = Rc::new(std::cell::Cell::new(None));
413        let capture = Builder::new({
414            let context = Rc::clone(&context);
415            move |_app, this| {
416                context.set(Some(this));
417                SizedBox::shrink().into_widget()
418            }
419        });
420        harness.set_child(
421            &mut app,
422            PageStorage::new(bucket.clone(), capture).into_widget(),
423        );
424        harness.pump(&mut app);
425        let context = context.get().expect("the probe built");
426        assert_eq!(PageStorage::maybe_of(&app, context), Some(bucket.handle()));
427
428        let identifier: KeyRef = waft_foundation::ValueKey::new("scroll").into();
429        bucket.write_state(&mut app, context, Rc::new(4.5f64), Some(identifier.clone()));
430        let read = bucket
431            .read_state(&app, context, Some(identifier))
432            .and_then(|data| data.downcast_ref::<f64>().copied());
433        assert_eq!(read, Some(4.5));
434    }
435}