Skip to main content

egui_kit/
remote.rs

1//! Queries and commands: data and mutations that aren't tied to a route, inspired by SvelteKit's
2//! [remote functions](https://svelte.dev/docs/kit/remote-functions).
3//!
4//! A route's `load` fetches what its page needs before it is shown. Some data doesn't belong to
5//! a route, though: a badge in a layout, an autocomplete, a count that several pages show. And
6//! changing data is often async too (a `POST` to a backend), which a view can't `await`.
7//!
8//! - A [`Query`] is async data that any view can read with [`Remote::query`]. The value is the
9//!   query's input, and also its cache key: views reading equal queries share one result.
10//! - A [`Command`] is an async mutation, started from a view with [`CommandHandle::run`]. Its
11//!   state (pending, output, error) belongs to the view, and when it succeeds it
12//!   [refreshes](Command::refreshes) the loads and queries that depend on what it changed.
13//!
14//! ```
15//! use egui::Ui;
16//! use egui_kit::RouteError;
17//! use egui_kit::extract::Remote;
18//! use egui_kit::remote::{Command, Query};
19//!
20//! #[derive(Clone, Default)]
21//! struct AppState;
22//!
23//! /// How many todos there are.
24//! #[derive(Clone, PartialEq)]
25//! struct TodoCount;
26//!
27//! impl Query<AppState> for TodoCount {
28//!     type Output = usize;
29//!
30//!     async fn run(self, _state: AppState) -> Result<usize, RouteError> {
31//!         Ok(3) // e.g. a `GET /todos/count`
32//!     }
33//!
34//!     fn depends(&self) -> Vec<String> {
35//!         vec!["todos".into()]
36//!     }
37//! }
38//!
39//! struct AddTodo(String);
40//!
41//! impl Command<AppState> for AddTodo {
42//!     type Output = ();
43//!
44//!     async fn run(self, _state: AppState) -> Result<(), RouteError> {
45//!         Ok(()) // e.g. a `POST /todos`
46//!     }
47//!
48//!     fn refreshes(&self) -> Vec<String> {
49//!         vec!["todos".into()]
50//!     }
51//! }
52//!
53//! fn view(ui: &mut Ui, remote: Remote<'_, AppState>) {
54//!     match remote.query(TodoCount).current() {
55//!         Some(count) => ui.label(format!("{count} todos")),
56//!         None => ui.spinner(),
57//!     };
58//!
59//!     let add = remote.command::<AddTodo>();
60//!     if ui.add_enabled(!add.is_pending(), egui::Button::new("Add")).clicked() {
61//!         add.run(AddTodo("Buy milk".into()));
62//!     }
63//!     if let Some(error) = add.error() {
64//!         ui.label(error.message);
65//!     }
66//! }
67//! ```
68//!
69//! Like `load`s, queries and commands are polled by the router, so no async runtime is needed,
70//! and their futures don't have to be `Send`.
71//!
72//! # Caching
73//!
74//! A query runs the first time a view reads it, and its result is kept for as long as views keep
75//! reading it: it is dropped after a frame in which no view did. While it reruns (after an
76//! [invalidation](crate::extract::Nav::invalidate) or a [refresh](Remote::refresh)),
77//! [`QueryState::current`] still has the previous value.
78
79use core::any::{Any, TypeId};
80use core::cell::RefCell;
81use core::future::Future;
82use core::marker::PhantomData;
83use core::task::Poll;
84use std::collections::HashMap;
85use std::fmt;
86use std::rc::Rc;
87
88use crate::error::RouteError;
89use crate::exec;
90use crate::extract::{FromView, ViewStore};
91use crate::load::Invalidation;
92use crate::page::{Frame, LocalBoxFuture, ViewContext};
93
94/// Async data that views read with [`Remote::query`], cached by value.
95///
96/// The type is the query and its value the input: `SearchAuthors("fe".into())` and
97/// `SearchAuthors("fer".into())` are two entries of the same query, and every view reading an
98/// equal value shares one result.
99pub trait Query<S>: Clone + PartialEq + 'static {
100    type Output: 'static;
101
102    /// Fetches the data, with a clone of the app state.
103    fn run(self, state: S) -> impl Future<Output = Result<Self::Output, RouteError>> + 'static;
104
105    /// Reruns the query when one of these keys is [invalidated](crate::extract::Nav::invalidate),
106    /// like [`Page::depends`](crate::page::Page::depends).
107    fn depends(&self) -> Vec<String> {
108        Vec::new()
109    }
110}
111
112/// An async mutation that views start with [`CommandHandle::run`].
113pub trait Command<S>: 'static {
114    type Output: 'static;
115
116    /// Carries out the mutation, with a clone of the app state.
117    fn run(self, state: S) -> impl Future<Output = Result<Self::Output, RouteError>> + 'static;
118
119    /// The keys to [invalidate](crate::extract::Nav::invalidate) once the command succeeded,
120    /// rerunning the loads and queries that depend on them.
121    fn refreshes(&self) -> Vec<String> {
122        Vec::new()
123    }
124}
125
126type QueryFuture = LocalBoxFuture<Result<Rc<dyn Any>, RouteError>>;
127
128/// A query's cached result.
129struct QueryEntry {
130    /// The query, to compare with the ones views read.
131    query: Box<dyn Any>,
132    keys: Vec<String>,
133    /// The last value it fetched.
134    value: Option<Rc<dyn Any>>,
135    /// Whether the last run failed.
136    error: Option<RouteError>,
137    future: Option<QueryFuture>,
138    /// Rerun on the next read.
139    stale: bool,
140    /// Whether a view read it during this frame.
141    read: bool,
142}
143
144/// The queries' cache and the commands in flight, owned by the app.
145#[derive(Default)]
146pub(crate) struct RemoteStore {
147    queries: RefCell<Vec<QueryEntry>>,
148    /// Yield the keys to invalidate.
149    commands: RefCell<Vec<LocalBoxFuture<Vec<String>>>>,
150}
151
152impl RemoteStore {
153    fn query<S: Clone, Q: Query<S>>(
154        &self,
155        query: &Q,
156        state: &S,
157        ctx: &egui::Context,
158    ) -> QueryState<Q::Output> {
159        let mut queries = self.queries.borrow_mut();
160        let index = queries
161            .iter()
162            .position(|entry| entry.query.downcast_ref::<Q>() == Some(query))
163            .unwrap_or_else(|| {
164                queries.push(QueryEntry {
165                    query: Box::new(query.clone()),
166                    keys: query.depends(),
167                    value: None,
168                    error: None,
169                    future: None,
170                    stale: true,
171                    read: false,
172                });
173                queries.len() - 1
174            });
175        let entry = &mut queries[index];
176        entry.read = true;
177        if entry.stale {
178            entry.stale = false;
179            let future = query.clone().run(state.clone());
180            entry.future = Some(Box::pin(async move {
181                future.await.map(|value| Rc::new(value) as Rc<dyn Any>)
182            }));
183        }
184        // Polled when read, so a query that is ready right away never shows a loading state.
185        if let Some(future) = &mut entry.future
186            && let Poll::Ready(result) = exec::poll_once(ctx, future.as_mut())
187        {
188            entry.future = None;
189            match result {
190                Ok(value) => {
191                    entry.value = Some(value);
192                    entry.error = None;
193                }
194                Err(error) => entry.error = Some(error),
195            }
196        }
197        QueryState {
198            value: entry
199                .value
200                .clone()
201                .map(|value| value.downcast().expect("stored by type")),
202            error: entry.error.clone(),
203            loading: entry.future.is_some(),
204        }
205    }
206
207    /// Reruns `query` on its next read.
208    fn refresh<Q: 'static + PartialEq>(&self, query: &Q) {
209        for entry in self.queries.borrow_mut().iter_mut() {
210            if entry.query.downcast_ref::<Q>() == Some(query) {
211                entry.stale = true;
212                entry.future = None;
213            }
214        }
215    }
216
217    /// Reruns the queries that depend on what `invalidation` hits, on their next read.
218    pub(crate) fn invalidate(&self, invalidation: &Invalidation) {
219        for entry in self.queries.borrow_mut().iter_mut() {
220            if invalidation.hits(&entry.keys) {
221                entry.stale = true;
222                entry.future = None;
223            }
224        }
225    }
226
227    /// Drops the queries no view read during the frame.
228    pub(crate) fn end_frame(&self) {
229        self.queries.borrow_mut().retain_mut(|entry| {
230            let read = entry.read;
231            entry.read = false;
232            read
233        });
234    }
235
236    /// Drives the commands in flight. Returns the keys that those that succeeded refresh.
237    pub(crate) fn poll_commands(&self, ctx: &egui::Context) -> Vec<String> {
238        let mut refreshes = Vec::new();
239        self.commands.borrow_mut().retain_mut(|future| {
240            match exec::poll_once(ctx, future.as_mut()) {
241                Poll::Ready(keys) => {
242                    refreshes.extend(keys);
243                    false
244                }
245                Poll::Pending => true,
246            }
247        });
248        refreshes
249    }
250}
251
252/// A query's result, as seen by a view: see [`Remote::query`].
253pub struct QueryState<T> {
254    value: Option<Rc<T>>,
255    error: Option<RouteError>,
256    loading: bool,
257}
258
259impl<T> QueryState<T> {
260    /// The last value the query fetched. While it reruns, or if the rerun failed, this is the
261    /// previous value.
262    pub fn current(&self) -> Option<&T> {
263        self.value.as_deref()
264    }
265
266    /// Why the last run failed.
267    pub fn error(&self) -> Option<&RouteError> {
268        self.error.as_ref()
269    }
270
271    /// Whether the query is running: for the first time if [`current`](Self::current) is
272    /// `None`, else rerunning.
273    pub fn is_loading(&self) -> bool {
274        self.loading
275    }
276}
277
278impl<T: fmt::Debug> fmt::Debug for QueryState<T> {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_struct("QueryState")
281            .field("current", &self.value)
282            .field("error", &self.error)
283            .field("loading", &self.loading)
284            .finish()
285    }
286}
287
288/// Queries and commands, in views: see the [module docs](crate::remote).
289///
290/// An extractor: add a `remote: Remote<'_, AppState>` argument to any view. It is `Copy`.
291pub struct Remote<'f, S> {
292    frame: &'f Frame<'f>,
293    store: &'f ViewStore,
294    state: &'f S,
295}
296
297impl<S> Clone for Remote<'_, S> {
298    fn clone(&self) -> Self {
299        *self
300    }
301}
302
303impl<S> Copy for Remote<'_, S> {}
304
305impl<S: 'static, D> FromView<S, D> for Remote<'_, S> {
306    type Item<'f> = Remote<'f, S>;
307
308    fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> Remote<'f, S> {
309        Remote {
310            frame: cx.frame(),
311            store: cx.store(),
312            state: cx.state(),
313        }
314    }
315}
316
317impl<'f, S: Clone + 'static> Remote<'f, S> {
318    /// Reads `query`, running it if it isn't cached. Call it every frame you show the result:
319    /// a query no view reads during a frame is dropped.
320    #[expect(
321        clippy::needless_pass_by_value,
322        reason = "`remote.query(SearchAuthors(prefix))` reads better than with a reference"
323    )]
324    pub fn query<Q: Query<S>>(&self, query: Q) -> QueryState<Q::Output> {
325        self.frame.remote.query(&query, self.state, &self.frame.ctx)
326    }
327
328    /// Reruns `query` the next time it is read. To rerun every query that depends on some data,
329    /// [invalidate](crate::extract::Nav::invalidate) it instead.
330    pub fn refresh<Q: Query<S>>(&self, query: &Q) {
331        self.frame.remote.refresh(query);
332        self.frame.ctx.request_repaint();
333    }
334
335    /// The view's handle to the command `C`: to run it, and to see whether it's running and
336    /// what it returned.
337    ///
338    /// Its state belongs to the view, for as long as its page (or layout) is shown. A command
339    /// still running when the page is left completes and refreshes what it changed, but its
340    /// output is dropped.
341    pub fn command<C: Command<S>>(&self) -> CommandHandle<'f, S, C> {
342        let slot = Rc::clone(
343            self.store
344                .commands
345                .borrow_mut()
346                .entry(TypeId::of::<C>())
347                .or_insert_with(|| Rc::new(RefCell::new(CommandSlot::<C::Output>::default()))),
348        );
349        CommandHandle {
350            remote: *self,
351            slot: slot.downcast().expect("stored by type"),
352            command: PhantomData,
353        }
354    }
355}
356
357/// The state of a view's command.
358struct CommandSlot<T> {
359    pending: usize,
360    output: Option<T>,
361    error: Option<RouteError>,
362}
363
364impl<T> Default for CommandSlot<T> {
365    fn default() -> Self {
366        Self {
367            pending: 0,
368            output: None,
369            error: None,
370        }
371    }
372}
373
374/// Commands' state, per view, by command type.
375pub(crate) type CommandSlots = RefCell<HashMap<TypeId, Rc<dyn Any>>>;
376
377/// A view's handle to the command `C`, from [`Remote::command`].
378pub struct CommandHandle<'f, S, C: Command<S>> {
379    remote: Remote<'f, S>,
380    slot: Rc<RefCell<CommandSlot<C::Output>>>,
381    command: PhantomData<fn(C)>,
382}
383
384impl<S: Clone + 'static, C: Command<S>> CommandHandle<'_, S, C> {
385    /// Starts `command`. Ignored in an [outgoing](crate::extract::Nav::is_outgoing) page.
386    pub fn run(&self, command: C) {
387        if self.remote.frame.outgoing {
388            return;
389        }
390        let refreshes = command.refreshes();
391        let future = command.run(self.remote.state.clone());
392        let slot = Rc::clone(&self.slot);
393        {
394            let mut slot = slot.borrow_mut();
395            slot.pending += 1;
396            slot.error = None;
397        }
398        self.remote
399            .frame
400            .remote
401            .commands
402            .borrow_mut()
403            .push(Box::pin(async move {
404                let result = future.await;
405                let mut slot = slot.borrow_mut();
406                slot.pending -= 1;
407                match result {
408                    Ok(output) => {
409                        slot.output = Some(output);
410                        refreshes
411                    }
412                    Err(error) => {
413                        slot.error = Some(error);
414                        Vec::new()
415                    }
416                }
417            }));
418        self.remote.frame.ctx.request_repaint();
419    }
420
421    /// Whether the command is running.
422    pub fn is_pending(&self) -> bool {
423        self.slot.borrow().pending > 0
424    }
425
426    /// What the command returned when it last succeeded, taken so that the view acts on it
427    /// once (e.g. navigates to what it created).
428    pub fn take_output(&self) -> Option<C::Output> {
429        self.slot.borrow_mut().output.take()
430    }
431
432    /// Why the command last failed. Cleared when it runs again.
433    pub fn error(&self) -> Option<RouteError> {
434        self.slot.borrow().error.clone()
435    }
436}