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