Skip to main content

Crate egui_kit

Crate egui_kit 

Source
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 segmentMatches
aboutexactly 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 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 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 hooksIn views
Path<T>, Query<T>: parameters and query&D / &mut D: the load’s data; &RouteError in error pages
State<T>: the app stateState<&T>: the app state
Parent: the data of the layouts aboveNav: links and navigation
Request: the url and parametersPageState<T>, Snapshot<T>, PersistentState<T>: view state
Scroll, HistoryState<&T>, Navigation, Request
Remote<S>: queries and commands

§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. Inspired by SvelteKit’s remote functions, a Query is async data any view can read, cached by value, and a Command an async mutation that a view starts and watches. A command refreshes the loads and queries that depend on what it changed. Views use both through the Remote extractor; see the remote module.

§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.
remote
Queries and commands: data and mutations that aren’t tied to a route, inspired by SvelteKit’s remote functions.

Structs§

EntryKey
Identifies one history entry, so the router can recognise entries it created (e.g. by shallow routing) when the user goes back or forward.
GotoOptions
Options for Nav::goto_with.
HistoryEntry
Layer
How one of the two pages is drawn in a frame of the transition (::view-transition-old / ::view-transition-new).
MemoryHistory
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_navigate callbacks.
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.
RouteError
An error that aborts a navigation and renders the nearest error page.
Router
The route builder.
RouterApp
A built router: owns the app state, the history and the page on screen.
TransitionFrame
The input of a transition effect for one frame.
ViewTransition
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.
NavigationKind
Rejection
Everything a hook, a load handler 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
BrowserHistory on wasm, MemoryHistory starting 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). Always false on native, where there is no portable way to ask.
redirect
Shorthand for Rejection::Redirect(Redirect::to(to)).