Skip to main content

cranpose_services/
browser_history.rs

1//! The browser's session history, as a page sees it: the URL fragment of the
2//! current entry, a number the app keeps in each entry it adds, and the
3//! user's moves through the entries with Back and Forward.
4//!
5//! The web host installs it; elsewhere [`browser_history`] is `None`. A
6//! navigation host keeps the history in step with its back stack.
7
8use std::rc::Rc;
9
10/// Session history of the page.
11pub trait BrowserHistory {
12    /// The URL fragment of the current entry, without the leading `#`.
13    fn fragment(&self) -> String;
14
15    /// The number this app keeps in the current entry, or `None` for an entry
16    /// it did not add, such as the page's first one or a fragment the user
17    /// typed.
18    fn depth(&self) -> Option<usize>;
19
20    /// Adds an entry after the current one, which becomes current, keeping
21    /// `depth` in it and showing `fragment` in the address bar.
22    fn push(&self, depth: usize, fragment: &str);
23
24    /// Replaces the current entry's number and fragment.
25    fn replace(&self, depth: usize, fragment: &str);
26
27    /// Moves `delta` entries back (negative) or forward, as the browser's own
28    /// buttons do. The move ends in an `on_move` call of [`Self::observe`].
29    fn go(&self, delta: isize);
30
31    /// Calls `on_move` each time the current entry changes by a move through
32    /// the history, until the observer is dropped.
33    fn observe(&self, on_move: Rc<dyn Fn()>) -> BrowserHistoryObserver;
34}
35
36/// Shared handle to a [`BrowserHistory`].
37pub type BrowserHistoryRef = Rc<dyn BrowserHistory>;
38
39/// Ends an observation of [`BrowserHistory::observe`] when dropped.
40pub struct BrowserHistoryObserver {
41    _stop: Option<Box<dyn std::any::Any>>,
42}
43
44impl BrowserHistoryObserver {
45    /// An observer whose `stop` value ends the observation when it drops.
46    pub fn new(stop: impl std::any::Any) -> Self {
47        Self {
48            _stop: Some(Box::new(stop)),
49        }
50    }
51}
52
53/// Installs the page's history, replacing any previously installed one.
54pub fn set_platform_browser_history(history: BrowserHistoryRef) {
55    crate::thread_state::with(|state| *state.browser_history.borrow_mut() = Some(history));
56}
57
58/// Removes the installed history (tests and teardown).
59pub fn clear_platform_browser_history() {
60    crate::thread_state::with(|state| *state.browser_history.borrow_mut() = None);
61}
62
63/// The page's session history, or `None` outside a browser.
64pub fn browser_history() -> Option<BrowserHistoryRef> {
65    crate::thread_state::with(|state| state.browser_history.borrow().clone())
66}