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    /// The title last set with `Nav::set_title`, and applied to the window.
60    title: Option<String>,
61    /// The user confirmed closing the window: close it after the frame.
62    close_confirmed: bool,
63    /// History moves made to undo a blocked back/forward, whose result we ignore.
64    ignored_pops: usize,
65
66    after_navigate: Vec<AfterNavigate<S>>,
67}
68
69impl<S: Clone + 'static> RouterApp<S> {
70    pub(crate) fn new(table: RouteTable<S>, state: S, history: Box<dyn History>) -> Self {
71        let initial = history.current();
72        let mut app = Self {
73            table,
74            state,
75            history,
76            session: Session::default(),
77            nav: NavState {
78                preload_on_hover: true,
79                ..NavState::default()
80            },
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            title: None,
93            close_confirmed: false,
94            ignored_pops: 0,
95            after_navigate: Vec::new(),
96        };
97        app.navigate(&initial.url, NavKind::Silent, GotoOptions::default());
98        app
99    }
100
101    /// Whether [`Nav::link`](crate::extract::Nav::link) preloads its target while hovered. On by default.
102    pub fn preload_on_hover(mut self, enabled: bool) -> Self {
103        self.nav.preload_on_hover = enabled;
104        self
105    }
106
107    /// Calls `callback` after every navigation, once the new page is mounted, e.g. for
108    /// analytics or focus management. Not called for invalidations.
109    pub fn after_navigate(mut self, callback: impl Fn(&Navigation, &S) + 'static) -> Self {
110        self.after_navigate.push(Box::new(callback));
111        self
112    }
113
114    pub fn state(&self) -> &S {
115        &self.state
116    }
117
118    /// The pattern of the page route that `url` matches, e.g. `/blog/{slug}`, or `None` if it
119    /// matches none (a 404). Doesn't navigate or run anything: e.g. to check in a test that
120    /// every address the app builds leads to a page.
121    ///
122    /// A match can still fail to load, e.g. with a [`Path`](crate::extract::Path) that doesn't
123    /// parse.
124    ///
125    /// ```
126    /// # use egui_kit::{MemoryHistory, Router};
127    /// # use egui_kit::page::Page;
128    /// let app = Router::<()>::new()
129    ///     .page("/blog/{slug}", Page::new(|_: &mut egui::Ui| {}))
130    ///     .with_state_and_history((), MemoryHistory::new("/"));
131    /// assert_eq!(app.matches("/blog/hello?draft"), Some("/blog/{slug}"));
132    /// assert_eq!(app.matches("/blog"), None);
133    /// ```
134    pub fn matches(&self, url: &str) -> Option<&str> {
135        self.table.page_route(url)
136    }
137
138    /// The request of the page on screen.
139    pub fn request(&self) -> Option<&Request> {
140        self.mounted.as_ref().map(|mounted| &mounted.request)
141    }
142
143    /// The url of the current history entry, see [`Nav::url`](crate::extract::Nav::url).
144    pub fn url(&self) -> Option<&str> {
145        self.mounted.as_ref().map(|mounted| mounted.url.as_str())
146    }
147
148    /// The title the views set with [`Nav::set_title`](crate::extract::Nav::set_title), as
149    /// applied to the browser tab or window.
150    pub fn title(&self) -> Option<&str> {
151        self.title.as_deref()
152    }
153
154    pub fn is_loading(&self) -> bool {
155        self.pending.is_some()
156    }
157
158    /// Navigates to `url`, adding a history entry. Going to the current url does nothing, unless
159    /// [`GotoOptions::invalidate_all`] asks for a reload. See
160    /// [`Nav::goto`](crate::extract::Nav::goto).
161    pub fn goto(&mut self, url: &str) {
162        self.goto_with(url, GotoOptions::default());
163    }
164
165    /// See [`Nav::goto_with`](crate::extract::Nav::goto_with).
166    pub fn goto_with(&mut self, url: &str, options: GotoOptions) {
167        self.request_goto(url, options);
168    }
169
170    pub fn back(&mut self) {
171        self.history.back();
172    }
173
174    pub fn forward(&mut self) {
175        self.history.forward();
176    }
177
178    /// See [`Nav::invalidate`](crate::extract::Nav::invalidate); e.g. after data changed in the background.
179    pub fn invalidate(&mut self, key: impl Into<String>) {
180        self.invalidate_with(Invalidation::Keys(vec![key.into()]));
181    }
182
183    /// See [`Nav::invalidate_all`](crate::extract::Nav::invalidate_all).
184    pub fn invalidate_all(&mut self) {
185        self.invalidate_with(Invalidation::All);
186    }
187
188    /// See [`Nav::preload`](crate::extract::Nav::preload).
189    pub fn preload(&mut self, url: &str) {
190        let (entry, request) = self.table.resolve(url);
191        let url = request.untracked_url();
192        let busy = |job: &Job<S>| job.request.untracked_url() == url;
193        if self
194            .pending
195            .as_ref()
196            .is_some_and(|pending| busy(&pending.job))
197            || self.preloads.iter().any(busy)
198        {
199            return;
200        }
201        let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
202        let job = Job::start(entry, request, &self.state, &previous, &Invalidation::None);
203        if self.preloads.len() == MAX_PRELOADS {
204            self.preloads.remove(0);
205        }
206        self.preloads.push(job);
207    }
208
209    /// Shows the current page, wrapped in its layouts.
210    pub fn ui(&mut self, ui: &mut Ui) {
211        let ctx = ui.ctx().clone();
212        #[cfg(feature = "remote")]
213        let _runtime = crate::remote::enter();
214        #[cfg(feature = "remote")]
215        crate::remote::set_context(&ctx);
216
217        #[cfg(not(target_arch = "wasm32"))]
218        self.handle_back_forward_input(ui);
219        #[cfg(not(target_arch = "wasm32"))]
220        self.handle_close_request(&ctx);
221        if let Some(entry) = self.history.poll(&ctx) {
222            self.traverse(entry);
223        }
224        self.poll(&ctx);
225
226        self.nav.shows_links = self.history.shows_links();
227        self.nav.can_go_back = self.history.can_go_back();
228        self.nav.can_go_forward = self.history.can_go_forward();
229        self.nav.blocked = self
230            .blocked
231            .as_ref()
232            .map(|blocked| blocked.navigation.clone());
233        let nav = RefCell::new(core::mem::take(&mut self.nav));
234        match &mut self.mounted {
235            Some(mounted) => {
236                render::render(ui, mounted, self.transition.as_mut(), &self.state, &nav);
237            }
238            None => {
239                ui.centered_and_justified(|ui| ui.spinner());
240            }
241        }
242        self.nav = nav.into_inner();
243        let was_blocking = self.blocking;
244        self.blocking = core::mem::take(&mut self.nav.blocking);
245        if self.blocking != was_blocking {
246            self.history.set_blocking(self.blocking);
247        }
248        if let Some((_, title)) = self.nav.title.take()
249            && self.title.as_ref() != Some(&title)
250        {
251            set_title(&ctx, &title);
252            self.title = Some(title);
253        }
254        let hovered_link = self.nav.hovered_link.take();
255        // Changing the link mid-click or mid-drag would disturb it.
256        if !ctx.input(|i| i.pointer.any_down()) {
257            self.history.hover_link(hovered_link.as_deref());
258        }
259        if let Some(transition) = &self.transition
260            && (transition.state.done.get() || !transition.state.claimed.get())
261        {
262            self.transition = None;
263        }
264
265        #[cfg(feature = "remote")]
266        crate::remote::end_frame();
267
268        let actions = core::mem::take(&mut self.nav.actions);
269        if !actions.is_empty() {
270            for action in actions {
271                self.apply(action);
272            }
273            ctx.request_repaint();
274        }
275        if core::mem::take(&mut self.close_confirmed) {
276            ctx.send_viewport_cmd(egui::ViewportCommand::Close);
277        }
278        self.poll(&ctx);
279    }
280
281    /// Mouse back/forward buttons and Alt+Left/Right. Browsers handle these themselves.
282    #[cfg(not(target_arch = "wasm32"))]
283    fn handle_back_forward_input(&mut self, ui: &Ui) {
284        use egui::{Key, Modifiers, PointerButton};
285
286        let (back, forward) = ui.input_mut(|i| {
287            let back = i.pointer.button_pressed(PointerButton::Extra1)
288                | i.consume_key(Modifiers::ALT, Key::ArrowLeft);
289            let forward = i.pointer.button_pressed(PointerButton::Extra2)
290                | i.consume_key(Modifiers::ALT, Key::ArrowRight);
291            (back, forward)
292        });
293        if back {
294            self.history.back();
295        }
296        if forward {
297            self.history.forward();
298        }
299    }
300
301    /// Holds back closing the window while the page blocks navigation, as a navigation of kind
302    /// [`Leave`](crate::NavigationKind::Leave). Browsers ask the user themselves.
303    #[cfg(not(target_arch = "wasm32"))]
304    fn handle_close_request(&mut self, ctx: &egui::Context) {
305        if ctx.input(|i| i.viewport().close_requested()) && self.should_block() {
306            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
307            self.block(Resume::Close, String::new(), Direction::None);
308        }
309    }
310
311    fn apply(&mut self, action: NavAction) {
312        match action {
313            NavAction::Goto(url, options) => self.request_goto(&url, options),
314            NavAction::Back => self.history.back(),
315            NavAction::Forward => self.history.forward(),
316            NavAction::Invalidate(invalidation) => self.invalidate_with(invalidation),
317            NavAction::Preload(url) => self.preload(&url),
318            NavAction::PushState(url, state) => self.shallow(url, state, true),
319            NavAction::ReplaceState(url, state) => self.shallow(url, state, false),
320            NavAction::ReplaceUrl(url) => {
321                let state = self.mounted.as_ref().and_then(|m| m.history_state.clone());
322                self.shallow(url, state, false);
323            }
324            NavAction::ConfirmNavigation => self.confirm_blocked(),
325            NavAction::CancelNavigation => self.blocked = None,
326        }
327    }
328
329    /// Applies the invalidations of commands, drives the preloads and the pending navigation;
330    /// commits the latter when done. Loads that complete synchronously are committed within the
331    /// same frame, so they never flash a loading state.
332    fn poll(&mut self, ctx: &egui::Context) {
333        #[cfg(feature = "remote")]
334        {
335            let invalidated = crate::remote::take_invalidated();
336            if !invalidated.is_empty() {
337                self.invalidate_with(Invalidation::Keys(invalidated));
338                ctx.request_repaint();
339            }
340        }
341        for job in &mut self.preloads {
342            job.poll(ctx);
343        }
344        while let Some(pending) = &mut self.pending {
345            if !pending.job.poll(ctx) {
346                return;
347            }
348            let mut pending = self.pending.take().expect("checked above");
349            let outcome = pending.job.take_outcome().expect("the job is done");
350            self.nav.loading = None;
351            self.commit(pending, outcome);
352        }
353    }
354
355    /// Shallow routing: a history entry for the mounted page, without a navigation.
356    fn shallow(&mut self, url: String, state: Option<Rc<dyn Any>>, push: bool) {
357        let Some(mounted) = &mut self.mounted else {
358            return;
359        };
360        if !url.is_empty() {
361            mounted.url = url;
362        }
363        if push {
364            self.key = self.history.push(&mounted.url);
365        } else {
366            self.history.replace(&mounted.url);
367        }
368        self.shown_key = self.key;
369        mounted.history_state = state.clone();
370        self.session.record(self.key, mounted.id, state);
371    }
372
373    /// The history moved to `entry` (back/forward). Entries of the mounted page only swap the
374    /// page state; anything else is a regular navigation, unless the page blocks it.
375    fn traverse(&mut self, entry: HistoryEntry) {
376        if self.ignored_pops > 0 {
377            self.ignored_pops -= 1;
378            return;
379        }
380        if let Some(mounted) = &mut self.mounted {
381            let state = match self.session.get(entry.key) {
382                Some(meta) if meta.page == mounted.id => Some(meta.state.clone()),
383                Some(_) => None,
384                // A new entry for the page's url, e.g. the user edited its `#hash`: adopt it.
385                None => (Request::new(&entry.url).untracked_url()
386                    == Request::new(&mounted.url).untracked_url())
387                .then(|| {
388                    self.session.record(entry.key, mounted.id, None);
389                    None
390                }),
391            };
392            if let Some(state) = state {
393                self.pending = None;
394                self.nav.loading = None;
395                self.key = entry.key;
396                self.shown_key = entry.key;
397                mounted.url = entry.url;
398                mounted.history_state = state;
399                return;
400            }
401        }
402
403        let direction = self.session.direction(self.shown_key, entry.key);
404        if direction != Direction::None && self.should_block() {
405            // The history already moved: move it back, and redo the move once confirmed.
406            match direction {
407                Direction::Back => self.history.forward(),
408                _ => self.history.back(),
409            }
410            self.ignored_pops += 1;
411            self.block(Resume::Traverse(direction), entry.url, direction);
412            return;
413        }
414        self.key = entry.key;
415        self.navigate(&entry.url, NavKind::Silent, GotoOptions::default());
416    }
417
418    /// Reruns the loads and queries that `invalidation` hits.
419    fn invalidate_with(&mut self, invalidation: Invalidation) {
420        #[cfg(feature = "remote")]
421        crate::remote::invalidate_queries(&invalidation);
422        self.reload(invalidation);
423    }
424
425    /// Reloads the mounted page with `invalidation`, after the pending navigation if any.
426    fn reload(&mut self, invalidation: Invalidation) {
427        self.preloads.clear();
428        if self.pending.is_some() {
429            self.deferred = core::mem::take(&mut self.deferred).merge(invalidation);
430            return;
431        }
432        if let Some(mounted) = &self.mounted {
433            let (url, id) = (mounted.request.untracked_url(), mounted.id);
434            self.start(
435                &url,
436                NavKind::Silent,
437                GotoOptions::default(),
438                0,
439                Some(id),
440                invalidation,
441            );
442        }
443    }
444}
445
446/// Shows `title` in the browser tab, or natively in the window's title bar.
447fn set_title(ctx: &egui::Context, title: &str) {
448    #[cfg(target_arch = "wasm32")]
449    {
450        let _ = ctx;
451        if let Some(document) = web_sys::window().and_then(|window| window.document()) {
452            document.set_title(title);
453        }
454    }
455    #[cfg(not(target_arch = "wasm32"))]
456    ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.to_owned()));
457}