Expand description
A router for 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.
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+←/→.
§Routing
Router::page adds a page at a path, Router::nest adds another router under a prefix.
A router’s layout, hooks and error page
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 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 is a view, created with Page::new, or a load and a
view, created with Page::with_load:
- A load is an
async fnof extractors returningResult<D, E>, whereE: Into<Rejection>. No async runtime is needed. While it runs, the previous page stays on screen. - A view is a function of
&mut Uiand extractors, called every frame. It gets the load’s data as&Dor&mut D.
A Layout wraps the pages of a router. It can have a load too, and its view
draws the page through the 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
reruns the loads that depend 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>, Query<T>: parameters and query | &D / &mut D: the load’s data; &RouteError in error pages |
State<T>: the app state | State<&T>: the app state |
Parent: the data of the layouts above | Nav: links and navigation |
Request: the url and parameters | PageState<T>, Snapshot<T>, PersistentState<T>: view state |
Scroll, HistoryState<&T>, 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 inside its router’s layout, or a default
one. Paths that match no route are a 404, a Path that doesn’t parse too, and
a 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));§State
The state passed to Router::with_state is available everywhere with the
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 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.
| Lives | |
|---|---|
PageState<T> | while the page or layout is shown |
Snapshot<T> | like PageState, and restored when coming back with back/forward |
PersistentState<T> | 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");
}Modules§
- extract
- Extractors: the arguments of hooks,
loads and views. - page
- Pages and layouts: what a route loads and shows.
Structs§
- Entry
Key - Identifies one history entry, so the router can recognise entries it created (e.g. by shallow routing) when the user goes back or forward.
- Goto
Options - Options for
Nav::goto_with. - History
Entry - Layer
- How one of the two pages is drawn in a frame of the transition
(
::view-transition-old/::view-transition-new). - Memory
History - An in-memory history stack, used on native targets and in tests.
- Navigation
- How the page on screen was reached. An extractor for views,
and passed to
after_navigatecallbacks. - Redirect
- Aborts a navigation and navigates to another url instead.
- Request
- The url being navigated to, together with the path parameters of the matched route.
- Route
Error - An error that aborts a navigation and renders the nearest error page.
- Router
- The route builder.
- Router
App - A built router: owns the app state, the history and the page on screen.
- Transition
Frame - The input of a transition effect for one frame.
- View
Transition - Animates page changes inside a layout. Use it instead of
Outlet::show:
Enums§
- Direction
- Where in the history the new page is, relative to the previous one.
- Navigation
Kind - Rejection
- Everything a hook, a
loadhandler or an extractor can abort a navigation with.
Traits§
- History
- A session history the router keeps in sync with the current page.
Functions§
- default_
history BrowserHistoryon wasm,MemoryHistorystarting at/elsewhere.- error
- Shorthand for
Rejection::Error(RouteError::new(status, message)). - prefers_
reduced_ motion - Whether the user asked their system for reduced motion (
prefers-reduced-motion: reduce). Alwaysfalseon native, where there is no portable way to ask. - redirect
- Shorthand for
Rejection::Redirect(Redirect::to(to)).