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 request of the page on screen.
113    pub fn request(&self) -> Option<&Request> {
114        self.mounted.as_ref().map(|mounted| &mounted.request)
115    }
116
117    /// The url of the current history entry, see [`Nav::url`](crate::extract::Nav::url).
118    pub fn url(&self) -> Option<&str> {
119        self.mounted.as_ref().map(|mounted| mounted.url.as_str())
120    }
121
122    pub fn is_loading(&self) -> bool {
123        self.pending.is_some()
124    }
125
126    /// Navigates to `url`, adding a history entry. See [`Nav::goto`](crate::extract::Nav::goto).
127    pub fn goto(&mut self, url: &str) {
128        self.goto_with(url, GotoOptions::default());
129    }
130
131    /// See [`Nav::goto_with`](crate::extract::Nav::goto_with).
132    pub fn goto_with(&mut self, url: &str, options: GotoOptions) {
133        self.request_goto(url, options);
134    }
135
136    pub fn back(&mut self) {
137        self.history.back();
138    }
139
140    pub fn forward(&mut self) {
141        self.history.forward();
142    }
143
144    /// See [`Nav::invalidate`](crate::extract::Nav::invalidate); e.g. after data changed in the background.
145    pub fn invalidate(&mut self, key: impl Into<String>) {
146        self.reload(Invalidation::Keys(vec![key.into()]));
147    }
148
149    /// See [`Nav::invalidate_all`](crate::extract::Nav::invalidate_all).
150    pub fn invalidate_all(&mut self) {
151        self.reload(Invalidation::All);
152    }
153
154    /// See [`Nav::preload`](crate::extract::Nav::preload).
155    pub fn preload(&mut self, url: &str) {
156        let (entry, request) = self.table.resolve(url);
157        let url = request.untracked_url();
158        let busy = |job: &Job<S>| job.request.untracked_url() == url;
159        if self
160            .pending
161            .as_ref()
162            .is_some_and(|pending| busy(&pending.job))
163            || self.preloads.iter().any(busy)
164        {
165            return;
166        }
167        let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
168        let job = Job::start(entry, request, &self.state, &previous, &Invalidation::None);
169        if self.preloads.len() == MAX_PRELOADS {
170            self.preloads.remove(0);
171        }
172        self.preloads.push(job);
173    }
174
175    /// Shows the current page, wrapped in its layouts.
176    pub fn ui(&mut self, ui: &mut Ui) {
177        let ctx = ui.ctx().clone();
178
179        #[cfg(not(target_arch = "wasm32"))]
180        self.handle_back_forward_input(ui);
181        if let Some(entry) = self.history.poll(&ctx) {
182            self.traverse(entry);
183        }
184        self.poll(&ctx);
185
186        self.nav.can_go_back = self.history.can_go_back();
187        self.nav.can_go_forward = self.history.can_go_forward();
188        self.nav.blocked = self
189            .blocked
190            .as_ref()
191            .map(|blocked| blocked.navigation.clone());
192        let nav = RefCell::new(core::mem::take(&mut self.nav));
193        match &mut self.mounted {
194            Some(mounted) => {
195                render::render(ui, mounted, self.transition.as_mut(), &self.state, &nav);
196            }
197            None => {
198                ui.centered_and_justified(|ui| ui.spinner());
199            }
200        }
201        self.nav = nav.into_inner();
202        self.blocking = core::mem::take(&mut self.nav.blocking);
203        if let Some(transition) = &self.transition
204            && (transition.state.done.get() || !transition.state.claimed.get())
205        {
206            self.transition = None;
207        }
208
209        let actions = core::mem::take(&mut self.nav.actions);
210        if !actions.is_empty() {
211            for action in actions {
212                self.apply(action);
213            }
214            self.poll(&ctx);
215            ctx.request_repaint();
216        }
217    }
218
219    /// Mouse back/forward buttons and Alt+Left/Right. Browsers handle these themselves.
220    #[cfg(not(target_arch = "wasm32"))]
221    fn handle_back_forward_input(&mut self, ui: &Ui) {
222        use egui::{Key, Modifiers, PointerButton};
223
224        let (back, forward) = ui.input_mut(|i| {
225            let back = i.pointer.button_pressed(PointerButton::Extra1)
226                | i.consume_key(Modifiers::ALT, Key::ArrowLeft);
227            let forward = i.pointer.button_pressed(PointerButton::Extra2)
228                | i.consume_key(Modifiers::ALT, Key::ArrowRight);
229            (back, forward)
230        });
231        if back {
232            self.history.back();
233        }
234        if forward {
235            self.history.forward();
236        }
237    }
238
239    fn apply(&mut self, action: NavAction) {
240        match action {
241            NavAction::Goto(url, options) => self.request_goto(&url, options),
242            NavAction::Back => self.history.back(),
243            NavAction::Forward => self.history.forward(),
244            NavAction::Invalidate(invalidation) => self.reload(invalidation),
245            NavAction::Preload(url) => self.preload(&url),
246            NavAction::PushState(url, state) => self.shallow(url, state, true),
247            NavAction::ReplaceState(url, state) => self.shallow(url, state, false),
248            NavAction::ConfirmNavigation => self.confirm_blocked(),
249            NavAction::CancelNavigation => self.blocked = None,
250        }
251    }
252
253    /// Drives the preloads and the pending navigation; commits the latter when done. Loads that
254    /// complete synchronously are committed within the same frame, so they never flash a
255    /// loading state.
256    fn poll(&mut self, ctx: &egui::Context) {
257        for job in &mut self.preloads {
258            job.poll(ctx);
259        }
260        while let Some(pending) = &mut self.pending {
261            if !pending.job.poll(ctx) {
262                return;
263            }
264            let mut pending = self.pending.take().expect("checked above");
265            let outcome = pending.job.take_outcome().expect("the job is done");
266            self.nav.loading = None;
267            self.commit(pending, outcome);
268        }
269    }
270
271    /// Shallow routing: a history entry for the mounted page, without a navigation.
272    fn shallow(&mut self, url: String, state: Option<Rc<dyn Any>>, push: bool) {
273        let Some(mounted) = &mut self.mounted else {
274            return;
275        };
276        if !url.is_empty() {
277            mounted.url = url;
278        }
279        if push {
280            self.key = self.history.push(&mounted.url);
281        } else {
282            self.history.replace(&mounted.url);
283        }
284        self.shown_key = self.key;
285        mounted.history_state = state.clone();
286        self.session.record(self.key, mounted.id, state);
287    }
288
289    /// The history moved to `entry` (back/forward). Entries of the mounted page only swap the
290    /// page state; anything else is a regular navigation, unless the page blocks it.
291    fn traverse(&mut self, entry: HistoryEntry) {
292        if self.ignored_pops > 0 {
293            self.ignored_pops -= 1;
294            return;
295        }
296        let meta = self.session.get(entry.key);
297        if let (Some(mounted), Some(meta)) = (&mut self.mounted, meta)
298            && meta.page == mounted.id
299        {
300            self.pending = None;
301            self.nav.loading = None;
302            self.key = entry.key;
303            self.shown_key = entry.key;
304            mounted.url = entry.url;
305            mounted.history_state = meta.state.clone();
306            return;
307        }
308
309        let direction = self.session.direction(self.shown_key, entry.key);
310        if direction != Direction::None && self.should_block() {
311            // The history already moved: move it back, and redo the move once confirmed.
312            match direction {
313                Direction::Back => self.history.forward(),
314                _ => self.history.back(),
315            }
316            self.ignored_pops += 1;
317            self.block(Resume::Traverse(direction), entry.url, direction);
318            return;
319        }
320        self.key = entry.key;
321        self.navigate(&entry.url, NavKind::Silent, GotoOptions::default());
322    }
323
324    /// Reloads the mounted page with `invalidation`, after the pending navigation if any.
325    fn reload(&mut self, invalidation: Invalidation) {
326        self.preloads.clear();
327        if self.pending.is_some() {
328            self.deferred = core::mem::take(&mut self.deferred).merge(invalidation);
329            return;
330        }
331        if let Some(mounted) = &self.mounted {
332            let (url, id) = (mounted.request.untracked_url(), mounted.id);
333            self.start(
334                &url,
335                NavKind::Silent,
336                GotoOptions::default(),
337                0,
338                Some(id),
339                invalidation,
340            );
341        }
342    }
343}