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
55/// `BrowserHistory` on wasm, [`MemoryHistory`] starting at `/` elsewhere.
56pub fn default_history() -> impl History {
57 #[cfg(target_arch = "wasm32")]
58 {
59 BrowserHistory::new(HistoryMode::Path)
60 }
61 #[cfg(not(target_arch = "wasm32"))]
62 {
63 MemoryHistory::new("/")
64 }
65}