egui-kit 0.3.1

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

mod app;
mod error;
mod exec;
pub mod extract;
mod history;
mod load;
mod navigation;
pub mod page;
#[cfg(feature = "remote")]
pub mod remote;
mod render;
mod request;
mod router;
mod session;
mod transition;

pub use app::RouterApp;
pub use error::{Redirect, Rejection, RouteError, error, redirect};
#[cfg(target_arch = "wasm32")]
pub use history::{BrowserHistory, HistoryMode};
pub use history::{EntryKey, History, HistoryEntry, MemoryHistory, default_history};
pub use navigation::{Direction, GotoOptions, Navigation, NavigationKind};
pub use request::Request;
pub use router::Router;
pub use transition::{Layer, TransitionFrame, ViewTransition, prefers_reduced_motion};

/// Calls `$m!` with 0 to 16 type parameters, for the extractor arguments of handlers and views.
macro_rules! all_tuples {
    ($m:ident) => {
        $m!();
        $m!(T1);
        $m!(T1, T2);
        $m!(T1, T2, T3);
        $m!(T1, T2, T3, T4);
        $m!(T1, T2, T3, T4, T5);
        $m!(T1, T2, T3, T4, T5, T6);
        $m!(T1, T2, T3, T4, T5, T6, T7);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
        $m!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
        $m!(
            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
        );
        $m!(
            T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
        );
    };
}
pub(crate) use all_tuples;