Skip to main content

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