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/// `BrowserHistory` on wasm, [`MemoryHistory`] starting at `/` elsewhere.
66pub fn default_history() -> impl History {
67    #[cfg(target_arch = "wasm32")]
68    {
69        BrowserHistory::new(HistoryMode::Path)
70    }
71    #[cfg(not(target_arch = "wasm32"))]
72    {
73        MemoryHistory::new("/")
74    }
75}