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