egui-kit 0.6.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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! [`RouterApp`]: the router at runtime.
//!
//! Each frame it picks up history changes, drives the pending navigation and preloads, draws the
//! mounted page and then applies what the views asked for. Starting, intercepting and
//! committing navigations lives in [`navigate`].

mod navigate;

use core::any::Any;
use core::cell::RefCell;
use std::rc::Rc;

use egui::Ui;

use crate::extract::{NavAction, NavState};
use crate::history::{EntryKey, History, HistoryEntry};
use crate::load::{Invalidation, Job};
use crate::navigation::{Direction, GotoOptions, Navigation};
use crate::render::{self, Mounted, Transition};
use crate::request::Request;
use crate::router::RouteTable;
use crate::session::Session;
use navigate::{Blocked, NavKind, Pending, Resume};

/// How many routes may be preloaded at once; the oldest preload is dropped beyond.
const MAX_PRELOADS: usize = 8;

type AfterNavigate<S> = Box<dyn Fn(&Navigation, &S)>;

/// A built router: owns the app state, the history and the page on screen.
///
/// Call [`RouterApp::ui`] every frame, e.g. from `eframe::App::ui`.
pub struct RouterApp<S> {
    table: RouteTable<S>,
    state: S,
    history: Box<dyn History>,
    session: Session,
    /// Shared with the views during a frame.
    nav: NavState,

    mounted: Option<Mounted<S>>,
    transition: Option<Transition<S>>,
    pending: Option<Pending<S>>,
    preloads: Vec<Job<S>>,
    /// Invalidations requested while a navigation was pending, applied once it's done.
    deferred: Invalidation,

    /// The history entry being shown or navigated to.
    key: EntryKey,
    /// The history entry of the mounted page.
    shown_key: EntryKey,
    next_page_id: u64,

    /// Whether the page blocked navigation during the last frame.
    blocking: bool,
    blocked: Option<Blocked>,
    /// Lets the next navigation through a block (after the user confirmed it).
    unblock_next: bool,
    /// The title last set with `Nav::set_title`, and applied to the window.
    title: Option<String>,
    /// The user confirmed closing the window: close it after the frame.
    close_confirmed: bool,
    /// History moves made to undo a blocked back/forward, whose result we ignore.
    ignored_pops: usize,

    after_navigate: Vec<AfterNavigate<S>>,
}

