egui-kit 0.2.0

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
435
436
//! Queries and commands: data and mutations that aren't tied to a route, inspired by SvelteKit's
//! [remote functions](https://svelte.dev/docs/kit/remote-functions).
//!
//! 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 that any view can read with [`Remote::query`]. The value is the
//!   query's input, and also its cache key: views reading equal queries share one result.
//! - A [`Command`] is an async mutation, started from a view with [`CommandHandle::run`]. Its
//!   state (pending, output, error) belongs to the view, and when it succeeds it
//!   [refreshes](Command::refreshes) the loads and queries that depend on what it changed.
//!
//! ```
//! use egui::Ui;
//! use egui_kit::RouteError;
//! use egui_kit::extract::Remote;
//! use egui_kit::remote::{Command, Query};
//!
//! #[derive(Clone, Default)]
//! struct AppState;
//!
//! /// How many todos there are.
//! #[derive(Clone, PartialEq)]
//! struct TodoCount;
//!
//! impl Query<AppState> for TodoCount {
//!     type Output = usize;
//!
//!     async fn run(self, _state: AppState) -> Result<usize, RouteError> {
//!         Ok(3) // e.g. a `GET /todos/count`
//!     }
//!
//!     fn depends(&self) -> Vec<String> {
//!         vec!["todos".into()]
//!     }
//! }
//!
//! struct AddTodo(String);
//!
//! impl Command<AppState> for AddTodo {
//!     type Output = ();
//!
//!     async fn run(self, _state: AppState) -> Result<(), RouteError> {
//!         Ok(()) // e.g. a `POST /todos`
//!     }
//!
//!     fn refreshes(&self) -> Vec<String> {
//!         vec!["todos".into()]
//!     }
//! }
//!
//! fn view(ui: &mut Ui, remote: Remote<'_, AppState>) {
//!     match remote.query(TodoCount).current() {
//!         Some(count) => ui.label(format!("{count} todos")),
//!         None => ui.spinner(),
//!     };
//!
//!     let add = remote.command::<AddTodo>();
//!     if ui.add_enabled(!add.is_pending(), egui::Button::new("Add")).clicked() {
//!         add.run(AddTodo("Buy milk".into()));
//!     }
//!     if let Some(error) = add.error() {
//!         ui.label(error.message);
//!     }
//! }
//! ```
//!
//! Like `load`s, queries and commands are polled by the router, so no async runtime is needed,
//! and their futures don't have to be `Send`.
//!
//! # Caching
//!
//! A query runs the first time a view reads it, and its result is kept for as long as views keep
//! reading it: it is dropped after a frame in which no view did. While it reruns (after an
//! [invalidation](crate::extract::Nav::invalidate) or a [refresh](Remote::refresh)),
//! [`QueryState::current`] still has the previous value.

use core::any::{Any, TypeId};
use core::cell::RefCell;
use core::future::Future;
use core::marker::PhantomData;
use core::task::Poll;
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;

use crate::error::RouteError;
use crate::exec;
use crate::extract::{FromView, ViewStore};
use crate::load::Invalidation;
use crate::page::{Frame, LocalBoxFuture, ViewContext};

/// Async data that views read with [`Remote::query`], cached by value.
///
/// The type is the query and its value the input: `SearchAuthors("fe".into())` and
/// `SearchAuthors("fer".into())` are two entries of the same query, and every view reading an
/// equal value shares one result.
pub trait Query<S>: Clone + PartialEq + 'static {
    type Output: 'static;

    /// Fetches the data, with a clone of the app state.
    fn run(self, state: S) -> impl Future<Output = Result<Self::Output, RouteError>> + 'static;

    /// Reruns the query when one of these keys is [invalidated](crate::extract::Nav::invalidate),
    /// like [`Page::depends`](crate::page::Page::depends).
    fn depends(&self) -> Vec<String> {
        Vec::new()
    }
}

/// An async mutation that views start with [`CommandHandle::run`].
pub trait Command<S>: 'static {
    type Output: 'static;

    /// Carries out the mutation, with a clone of the app state.
    fn run(self, state: S) -> impl Future<Output = Result<Self::Output, RouteError>> + 'static;

    /// The keys to [invalidate](crate::extract::Nav::invalidate) once the command succeeded,
    /// rerunning the loads and queries that depend on them.
    fn refreshes(&self) -> Vec<String> {
        Vec::new()
    }
}

type QueryFuture = LocalBoxFuture<Result<Rc<dyn Any>, RouteError>>;

