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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Queries and commands: async data and mutations, as easy to start as `tokio::spawn`, inspired
//! by SvelteKit's [remote functions](https://svelte.dev/docs/kit/remote-functions) and `TanStack`
//! Query.
//!
//! A route's `load` fetches what its page needs before it is shown. Some data doesn't belong to
//! a route, though: a badge in a layout, an autocomplete, a count that several pages show. And
//! changing data is often async too (a `POST` to a backend), which a view can't `await`.
//!
//! - A [`Query`] is async data: it fetches on its first read, and can be
//!   [refreshed](Query::refresh), [refetched periodically](Query::refetch_every) and
//!   [cached](Query::key), so that queries with the same key share one result. A [`Live`]
//!   makes one from inputs that change.
//! - A [`Command`] is an async mutation: [run](Command::run) it, and see whether it's pending
//!   and how it ended. Once it succeeded, it [refreshes](Command::refreshes) the loads and
//!   queries that depend on what it changed.
//!
//! Both are plain values: keep them in the app state, a [`PageState`](crate::extract::PageState)
//! or any struct of yours. Clones share their state.
//!
//! # Example
//!
//! A todo list that fetches the todos from a backend, and adds one with a `POST`:
//!
//! ```
//! use std::sync::{Arc, Mutex};
//!
//! use egui::Ui;
//! use egui_kit::remote::{self, Command, Query, QueryState};
//!
//! /// The backend. A stand-in for an HTTP client like `reqwest::Client`: cheap to clone, and
//! /// `Send`, as queries and commands run on other threads.
//! #[derive(Clone, Default)]
//! struct Api {
//!     todos: Arc<Mutex<Vec<String>>>,
//! }
//!
//! impl Api {
//!     /// `GET /todos`
//!     async fn todos(&self) -> Result<Vec<String>, String> {
//!         Ok(self.todos.lock().unwrap().clone())
//!     }
//!
//!     /// `POST /todos`
//!     async fn add_todo(&self, title: String) -> Result<(), String> {
//!         if title.is_empty() {
//!             return Err("a todo needs a title".into());
//!         }
//!         self.todos.lock().unwrap().push(title);
//!         Ok(())
//!     }
//! }
//!
//! struct TodoList {
//!     api: Api,
//!     todos: Query<Vec<String>, String>,
//!     add: Command<(), String>,
//!     title: String,
//! }
//!
//! impl TodoList {
//!     fn new(api: Api) -> Self {
//!         // The closure is called for every fetch (the first one, refreshes, refetches), and
//!         // returns a new future each time, with its own clone of the client.
//!         let todos = remote::query({
//!             let api = api.clone();
//!             move || {
//!                 let api = api.clone();
//!                 async move { api.todos().await }
//!             }
//!         })
//!         // Every query with this key, anywhere in the app, shares this one's value.
//!         .key("todos")
//!         // Refetch when "todos" is invalidated, e.g. by the command below.
//!         .depends("todos");
//!
//!         Self {
//!             api,
//!             todos,
//!             // Invalidates "todos" once a todo was added.
//!             add: remote::command().refreshes("todos"),
//!             title: String::new(),
//!         }
//!     }
//!
//!     fn ui(&mut self, ui: &mut Ui) {
//!         match self.todos.state() {
//!             QueryState::Loading => {
//!                 ui.spinner();
//!             }
//!             QueryState::Ready(todos) => {
//!                 for todo in todos.iter() {
//!                     ui.label(todo);
//!                 }
//!             }
//!             QueryState::Failed(error) => {
//!                 ui.label(format!("Couldn't load the todos: {error}"));
//!             }
//!         }
//!
//!         ui.horizontal(|ui| {
//!             ui.text_edit_singleline(&mut self.title);
//!             if ui.add_enabled(!self.add.is_pending(), egui::Button::new("Add")).clicked() {
//!                 let api = self.api.clone();
//!                 let title = core::mem::take(&mut self.title);
//!                 self.add.run(async move { api.add_todo(title).await });
//!             }
//!         });
//!         if let Some(error) = self.add.error() {
//!             ui.label(&*error);
//!         }
//!     }
//! }
//! ```
//!
//! When the `POST` succeeds, the command invalidates `"todos"`, the query refetches, and the
//! list shows the new todo. Nothing else has to tell the list that it changed.
//!
//! # Keys, dependencies and refreshes
//!
//! They answer different questions:
//!
//! | | Answers | Set with |
//! |---|---|---|
//! | key | *Which* data is this? Queries with the same key are the same data. | [`Query::key`] |
//! | dependency | *When* is it outdated? It refetches when one of its dependencies is invalidated. | [`Query::depends`], [`Page::depends`] |
//! | refresh | *What* did a mutation change? The dependencies it invalidates when it succeeds. | [`Command::refreshes`] |
//!
//! A **key** identifies a query's value in the cache. Queries with the same key (and value and
//! error types) share one state: they fetch once for all of them, and a query created later
//! finds the value right away, e.g. when a page is opened again. So the key must contain
//! everything the fetch depends on: `("user", id)`, not `"user"`. A query without a key has a
//! value of its own, which is dropped with it. The key is only hashed, never kept or printed, so
//! it may contain secrets, like the session token of per-user data: `("todos", &token)`.
//!
//! A **dependency** is a name for some data on the backend, like `"todos"` or `"users"`. It is
//! the same kind of name as a load's [`Page::depends`]: a single invalidation reruns the loads
//! and refetches the queries that depend on it, so many queries can depend on one name, and a
//! query can depend on several. Dependencies are coarser than keys: `("user", 1)` and
//! `("user", 2)` are two keys that both depend on `"users"`.
//!
//! A **refresh** invalidates a dependency once a command succeeded: the command says what it
//! changed, and doesn't need to know who shows it. Invalidating a dependency directly does the
//! same, with [`Nav::invalidate`] in a view, or with [`invalidate`] from anywhere on the UI
//! thread.
//!
//! ```
//! # use egui_kit::remote::{self, Command, Query};
//! # #[derive(Clone)]
//! # struct Api;
//! # impl Api {
//! #     async fn user(&self, _id: u32) -> Result<String, String> { Ok("Ferris".into()) }
//! #     async fn rename(&self, _id: u32, _name: String) -> Result<(), String> { Ok(()) }
//! # }
//! fn user(api: &Api, id: u32) -> Query<String, String> {
//!     let api = api.clone();
//!     remote::query(move || {
//!         let api = api.clone();
//!         async move { api.user(id).await }
//!     })
//!     .key(("user", id)) // one cache entry per user
//!     .depends("users") // refetched when any user changes
//! }
//!
//! fn rename(api: &Api, rename: &Command<(), String>, id: u32, name: String) {
//!     let api = api.clone();
//!     // `rename` was created with `remote::command().refreshes("users")`: once it succeeded,
//!     // every user query refetches, and so do the loads with `.depends("users")`.
//!     rename.run(async move { api.rename(id, name).await });
//! }
//! ```
//!
//! The [`RouterApp`] applies invalidations at its next frame. A query that is invalidated keeps
//! its value, and refetches the next time it is read.
//!
//! # Queries from changing inputs
//!
//! A query is made from its inputs: a date range, a search text, a form to check. A new query
//! fetches on its first read, so a view can't make one from its current inputs every frame: it
//! would fetch every frame. Keep a [`Live`] instead and [update](Live::update) it every frame
//! with the inputs: it makes a new query only when they changed. It can also keep showing the
//! previous value while the new one loads, and wait for the inputs to settle (a search being
//! typed) before it asks.
//!
//! ```
//! # use egui_kit::remote::{self, Live, Query};
//! # #[derive(Clone)]
//! # struct Api;
//! # impl Api {
//! #     async fn week(&self, _monday: u32) -> Result<Vec<String>, String> { Ok(Vec::new()) }
//! # }
//! fn week(api: &Api, monday: u32) -> Query<Vec<String>, String> {
//!     let api = api.clone();
//!     remote::query(move || {
//!         let api = api.clone();
//!         async move { api.week(monday).await }
//!     })
//!     .key(("week", monday))
//! }
//!
//! fn calendar(
//!     ui: &mut egui::Ui,
//!     api: &Api,
//!     monday: u32,
//!     appointments: &mut Live<Vec<String>, String>,
//! ) {
//!     // `appointments` is `remote::live().keep_previous()`: the week before stays until the
//!     // next one arrives.
//!     if let Some(list) = appointments.update(monday, || week(api, monday)).data() {
//!         for appointment in list.iter() {
//!             ui.label(appointment);
//!         }
//!     }
//! }
//! ```
//!
//! # Runtimes
//!
//! Natively, queries and commands run on a Tokio runtime, so their futures must be `Send` (see
//! [`MaybeSend`]). It is the one the app entered if any (a multi-threaded one, as nothing drives
//! a current-thread runtime between frames), else one that egui-kit starts. [`RouterApp::ui`]
//! enters it too, so that hooks and loads can use Tokio-based clients like `reqwest`. On the
//! web, futures run on the browser's event loop and needn't be `Send`.
//!
//! A query or command wakes egui up when it finishes, once the app's context is known on this
//! thread: a [`RouterApp`] sets it at each frame, and [`set_context`] before the router's first
//! frame (e.g. for a command that checks a stored session before the router is built) or in an
//! app without a router. Work started earlier wakes egui up too, if the context is known by the
//! time it finishes. Its result is picked up when it is read.
//!
//! # Caching
//!
//! A query fetches on its first read, and keeps its value while it refetches. A keyed value
//! outlives its queries for [a while](Query::cache_for), so that a page opened again shows it
//! right away. A query reading a cached value for the first time refetches it if it is [older
//! than `stale_after`](Query::stale_after), showing the cached value meanwhile.
//!
//! Dropping a query's state (its last clone, and its cache entry if keyed) aborts its fetch,
//! like refreshing it aborts the one in progress. Commands always run to completion.
//!
//! [`RouterApp`]: crate::RouterApp
//! [`RouterApp::ui`]: crate::RouterApp::ui
//! [`Page::depends`]: crate::page::Page::depends
//! [`Nav::invalidate`]: crate::extract::Nav::invalidate

