Skip to main content

egui_kit/
lib.rs

1//! A router for [egui](https://github.com/emilk/egui), inspired by SvelteKit's routing and axum's
2//! API.
3//!
4//! Routes map paths to pages. A page has an optional async `load` that runs when the page is
5//! navigated to, and a view that is called every frame with what the load returned. Both get their
6//! inputs as typed function arguments, the [extractors](extract).
7//!
8//! ```
9//! use egui::Ui;
10//! use egui_kit::{Rejection, Router, RouterApp};
11//! use egui_kit::extract::{Nav, Path};
12//! use egui_kit::page::Page;
13//!
14//! fn home(ui: &mut Ui, nav: Nav) {
15//!     ui.heading("Home");
16//!     nav.link(ui, "Say hello", "/hello/ferris");
17//! }
18//!
19//! async fn load_greeting(Path(name): Path<String>) -> Result<String, Rejection> {
20//!     Ok(format!("Hello, {name}!"))
21//! }
22//!
23//! fn greeting(ui: &mut Ui, greeting: &String, nav: Nav) {
24//!     ui.heading(greeting);
25//!     nav.link(ui, "Home", "/");
26//! }
27//!
28//! fn app() -> RouterApp<()> {
29//!     Router::new()
30//!         .page("/", Page::new(home))
31//!         .page("/hello/{name}", Page::with_load(load_greeting, greeting))
32//!         .with_state(())
33//! }
34//!
35//! // Call this every frame, e.g. from `eframe::App::ui`.
36//! fn frame(app: &mut RouterApp<()>, ui: &mut Ui) {
37//!     app.ui(ui);
38//! }
39//! ```
40//!
41//! On the web, the router uses the browser's history, so the address bar and the back/forward
42//! buttons work. Natively, it keeps the history in memory and handles the mouse's back/forward
43//! buttons and Alt+←/→.
44//!
45//! # Routing
46//!
47//! [`Router::page`] adds a page at a path, [`Router::nest`] adds another router under a prefix.
48//! A router's [layout](Router::layout), [hooks](Router::hook) and [error page](Router::error)
49//! apply to its own pages and to the routers nested in it.
50//!
51//! | Path segment | Matches |
52//! |---|---|
53//! | `about` | exactly `about` |
54//! | `{slug}` | any segment |
55//! | `{id=int}` | a segment the [`int` matcher](Router::matcher) accepts |
56//! | `{?lang}`, `{?lang=lang}` | an optional segment |
57//! | `{*path}` | the rest of the path (last segment only) |
58//!
59//! When several routes match, static segments win over parameters with a matcher, which win over
60//! plain parameters.
61//!
62//! ```
63//! use egui::Ui;
64//! use egui_kit::Router;
65//! use egui_kit::page::{Layout, Outlet, Page};
66//!
67//! fn view(ui: &mut Ui) {
68//!     ui.label("A page");
69//! }
70//!
71//! fn blog_layout(ui: &mut Ui, mut outlet: Outlet) {
72//!     ui.heading("Blog");
73//!     outlet.show(ui);
74//! }
75//!
76//! let blog = Router::new()
77//!     .layout(Layout::new(blog_layout))
78//!     .page("/", Page::new(view)) // `/blog`
79//!     .page("/{slug}", Page::new(view)) // `/blog/hello-world`
80//!     .page("/{slug}/print", Page::new(view).reset_layouts()); // without the blog layout
81//!
82//! let app = Router::<()>::new()
83//!     .matcher("int", |segment| segment.parse::<u32>().is_ok())
84//!     .page("/", Page::new(view))
85//!     .page("/users/{id=int}", Page::new(view)) // `/users/7`, but not `/users/ferris`
86//!     .page("/{?lang}/about", Page::new(view)) // `/about` and `/de/about`
87//!     .page("/files/{*path}", Page::new(view)) // `/files/a/b/c`
88//!     .nest("/blog", blog)
89//!     .with_state(());
90//! ```
91//!
92//! [`Router::merge`] adds a router's pages at the same level, keeping its layout, hooks and error
93//! page to its own pages. Building the app panics on conflicting routes and unknown matchers.
94//!
95//! # Pages and layouts
96//!
97//! A [`Page`](page::Page) is a view, created with [`Page::new`](page::Page::new), or a load and a
98//! view, created with [`Page::with_load`](page::Page::with_load):
99//!
100//! - A **load** is an `async fn` of extractors returning `Result<D, E>`, where
101//!   `E: Into<Rejection>`. No async runtime is needed. While it runs, the previous page stays on
102//!   screen.
103//! - A **view** is a function of `&mut Ui` and extractors, called every frame. It gets the load's
104//!   data as `&D` or `&mut D`.
105//!
106//! A [`Layout`](page::Layout) wraps the pages of a router. It can have a load too, and its view
107//! draws the page through the [`Outlet`](page::Outlet), or animates page changes with a
108//! [`ViewTransition`].
109//!
110//! ```
111//! use egui::Ui;
112//! use egui_kit::{Rejection, Router, ViewTransition, error};
113//! use egui_kit::extract::{Nav, Parent, Path};
114//! use egui_kit::page::{Layout, Outlet, Page};
115//!
116//! #[derive(Clone)]
117//! struct Blog {
118//!     posts: Vec<String>,
119//! }
120//!
121//! async fn load_blog() -> Result<Blog, Rejection> {
122//!     Ok(Blog { posts: vec!["hello".into(), "world".into()] })
123//! }
124//!
125//! fn blog_layout(ui: &mut Ui, outlet: Outlet, blog: &Blog, nav: Nav) {
126//!     for post in &blog.posts {
127//!         nav.nav_link(ui, post, &format!("/blog/{post}"));
128//!     }
129//!     ViewTransition::slide().show(ui, outlet);
130//! }
131//!
132//! struct Post {
133//!     slug: String,
134//!     comment: String,
135//! }
136//!
137//! // `Parent` gives access to the data of the layouts above.
138//! async fn load_post(Path(slug): Path<String>, parent: Parent) -> Result<Post, Rejection> {
139//!     let blog = parent.get::<Blog>().await?;
140//!     if !blog.posts.contains(&slug) {
141//!         return Err(error(404, "no such post"));
142//!     }
143//!     Ok(Post { slug, comment: String::new() })
144//! }
145//!
146//! fn post(ui: &mut Ui, post: &mut Post) {
147//!     ui.heading(&post.slug);
148//!     ui.text_edit_singleline(&mut post.comment);
149//! }
150//!
151//! let blog = Router::<()>::new()
152//!     .layout(Layout::with_load(load_blog, blog_layout).depends("app:posts"))
153//!     .page("/{slug}", Page::with_load(load_post, post));
154//! ```
155//!
156//! A load only reruns when the parameters, query or parent data it uses change: above, going from
157//! one post to another doesn't reload the blog. [`Nav::invalidate`](extract::Nav::invalidate)
158//! reruns the loads that [`depend`](page::Page::depends) on a key. Links preload their target
159//! while hovered.
160//!
161//! # Extractors
162//!
163//! Extractors are the arguments of loads, hooks and views. The [`extract`] module lists all of
164//! them.
165//!
166//! ```
167//! use egui::Ui;
168//! use egui_kit::Rejection;
169//! use egui_kit::extract::{Nav, Path, Query, State};
170//! use serde::Deserialize;
171//!
172//! #[derive(Clone)]
173//! struct AppState;
174//!
175//! #[derive(Deserialize)]
176//! struct Pagination {
177//!     page: Option<u32>,
178//! }
179//!
180//! async fn load(
181//!     Path((user, repo)): Path<(String, String)>,
182//!     Query(pagination): Query<Pagination>,
183//!     State(state): State<AppState>,
184//! ) -> Result<Vec<String>, Rejection> {
185//!     let page = pagination.page.unwrap_or(1);
186//!     Ok(vec![format!("{user}/{repo}, page {page}")])
187//! }
188//!
189//! fn view(ui: &mut Ui, issues: &Vec<String>, nav: Nav) {
190//!     for issue in issues {
191//!         ui.label(issue);
192//!     }
193//!     if ui.button("Back").clicked() {
194//!         nav.back();
195//!     }
196//! }
197//! ```
198//!
199//! | In loads and hooks | In views |
200//! |---|---|
201//! | [`Path<T>`](extract::Path), [`Query<T>`](extract::Query): parameters and query | `&D` / `&mut D`: the load's data; `&RouteError` in error pages |
202//! | [`State<T>`](extract::State): the app state | [`State<&T>`](extract::State): the app state |
203//! | [`Parent`](extract::Parent): the data of the layouts above | [`Nav`](extract::Nav): links and navigation |
204//! | [`Request`]: the url and parameters | [`PageState<T>`](extract::PageState), [`Snapshot<T>`](extract::Snapshot), [`PersistentState<T>`](extract::PersistentState): [view state](#view-state) |
205//! | | [`Scroll`](extract::Scroll), [`HistoryState<&T>`](extract::HistoryState), [`Navigation`], [`Request`] |
206//!
207//! # Errors and redirects
208//!
209//! Loads and hooks return a [`Rejection`] to abort a navigation: a [`RouteError`], created with
210//! [`error`], or a [`Redirect`], created with [`redirect`]. Any error type that implements
211//! `Into<Rejection>` can be returned, so `?` works.
212//!
213//! An error shows the nearest [error page](Router::error) inside its router's layout, or a default
214//! one. Paths that match no route are a 404, a [`Path`](extract::Path) that doesn't parse too, and
215//! a [`Query`](extract::Query) that doesn't parse is a 400.
216//!
217//! ```
218//! use egui::Ui;
219//! use egui_kit::{Rejection, RouteError, Router, redirect};
220//! use egui_kit::extract::{Nav, State};
221//! use egui_kit::page::Page;
222//!
223//! #[derive(Clone)]
224//! struct AppState {
225//!     logged_in: bool,
226//! }
227//!
228//! // A hook runs before the loads of the router's pages.
229//! async fn require_login(State(state): State<AppState>) -> Result<(), Rejection> {
230//!     if state.logged_in { Ok(()) } else { Err(redirect("/login")) }
231//! }
232//!
233//! fn error_page(ui: &mut Ui, error: &RouteError, nav: Nav) {
234//!     ui.heading(format!("{}: {}", error.status, error.message));
235//!     nav.link(ui, "Home", "/");
236//! }
237//!
238//! fn view(ui: &mut Ui) {
239//!     ui.label("Admin");
240//! }
241//!
242//! let admin = Router::<AppState>::new()
243//!     .hook(require_login)
244//!     .error(error_page)
245//!     .page("/", Page::new(view));
246//! ```
247//!
248//! # State
249//!
250//! The state passed to [`Router::with_state`] is available everywhere with the
251//! [`State`](extract::State) extractor. Views borrow it as `State<&T>`, loads and hooks get a clone
252//! as `State<T>`, so keep shared data behind an `Rc`. Nothing gets `&mut` access to it; use `Cell`
253//! or `RefCell` to change it. [`FromRef`](extract::FromRef) lets you extract a part of the state.
254//! [`RouterApp::state`] gives access to it outside of the router.
255//!
256//! ```
257//! use std::cell::RefCell;
258//! use std::rc::Rc;
259//!
260//! use egui::Ui;
261//! use egui_kit::{Rejection, Router};
262//! use egui_kit::extract::{FromRef, State};
263//! use egui_kit::page::Page;
264//!
265//! #[derive(Clone, Default)]
266//! struct AppState {
267//!     db: Db,
268//! }
269//!
270//! #[derive(Clone, Default)]
271//! struct Db {
272//!     todos: Rc<RefCell<Vec<String>>>,
273//! }
274//!
275//! impl FromRef<AppState> for Db {
276//!     fn from_ref(state: &AppState) -> &Db {
277//!         &state.db
278//!     }
279//! }
280//!
281//! async fn load(State(db): State<Db>) -> Result<usize, Rejection> {
282//!     Ok(db.todos.borrow().len())
283//! }
284//!
285//! fn view(ui: &mut Ui, count: &usize, State(db): State<&Db>) {
286//!     ui.label(format!("{count} todos when the page was loaded"));
287//!     if ui.button("Add").clicked() {
288//!         db.todos.borrow_mut().push("New todo".into());
289//!     }
290//! }
291//!
292//! let app = Router::new()
293//!     .page("/", Page::with_load(load, view))
294//!     .with_state(AppState::default());
295//! ```
296//!
297//! ## View state
298//!
299//! Views can own state that the router keeps for them. It is created with `T::default()` the
300//! first time a view extracts it.
301//!
302//! | | Lives |
303//! |---|---|
304//! | [`PageState<T>`](extract::PageState) | while the page or layout is shown |
305//! | [`Snapshot<T>`](extract::Snapshot) | like `PageState`, and restored when coming back with back/forward |
306//! | [`PersistentState<T>`](extract::PersistentState) | across app restarts, with eframe's `persistence` feature |
307//!
308//! ```
309//! use egui::Ui;
310//! use egui_kit::extract::{PageState, PersistentState, Snapshot};
311//! use serde::{Deserialize, Serialize};
312//!
313//! #[derive(Default)]
314//! struct Draft {
315//!     title: String,
316//! }
317//!
318//! #[derive(Default)]
319//! struct Search {
320//!     text: String,
321//! }
322//!
323//! #[derive(Clone, Default, Serialize, Deserialize)]
324//! struct Preferences {
325//!     compact: bool,
326//! }
327//!
328//! fn view(
329//!     ui: &mut Ui,
330//!     mut draft: PageState<Draft>,
331//!     mut search: Snapshot<Search>,
332//!     mut preferences: PersistentState<Preferences>,
333//! ) {
334//!     ui.text_edit_singleline(&mut draft.title);
335//!     ui.text_edit_singleline(&mut search.text);
336//!     ui.checkbox(&mut preferences.compact, "Compact");
337//! }
338//! ```
339
340mod app;
341mod error;
342mod exec;
343pub mod extract;
344mod history;
345mod load;
346mod navigation;
347pub mod page;
348mod render;
349mod request;
350mod router;
351mod session;
352mod transition;
353
354pub use app::RouterApp;
355pub use error::{Redirect, Rejection, RouteError, error, redirect};
356#[cfg(target_arch = "wasm32")]
357pub use history::{BrowserHistory, HistoryMode};
358pub use history::{EntryKey, History, HistoryEntry, MemoryHistory, default_history};
359pub use navigation::{Direction, GotoOptions, Navigation, NavigationKind};
360pub use request::Request;
361pub use router::Router;
362pub use transition::{Layer, TransitionFrame, ViewTransition, prefers_reduced_motion};
363
364/// Calls `$m!` with 0 to 16 type parameters, for the extractor arguments of handlers and views.
365macro_rules! all_tuples {
366    ($m:ident) => {
367        $m!();
368        $m!(T1);
369        $m!(T1, T2);
370        $m!(T1, T2, T3);
371        $m!(T1, T2, T3, T4);
372        $m!(T1, T2, T3, T4, T5);
373        $m!(T1, T2, T3, T4, T5, T6);
374        $m!(T1, T2, T3, T4, T5, T6, T7);
375        $m!(T1, T2, T3, T4, T5, T6, T7, T8);
376        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
377        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
378        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
379        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
380        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
381        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
382        $m!(
383            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
384        );
385        $m!(
386            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
387        );
388    };
389}
390pub(crate) use all_tuples;