impl<S: Clone + 'static> RouterApp<S> {
    pub(crate) fn new(table: RouteTable<S>, state: S, history: Box<dyn History>) -> Self {
        let initial = history.current();
        let mut app = Self {
            table,
            state,
            history,
            session: Session::default(),
            nav: NavState {
                preload_on_hover: true,
                ..NavState::default()
            },
            mounted: None,
            transition: None,
            pending: None,
            preloads: Vec::new(),
            deferred: Invalidation::None,
            key: initial.key,
            shown_key: initial.key,
            next_page_id: 0,
            blocking: false,
            blocked: None,
            unblock_next: false,
            title: None,
            close_confirmed: false,
            ignored_pops: 0,
            after_navigate: Vec::new(),
        };
        app.navigate(&initial.url, NavKind::Silent, GotoOptions::default());
        app
    }

    /// Whether [`Nav::link`](crate::extract::Nav::link) preloads its target while hovered. On by default.
    pub fn preload_on_hover(mut self, enabled: bool) -> Self {
        self.nav.preload_on_hover = enabled;
        self
    }

    /// Calls `callback` after every navigation, once the new page is mounted, e.g. for
    /// analytics or focus management. Not called for invalidations.
    pub fn after_navigate(mut self, callback: impl Fn(&Navigation, &S) + 'static) -> Self {
        self.after_navigate.push(Box::new(callback));
        self
    }

    pub fn state(&self) -> &S {
        &self.state
    }

    /// The pattern of the page route that `url` matches, e.g. `/blog/{slug}`, or `None` if it
    /// matches none (a 404). Doesn't navigate or run anything: e.g. to check in a test that
    /// every address the app builds leads to a page.
    ///
    /// A match can still fail to load, e.g. with a [`Path`](crate::extract::Path) that doesn't
    /// parse.
    ///
    /// ```
    /// # use egui_kit::{MemoryHistory, Router};
    /// # use egui_kit::page::Page;
    /// let app = Router::<()>::new()
    ///     .page("/blog/{slug}", Page::new(|_: &mut egui::Ui| {}))
    ///     .with_state_and_history((), MemoryHistory::new("/"));
    /// assert_eq!(app.matches("/blog/hello?draft"), Some("/blog/{slug}"));
    /// assert_eq!(app.matches("/blog"), None);
    /// ```
    pub fn matches(&self, url: &str) -> Option<&str> {
        self.table.page_route(url)
    }

    /// The request of the page on screen.
    pub fn request(&self) -> Option<&Request> {
        self.mounted.as_ref().map(|mounted| &mounted.request)
    }

    /// The url of the current history entry, see [`Nav::url`](crate::extract::Nav::url).
    pub fn url(&self) -> Option<&str> {
        self.mounted.as_ref().map(|mounted| mounted.url.as_str())
    }

    /// The title the views set with [`Nav::set_title`](crate::extract::Nav::set_title), as
    /// applied to the browser tab or window.
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    pub fn is_loading(&self) -> bool {
        self.pending.is_some()
    }

    /// Navigates to `url`, adding a history entry. Going to the current url does nothing, unless
    /// [`GotoOptions::invalidate_all`] asks for a reload. See
    /// [`Nav::goto`](crate::extract::Nav::goto).
    pub fn goto(&mut self, url: &str) {
        self.goto_with(url, GotoOptions::default());
    }

    /// See [`Nav::goto_with`](crate::extract::Nav::goto_with).
    pub fn goto_with(&mut self, url: &str, options: GotoOptions) {
        self.request_goto(url, options);
    }

    pub fn back(&mut self) {
        self.history.back();
    }

    pub fn forward(&mut self) {
        self.history.forward();
    }

    /// See [`Nav::invalidate`](crate::extract::Nav::invalidate); e.g. after data changed in the background.
    pub fn invalidate(&mut self, key: impl Into<String>) {
        self.invalidate_with(Invalidation::Keys(vec![key.into()]));
    }

    /// See [`Nav::invalidate_all`](crate::extract::Nav::invalidate_all).
    pub fn invalidate_all(&mut self) {
        self.invalidate_with(Invalidation::All);
    }

    /// See [`Nav::preload`](crate::extract::Nav::preload).
    pub fn preload(&mut self, url: &str) {
        let (entry, request) = self.table.resolve(url);
        let url = request.untracked_url();
        let busy = |job: &Job<S>| job.request.untracked_url() == url;
        if self
            .pending
            .as_ref()
            .is_some_and(|pending| busy(&pending.job))
            || self.preloads.iter().any(busy)
        {
            return;
        }
        let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
        let job = Job::start(entry, request, &self.state, &previous, &Invalidation::None);
        if self.preloads.len() == MAX_PRELOADS {
            self.preloads.remove(0);
        }
        self.preloads.push(job);
    }

    /// Shows the current page, wrapped in its layouts.
    pub fn ui(&mut self, ui: &mut Ui) {
        let ctx = ui.ctx().clone();
        #[cfg(feature = "remote")]
        let _runtime = crate::remote::enter();
        #[cfg(feature = "remote")]
        crate::remote::set_context(&ctx);

        #[cfg(not(target_arch = "wasm32"))]
        self.handle_back_forward_input(ui);
        #[cfg(not(target_arch = "wasm32"))]
        self.handle_close_request(&ctx);
        if let Some(entry) = self.history.poll(&ctx) {
            self.traverse(entry);
        }
        self.poll(&ctx);

        self.nav.shows_links = self.history.shows_links();
        self.nav.can_go_back = self.history.can_go_back();
        self.nav.can_go_forward = self.history.can_go_forward();
        self.nav.blocked = self
            .blocked
            .as_ref()
            .map(|blocked| blocked.navigation.clone());
        let nav = RefCell::new(core::mem::take(&mut self.nav));
        match &mut self.mounted {
            Some(mounted) => {
                render::render(ui, mounted, self.transition.as_mut(), &self.state, &nav);
            }
            None => {
                ui.centered_and_justified(|ui| ui.spinner());
            }
        }
        self.nav = nav.into_inner();
        let was_blocking = self.blocking;
        self.blocking = core::mem::take(&mut self.nav.blocking);
        if self.blocking != was_blocking {
            self.history.set_blocking(self.blocking);
        }
        if let Some((_, title)) = self.nav.title.take()
            && self.title.as_ref() != Some(&title)
        {
            set_title(&ctx, &title);
            self.title = Some(title);
        }
        let hovered_link = self.nav.hovered_link.take();
        // Changing the link mid-click or mid-drag would disturb it.
        if !ctx.input(|i| i.pointer.any_down()) {
            self.history.hover_link(hovered_link.as_deref());
        }
        if let Some(transition) = &self.transition
            && (transition.state.done.get() || !transition.state.claimed.get())
        {
            self.transition = None;
        }

        #[cfg(feature = "remote")]
        crate::remote::end_frame();

        let actions = core::mem::take(&mut self.nav.actions);
        if !actions.is_empty() {
            for action in actions {
                self.apply(action);
            }
            ctx.request_repaint();
        }
        if core::mem::take(&mut self.close_confirmed) {
            ctx.send_viewport_cmd(egui::ViewportCommand::Close);
        }
        self.poll(&ctx);
    }

    /// Mouse back/forward buttons and Alt+Left/Right. Browsers handle these themselves.
    #[cfg(not(target_arch = "wasm32"))]
    fn handle_back_forward_input(&mut self, ui: &Ui) {
        use egui::{Key, Modifiers, PointerButton};

        let (back, forward) = ui.input_mut(|i| {
            let back = i.pointer.button_pressed(PointerButton::Extra1)
                | i.consume_key(Modifiers::ALT, Key::ArrowLeft);
            let forward = i.pointer.button_pressed(PointerButton::Extra2)
                | i.consume_key(Modifiers::ALT, Key::ArrowRight);
            (back, forward)
        });
        if back {
            self.history.back();
        }
        if forward {
            self.history.forward();
        }
    }

    /// Holds back closing the window while the page blocks navigation, as a navigation of kind
    /// [`Leave`](crate::NavigationKind::Leave). Browsers ask the user themselves.
    #[cfg(not(target_arch = "wasm32"))]
    fn handle_close_request(&mut self, ctx: &egui::Context) {
        if ctx.input(|i| i.viewport().close_requested()) && self.should_block() {
            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
            self.block(Resume::Close, String::new(), Direction::None);
        }
    }

    fn apply(&mut self, action: NavAction) {
        match action {
            NavAction::Goto(url, options) => self.request_goto(&url, options),
            NavAction::Back => self.history.back(),
            NavAction::Forward => self.history.forward(),
            NavAction::Invalidate(invalidation) => self.invalidate_with(invalidation),
            NavAction::Preload(url) => self.preload(&url),
            NavAction::PushState(url, state) => self.shallow(url, state, true),
            NavAction::ReplaceState(url, state) => self.shallow(url, state, false),
            NavAction::ReplaceUrl(url) => {
                let state = self.mounted.as_ref().and_then(|m| m.history_state.clone());
                self.shallow(url, state, false);
            }
            NavAction::ConfirmNavigation => self.confirm_blocked(),
            NavAction::CancelNavigation => self.blocked = None,
        }
    }

    /// Applies the invalidations of commands, drives the preloads and the pending navigation;
    /// commits the latter when done. Loads that complete synchronously are committed within the
    /// same frame, so they never flash a loading state.
    fn poll(&mut self, ctx: &egui::Context) {
        #[cfg(feature = "remote")]
        {
            let invalidated = crate::remote::take_invalidated();
            if !invalidated.is_empty() {
                self.invalidate_with(Invalidation::Keys(invalidated));
                ctx.request_repaint();
            }
        }
        for job in &mut self.preloads {
            job.poll(ctx);
        }
        while let Some(pending) = &mut self.pending {
            if !pending.job.poll(ctx) {
                return;
            }
            let mut pending = self.pending.take().expect("checked above");
            let outcome = pending.job.take_outcome().expect("the job is done");
            self.nav.loading = None;
            self.commit(pending, outcome);
        }
    }

    /// Shallow routing: a history entry for the mounted page, without a navigation.
    fn shallow(&mut self, url: String, state: Option<Rc<dyn Any>>, push: bool) {
        let Some(mounted) = &mut self.mounted else {
            return;
        };
        if !url.is_empty() {
            mounted.url = url;
        }
        if push {
            self.key = self.history.push(&mounted.url);
        } else {
            self.history.replace(&mounted.url);
        }
        self.shown_key = self.key;
        mounted.history_state = state.clone();
        self.session.record(self.key, mounted.id, state);
    }

    /// The history moved to `entry` (back/forward). Entries of the mounted page only swap the
    /// page state; anything else is a regular navigation, unless the page blocks it.
    fn traverse(&mut self, entry: HistoryEntry) {
        if self.ignored_pops > 0 {
            self.ignored_pops -= 1;
            return;
        }
        if let Some(mounted) = &mut self.mounted {
            let state = match self.session.get(entry.key) {
                Some(meta) if meta.page == mounted.id => Some(meta.state.clone()),
                Some(_) => None,
                // A new entry for the page's url, e.g. the user edited its `#hash`: adopt it.
                None => (Request::new(&entry.url).untracked_url()
                    == Request::new(&mounted.url).untracked_url())
                .then(|| {
                    self.session.record(entry.key, mounted.id, None);
                    None
                }),
            };
            if let Some(state) = state {
                self.pending = None;
                self.nav.loading = None;
                self.key = entry.key;
                self.shown_key = entry.key;
                mounted.url = entry.url;
                mounted.history_state = state;
                return;
            }
        }

        let direction = self.session.direction(self.shown_key, entry.key);
        if direction != Direction::None && self.should_block() {
            // The history already moved: move it back, and redo the move once confirmed.
            match direction {
                Direction::Back => self.history.forward(),
                _ => self.history.back(),
            }
            self.ignored_pops += 1;
            self.block(Resume::Traverse(direction), entry.url, direction);
            return;
        }
        self.key = entry.key;
        self.navigate(&entry.url, NavKind::Silent, GotoOptions::default());
    }

    /// Reruns the loads and queries that `invalidation` hits.
    fn invalidate_with(&mut self, invalidation: Invalidation) {
        #[cfg(feature = "remote")]
        crate::remote::invalidate_queries(&invalidation);
        self.reload(invalidation);
    }

    /// Reloads the mounted page with `invalidation`, after the pending navigation if any.
    fn reload(&mut self, invalidation: Invalidation) {
        self.preloads.clear();
        if self.pending.is_some() {
            self.deferred = core::mem::take(&mut self.deferred).merge(invalidation);
            return;
        }
        if let Some(mounted) = &self.mounted {
            let (url, id) = (mounted.request.untracked_url(), mounted.id);
            self.start(
                &url,
                NavKind::Silent,
                GotoOptions::default(),
                0,
                Some(id),
                invalidation,
            );
        }
    }
}

/// Shows `title` in the browser tab, or natively in the window's title bar.
fn set_title(ctx: &egui::Context, title: &str) {
    #[cfg(target_arch = "wasm32")]
    {
        let _ = ctx;
        if let Some(document) = web_sys::window().and_then(|window| window.document()) {
            document.set_title(title);
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.to_owned()));
}