mod command;
mod live;
mod query;
mod runtime;

use core::any::{Any, TypeId};
use core::cell::RefCell;
use core::hash::{BuildHasher as _, Hash};
use core::time::Duration;
use std::collections::HashMap;
use std::hash::RandomState;
use std::rc::{Rc, Weak};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};

use web_time::Instant;

pub use command::{Command, command};
pub use live::{Live, live};
pub use query::{Query, QueryState, query};
pub use runtime::MaybeSend;
pub(crate) use runtime::enter;

use crate::load::Invalidation;

/// A query's state, as the registry sees it.
trait Entry {
    /// Marks it for a refetch if `invalidation` hits what it depends on.
    fn invalidate(&self, invalidation: &Invalidation);

    /// Whether a cache entry no query uses should be dropped.
    fn expired(&self, now: Instant) -> bool;

    fn as_any(self: Rc<Self>) -> Rc<dyn Any>;
}

/// The queries and commands of this thread.
#[derive(Default)]
struct Registry {
    /// Every query's state, to invalidate them.
    entries: Vec<Weak<dyn Entry>>,
    /// How many entries were left after the dropped ones were last pruned.
    pruned_len: usize,
    /// The state of keyed queries, by value type and key.
    cache: HashMap<(TypeId, u64), Rc<dyn Entry>>,
    /// The app's context, to wake it up when a query or command finished. Shared with them, so
    /// that the ones started before it was known wake it up too.
    ctx: Arc<Mutex<Option<egui::Context>>>,
    /// Keys to invalidate, from [`invalidate`] and from the commands that succeeded.
    invalidated: Arc<Mutex<Vec<String>>>,
}

