Skip to main content

egui_kit/
app.rs

1//! [`RouterApp`]: the router at runtime.
2//!
3//! Each frame it picks up history changes, drives the pending navigation and preloads, draws the
4//! mounted page and then applies what the views asked for. Starting, intercepting and
5//! committing navigations lives in [`navigate`].
6
7mod navigate;
8
9use core::any::Any;
10use core::cell::RefCell;
11use std::rc::Rc;
12
13use egui::Ui;
14
15use crate::extract::{NavAction, NavState};
16use crate::history::{EntryKey, History, HistoryEntry};
17use crate::load::{Invalidation, Job};
18use crate::navigation::{Direction, GotoOptions, Navigation};
19use crate::render::{self, Mounted, Transition};
20use crate::request::Request;
21use crate::router::RouteTable;
22use crate::session::Session;
23use navigate::{Blocked, NavKind, Pending, Resume};
24
25/// How many routes may be preloaded at once; the oldest preload is dropped beyond.
26const MAX_PRELOADS: usize = 8;
27
28type AfterNavigate<S> = Box<dyn Fn(&Navigation, &S)>;
29
30/// A built router: owns the app state, the history and the page on screen.
31///
32/// Call [`RouterApp::ui`] every frame, e.g. from `eframe::App::ui`.
33pub struct RouterApp<S> {
34    table: RouteTable<S>,
35    state: S,
36    history: Box<dyn History>,
37    session: Session,
38    /// Shared with the views during a frame.
39    nav: NavState,
40
41    mounted: Option<Mounted<S>>,
42    transition: Option<Transition<S>>,
43    pending: Option<Pending<S>>,
44    preloads: Vec<Job<S>>,
45    /// Invalidations requested while a navigation was pending, applied once it's done.
46    deferred: Invalidation,
47
48    /// The history entry being shown or navigated to.
49    key: EntryKey,
50    /// The history entry of the mounted page.
51    shown_key: EntryKey,
52    next_page_id: u64,
53
54    /// Whether the page blocked navigation during the last frame.
55    blocking: bool,
56    blocked: Option<Blocked>,
57    /// Lets the next navigation through a block (after the user confirmed it).
58    unblock_next: bool,
59    /// History moves made to undo a blocked back/forward, whose result we ignore.
60    ignored_pops: usize,
61
62    after_navigate: Vec<AfterNavigate<S>>,
63}
64
65impl<S: Clone + 'static> RouterApp<S> {
66    pub(crate) fn new(table: RouteTable<S>, state: S, history: Box<dyn History>) -> Self {
67        let initial = history.current();
68        let mut app = Self {
69            table,
70            state,
71            history,
72            session: Session::default(),
73            nav: NavState {
74                preload_on_hover: true,
75                ..NavState::default()
76            },
77            mounted: None,
78            transition: None,
79            pending: None,
80            preloads: Vec::new(),
81            deferred: Invalidation::None,
82            key: initial.key,
83            shown_key: initial.key,
84            next_page_id: 0,
85            blocking: false,
86            blocked: None,
87            unblock_next: false,
88            ignored_pops: 0,
89            after_navigate: Vec::new(),
90        };
91        app.navigate(&initial.url, NavKind::Silent, GotoOptions::default());
92        app
93    }
94
95    /// Whether [`Nav::link`](crate::extract::Nav::link) preloads its target while hovered. On by default.
96    pub fn preload_on_hover(mut self, enabled: bool) -> Self {
97        self.nav.preload_on_hover = enabled;
98        self
99    }
100
101    /// Calls `callback` after every navigation, once the new page is mounted, e.g. for
102    /// analytics or focus management. Not called for invalidations.
103    pub fn after_navigate(mut self, callback: impl Fn(&Navigation, &S) + 'static) -> Self {
104        self.after_navigate.push(Box::new(callback));
105        self
106    }
107
108    pub fn state(&self) -> &S {
109        &self.state
110    }
111
112    /// The pattern of the page route that `url` matches, e.g. `/blog/{slug}`, or `None` if it
113    /// matches none (a 404). Doesn't navigate or run anything: e.g. to check in a test that
114    /// every address the app builds leads to a page.
115    ///
116    /// A match can still fail to load, e.g. with a [`Path`](crate::extract::Path) that doesn't
117    /// parse.
118    ///
119    /// ```
120    /// # use egui_kit::{MemoryHistory, Router};
121    /// # use egui_kit::page::Page;
122    /// let app = Router::<()>::new()
123    ///     .page("/blog/{slug}", Page::new(|_: &mut egui::Ui| {}))
124    ///     .with_state_and_history((), MemoryHistory::new("/"));
125    /// assert_eq!(app.matches("/blog/hello?draft"), Some("/blog/{slug}"));
126    /// assert_eq!(app.matches("/blog"), None);
127    /// ```
128    pub fn matches(&self, url: &str) -> Option<&str> {
129        self.table.page_route(url)
130    }
131
132    /// The request of the page on screen.
133    pub fn request(&self) -> Option<&Request> {
134        self.mounted.as_ref().map(|mounted| &mounted.request)
135    }
136
137    /// The url of the current history entry, see [`Nav::url`](crate::extract::Nav::url).
138    pub fn url(&self) -> Option<&str> {
139        self.mounted.as_ref().map(|mounted| mounted.url.as_str())
140    }
141
142    pub fn is_loading(&self) -> bool {
143        self.pending.is_some()
144    }
145
146    /// Navigates to `url`, adding a history entry. Going to the current url does nothing, unless
147    /// [`GotoOptions::invalidate_all`] asks for a reload. See
148    /// [`Nav::goto`](crate::extract::Nav::goto).
149    pub fn goto(&mut self, url: &str) {
150        self.goto_with(url, GotoOptions::default());
151    }
152
153    /// See [`Nav::goto_with`](crate::extract::Nav::goto_with).
154    pub fn goto_with(&mut self, url: &str, options: GotoOptions) {
155        self.request_goto(url, options);
156    }
157
158    pub fn back(&mut self) {
159        self.history.back();
160    }
161
162    pub fn forward(&mut self) {
163        self.history.forward();
164    }
165
166    /// See [`Nav::invalidate`](crate::extract::Nav::invalidate); e.g. after data changed in the background.
167    pub fn invalidate(&mut self, key: impl Into<String>) {
168        self.invalidate_with(Invalidation::Keys(vec![key.into()]));
169    }
170
171    /// See [`Nav::invalidate_all`](crate::extract::Nav::invalidate_all).
172    pub fn invalidate_all(&mut self) {
173        self.invalidate_with(Invalidation::All);
174    }
175
176    /// See [`Nav::preload`](crate::extract::Nav::preload).
177    pub fn preload(&mut self, url: &str) {
178        let (entry, request) = self.table.resolve(url);
179        let url = request.untracked_url();
180        let busy = |job: &Job<S>| job.request.untracked_url() == url;
181        if self
182            .pending
183            .as_ref()
184            .is_some_and(|pending| busy(&pending.job))
185            || self.preloads.iter().any(busy)
186        {
187            return;
188        }
189        let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
190        let job = Job::start(entry, request, &self.state, &previous, &Invalidation::None);
191        if self.preloads.len() == MAX_PRELOADS {
192            self.preloads.remove(0);
193        }
194        self.preloads.push(job);
195    }
196
197    /// Shows the current page, wrapped in its layouts.
198    pub fn ui(&mut self, ui: &mut Ui) {
199        let ctx = ui.ctx().clone();
200        #[cfg(feature = "remote")]
201        let _runtime = crate::remote::enter();
202        #[cfg(feature = "remote")]
203        crate::remote::begin_frame(&ctx);
204
205        #[cfg(not(target_arch = "wasm32"))]
206        self.handle_back_forward_input(ui);
207        if let Some(entry) = self.history.poll(&ctx) {
208            self.traverse(entry);
209        }
210        self.poll(&ctx);
211
212        self.nav.shows_links = self.history.shows_links();
213        self.nav.can_go_back = self.history.can_go_back();
214        self.nav.can_go_forward = self.history.can_go_forward();
215        self.nav.blocked = self
216            .blocked
217            .as_ref()
218            .map(|blocked| blocked.navigation.clone());
219        let nav = RefCell::new(core::mem::take(&mut self.nav));
220        match &mut self.mounted {
221            Some(mounted) => {
222                render::render(ui, mounted, self.transition.as_mut(), &self.state, &nav);
223            }
224            None => {
225                ui.centered_and_justified(|ui| ui.spinner());
226            }
227        }
228        self.nav = nav.into_inner();
229        self.blocking = core::mem::take(&mut self.nav.blocking);
230        let hovered_link = self.nav.hovered_link.take();
231        // Changing the link mid-click or mid-drag would disturb it.
232        if !ctx.input(|i| i.pointer.any_down()) {
233            self.history.hover_link(hovered_link.as_deref());
234        }
235        if let Some(transition) = &self.transition
236            && (transition.state.done.get() || !transition.state.claimed.get())
237        {
238            self.transition = None;
239        }
240
241        #[cfg(feature = "remote")]
242        crate::remote::end_frame();
243
244        let actions = core::mem::take(&mut self.nav.actions);
245        if !actions.is_empty() {
246            for action in actions {
247                self.apply(action);
248            }
249            ctx.request_repaint();
250        }
251        self.poll(&ctx);
252    }
253
254    /// Mouse back/forward buttons and Alt+Left/Right. Browsers handle these themselves.
255    #[cfg(not(target_arch = "wasm32"))]
256    fn handle_back_forward_input(&mut self, ui: &Ui) {
257        use egui::{Key, Modifiers, PointerButton};
258
259        let (back, forward) = ui.input_mut(|i| {
260            let back = i.pointer.button_pressed(PointerButton::Extra1)
261                | i.consume_key(Modifiers::ALT, Key::ArrowLeft);
262            let forward = i.pointer.button_pressed(PointerButton::Extra2)
263                | i.consume_key(Modifiers::ALT, Key::ArrowRight);
264            (back, forward)
265        });
266        if back {
267            self.history.back();
268        }
269        if forward {
270            self.history.forward();
271        }
272    }
273
274    fn apply(&mut self, action: NavAction) {
275        match action {
276            NavAction::Goto(url, options) => self.request_goto(&url, options),
277            NavAction::Back => self.history.back(),
278            NavAction::Forward => self.history.forward(),
279            NavAction::Invalidate(invalidation) => self.invalidate_with(invalidation),
280            NavAction::Preload(url) => self.preload(&url),
281            NavAction::PushState(url, state) => self.shallow(url, state, true),
282            NavAction::ReplaceState(url, state) => self.shallow(url, state, false),
283            NavAction::ReplaceUrl(url) => {
284                let state = self.mounted.as_ref().and_then(|m| m.history_state.clone());
285                self.shallow(url, state, false);
286            }
287            NavAction::ConfirmNavigation => self.confirm_blocked(),
288            NavAction::CancelNavigation => self.blocked = None,
289        }
290    }
291
292    /// Applies the invalidations of commands, drives the preloads and the pending navigation;
293    /// commits the latter when done. Loads that complete synchronously are committed within the
294    /// same frame, so they never flash a loading state.
295    fn poll(&mut self, ctx: &egui::Context) {
296        #[cfg(feature = "remote")]
297        {
298            let invalidated = crate::remote::take_invalidated();
299            if !invalidated.is_empty() {
300                self.invalidate_with(Invalidation::Keys(invalidated));
301                ctx.request_repaint();
302            }
303        }
304        for job in &mut self.preloads {
305            job.poll(ctx);
306        }
307        while let Some(pending) = &mut self.pending {
308            if !pending.job.poll(ctx) {
309                return;
310            }
311            let mut pending = self.pending.take().expect("checked above");
312            let outcome = pending.job.take_outcome().expect("the job is done");
313            self.nav.loading = None;
314            self.commit(pending, outcome);
315        }
316    }
317
318    /// Shallow routing: a history entry for the mounted page, without a navigation.
319    fn shallow(&mut self, url: String, state: Option<Rc<dyn Any>>, push: bool) {
320        let Some(mounted) = &mut self.mounted else {
321            return;
322        };
323        if !url.is_empty() {
324            mounted.url = url;
325        }
326        if push {
327            self.key = self.history.push(&mounted.url);
328        } else {
329            self.history.replace(&mounted.url);
330        }
331        self.shown_key = self.key;
332        mounted.history_state = state.clone();
333        self.session.record(self.key, mounted.id, state);
334    }
335
336    /// The history moved to `entry` (back/forward). Entries of the mounted page only swap the
337    /// page state; anything else is a regular navigation, unless the page blocks it.
338    fn traverse(&mut self, entry: HistoryEntry) {
339        if self.ignored_pops > 0 {
340            self.ignored_pops -= 1;
341            return;
342        }
343        let meta = self.session.get(entry.key);
344        if let (Some(mounted), Some(meta)) = (&mut self.mounted, meta)
345            && meta.page == mounted.id
346        {
347            self.pending = None;
348            self.nav.loading = None;
349            self.key = entry.key;
350            self.shown_key = entry.key;
351            mounted.url = entry.url;
352            mounted.history_state = meta.state.clone();
353            return;
354        }
355
356        let direction = self.session.direction(self.shown_key, entry.key);
357        if direction != Direction::None && self.should_block() {
358            // The history already moved: move it back, and redo the move once confirmed.
359            match direction {
360                Direction::Back => self.history.forward(),
361                _ => self.history.back(),
362            }
363            self.ignored_pops += 1;
364            self.block(Resume::Traverse(direction), entry.url, direction);
365            return;
366        }
367        self.key = entry.key;
368        self.navigate(&entry.url, NavKind::Silent, GotoOptions::default());
369    }
370
371    /// Reruns the loads and queries that `invalidation` hits.
372    fn invalidate_with(&mut self, invalidation: Invalidation) {
373        #[cfg(feature = "remote")]
374        crate::remote::invalidate_queries(&invalidation);
375        self.reload(invalidation);
376    }
377
378    /// Reloads the mounted page with `invalidation`, after the pending navigation if any.
379    fn reload(&mut self, invalidation: Invalidation) {
380        self.preloads.clear();
381        if self.pending.is_some() {
382            self.deferred = core::mem::take(&mut self.deferred).merge(invalidation);
383            return;
384        }
385        if let Some(mounted) = &self.mounted {
386            let (url, id) = (mounted.request.untracked_url(), mounted.id);
387            self.start(
388                &url,
389                NavKind::Silent,
390                GotoOptions::default(),
391                0,
392                Some(id),
393                invalidation,
394            );
395        }
396    }
397}