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;
12
13/// Values by type. A value is taken out while a view uses it and put back afterwards, so a view
14/// can hold several types at once without borrowing the map.
15#[derive(Default)]
16pub(crate) struct TypeMap(RefCell<HashMap<TypeId, Option<Box<dyn Any>>>>);
17
18impl TypeMap {
19 fn take<T: 'static>(&self, init: impl FnOnce() -> T) -> Box<T> {
20 let mut map = self.0.borrow_mut();
21 let slot = map
22 .entry(TypeId::of::<T>())
23 .or_insert_with(|| Some(Box::new(init())));
24 let value = slot.take().unwrap_or_else(|| {
25 panic!(
26 "egui-kit: a view can only extract `{}` once",
27 type_name::<T>()
28 )
29 });
30 value.downcast().expect("stored by type")
31 }
32
33 fn put<T: 'static>(&self, value: Box<T>) {
34 self.0.borrow_mut().insert(TypeId::of::<T>(), Some(value));
35 }
36
37 fn contains<T: 'static>(&self) -> bool {
38 self.0.borrow().contains_key(&TypeId::of::<T>())
39 }
40
41 pub(crate) fn take_all(&self) -> Self {
42 Self(RefCell::new(core::mem::take(&mut *self.0.borrow_mut())))
43 }
44}
45
46/// The state of one page instance or layout: its [`PageState`]s and [`Snapshot`]s.
47#[derive(Default)]
48pub(crate) struct ViewStore {
49 pub(crate) page: TypeMap,
50 pub(crate) snapshot: TypeMap,
51}
52
53impl ViewStore {
54 /// A fresh store that continues `left`'s snapshots (coming back with back/forward).
55 pub(crate) fn restored(left: &Self) -> Self {
56 Self {
57 page: TypeMap::default(),
58 snapshot: left.snapshot.take_all(),
59 }
60 }
61}
62
63/// Makes a view state from the view's data.
64fn from_data<S, D: 'static, T: for<'d> From<&'d D>>(cx: &ViewContext<'_, S>) -> T {
65 cx.peek_data(|data| {
66 T::from(
67 data.downcast_ref::<D>()
68 .expect("egui-kit: the data does not match the view (this is a bug)"),
69 )
70 })
71}
72
73/// A view state type: a value taken out of its map while the view uses it.
74macro_rules! view_state {
75 ($(#[$doc:meta])* $name:ident) => {
76 $(#[$doc])*
77 pub struct $name<'f, T: 'static> {
78 value: Option<Box<T>>,
79 map: &'f TypeMap,
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
112/// The extractors of a view state, created with `T::default()` and from the view's data.
113macro_rules! view_state_extractors {
114 ($default:ident, $from:ident, $map:ident) => {
115 impl<S: 'static, D, T: Default + 'static> FromView<S, D> for $default<'_, T> {
116 type Item<'f> = $default<'f, T>;
117
118 fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> $default<'f, T> {
119 let map = &cx.store().$map;
120 $default {
121 value: Some(map.take(T::default)),
122 map,
123 }
124 }
125 }
126
127 impl<S: 'static, D: 'static, T> FromView<S, D> for $from<'_, T>
128 where
129 T: for<'d> From<&'d D> + 'static,
130 {
131 type Item<'f> = $from<'f, T>;
132
133 // Before any extractor takes the data.
134 fn prepare(cx: &ViewContext<'_, S>) {
135 let map = &cx.store().$map;
136 if !map.contains::<T>() {
137 map.put(Box::new(from_data::<S, D, T>(cx)));
138 }
139 }
140
141 fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> $from<'f, T> {
142 let map = &cx.store().$map;
143 $from {
144 value: Some(map.take(|| from_data::<S, D, T>(cx))),
145 map,
146 }
147 }
148 }
149 };
150}
151
152view_state!(
153 /// State a view owns for as long as its page is shown.
154 ///
155 /// Created with `T::default()` the first time it is extracted, then kept from frame to frame:
156 /// use it for what the user does on the page (a form's text, a toggle). Unlike the `load`'s
157 /// data, it survives invalidations. It is dropped when the user navigates away, and starts
158 /// over when they come back. For state that comes back with back/forward, use [`Snapshot`].
159 ///
160 /// In a page view, it belongs to the page instance, which shallow routing and invalidations
161 /// keep. In a layout view, it belongs to the layout and lasts as long as the layout stays on
162 /// screen, so it survives navigations between the pages below it.
163 ///
164 /// Each type is one value per view: use a dedicated type, not `String` or `bool`.
165 ///
166 /// ```
167 /// use egui::Ui;
168 /// use egui_kit::extract::PageState;
169 ///
170 /// #[derive(Default)]
171 /// struct Draft {
172 /// title: String,
173 /// }
174 ///
175 /// fn view(ui: &mut Ui, mut draft: PageState<Draft>) {
176 /// ui.text_edit_singleline(&mut draft.title);
177 /// }
178 /// ```
179 ///
180 /// To start from the `load`'s data, see [`PageStateFrom`].
181 PageState
182);
183
184view_state!(
185 /// Like [`PageState`], but created from the view's data (what its `load` returned) with
186 /// `T::from(&data)`, the first time it is extracted.
187 ///
188 /// ```
189 /// use egui::Ui;
190 /// use egui_kit::extract::PageStateFrom;
191 ///
192 /// struct Post {
193 /// title: String,
194 /// }
195 ///
196 /// struct Form {
197 /// title: String,
198 /// }
199 ///
200 /// impl From<&Post> for Form {
201 /// fn from(post: &Post) -> Self {
202 /// Self { title: post.title.clone() }
203 /// }
204 /// }
205 ///
206 /// fn edit(ui: &mut Ui, post: &Post, mut form: PageStateFrom<Form>) {
207 /// ui.label(format!("Editing {}", post.title));
208 /// ui.text_edit_singleline(&mut form.title);
209 /// }
210 /// ```
211 ///
212 /// It shares its value with a [`PageState`] of the same type.
213 PageStateFrom
214);
215
216view_state!(
217 /// Like [`PageState`], but kept when the user navigates away and restored when they come
218 /// back with back/forward.
219 ///
220 /// Use it for UI state worth getting back, such as a half-typed search or a draft. A new
221 /// navigation to the page (a link, `goto`) starts over with `T::default()`. Snapshots are kept
222 /// in memory, so a browser reload or an app restart loses them; see
223 /// [`PersistentState`](super::PersistentState) for state that survives those.
224 ///
225 /// ```
226 /// use egui::Ui;
227 /// use egui_kit::extract::Snapshot;
228 ///
229 /// #[derive(Default)]
230 /// struct Search {
231 /// text: String,
232 /// }
233 ///
234 /// fn view(ui: &mut Ui, mut search: Snapshot<Search>) {
235 /// ui.text_edit_singleline(&mut search.text);
236 /// }
237 /// ```
238 Snapshot
239);
240
241view_state!(
242 /// Like [`Snapshot`], but created from the view's data (what its `load` returned) with
243 /// `T::from(&data)`, like a [`PageStateFrom`]. A snapshot that comes back with back/forward
244 /// keeps its value.
245 SnapshotFrom
246);
247
248view_state_extractors!(PageState, PageStateFrom, page);
249view_state_extractors!(Snapshot, SnapshotFrom, snapshot);