thread_local! {
    static REGISTRY: RefCell<Registry> = RefCell::default();
}

fn with_registry<R>(f: impl FnOnce(&mut Registry) -> R) -> R {
    REGISTRY.with(|registry| f(&mut registry.borrow_mut()))
}

impl Registry {
    /// Forgets the entries of the dropped queries.
    fn prune(&mut self) {
        self.entries.retain(|entry| entry.strong_count() > 0);
        self.pruned_len = self.entries.len();
    }
}

fn context() -> Option<egui::Context> {
    with_registry(|registry| lock(&registry.ctx).clone())
}

/// The app's context, as it will be when a query or command finishes.
fn shared_context() -> Arc<Mutex<Option<egui::Context>>> {
    with_registry(|registry| Arc::clone(&registry.ctx))
}

/// Wakes the app up, if its context is known.
fn request_repaint(ctx: &Mutex<Option<egui::Context>>) {
    let ctx = lock(ctx).clone();
    if let Some(ctx) = ctx {
        ctx.request_repaint();
    }
}

/// Hashes query keys and [`Live`] inputs, the same way for the whole process.
fn hash(value: impl Hash) -> u64 {
    static HASHER: LazyLock<RandomState> = LazyLock::new(RandomState::new);
    HASHER.hash_one(value)
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Reruns the loads and queries that depend on `key`, like
/// [`Nav::invalidate`](crate::extract::Nav::invalidate), from anywhere on the UI thread. The
/// router applies it at its next frame.
pub fn invalidate(key: impl Into<String>) {
    let invalidated = with_registry(|registry| Arc::clone(&registry.invalidated));
    lock(&invalidated).push(key.into());
    request_repaint(&shared_context());
}

/// Sets the app's context on this thread, so that queries and commands wake it up when they
/// finish, including the ones in progress.
///
/// A [`RouterApp`](crate::RouterApp) sets it at the start of each frame. Call it yourself when
/// queries or commands run before the router's first frame, or in an app without a router,
/// e.g. in the app's constructor, with eframe's `CreationContext::egui_ctx`:
///
/// ```
/// use egui_kit::remote::{self, Command};
///
/// struct Shell {
///     check_session: Command<bool, String>,
/// }
///
/// impl Shell {
///     fn new(ctx: &egui::Context) -> Self {
///         // Without it, a reactive app would show its spinner until the mouse moves.
///         remote::set_context(ctx);
///         let check_session = remote::command();
///         check_session.run(async { Ok(true) });
///         Self { check_session }
///     }
/// }
/// ```
pub fn set_context(ctx: &egui::Context) {
    *lock(&shared_context()) = Some(ctx.clone());
}

/// The keys [invalidated](invalidate) since the last call.
pub(crate) fn take_invalidated() -> Vec<String> {
    let invalidated = with_registry(|registry| Arc::clone(&registry.invalidated));
    core::mem::take(&mut *lock(&invalidated))
}

/// Marks the queries that depend on what `invalidation` hits for a refetch.
pub(crate) fn invalidate_queries(invalidation: &Invalidation) {
    let entries: Vec<_> = with_registry(|registry| {
        registry.prune();
        registry.entries.iter().filter_map(Weak::upgrade).collect()
    });
    for entry in entries {
        entry.invalidate(invalidation);
    }
}

/// Drops the cache entries that no query used for long enough, and forgets the dropped
/// queries.
pub(crate) fn end_frame() {
    let now = Instant::now();
    // Dropped outside of the registry: dropping a query's state aborts its fetch.
    let _expired: Vec<_> = with_registry(|registry| {
        // Once the entries doubled, so that pruning takes amortized constant time per query.
        if registry.entries.len() > (2 * registry.pruned_len).max(PRUNE_AT) {
            registry.prune();
        }
        let keys: Vec<_> = registry
            .cache
            .iter()
            .filter(|(_, entry)| Rc::strong_count(entry) == 1 && entry.expired(now))
            .map(|(key, _)| *key)
            .collect();
        keys.into_iter()
            .filter_map(|key| registry.cache.remove(&key))
            .collect()
    });
}

/// How many query entries there may be before [`end_frame`] first prunes them.
const PRUNE_AT: usize = 64;

/// How long a keyed query's value is kept by default once no query uses it.
const CACHE_FOR: Duration = Duration::from_mins(5);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dropped_queries_are_pruned_without_invalidations() {
        for _ in 0..1000 {
            drop(query(|| async { Ok::<_, ()>(()) }));
            end_frame();
        }
        let len = with_registry(|registry| registry.entries.len());
        assert!(len <= PRUNE_AT, "{len} entries");
    }
}