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