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+←/→. 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, 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. A #fragment takes no part in matching or loading: going to /docs#install
from /docs only adds a history entry, and the page reads it with
Nav::fragment.
use egui::Ui;
use egui_kit::Router;
use egui_kit::page::{Layout, Children, Page};
fn view(ui: &mut Ui) {
ui.label("A page");
}
fn blog_layout(ui: &mut Ui, mut children: Children) {
ui.heading("Blog");
children.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.
§Building urls
href fills in a route pattern. It percent-encodes the parameters, so that a slug with a
space, ?, # or / still leads to its page, and adds a query and fragment:
use egui_kit::extract::Nav;
use egui_kit::href;
fn post_link(ui: &mut egui::Ui, nav: Nav, title: &str, slug: &str) {
nav.link(ui, title, &href("/blog/{slug}").param("slug", slug).to_string());
if ui.button("Print").clicked() {
nav.goto(href("/blog/{slug}/print").param("slug", slug));
}
}§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 Children, 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, Children, 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, children: Children, blog: &Blog, nav: Nav) {
for post in &blog.posts {
nav.nav_link(ui, post, &format!("/blog/{post}"));
}
ViewTransition::slide().show(ui, children);
}
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 | LayoutData<T>: 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));§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 is async data that fetches when read, can be refreshed and cached,
and a 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; see the remote module.
#[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 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, or from the load’s data with
PageStateFrom<T> and SnapshotFrom<T>.
| 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.
- remote
- Queries and commands: async data and mutations, as easy to start as
tokio::spawn, inspired by SvelteKit’s remote functions andTanStackQuery.
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 - Href
- A url being built from a route pattern, see
href. Turned into a url withDisplayorString::from. - 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
Children::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)). - href
- Builds a url from a route pattern, percent-encoding the parameters, so that the router matches it and decodes the same values.
- 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)). SeeRedirectfor how it updates the history.