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