/// A query's cached result.
struct QueryEntry {
    /// The query, to compare with the ones views read.
    query: Box<dyn Any>,
    keys: Vec<String>,
    /// The last value it fetched.
    value: Option<Rc<dyn Any>>,
    /// Whether the last run failed.
    error: Option<RouteError>,
    future: Option<QueryFuture>,
    /// Rerun on the next read.
    stale: bool,
    /// Whether a view read it during this frame.
    read: bool,
}

/// The queries' cache and the commands in flight, owned by the app.
#[derive(Default)]
pub(crate) struct RemoteStore {
    queries: RefCell<Vec<QueryEntry>>,
    /// Yield the keys to invalidate.
    commands: RefCell<Vec<LocalBoxFuture<Vec<String>>>>,
}

impl RemoteStore {
    fn query<S: Clone, Q: Query<S>>(
        &self,
        query: &Q,
        state: &S,
        ctx: &egui::Context,
    ) -> QueryState<Q::Output> {
        let mut queries = self.queries.borrow_mut();
        let index = queries
            .iter()
            .position(|entry| entry.query.downcast_ref::<Q>() == Some(query))
            .unwrap_or_else(|| {
                queries.push(QueryEntry {
                    query: Box::new(query.clone()),
                    keys: query.depends(),
                    value: None,
                    error: None,
                    future: None,
                    stale: true,
                    read: false,
                });
                queries.len() - 1
            });
        let entry = &mut queries[index];
        entry.read = true;
        if entry.stale {
            entry.stale = false;
            let future = query.clone().run(state.clone());
            entry.future = Some(Box::pin(async move {
                future.await.map(|value| Rc::new(value) as Rc<dyn Any>)
            }));
        }
        // Polled when read, so a query that is ready right away never shows a loading state.
        if let Some(future) = &mut entry.future
            && let Poll::Ready(result) = exec::poll_once(ctx, future.as_mut())
        {
            entry.future = None;
            match result {
                Ok(value) => {
                    entry.value = Some(value);
                    entry.error = None;
                }
                Err(error) => entry.error = Some(error),
            }
        }
        QueryState {
            value: entry
                .value
                .clone()
                .map(|value| value.downcast().expect("stored by type")),
            error: entry.error.clone(),
            loading: entry.future.is_some(),
        }
    }

    /// Reruns `query` on its next read.
    fn refresh<Q: 'static + PartialEq>(&self, query: &Q) {
        for entry in self.queries.borrow_mut().iter_mut() {
            if entry.query.downcast_ref::<Q>() == Some(query) {
                entry.stale = true;
                entry.future = None;
            }
        }
    }

    /// Reruns the queries that depend on what `invalidation` hits, on their next read.
    pub(crate) fn invalidate(&self, invalidation: &Invalidation) {
        for entry in self.queries.borrow_mut().iter_mut() {
            if invalidation.hits(&entry.keys) {
                entry.stale = true;
                entry.future = None;
            }
        }
    }

    /// Drops the queries no view read during the frame.
    pub(crate) fn end_frame(&self) {
        self.queries.borrow_mut().retain_mut(|entry| {
            let read = entry.read;
            entry.read = false;
            read
        });
    }

    /// Drives the commands in flight. Returns the keys that those that succeeded refresh.
    pub(crate) fn poll_commands(&self, ctx: &egui::Context) -> Vec<String> {
        let mut refreshes = Vec::new();
        self.commands.borrow_mut().retain_mut(|future| {
            match exec::poll_once(ctx, future.as_mut()) {
                Poll::Ready(keys) => {
                    refreshes.extend(keys);
                    false
                }
                Poll::Pending => true,
            }
        });
        refreshes
    }
}

/// A query's result, as seen by a view: see [`Remote::query`].
pub struct QueryState<T> {
    value: Option<Rc<T>>,
    error: Option<RouteError>,
    loading: bool,
}

impl<T> QueryState<T> {
    /// The last value the query fetched. While it reruns, or if the rerun failed, this is the
    /// previous value.
    pub fn current(&self) -> Option<&T> {
        self.value.as_deref()
    }

    /// Why the last run failed.
    pub fn error(&self) -> Option<&RouteError> {
        self.error.as_ref()
    }

    /// Whether the query is running: for the first time if [`current`](Self::current) is
    /// `None`, else rerunning.
    pub fn is_loading(&self) -> bool {
        self.loading
    }
}

impl<T: fmt::Debug> fmt::Debug for QueryState<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("QueryState")
            .field("current", &self.value)
            .field("error", &self.error)
            .field("loading", &self.loading)
            .finish()
    }
}

