egui_kit/extract.rs
1//! Extractors: the arguments of hooks, `load`s and views.
2//!
3//! Hooks and `load`s are async functions whose arguments implement [`FromRequest`]; views are
4//! functions of a `&mut egui::Ui` whose other arguments implement [`FromView`]. The extractors
5//! can be in any order.
6//!
7//! # In hooks and `load`s
8//!
9//! | Extractor | Gives you |
10//! |---|---|
11//! | [`Path<T>`] | the route's path parameters, deserialized with serde |
12//! | [`Query<T>`] | the query string, deserialized with serde |
13//! | [`State<T>`] | a clone of the app state, or of any part of it that implements [`FromRef`] |
14//! | [`Parent`] | the data loaded by the layouts above |
15//! | [`Request`] | the url and the route's parameters, untyped |
16//!
17//! What a `load` extracts decides when it reruns: [`Path`] and [`Query`] make it depend on the
18//! parameters and the query, [`Parent`] on the layouts above.
19//!
20//! # In views
21//!
22//! | Extractor | Gives you |
23//! |---|---|
24//! | `&mut D` / `&D` | the data the `load` returned (`()` without one), checked at compile time |
25//! | `&RouteError` | the error, in error pages |
26//! | [`LayoutData<T>`] | the data of the nearest layout around the view that loaded a `T` |
27//! | [`State<&T>`](State) | the app state, or any part of it that implements [`FromRef`], borrowed |
28//! | [`Nav`] | the router: links, `goto`, back/forward, loading, invalidation, shallow routing, blocking |
29//! | [`Scroll`] | the page's scroll area, whose position the router restores |
30//! | [`PageState<T>`] | state the view owns while its page is shown |
31//! | [`PageStateFrom<T>`] | like [`PageState`], created from the `load`'s data |
32//! | [`Snapshot<T>`] | like [`PageState`], and restored when coming back with back/forward |
33//! | [`PersistentState<T>`] | app-wide state that survives app restarts, like `localStorage` |
34//! | [`HistoryState<&T>`](HistoryState) | the shallow-routing state of the current history entry |
35//! | [`Navigation`] | how the page was reached: from where, how, in which history direction |
36//! | [`Request`] | the url the page was loaded with, and its route's parameters |
37//!
38//! Layout views also get the [`Children`](crate::page::Children) as their second argument; it is not an
39//! extractor, every layout has exactly one.
40//!
41//! # Borrowing and mutating
42//!
43//! Views run synchronously within the frame, so what they extract is borrowed from the router:
44//! nothing big is cloned every frame. Hooks and `load`s are futures that can outlive the frame,
45//! so they get owned values, cloned once per navigation.
46//!
47//! # Which state to use
48//!
49//! | | Lives | Mutable by views |
50//! |---|---|---|
51//! | [`State<&T>`](State) | as long as the app, shared by everything | through `Cell` / `RefCell` |
52//! | `&mut D` (the `load`'s data) | until the `load` reruns | yes |
53//! | [`PageState<T>`] | while the page (or layout) is shown, across invalidations | yes |
54//! | [`Snapshot<T>`] | like [`PageState`], and restored when coming back with back/forward | yes |
55//! | [`HistoryState<&T>`](HistoryState) | with its history entry, set by [`Nav::push_state`] | through [`Nav`] |
56//! | [`PersistentState<T>`] | across app restarts, shared by the whole app | yes |
57//!
58//! A rule of thumb: what you loaded goes in the `load`'s data, what the user did goes in a
59//! [`PageState`] or a [`Snapshot`], and preferences go in a [`PersistentState`]. The app state
60//! is shared by every view at once, so no view can get `&mut` access to it.
61//!
62//! [`RouteError`]: crate::RouteError
63
64mod history_state;
65mod layout_data;
66mod nav;
67pub(crate) mod parent;
68mod path;
69mod persistent_state;
70mod query;
71mod scroll;
72mod state;
73mod view_state;
74
75use crate::error::Rejection;
76use crate::navigation::Navigation;
77use crate::page::ViewContext;
78use crate::request::Request;
79pub use history_state::HistoryState;
80pub use layout_data::LayoutData;
81pub use nav::Nav;
82pub(crate) use nav::{NavAction, NavState};
83pub use parent::Parent;
84pub use path::Path;
85pub use persistent_state::PersistentState;
86pub use query::Query;
87pub(crate) use scroll::PageScroll;
88pub use scroll::Scroll;
89pub use state::{FromRef, State};
90pub(crate) use view_state::ViewStore;
91pub use view_state::{PageState, PageStateFrom, Snapshot, SnapshotFrom};
92
93/// Types that can be extracted from a navigation, used as arguments of hooks and `load`s.
94///
95/// Extraction is synchronous and runs before the handler's future is created. What an extractor
96/// reads from the [`Request`] (path, query, params) decides when the `load` reruns.
97#[diagnostic::on_unimplemented(
98 message = "`{Self}` can't be extracted in a hook or `load`",
99 note = "hooks and `load`s own what they extract: `State<T>` rather than `State<&T>`",
100 note = "see the `egui_kit::extract` module for the available extractors"
101)]
102pub trait FromRequest<S>: Sized {
103 /// Extracts the value from the request and the app state.
104 ///
105 /// # Errors
106 ///
107 /// The [`Rejection`] is handled like one returned from the hook or `load` itself: an error
108 /// renders the nearest error page, a redirect navigates elsewhere.
109 fn from_request(req: &Request, state: &S) -> Result<Self, Rejection>;
110}
111
112/// Types that can be extracted for a view, used as arguments of page, layout and error views.
113///
114/// `S` is the app state and `D` the data of the view: what its `load` returned
115/// (`()` without one), or the [`RouteError`](crate::RouteError) for error pages. `Item` is the
116/// extractor with the lifetime of the frame, e.g. `Nav<'f>` for `Nav<'_>`.
117///
118/// A custom extractor, e.g. for the signed-in user:
119///
120/// ```
121/// use egui_kit::page::ViewContext;
122/// use egui_kit::extract::FromView;
123///
124/// #[derive(Clone)]
125/// struct AppState {
126/// user: Option<String>,
127/// }
128///
129/// struct User(Option<String>);
130///
131/// impl<D> FromView<AppState, D> for User {
132/// type Item<'f> = User;
133///
134/// fn from_view(cx: &ViewContext<'_, AppState>) -> User {
135/// User(cx.state().user.clone())
136/// }
137/// }
138/// ```
139#[diagnostic::on_unimplemented(
140 message = "`{Self}` can't be extracted in a view",
141 note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
142 note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
143 note = "see the `egui_kit::extract` module for the available extractors"
144)]
145pub trait FromView<S: 'static, D>: Sized {
146 type Item<'f>;
147
148 /// Whether this takes the view's data mutably (`&mut D`).
149 #[doc(hidden)]
150 const BORROWS_DATA_MUT: bool = false;
151
152 /// Called for every extractor of a view before any is extracted, e.g. to read the data
153 /// before an extractor takes it.
154 #[doc(hidden)]
155 fn prepare(_cx: &ViewContext<'_, S>) {}
156
157 fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> Self::Item<'f>;
158}
159
160impl<S> FromRequest<S> for Request {
161 fn from_request(req: &Request, _state: &S) -> Result<Self, Rejection> {
162 Ok(req.clone())
163 }
164}
165
166/// The url the page was loaded with and the parameters of its route. Unaffected by shallow
167/// routing, see [`Nav::url`].
168impl<S: 'static, D> FromView<S, D> for Request {
169 type Item<'f> = Self;
170
171 fn from_view(cx: &ViewContext<'_, S>) -> Self {
172 cx.frame().request.clone()
173 }
174}
175
176/// How the page was reached.
177impl<S: 'static, D> FromView<S, D> for Navigation {
178 type Item<'f> = Self;
179
180 fn from_view(cx: &ViewContext<'_, S>) -> Self {
181 cx.frame().navigation.clone()
182 }
183}
184
185/// The view's data: what its `load` returned, or the error of an error page.
186impl<S: 'static, D: 'static> FromView<S, D> for &mut D {
187 type Item<'f> = &'f mut D;
188
189 const BORROWS_DATA_MUT: bool = true;
190
191 fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> &'f mut D {
192 cx.take_data_mut().downcast_mut().expect(MISMATCH)
193 }
194}
195
196/// Read-only access to the view's data.
197impl<S: 'static, D: 'static> FromView<S, D> for &D {
198 type Item<'f> = &'f D;
199
200 fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> &'f D {
201 cx.take_data().downcast_ref().expect(MISMATCH)
202 }
203}
204
205const MISMATCH: &str = "egui-kit: the data does not match the view (this is a bug)";