Skip to main content

egui_kit/
history.rs

1//! Where the current url lives: in memory (native) or in the browser's address bar (wasm).
2
3#[cfg(target_arch = "wasm32")]
4mod browser;
5mod memory;
6
7#[cfg(target_arch = "wasm32")]
8pub use browser::{BrowserHistory, HistoryMode};
9pub use memory::MemoryHistory;
10
11/// Identifies one history entry, so the router can recognise entries it created
12/// (e.g. by [shallow routing](crate::extract::Nav::push_state)) when the user goes back or forward.
13///
14/// Keys must be unique among the entries of a history, including entries left over from an
15/// earlier session (a browser reload).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct EntryKey(pub u64);
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct HistoryEntry {
21    /// An app-relative url: a path plus optional query, e.g. `/blog?page=2`.
22    pub url: String,
23    pub key: EntryKey,
24}
25
26/// A session history the router keeps in sync with the current page.
27pub trait History {
28    /// The current entry. Used to pick the initial route.
29    fn current(&self) -> HistoryEntry;
30
31    /// Adds a new entry and returns its key.
32    fn push(&mut self, url: &str) -> EntryKey;
33
34    /// Changes the url of the current entry, keeping its key.
35    fn replace(&mut self, url: &str);
36
37    /// Moves one entry back. The resulting entry is reported through [`History::poll`].
38    fn back(&mut self);
39
40    /// Moves one entry forward. The resulting entry is reported through [`History::poll`].
41    fn forward(&mut self);
42
43    fn can_go_back(&self) -> bool;
44
45    fn can_go_forward(&self) -> bool;
46
47    /// Returns the entry the history moved to by itself since the last call (back/forward,
48    /// or the browser's buttons). Entries the history doesn't know (e.g. the user edited the
49    /// url's `#hash`) must be given a fresh key.
50    ///
51    /// `ctx` can be stored to request a repaint when such a change happens outside a frame.
52    fn poll(&mut self, ctx: &egui::Context) -> Option<HistoryEntry>;
53
54    /// Whether [`History::hover_link`] shows hovered links to the platform, which then also
55    /// opens them in a new tab on Ctrl/Cmd/Shift-click (so the router doesn't follow those).
56    fn shows_links(&self) -> bool {
57        false
58    }
59
60    /// Called after every frame with the url of the [link](crate::extract::Nav::link) under the
61    /// pointer, if any.
62    fn hover_link(&mut self, _url: Option<&str>) {}
63}
64
65/// A history chosen at runtime, e.g. a [`MemoryHistory`] in tests and the default one otherwise.
66///
67/// ```
68/// use egui_kit::{History, MemoryHistory, Router, default_history};
69///
70/// let history: Box<dyn History> = if cfg!(test) {
71///     Box::new(MemoryHistory::new("/settings"))
72/// } else {
73///     Box::new(default_history())
74/// };
75/// let app = Router::<()>::new().with_state_and_history((), history);
76/// ```
77impl<H: History + ?Sized> History for Box<H> {
78    fn current(&self) -> HistoryEntry {
79        (**self).current()
80    }
81
82    fn push(&mut self, url: &str) -> EntryKey {
83        (**self).push(url)
84    }
85
86    fn replace(&mut self, url: &str) {
87        (**self).replace(url);
88    }
89
90    fn back(&mut self) {
91        (**self).back();
92    }
93
94    fn forward(&mut self) {
95        (**self).forward();
96    }
97
98    fn can_go_back(&self) -> bool {
99        (**self).can_go_back()
100    }
101
102    fn can_go_forward(&self) -> bool {
103        (**self).can_go_forward()
104    }
105
106    fn poll(&mut self, ctx: &egui::Context) -> Option<HistoryEntry> {
107        (**self).poll(ctx)
108    }
109
110    fn shows_links(&self) -> bool {
111        (**self).shows_links()
112    }
113
114    fn hover_link(&mut self, url: Option<&str>) {
115        (**self).hover_link(url);
116    }
117}
118
119/// `BrowserHistory` on wasm, [`MemoryHistory`] starting at `/` elsewhere.
120pub fn default_history() -> impl History {
121    #[cfg(target_arch = "wasm32")]
122    {
123        BrowserHistory::new(HistoryMode::Path)
124    }
125    #[cfg(not(target_arch = "wasm32"))]
126    {
127        MemoryHistory::new("/")
128    }
129}