egui-kit 0.5.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
//! Starting, blocking and committing navigations.

use super::*;
use crate::error::{Rejection, RouteError};
use crate::extract::{PageScroll, ViewStore};
use crate::load::Outcome;
use crate::navigation::NavigationKind;
use crate::render::{Content, error_view};
use crate::request::split_fragment;
use crate::router::{Level, Target};
use crate::session::Visit;

const MAX_REDIRECTS: u8 = 20;

/// How a finished navigation updates the history.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum NavKind {
    Push,
    Replace,
    /// The history already points at the url (back/forward, initial load, invalidation).
    Silent,
}

/// A navigation whose hooks and loads are running.
pub(super) struct Pending<S> {
    pub(super) job: Job<S>,
    /// The url that was asked for, before any redirects.
    requested: String,
    /// The `#fragment` of the url being loaded (of the redirect target, after a redirect), added
    /// to its history entry.
    fragment: Option<String>,
    kind: NavKind,
    options: GotoOptions,
    redirects: u8,
    /// Set when reloading the mounted page (invalidation), which stays the same page instance.
    reload_of: Option<u64>,
    /// Carried over to the navigation that replaces this one, so it isn't lost.
    invalidation: Invalidation,
}

/// How to carry out a blocked navigation once confirmed.
pub(super) enum Resume {
    Goto(String, GotoOptions),
    Traverse(Direction),
    /// Closing the window (natively; browsers ask the user themselves).
    #[cfg_attr(target_arch = "wasm32", expect(dead_code, reason = "native only"))]
    Close,
}

pub(super) struct Blocked {
    pub(super) navigation: Navigation,
    resume: Resume,
}

