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. Outside of views, use
22/// [`PersistentState::get`] and [`PersistentState::set`].
23///
24/// Saving needs eframe's `persistence` feature. Without it, the value still lives in egui's
25/// memory, for as long as the app runs.
26///
27/// ```
28/// use egui::Ui;
29/// use egui_kit::extract::PersistentState;
30/// use serde::{Deserialize, Serialize};
31///
32/// #[derive(Clone, Default, Serialize, Deserialize)]
33/// struct Preferences {
34///     compact: bool,
35/// }
36///
37/// fn view(ui: &mut Ui, mut preferences: PersistentState<Preferences>) {
38///     ui.checkbox(&mut preferences.compact, "Compact");
39/// }
40/// ```
41pub struct PersistentState<'f, T>
42where
43    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
44{
45    value: Option<T>,
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        PersistentState {
58            value: Some(Self::get(ctx)),
59            ctx,
60        }
61    }
62}
63
64/// Outside of views, e.g. to apply a theme before the router draws.
65impl<T> PersistentState<'_, T>
66where
67    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
68{
69    /// The value.
70    ///
71    /// ```
72    /// # use egui_kit::extract::PersistentState;
73    /// # #[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
74    /// # struct Preferences { dark: bool }
75    /// fn apply_theme(ctx: &egui::Context) {
76    ///     let preferences = PersistentState::<Preferences>::get(ctx);
77    ///     ctx.set_theme(if preferences.dark { egui::Theme::Dark } else { egui::Theme::Light });
78    /// }
79    /// ```
80    pub fn get(ctx: &egui::Context) -> T {
81        ctx.data_mut(|data| data.get_persisted_mut_or_default::<T>(Self::id()).clone())
82    }
83
84    /// Replaces the value.
85    pub fn set(ctx: &egui::Context, value: T) {
86        ctx.data_mut(|data| data.insert_persisted(Self::id(), value));
87    }
88
89    /// Where the value is kept in egui's [memory](egui::Memory).
90    pub fn id() -> Id {
91        Id::unique(("egui_kit::PersistentState", type_name::<T>()))
92    }
93}
94
95impl<T> Deref for PersistentState<'_, T>
96where
97    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
98{
99    type Target = T;
100
101    fn deref(&self) -> &T {
102        self.value.as_ref().expect("present until dropped")
103    }
104}
105
106impl<T> DerefMut for PersistentState<'_, T>
107where
108    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
109{
110    fn deref_mut(&mut self) -> &mut T {
111        self.value.as_mut().expect("present until dropped")
112    }
113}
114
115impl<T> Drop for PersistentState<'_, T>
116where
117    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static,
118{
119    fn drop(&mut self) {
120        if let Some(value) = self.value.take() {
121            Self::set(self.ctx, value);
122        }
123    }
124}
125
126impl<T> fmt::Debug for PersistentState<'_, T>
127where
128    T: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static + fmt::Debug,
129{
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.debug_tuple("PersistentState").field(&**self).finish()
132    }
133}