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