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