/// Queries and commands, in views: see the [module docs](crate::remote).
///
/// An extractor: add a `remote: Remote<'_, AppState>` argument to any view. It is `Copy`.
pub struct Remote<'f, S> {
    frame: &'f Frame<'f>,
    store: &'f ViewStore,
    state: &'f S,
}

impl<S> Clone for Remote<'_, S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S> Copy for Remote<'_, S> {}

impl<S: 'static, D> FromView<S, D> for Remote<'_, S> {
    type Item<'f> = Remote<'f, S>;

    fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> Remote<'f, S> {
        Remote {
            frame: cx.frame(),
            store: cx.store(),
            state: cx.state(),
        }
    }
}

impl<'f, S: Clone + 'static> Remote<'f, S> {
    /// Reads `query`, running it if it isn't cached. Call it every frame you show the result:
    /// a query no view reads during a frame is dropped.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "`remote.query(SearchAuthors(prefix))` reads better than with a reference"
    )]
    pub fn query<Q: Query<S>>(&self, query: Q) -> QueryState<Q::Output> {
        self.frame.remote.query(&query, self.state, &self.frame.ctx)
    }

    /// Reruns `query` the next time it is read. To rerun every query that depends on some data,
    /// [invalidate](crate::extract::Nav::invalidate) it instead.
    pub fn refresh<Q: Query<S>>(&self, query: &Q) {
        self.frame.remote.refresh(query);
        self.frame.ctx.request_repaint();
    }

    /// The view's handle to the command `C`: to run it, and to see whether it's running and
    /// what it returned.
    ///
    /// Its state belongs to the view, for as long as its page (or layout) is shown. A command
    /// still running when the page is left completes and refreshes what it changed, but its
    /// output is dropped.
    pub fn command<C: Command<S>>(&self) -> CommandHandle<'f, S, C> {
        let slot = Rc::clone(
            self.store
                .commands
                .borrow_mut()
                .entry(TypeId::of::<C>())
                .or_insert_with(|| Rc::new(RefCell::new(CommandSlot::<C::Output>::default()))),
        );
        CommandHandle {
            remote: *self,
            slot: slot.downcast().expect("stored by type"),
            command: PhantomData,
        }
    }
}

/// The state of a view's command.
struct CommandSlot<T> {
    pending: usize,
    output: Option<T>,
    error: Option<RouteError>,
}

impl<T> Default for CommandSlot<T> {
    fn default() -> Self {
        Self {
            pending: 0,
            output: None,
            error: None,
        }
    }
}

/// Commands' state, per view, by command type.
pub(crate) type CommandSlots = RefCell<HashMap<TypeId, Rc<dyn Any>>>;

/// A view's handle to the command `C`, from [`Remote::command`].
pub struct CommandHandle<'f, S, C: Command<S>> {
    remote: Remote<'f, S>,
    slot: Rc<RefCell<CommandSlot<C::Output>>>,
    command: PhantomData<fn(C)>,
}

impl<S: Clone + 'static, C: Command<S>> CommandHandle<'_, S, C> {
    /// Starts `command`. Ignored in an [outgoing](crate::extract::Nav::is_outgoing) page.
    pub fn run(&self, command: C) {
        if self.remote.frame.outgoing {
            return;
        }
        let refreshes = command.refreshes();
        let future = command.run(self.remote.state.clone());
        let slot = Rc::clone(&self.slot);
        {
            let mut slot = slot.borrow_mut();
            slot.pending += 1;
            slot.error = None;
        }
        self.remote
            .frame
            .remote
            .commands
            .borrow_mut()
            .push(Box::pin(async move {
                let result = future.await;
                let mut slot = slot.borrow_mut();
                slot.pending -= 1;
                match result {
                    Ok(output) => {
                        slot.output = Some(output);
                        refreshes
                    }
                    Err(error) => {
                        slot.error = Some(error);
                        Vec::new()
                    }
                }
            }));
        self.remote.frame.ctx.request_repaint();
    }

    /// Whether the command is running.
    pub fn is_pending(&self) -> bool {
        self.slot.borrow().pending > 0
    }

    /// What the command returned when it last succeeded, taken so that the view acts on it
    /// once (e.g. navigates to what it created).
    pub fn take_output(&self) -> Option<C::Output> {
        self.slot.borrow_mut().output.take()
    }

    /// Why the command last failed. Cleared when it runs again.
    pub fn error(&self) -> Option<RouteError> {
        self.slot.borrow().error.clone()
    }
}