Skip to main content

egui_kit/extract/
persistent_state.rs

1//! [`PersistentState`]: app-wide state that survives app restarts, like `localStorage`.
2
3use core::any::type_name;
4use core::ops::{Deref, DerefMut};
5use std::fmt;
6
7use egui::Id;
8use serde::Serialize;
9use serde::de::DeserializeOwned;
10
11use super::FromView;
12use crate::page::ViewContext;
13
14/// State that outlives the app, saved with egui's persisted memory.
15///
16/// eframe writes it to disk natively and to `localStorage` on the web. Like `localStorage`, there
17/// is one value per type for the whole app, shared by every view that extracts it.
18///
19/// Use it for preferences: a theme, a sort order, a collapsed sidebar. It is created with
20/// `T::default()`, read at the start of the view and written back when the view returns (the
21/// last view to write wins), so keep it small.
22///
23/// Saving needs eframe's `persistence` feature. Without it, the value still lives in egui's
24/// memory, for as long as the app runs.
25///
26/// ```
27/// use egui::Ui;
28/// use egui_kit::extract::PersistentState;
29/// use serde::{Deserialize, Serialize};
30///
31/// #[derive(Clone, Default, Serialize, Deserialize)]
32/// struct Preferences {
33///     compact: bool,
34/// }
35///
36/// fn view(ui: &mut Ui, mut preferences: PersistentState<Preferences>) {
37///     ui.checkbox(&mut preferences.compact, "Compact");
38/// }
39/// ```
40pub struct PersistentState<'f, T>
41where
42    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
43{
44    value: Option<T>,
45    id: Id,
46    ctx: &'f egui::Context,
47}
48
49impl<S: 'static, D, T> FromView<S, D> for PersistentState<'_, T>
50where
51    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
52{
53    type Item<'f> = PersistentState<'f, T>;
54
55    fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> PersistentState<'f, T> {
56        let ctx = &cx.frame().ctx;
57        let id = Id::new(("egui_kit::PersistentState", type_name::<T>()));
58        let value = ctx.data_mut(|data| data.get_persisted_mut_or_default::<T>(id).clone());
59        PersistentState {
60            value: Some(value),
61            id,
62            ctx,
63        }
64    }
65}
66
67impl<T> Deref for PersistentState<'_, T>
68where
69    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
70{
71    type Target = T;
72
73    fn deref(&self) -> &T {
74        self.value.as_ref().expect("present until dropped")
75    }
76}
77
78impl<T> DerefMut for PersistentState<'_, T>
79where
80    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
81{
82    fn deref_mut(&mut self) -> &mut T {
83        self.value.as_mut().expect("present until dropped")
84    }
85}
86
87impl<T> Drop for PersistentState<'_, T>
88where
89    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
90{
91    fn drop(&mut self) {
92        if let Some(value) = self.value.take() {
93            self.ctx
94                .data_mut(|data| data.insert_persisted(self.id, value));
95        }
96    }
97}
98
99impl<T> fmt::Debug for PersistentState<'_, T>
100where
101    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static + fmt::Debug,
102{
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.debug_tuple("PersistentState").field(&**self).finish()
105    }
106}