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