Skip to main content

egui_kit/extract/
view_state.rs

1//! [`PageState`] and [`Snapshot`]: state owned by a view, for as long as the page (or layout) is
2//! shown, and kept across back/forward for snapshots.
3
4use core::any::{Any, TypeId, type_name};
5use core::cell::RefCell;
6use core::ops::{Deref, DerefMut};
7use std::collections::HashMap;
8use std::fmt;
9
10use super::FromView;
11use crate::page::ViewContext;
12use crate::remote::CommandSlots;
13
14/// Values by type. A value is taken out while a view uses it and put back afterwards, so a view
15/// can hold several types at once without borrowing the map.
16#[derive(Default)]
17pub(crate) struct TypeMap(RefCell<HashMap<TypeId, Option<Box<dyn Any>>>>);
18
19impl TypeMap {
20    fn take<T: Default + 'static>(&self) -> Box<T> {
21        let mut map = self.0.borrow_mut();
22        let slot = map
23            .entry(TypeId::of::<T>())
24            .or_insert_with(|| Some(Box::new(T::default())));
25        let value = slot.take().unwrap_or_else(|| {
26            panic!(
27                "egui-kit: a view can only extract `{}` once",
28                type_name::<T>()
29            )
30        });
31        value.downcast().expect("stored by type")
32    }
33
34    fn put<T: 'static>(&self, value: Box<T>) {
35        self.0.borrow_mut().insert(TypeId::of::<T>(), Some(value));
36    }
37
38    pub(crate) fn take_all(&self) -> Self {
39        Self(RefCell::new(core::mem::take(&mut *self.0.borrow_mut())))
40    }
41}
42
43/// The state of one page instance or layout: its [`PageState`]s, [`Snapshot`]s and commands.
44#[derive(Default)]
45pub(crate) struct ViewStore {
46    pub(crate) page: TypeMap,
47    pub(crate) snapshot: TypeMap,
48    pub(crate) commands: CommandSlots,
49}
50
51impl ViewStore {
52    /// A fresh store that continues `left`'s snapshots (coming back with back/forward).
53    pub(crate) fn restored(left: &Self) -> Self {
54        Self {
55            page: TypeMap::default(),
56            snapshot: left.snapshot.take_all(),
57            commands: CommandSlots::default(),
58        }
59    }
60}
61
62macro_rules! view_state {
63    ($(#[$doc:meta])* $name:ident, $map:ident) => {
64        $(#[$doc])*
65        pub struct $name<'f, T: 'static> {
66            value: Option<Box<T>>,
67            map: &'f TypeMap,
68        }
69
70        impl<S: 'static, D, T: Default + 'static> FromView<S, D> for $name<'_, T> {
71            type Item<'f> = $name<'f, T>;
72
73            fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> $name<'f, T> {
74                let map = &cx.store().$map;
75                $name {
76                    value: Some(map.take()),
77                    map,
78                }
79            }
80        }
81
82        impl<T> Deref for $name<'_, T> {
83            type Target = T;
84
85            fn deref(&self) -> &T {
86                self.value.as_ref().expect("present until dropped")
87            }
88        }
89
90        impl<T> DerefMut for $name<'_, T> {
91            fn deref_mut(&mut self) -> &mut T {
92                self.value.as_mut().expect("present until dropped")
93            }
94        }
95
96        impl<T> Drop for $name<'_, T> {
97            fn drop(&mut self) {
98                if let Some(value) = self.value.take() {
99                    self.map.put(value);
100                }
101            }
102        }
103
104        impl<T: fmt::Debug> fmt::Debug for $name<'_, T> {
105            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106                f.debug_tuple(stringify!($name)).field(&**self).finish()
107            }
108        }
109    };
110}
111
112view_state!(
113    /// State a view owns for as long as its page is shown.
114    ///
115    /// Created with `T::default()` the first time it is extracted, then kept from frame to frame:
116    /// use it for what the user does on the page (a form's text, a toggle). Unlike the `load`'s
117    /// data, it survives invalidations. It is dropped when the user navigates away, and starts
118    /// over when they come back. For state that comes back with back/forward, use [`Snapshot`].
119    ///
120    /// In a page view, it belongs to the page instance, which shallow routing and invalidations
121    /// keep. In a layout view, it belongs to the layout and lasts as long as the layout stays on
122    /// screen, so it survives navigations between the pages below it.
123    ///
124    /// Each type is one value per view: use a dedicated type, not `String` or `bool`.
125    ///
126    /// ```
127    /// use egui::Ui;
128    /// use egui_kit::extract::PageState;
129    ///
130    /// #[derive(Default)]
131    /// struct Draft {
132    ///     title: String,
133    /// }
134    ///
135    /// fn view(ui: &mut Ui, mut draft: PageState<Draft>) {
136    ///     ui.text_edit_singleline(&mut draft.title);
137    /// }
138    /// ```
139    ///
140    /// To start from the `load`'s data, make the field an `Option` and fill it on first use:
141    /// `draft.title.get_or_insert_with(|| data.title.clone())`.
142    PageState,
143    page
144);
145
146view_state!(
147    /// Like [`PageState`], but kept when the user navigates away and restored when they come
148    /// back with back/forward.
149    ///
150    /// Use it for UI state worth getting back, such as a half-typed search or a draft. A new
151    /// navigation to the page (a link, `goto`) starts over with `T::default()`. Snapshots are kept
152    /// in memory, so a browser reload or an app restart loses them; see
153    /// [`PersistentState`](super::PersistentState) for state that survives those.
154    ///
155    /// ```
156    /// use egui::Ui;
157    /// use egui_kit::extract::Snapshot;
158    ///
159    /// #[derive(Default)]
160    /// struct Search {
161    ///     text: String,
162    /// }
163    ///
164    /// fn view(ui: &mut Ui, mut search: Snapshot<Search>) {
165    ///     ui.text_edit_singleline(&mut search.text);
166    /// }
167    /// ```
168    Snapshot,
169    snapshot
170);