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