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+←/→. 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, Children, Page};
67//!
68//! fn view(ui: &mut Ui) {
69//!     ui.label("A page");
70//! }
71//!
72//! fn blog_layout(ui: &mut Ui, mut children: Children) {
73//!     ui.heading("Blog");
74//!     children.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 [`Children`](page::Children), 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, Children, 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, children: Children, 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, children);
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 | [`LayoutData<T>`](extract::LayoutData): the data of the layouts above |
205//! | | [`Nav`](extract::Nav): links and navigation |
206//! | [`Request`]: the url and parameters | [`PageState<T>`](extract::PageState), [`Snapshot<T>`](extract::Snapshot), [`PersistentState<T>`](extract::PersistentState): [view state](#view-state) |
207//! | | [`Scroll`](extract::Scroll), [`HistoryState<&T>`](extract::HistoryState), [`Navigation`], [`Request`] |
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`. With the `remote` feature (on by default), a
254//! [`Query`](remote::Query) is async data that fetches when read, can be refreshed and cached,
255//! and a [`Command`](remote::Command) an async mutation that refreshes the loads and queries
256//! that depend on what it changed. Both are plain values, kept in the app state or a
257//! [`PageState`](extract::PageState); see the [`remote`] module.
258//!
259//! ```
260//! # use egui_kit::remote::{self, Query};
261//! # async fn count_posts() -> Result<usize, String> { Ok(3) }
262//! #[derive(Clone)]
263//! struct AppState {
264//!     posts: Query<usize, String>,
265//! }
266//!
267//! let state = AppState {
268//!     posts: remote::query(count_posts).depends("posts"),
269//! };
270//! ```
271//!
272//! # State
273//!
274//! The state passed to [`Router::with_state`] is available everywhere with the
275//! [`State`](extract::State) extractor. Views borrow it as `State<&T>`, loads and hooks get a clone
276//! as `State<T>`, so keep shared data behind an `Rc`. Nothing gets `&mut` access to it; use `Cell`
277//! or `RefCell` to change it. [`FromRef`](extract::FromRef) lets you extract a part of the state.
278//! [`RouterApp::state`] gives access to it outside of the router.
279//!
280//! ```
281//! use std::cell::RefCell;
282//! use std::rc::Rc;
283//!
284//! use egui::Ui;
285//! use egui_kit::{Rejection, Router};
286//! use egui_kit::extract::{FromRef, State};
287//! use egui_kit::page::Page;
288//!
289//! #[derive(Clone, Default)]
290//! struct AppState {
291//!     db: Db,
292//! }
293//!
294//! #[derive(Clone, Default)]
295//! struct Db {
296//!     todos: Rc<RefCell<Vec<String>>>,
297//! }
298//!
299//! impl FromRef<AppState> for Db {
300//!     fn from_ref(state: &AppState) -> &Db {
301//!         &state.db
302//!     }
303//! }
304//!
305//! async fn load(State(db): State<Db>) -> Result<usize, Rejection> {
306//!     Ok(db.todos.borrow().len())
307//! }
308//!
309//! fn view(ui: &mut Ui, count: &usize, State(db): State<&Db>) {
310//!     ui.label(format!("{count} todos when the page was loaded"));
311//!     if ui.button("Add").clicked() {
312//!         db.todos.borrow_mut().push("New todo".into());
313//!     }
314//! }
315//!
316//! let app = Router::new()
317//!     .page("/", Page::with_load(load, view))
318//!     .with_state(AppState::default());
319//! ```
320//!
321//! ## View state
322//!
323//! Views can own state that the router keeps for them. It is created with `T::default()` the
324//! first time a view extracts it, or from the `load`'s data with
325//! [`PageStateFrom<T>`](extract::PageStateFrom) and [`SnapshotFrom<T>`](extract::SnapshotFrom).
326//!
327//! | | Lives |
328//! |---|---|
329//! | [`PageState<T>`](extract::PageState) | while the page or layout is shown |
330//! | [`Snapshot<T>`](extract::Snapshot) | like `PageState`, and restored when coming back with back/forward |
331//! | [`PersistentState<T>`](extract::PersistentState) | across app restarts, with eframe's `persistence` feature |
332//!
333//! ```
334//! use egui::Ui;
335//! use egui_kit::extract::{PageState, PersistentState, Snapshot};
336//! use serde::{Deserialize, Serialize};
337//!
338//! #[derive(Default)]
339//! struct Draft {
340//!     title: String,
341//! }
342//!
343//! #[derive(Default)]
344//! struct Search {
345//!     text: String,
346//! }
347//!
348//! #[derive(Clone, Default, Serialize, Deserialize)]
349//! struct Preferences {
350//!     compact: bool,
351//! }
352//!
353//! fn view(
354//!     ui: &mut Ui,
355//!     mut draft: PageState<Draft>,
356//!     mut search: Snapshot<Search>,
357//!     mut preferences: PersistentState<Preferences>,
358//! ) {
359//!     ui.text_edit_singleline(&mut draft.title);
360//!     ui.text_edit_singleline(&mut search.text);
361//!     ui.checkbox(&mut preferences.compact, "Compact");
362//! }
363//! ```
364
365mod app;
366mod error;
367mod exec;
368pub mod extract;
369mod history;
370mod load;
371mod navigation;
372pub mod page;
373#[cfg(feature = "remote")]
374pub mod remote;
375mod render;
376mod request;
377mod router;
378mod session;
379mod transition;
380
381pub use app::RouterApp;
382pub use error::{Redirect, Rejection, RouteError, error, redirect};
383#[cfg(target_arch = "wasm32")]
384pub use history::{BrowserHistory, HistoryMode};
385pub use history::{EntryKey, History, HistoryEntry, MemoryHistory, default_history};
386pub use navigation::{Direction, GotoOptions, Navigation, NavigationKind};
387pub use request::Request;
388pub use router::Router;
389pub use transition::{Layer, TransitionFrame, ViewTransition, prefers_reduced_motion};
390
391/// Calls `$m!` with 0 to 16 type parameters, for the extractor arguments of handlers and views.
392macro_rules! all_tuples {
393    ($m:ident) => {
394        $m!();
395        $m!(T1);
396        $m!(T1, T2);
397        $m!(T1, T2, T3);
398        $m!(T1, T2, T3, T4);
399        $m!(T1, T2, T3, T4, T5);
400        $m!(T1, T2, T3, T4, T5, T6);
401        $m!(T1, T2, T3, T4, T5, T6, T7);
402        $m!(T1, T2, T3, T4, T5, T6, T7, T8);
403        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
404        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
405        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
406        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
407        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
408        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
409        $m!(
410            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
411        );
412        $m!(
413            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
414        );
415    };
416}
417pub(crate) use all_tuples;