Skip to main content

xrack_runtime/
stack.rs

1use crate::Property;
2use std::{
3    cell::Cell,
4    sync::{
5        Arc,
6        atomic::{AtomicU64, Ordering},
7    },
8};
9
10static NEXT_REVISION: AtomicU64 = AtomicU64::new(1);
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum StackNavigation<'a> {
14    Push(&'a str),
15    Pop,
16    Replace(&'a str),
17    PopTo(&'a str),
18    Reset(&'a str),
19    PushPages(&'a [String]),
20    ResetTo(&'a [String]),
21}
22
23#[derive(Debug, PartialEq, Eq)]
24pub struct StackSnapshot {
25    routes: Vec<&'static str>,
26    revision: u64,
27}
28
29impl StackSnapshot {
30    fn new(routes: Vec<&'static str>) -> Self {
31        let revision = NEXT_REVISION
32            .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
33                value.checked_add(1)
34            })
35            .expect("navigation revision exhausted");
36        Self { routes, revision }
37    }
38
39    pub fn routes(&self) -> &[&'static str] {
40        &self.routes
41    }
42
43    pub fn current(&self) -> Option<&'static str> {
44        self.routes.last().copied()
45    }
46
47    pub fn depth(&self) -> usize {
48        self.routes.len()
49    }
50
51    pub fn revision(&self) -> u64 {
52        self.revision
53    }
54}
55
56#[derive(Default)]
57#[doc(hidden)]
58pub struct StackState {
59    snapshot: Property<Arc<StackSnapshot>>,
60    notifying: Cell<bool>,
61}
62
63struct NavigationGuard<'a>(&'a Cell<bool>);
64
65impl Drop for NavigationGuard<'_> {
66    fn drop(&mut self) {
67        self.0.set(false);
68    }
69}
70
71impl StackState {
72    pub fn snapshot(
73        &self,
74        pages: &[&'static str],
75        initial: impl FnOnce() -> String,
76    ) -> Arc<StackSnapshot> {
77        self.snapshot.get(|| {
78            let initial = initial();
79            let route = pages
80                .iter()
81                .copied()
82                .find(|&page| page == initial)
83                .or_else(|| pages.first().copied());
84            Arc::new(StackSnapshot::new(route.into_iter().collect()))
85        })
86    }
87
88    pub fn navigate(
89        &self,
90        pages: &[&'static str],
91        initial: impl FnOnce() -> String,
92        expected: Option<u64>,
93        action: StackNavigation<'_>,
94        changed: impl FnOnce(&StackSnapshot),
95    ) -> bool {
96        if self.notifying.replace(true) {
97            return false;
98        }
99        let _guard = NavigationGuard(&self.notifying);
100        let current = self.snapshot(pages, initial);
101        if expected.is_some_and(|revision| revision != current.revision()) {
102            return false;
103        }
104        let resolve = |route| pages.iter().copied().find(|&page| page == route);
105        let mut routes = current.routes.clone();
106        match action {
107            StackNavigation::Push(route) | StackNavigation::Replace(route) => {
108                let Some(page) = resolve(route).filter(|page| !routes.contains(page)) else {
109                    return false;
110                };
111                if matches!(action, StackNavigation::Replace(_)) {
112                    routes.pop();
113                }
114                routes.push(page);
115            }
116            StackNavigation::Pop if routes.len() > 1 => {
117                routes.pop();
118            }
119            StackNavigation::Pop => return false,
120            StackNavigation::PopTo(route) => {
121                let Some(index) = routes.iter().position(|&page| page == route) else {
122                    return false;
123                };
124                routes.truncate(index + 1);
125            }
126            StackNavigation::Reset(route) => {
127                let Some(page) = resolve(route) else {
128                    return false;
129                };
130                routes.clear();
131                routes.push(page);
132            }
133            StackNavigation::PushPages(path) | StackNavigation::ResetTo(path) => {
134                if path.is_empty() {
135                    return false;
136                }
137                if matches!(action, StackNavigation::ResetTo(_)) {
138                    routes.clear();
139                }
140                for route in path {
141                    let Some(page) = resolve(route.as_str()).filter(|page| !routes.contains(page))
142                    else {
143                        return false;
144                    };
145                    routes.push(page);
146                }
147            }
148        }
149        if routes == current.routes {
150            return false;
151        }
152        let next = Arc::new(StackSnapshot::new(routes));
153        self.snapshot.set(next.clone());
154        changed(&next);
155        true
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn navigation_rejects_stale_actions_and_reentrant_notifications() {
165        let stack = StackState::default();
166        let pages = ["home", "detail", "preview"];
167        let initial = || "home".to_owned();
168        let initial_revision = stack.snapshot(&pages, initial).revision();
169        let calls = Cell::new(0);
170        assert!(stack.navigate(
171            &pages,
172            initial,
173            Some(initial_revision),
174            StackNavigation::Push("detail"),
175            |snapshot| {
176                assert_eq!(snapshot.routes(), ["home", "detail"]);
177                calls.set(calls.get() + 1);
178                assert!(!stack.navigate(
179                    &pages,
180                    initial,
181                    None,
182                    StackNavigation::Pop,
183                    |_| unreachable!(),
184                ));
185            },
186        ));
187        assert!(!stack.navigate(
188            &pages,
189            initial,
190            Some(initial_revision),
191            StackNavigation::Pop,
192            |_| unreachable!(),
193        ));
194        assert!(!stack.navigate(
195            &pages,
196            initial,
197            None,
198            StackNavigation::Push("home"),
199            |_| unreachable!(),
200        ));
201        assert!(stack.navigate(
202            &pages,
203            initial,
204            None,
205            StackNavigation::Replace("preview"),
206            |_| calls.set(calls.get() + 1),
207        ));
208        assert_eq!(
209            stack.snapshot(&pages, initial).routes(),
210            ["home", "preview"]
211        );
212        assert_eq!(calls.get(), 2);
213    }
214
215    #[test]
216    fn navigation_paths_commit_atomically_and_notify_once() {
217        let stack = StackState::default();
218        let pages = ["home", "detail", "preview", "summary"];
219        let initial = || "home".to_owned();
220        let before = stack.snapshot(&pages, initial);
221        let bad = ["detail", "missing"].map(str::to_owned);
222        assert!(!stack.navigate(
223            &pages,
224            initial,
225            None,
226            StackNavigation::PushPages(&bad),
227            |_| unreachable!()
228        ));
229        let duplicate = ["detail", "home", "detail"].map(str::to_owned);
230        assert!(!stack.navigate(
231            &pages,
232            initial,
233            None,
234            StackNavigation::ResetTo(&duplicate),
235            |_| unreachable!()
236        ));
237        assert!(Arc::ptr_eq(&before, &stack.snapshot(&pages, initial)));
238
239        let calls = Cell::new(0);
240        let path = ["detail", "preview"].map(str::to_owned);
241        assert!(stack.navigate(
242            &pages,
243            initial,
244            None,
245            StackNavigation::PushPages(&path),
246            |next| {
247                assert_eq!(next.routes(), ["home", "detail", "preview"]);
248                calls.set(calls.get() + 1);
249            }
250        ));
251        let reset = ["home", "summary"].map(str::to_owned);
252        assert!(stack.navigate(
253            &pages,
254            initial,
255            None,
256            StackNavigation::ResetTo(&reset),
257            |next| {
258                assert_eq!(next.routes(), ["home", "summary"]);
259                calls.set(calls.get() + 1);
260            }
261        ));
262        assert_eq!(calls.get(), 2);
263    }
264}