Skip to main content

egui_kit/extract/
nav.rs

1//! [`Nav`]: the views' handle to the router.
2
3use core::any::Any;
4use std::rc::Rc;
5
6use egui::{Response, Ui};
7
8use super::FromView;
9use crate::load::Invalidation;
10use crate::navigation::{GotoOptions, Navigation};
11use crate::page::{Frame, ViewContext};
12
13/// Requests from views, applied after the frame.
14pub(crate) enum NavAction {
15    Goto(String, GotoOptions),
16    Back,
17    Forward,
18    Invalidate(Invalidation),
19    Preload(String),
20    /// Shallow routing: a new or replaced history entry without a navigation.
21    PushState(String, Option<Rc<dyn Any>>),
22    ReplaceState(String, Option<Rc<dyn Any>>),
23    /// Shallow routing that keeps the entry's state.
24    ReplaceUrl(String),
25    ConfirmNavigation,
26    CancelNavigation,
27}
28
29/// Router state shared with the views during a frame.
30#[derive(Default)]
31pub(crate) struct NavState {
32    pub(crate) actions: Vec<NavAction>,
33    pub(crate) loading: Option<String>,
34    pub(crate) can_go_back: bool,
35    pub(crate) can_go_forward: bool,
36    pub(crate) preload_on_hover: bool,
37    /// Whether the history shows hovered links (and opens modified clicks) itself.
38    pub(crate) shows_links: bool,
39    /// The link under the pointer, set during the frame.
40    pub(crate) hovered_link: Option<String>,
41    /// Set by [`Nav::block_navigation`] during the frame.
42    pub(crate) blocking: bool,
43    pub(crate) blocked: Option<Navigation>,
44}
45
46/// The router, as seen by a view: navigating, loading, shallow routing and blocking.
47///
48/// An extractor: add a `nav: Nav` argument to any view. It is `Copy`, so it can be used in
49/// nested closures. Requests are queued and applied after the frame.
50#[derive(Clone, Copy)]
51pub struct Nav<'f> {
52    pub(crate) frame: &'f Frame<'f>,
53}
54
55impl<S: 'static, D> FromView<S, D> for Nav<'_> {
56    type Item<'f> = Nav<'f>;
57
58    fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> Nav<'f> {
59        cx.nav()
60    }
61}
62
63impl Nav<'_> {
64    fn push(&self, action: NavAction) {
65        self.frame.nav.borrow_mut().actions.push(action);
66    }
67}
68
69/// Where we are.
70impl<'f> Nav<'f> {
71    /// The url of the current history entry. Differs from the page's
72    /// [`Request`](crate::Request) after [`Nav::push_state`] / [`Nav::replace_state`] with a
73    /// new url.
74    pub fn url(&self) -> &'f str {
75        self.frame.url
76    }
77
78    /// Whether `href` is the current path, or (for anything but `/`) a parent of it. The path
79    /// is [`Nav::url`]'s, so it follows shallow routing.
80    pub fn is_active(&self, href: &str) -> bool {
81        let path = |url: &str| crate::router::normalize(url.split('?').next().unwrap_or_default());
82        let (href, path) = (path(href), path(self.frame.url));
83        path == href
84            || (href != "/" && path.starts_with(&href) && path[href.len()..].starts_with('/'))
85    }
86
87    /// Whether this is the previous page, rendered while a [`ViewTransition`](crate::ViewTransition)
88    /// animates it out. Its `Ui` is disabled (without looking so), and its navigation calls are
89    /// ignored. Skip things that live outside the page's `Ui` (windows, modals, popups), which
90    /// the transition can't fade, clip or disable.
91    pub fn is_outgoing(&self) -> bool {
92        self.frame.outgoing
93    }
94}
95
96/// Navigating.
97impl Nav<'_> {
98    /// Navigates to `url`, adding a history entry.
99    ///
100    /// The current page stays visible until all hooks and `load` handlers of the new route finished.
101    /// Going to the current url does nothing (the page keeps its state), unless
102    /// [`GotoOptions::invalidate_all`] asks for a reload. Going to the url that is already
103    /// loading, with the same options, keeps that navigation going, so a view may ask for it
104    /// every frame until it is done.
105    pub fn goto(&self, url: impl Into<String>) {
106        self.goto_with(url, GotoOptions::default());
107    }
108
109    /// [`Nav::goto`] with options.
110    pub fn goto_with(&self, url: impl Into<String>, options: GotoOptions) {
111        self.push(NavAction::Goto(url.into(), options));
112    }
113
114    /// Navigates to `url`, replacing the current history entry. Like [`Nav::goto`], going to the
115    /// current url does nothing, unless [`GotoOptions::invalidate_all`] asks for a reload.
116    pub fn replace(&self, url: impl Into<String>) {
117        self.goto_with(url, GotoOptions::default().replace_state());
118    }
119
120    pub fn back(&self) {
121        self.push(NavAction::Back);
122    }
123
124    pub fn forward(&self) {
125        self.push(NavAction::Forward);
126    }
127
128    pub fn can_go_back(&self) -> bool {
129        self.frame.nav.borrow().can_go_back
130    }
131
132    pub fn can_go_forward(&self) -> bool {
133        self.frame.nav.borrow().can_go_forward
134    }
135
136    /// A hyperlink that navigates within the app. Preloads the target while hovered,
137    /// unless [disabled](crate::RouterApp::preload_on_hover).
138    pub fn link(&self, ui: &mut Ui, text: impl Into<egui::WidgetText>, href: &str) -> Response {
139        let mut response = ui.link(text);
140        // The browser shows the url itself.
141        if !self.frame.nav.borrow().shows_links {
142            response = response.on_hover_text(href);
143        }
144        self.follow(&response, href);
145        response
146    }
147
148    /// A selectable label that is highlighted when `href` [is active](Self::is_active).
149    pub fn nav_link(&self, ui: &mut Ui, text: impl Into<egui::WidgetText>, href: &str) -> Response {
150        let response = ui.selectable_label(self.is_active(href), text);
151        self.follow(&response, href);
152        response
153    }
154
155    /// Makes any widget behave like a [link](Self::link) to `href`: a click navigates there,
156    /// hovering preloads it and lets the browser show it (see `BrowserHistory::link_preview`),
157    /// which then also opens Ctrl/Cmd/Shift-clicks in a new tab.
158    ///
159    /// ```
160    /// # use egui_kit::extract::Nav;
161    /// fn card(ui: &mut egui::Ui, nav: Nav, title: &str, href: &str) {
162    ///     let response = egui::Frame::group(ui.style())
163    ///         .show(ui, |ui| ui.heading(title))
164    ///         .response
165    ///         .interact(egui::Sense::click());
166    ///     nav.follow(&response, href);
167    /// }
168    /// ```
169    pub fn follow(&self, response: &Response, href: &str) {
170        if response.hovered() && !self.frame.outgoing {
171            self.frame.nav.borrow_mut().hovered_link = Some(href.to_owned());
172        }
173        if response.clicked() {
174            // The browser opens Ctrl/Cmd/Shift-clicked links in a new tab or window.
175            let modified = response
176                .ctx
177                .input(|i| i.modifiers.ctrl || i.modifiers.command || i.modifiers.shift);
178            if !(modified && self.frame.nav.borrow().shows_links) {
179                self.goto(href);
180            }
181        } else if response.hovered() && self.frame.nav.borrow().preload_on_hover {
182            self.preload(href);
183        }
184    }
185}
186
187/// Loading.
188impl Nav<'_> {
189    /// Whether a navigation is in progress.
190    pub fn is_loading(&self) -> bool {
191        self.frame.nav.borrow().loading.is_some()
192    }
193
194    /// The url currently being loaded, if any.
195    pub fn loading_url(&self) -> Option<String> {
196        self.frame.nav.borrow().loading.clone()
197    }
198
199    /// Starts loading `url` (hooks and loads) in the background, so that navigating there is
200    /// instant. Preloads are dropped once any navigation finishes.
201    pub fn preload(&self, url: impl Into<String>) {
202        self.push(NavAction::Preload(url.into()));
203    }
204
205    /// Reruns the loads of the current page that [depend](crate::page::Page::depends) on `key`, and
206    /// the loads below them that use [`Parent`](crate::extract::Parent). Queries that depend on
207    /// it refetch too.
208    pub fn invalidate(&self, key: impl Into<String>) {
209        self.push(NavAction::Invalidate(Invalidation::Keys(vec![key.into()])));
210    }
211
212    /// Reruns all loads of the current page, and refetches all queries.
213    pub fn invalidate_all(&self) {
214        self.push(NavAction::Invalidate(Invalidation::All));
215    }
216}
217
218/// Shallow routing.
219impl Nav<'_> {
220    /// Adds a history entry with `url` (`""` keeps the current url) and attaches `state` to it,
221    /// without running hooks or loads. The page stays as it is and can read the state with the
222    /// [`HistoryState`](super::HistoryState) extractor.
223    ///
224    /// Going back and forward between entries of the same page only swaps the page state.
225    /// Entries of a page that is no longer shown are loaded normally, and get their state back.
226    /// A browser reload loses all page state, so `url` should also work on its own, e.g. for a
227    /// photo opened in a modal, the photo's own page.
228    pub fn push_state<T: Any>(&self, url: impl Into<String>, state: T) {
229        self.push(NavAction::PushState(url.into(), Some(Rc::new(state))));
230    }
231
232    /// Like [`Nav::push_state`], but replaces the state (and url) of the current entry.
233    pub fn replace_state<T: Any>(&self, url: impl Into<String>, state: T) {
234        self.push(NavAction::ReplaceState(url.into(), Some(Rc::new(state))));
235    }
236
237    /// Changes the url of the current entry, keeping its state: to keep the address in step with
238    /// the page (another day in a calendar, another tab) without a navigation. Like
239    /// [`Nav::replace_state`], the url should also work on its own.
240    pub fn replace_url(&self, url: impl Into<String>) {
241        self.push(NavAction::ReplaceUrl(url.into()));
242    }
243
244    /// Removes the state of the current entry, keeping its url.
245    pub fn clear_history_state(&self) {
246        self.push(NavAction::ReplaceState(String::new(), None));
247    }
248}
249
250/// Blocking navigation.
251impl Nav<'_> {
252    /// Call every frame while leaving the page would lose something (e.g. unsaved changes).
253    /// Navigations away from the page (links, `goto`, back/forward) are then held back until
254    /// you [confirm](Self::confirm_navigation) or [cancel](Self::cancel_navigation) them;
255    /// see [`Nav::blocked_navigation`]. Shallow routing and invalidation are not affected.
256    ///
257    /// Closing the browser tab or reloading it can't be blocked this way.
258    pub fn block_navigation(&self) {
259        self.frame.nav.borrow_mut().blocking = true;
260    }
261
262    /// The navigation being held back, to ask the user what to do.
263    pub fn blocked_navigation(&self) -> Option<Navigation> {
264        self.frame.nav.borrow().blocked.clone()
265    }
266
267    /// Lets the [blocked navigation](Self::blocked_navigation) happen.
268    pub fn confirm_navigation(&self) {
269        self.push(NavAction::ConfirmNavigation);
270    }
271
272    /// Drops the [blocked navigation](Self::blocked_navigation).
273    pub fn cancel_navigation(&self) {
274        self.push(NavAction::CancelNavigation);
275    }
276}