impl<S: Clone + 'static> RouterApp<S> {
    /// A navigation asked for by the app (links, `goto`), unless the page blocks it.
    pub(super) fn request_goto(&mut self, url: &str, options: GotoOptions) {
        let to = Request::new(url).untracked_url();
        let fragment = split_fragment(url).1;
        // Already on its way there: restarting would cancel the loads, which never finish if
        // the view asks again every frame.
        if self.pending.as_ref().is_some_and(|pending| {
            pending.reload_of.is_none() && pending.requested == to && pending.options == options
        }) {
            return;
        }
        let same_url = self
            .mounted
            .as_ref()
            .is_some_and(|mounted| Request::new(&mounted.url).untracked_url() == to);
        // Already there: the page keeps its state, and a navigation elsewhere that is still
        // loading is abandoned. `invalidate_all` asks for a reload, though.
        if same_url && !options.invalidate_all {
            if self.pending.as_ref().is_some_and(|pending| {
                pending.reload_of.is_none() && pending.invalidation == Invalidation::None
            }) {
                self.pending = None;
                self.nav.loading = None;
            }
            // Only the fragment changes: a history entry for the same page, like a browser.
            if let Some(mounted) = &self.mounted
                && split_fragment(&mounted.url).1 != fragment
            {
                let state = mounted.history_state.clone();
                self.shallow(with_fragment(&to, fragment), state, !options.replace_state);
            }
            return;
        }
        if !same_url && self.should_block() {
            return self.block(
                Resume::Goto(url.to_owned(), options),
                to,
                Direction::Forward,
            );
        }
        // Like a browser, reloading the current url replaces the entry.
        let kind = if options.replace_state || same_url {
            NavKind::Replace
        } else {
            NavKind::Push
        };
        self.navigate(url, kind, options);
    }

    /// Whether a navigation away from the page must wait for the user's confirmation.
    pub(super) fn should_block(&mut self) -> bool {
        let unblocked = core::mem::take(&mut self.unblock_next);
        self.blocking && !unblocked
    }

    pub(super) fn block(&mut self, resume: Resume, to: String, direction: Direction) {
        let kind = match resume {
            Resume::Goto(..) => NavigationKind::Goto,
            Resume::Traverse(_) => NavigationKind::Popstate,
            Resume::Close => NavigationKind::Leave,
        };
        let navigation = Navigation {
            from: self.mounted.as_ref().map(|mounted| mounted.url.clone()),
            to,
            kind,
            direction,
        };
        self.blocked = Some(Blocked { navigation, resume });
    }

    pub(super) fn confirm_blocked(&mut self) {
        let Some(blocked) = self.blocked.take() else {
            return;
        };
        self.unblock_next = true;
        match blocked.resume {
            Resume::Goto(url, options) => self.request_goto(&url, options),
            Resume::Traverse(Direction::Back) => self.history.back(),
            Resume::Traverse(_) => self.history.forward(),
            // With `unblock_next` set, the next close request goes through.
            Resume::Close => self.close_confirmed = true,
        }
    }

    pub(super) fn navigate(&mut self, url: &str, kind: NavKind, options: GotoOptions) {
        let invalidation = if options.invalidate_all {
            Invalidation::All
        } else {
            Invalidation::None
        };
        self.start(url, kind, options, 0, None, invalidation);
    }

    /// Starts loading `url` (or adopts its preload), replacing any navigation in progress.
    /// What the replaced navigation invalidated is invalidated by this one too.
    pub(super) fn start(
        &mut self,
        url: &str,
        kind: NavKind,
        options: GotoOptions,
        redirects: u8,
        reload_of: Option<u64>,
        invalidation: Invalidation,
    ) {
        let invalidation = match self.pending.take() {
            Some(replaced) => replaced.invalidation.merge(invalidation),
            None => invalidation,
        };
        let fragment = split_fragment(url).1.map(str::to_owned);
        let (entry, request) = self.table.resolve(url);
        let url = request.untracked_url();
        let preloaded = (invalidation == Invalidation::None)
            .then(|| {
                self.preloads
                    .iter()
                    .position(|job| job.request.untracked_url() == url)
            })
            .flatten()
            .map(|index| self.preloads.remove(index));
        let job = preloaded.unwrap_or_else(|| {
            let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
            Job::start(entry, request, &self.state, &previous, &invalidation)
        });

        self.nav.loading = Some(url.clone());
        self.pending = Some(Pending {
            job,
            requested: url,
            fragment,
            kind,
            options,
            redirects,
            reload_of,
            invalidation,
        });
    }

    /// Shows the outcome of a navigation: follows redirects, updates the history, swaps the
    /// mounted page and starts the transition.
    pub(super) fn commit(&mut self, pending: Pending<S>, outcome: Outcome) {
        let Pending {
            job,
            requested,
            fragment,
            kind,
            options,
            redirects,
            reload_of,
            ..
        } = pending;
        let levels = &job.entry.levels;
        let content = match (outcome.failure, outcome.page, &job.entry.target) {
            (Some((_, Rejection::Redirect(redirect))), ..) if redirects < MAX_REDIRECTS => {
                let kind = if kind == NavKind::Push {
                    NavKind::Push
                } else {
                    NavKind::Replace
                };
                self.start(
                    &redirect.to,
                    kind,
                    options,
                    redirects + 1,
                    None,
                    Invalidation::None,
                );
                if let Some(pending) = &mut self.pending {
                    pending.requested = requested;
                }
                return;
            }
            (Some((failed, Rejection::Redirect(_))), ..) => {
                error_view(levels, failed, RouteError::internal("too many redirects"))
            }
            (Some((failed, Rejection::Error(error))), ..) => error_view(levels, failed, error),
            (None, Some(data), Target::Page(page)) => Content::Page {
                page: Rc::clone(page),
                data,
            },
            _ => unreachable!("a route without failures loaded its page"),
        };

        let url = job.request.untracked_url();
        let entry_url = with_fragment(&url, fragment.as_deref());
        match kind {
            NavKind::Push => self.key = self.history.push(&entry_url),
            NavKind::Replace => self.history.replace(&entry_url),
            NavKind::Silent => {}
        }

        let previous = self.mounted.take();
        let navigation_kind = match (reload_of, &previous, kind) {
            (Some(_), _, _) => NavigationKind::Invalidate,
            (None, None, _) => NavigationKind::Enter,
            (None, Some(_), NavKind::Push) => NavigationKind::Goto,
            (None, Some(_), NavKind::Replace) => NavigationKind::Replace,
            (None, Some(_), NavKind::Silent) => NavigationKind::Popstate,
        };
        let direction = match navigation_kind {
            NavigationKind::Goto => Direction::Forward,
            NavigationKind::Popstate => self.session.direction(self.shown_key, self.key),
            _ => Direction::None,
        };
        let navigation = Navigation {
            from: previous.as_ref().map(|previous| previous.url.clone()),
            to: url,
            kind: navigation_kind,
            direction,
        };
        let history_state = match kind {
            // Back/forward to an entry of an earlier page, or a reload: restore its state.
            NavKind::Silent => self
                .session
                .get(self.key)
                .and_then(|meta| meta.state.clone()),
            NavKind::Push | NavKind::Replace => None,
        };

        // Only a reload keeps the page instance. Other navigations may keep the page's data, but
        // show a different url, so they get their own instance (and history entry identity).
        // Back/forward to a page that was left continues that instance's snapshots.
        let reload = reload_of.is_some();
        let node = content.page_node();
        let visit = match navigation_kind {
            NavigationKind::Popstate => self
                .session
                .get(self.key)
                .map(|meta| meta.page)
                .and_then(|page| Some((page, self.session.take_visit(page, node)?))),
            _ => None,
        };
        let (id, store) = match (&previous, &visit) {
            (Some(previous), _) if reload => (previous.id, Rc::clone(&previous.store)),
            (_, Some((page, visit))) => (*page, Rc::new(ViewStore::restored(&visit.page))),
            _ => {
                self.next_page_id += 1;
                (self.next_page_id, Rc::default())
            }
        };
        let layout_stores = layout_stores(
            levels,
            previous.as_ref(),
            visit.as_ref().map(|(_, visit)| visit),
        );

        let mut mounted = Mounted {
            id,
            request: job.request,
            url: self.history.current().url,
            history_state,
            levels: levels.clone(),
            layouts: outcome.layouts,
            layout_stores,
            store,
            content,
            navigation: navigation.clone(),
            scroll: PageScroll::default(),
        };
        let previous = match previous {
            Some(previous) if reload => {
                mounted.scroll = previous.scroll;
                None
            }
            previous => {
                if let Some(previous) = &previous {
                    self.leave(previous, &mounted);
                }
                mounted.scroll.restore.set(match navigation_kind {
                    NavigationKind::Popstate => {
                        self.session.get(self.key).and_then(|meta| meta.scroll)
                    }
                    _ if options.no_scroll => previous
                        .as_ref()
                        .map(|previous| previous.scroll.offset.get()),
                    _ => None,
                });
                previous
            }
        };

        self.session
            .record(self.key, mounted.id, mounted.history_state.clone());
        self.shown_key = self.key;
        self.mounted = Some(mounted);
        // Preloads were planned against the previous page.
        self.preloads.clear();
        // Transitions start once everything is loaded.
        self.transition = previous.map(|previous| Transition {
            previous,
            direction,
            state: Default::default(),
        });
        if navigation_kind != NavigationKind::Invalidate {
            for callback in &self.after_navigate {
                callback(&navigation, &self.state);
            }
        }

        let deferred = core::mem::take(&mut self.deferred);
        if deferred != Invalidation::None {
            self.reload(deferred);
        }
    }

    /// Remembers what back/forward restores of the page being left: its snapshots (with those of
    /// the layouts that leave with it) and the scroll position of its history entry.
    fn leave(&mut self, previous: &Mounted<S>, next: &Mounted<S>) {
        let kept = |store: &Rc<ViewStore>| {
            next.layout_stores
                .iter()
                .flatten()
                .any(|kept| Rc::ptr_eq(kept, store))
        };
        let layouts = previous
            .levels
            .iter()
            .zip(&previous.layout_stores)
            .filter_map(|(level, store)| Some((level.layout.as_ref()?.loader.id, store.clone()?)))
            .filter(|(_, store)| !kept(store))
            .collect();
        let visit = Visit {
            node: previous.content.page_node(),
            page: Rc::clone(&previous.store),
            layouts,
        };
        self.session.save_visit(previous.id, visit);

        if self.shown_key == self.key {
            // The entry is being replaced by another page.
            return;
        }
        if let Some(meta) = self.session.get_mut(self.shown_key) {
            meta.scroll = Some(previous.scroll.offset.get());
        }
    }
}

/// `url` with `#fragment` appended, if any.
fn with_fragment(url: &str, fragment: Option<&str>) -> String {
    match fragment {
        Some(fragment) => format!("{url}#{fragment}"),
        None => url.to_owned(),
    }
}

/// The view stores of the layouts of `levels`: kept from the previous page while the layout
/// stays on screen, restored from a visit on back/forward, fresh otherwise.
fn layout_stores<S>(
    levels: &[Rc<Level<S>>],
    previous: Option<&Mounted<S>>,
    visit: Option<&Visit>,
) -> Vec<Option<Rc<ViewStore>>> {
    levels
        .iter()
        .map(|level| {
            let node = level.layout.as_ref()?.loader.id;
            let kept = previous.and_then(|previous| previous.layout_store(node));
            let restored = || {
                let (_, left) = visit?.layouts.iter().find(|(id, _)| *id == node)?;
                Some(Rc::new(ViewStore::restored(left)))
            };
            Some(kept.or_else(restored).unwrap_or_default())
        })
        .collect()
}