egui_kit/extract/state.rs
1//! [`State`]: the app state, in hooks, `load`s and views.
2
3use super::{FromRequest, FromView};
4use crate::error::Rejection;
5use crate::page::ViewContext;
6use crate::request::Request;
7
8/// The app state passed to [`Router::with_state`](crate::Router::with_state), or a part of it
9/// that implements [`FromRef`].
10///
11/// - **Views borrow it**: `State<&T>`. They run synchronously within the frame, so they never
12/// pay for a clone, however big the state is.
13/// - **Hooks and `load`s own it**: `State<T>`, a clone (hence `T: Clone`). Their futures can
14/// outlive the frame, but they only run once per navigation. Keep shared data behind `Rc`
15/// anyway, so the clone is cheap and changes are visible everywhere.
16///
17/// A view asking for an owned `State<T>` doesn't compile, so it can't clone by accident:
18///
19/// ```compile_fail
20/// # use egui_kit::extract::State;
21/// # use egui_kit::page::Page;
22/// fn view(ui: &mut egui::Ui, State(state): State<String>) {}
23///
24/// let page = Page::<String>::new(view); // `State<&String>` would work
25/// ```
26///
27/// Neither can get `&mut` access: every view of the page (and every load) shares the state, and
28/// a layout's view still holds it while its page draws. Mutate it with `Cell` and `RefCell`.
29///
30/// ```
31/// use std::cell::Cell;
32/// use std::rc::Rc;
33///
34/// use egui::Ui;
35/// use egui_kit::Rejection;
36/// use egui_kit::extract::State;
37///
38/// #[derive(Clone, Default)]
39/// struct AppState {
40/// clicks: Rc<Cell<u32>>,
41/// }
42///
43/// async fn load(State(state): State<AppState>) -> Result<u32, Rejection> {
44/// Ok(state.clicks.get())
45/// }
46///
47/// fn view(ui: &mut Ui, State(state): State<&AppState>) {
48/// if ui.button("Click").clicked() {
49/// state.clicks.set(state.clicks.get() + 1);
50/// }
51/// }
52/// ```
53#[derive(Debug, Clone, Copy, Default)]
54pub struct State<T>(pub T);
55
56impl<S, T: FromRef<S> + Clone> FromRequest<S> for State<T> {
57 fn from_request(_req: &Request, state: &S) -> Result<Self, Rejection> {
58 Ok(Self(T::from_ref(state).clone()))
59 }
60}
61
62impl<S: 'static, D, T: FromRef<S> + 'static> FromView<S, D> for State<&'_ T> {
63 type Item<'f> = State<&'f T>;
64
65 fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> State<&'f T> {
66 State(T::from_ref(cx.state()))
67 }
68}
69
70/// A part of the app state that [`State`] can extract on its own, e.g. `State<&Db>` for an
71/// `AppState` with a `db` field.
72///
73/// It borrows: a part is a field of the state, which views borrow and
74/// hooks and `load`s clone. Every state is a part of itself.
75///
76/// ```
77/// use egui_kit::extract::FromRef;
78///
79/// #[derive(Clone)]
80/// struct AppState {
81/// db: Db,
82/// }
83///
84/// #[derive(Clone)]
85/// struct Db;
86///
87/// impl FromRef<AppState> for Db {
88/// fn from_ref(state: &AppState) -> &Db {
89/// &state.db
90/// }
91/// }
92/// ```
93pub trait FromRef<S> {
94 fn from_ref(state: &S) -> &Self;
95}
96
97impl<S> FromRef<S> for S {
98 fn from_ref(state: &S) -> &S {
99 state
100 }
101}