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