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 index_of(&self, route: &str) -> Option<usize> {
48 self.routes.iter().position(|page| *page == route)
49 }
50
51 pub fn depth(&self) -> usize {
52 self.routes.len()
53 }
54
55 pub fn revision(&self) -> u64 {
56 self.revision
57 }
58}
59
60#[doc(hidden)]
62pub struct StackChange<'a> {
63 pub before: &'a StackSnapshot,
64 pub after: &'a StackSnapshot,
65}
66
67impl StackChange<'_> {
68 pub fn deactivated(&self) -> Option<&'static str> {
69 self.before
70 .current()
71 .filter(|page| Some(*page) != self.after.current())
72 }
73
74 pub fn activated(&self) -> Option<&'static str> {
75 self.after
76 .current()
77 .filter(|page| Some(*page) != self.before.current())
78 }
79
80 pub fn removed(&self) -> impl Iterator<Item = &'static str> + '_ {
81 self.before
82 .routes
83 .iter()
84 .copied()
85 .rev()
86 .filter(|route| self.after.index_of(route).is_none())
87 }
88}
89
90#[derive(Default)]
91#[doc(hidden)]
92pub struct StackState {
93 snapshot: Property<Arc<StackSnapshot>>,
94 notifying: Cell<bool>,
95}
96
97struct NavigationGuard<'a>(&'a Cell<bool>);
98
99impl Drop for NavigationGuard<'_> {
100 fn drop(&mut self) {
101 self.0.set(false);
102 }
103}
104
105impl StackState {
106 pub fn snapshot(
107 &self,
108 pages: &[&'static str],
109 initial: impl FnOnce() -> String,
110 ) -> Arc<StackSnapshot> {
111 self.snapshot.get(|| {
112 let initial = initial();
113 let route = pages
114 .iter()
115 .copied()
116 .find(|&page| page == initial)
117 .or_else(|| pages.first().copied());
118 Arc::new(StackSnapshot::new(route.into_iter().collect()))
119 })
120 }
121
122 pub fn navigate(
123 &self,
124 pages: &[&'static str],
125 initial: impl FnOnce() -> String,
126 expected: Option<u64>,
127 action: StackNavigation<'_>,
128 changed: impl FnOnce(&StackSnapshot),
129 ) -> bool {
130 self.navigate_guarded(
131 pages,
132 initial,
133 expected,
134 action,
135 |_, _, _| true,
136 |change| {
137 changed(change.after);
138 },
139 )
140 }
141
142 pub fn navigate_guarded(
143 &self,
144 pages: &[&'static str],
145 initial: impl FnOnce() -> String,
146 expected: Option<u64>,
147 action: StackNavigation<'_>,
148 mut can_leave: impl FnMut(&str, &str, bool) -> bool,
149 changed: impl FnOnce(StackChange<'_>),
150 ) -> bool {
151 if self.notifying.replace(true) {
152 return false;
153 }
154 let _guard = NavigationGuard(&self.notifying);
155 let current = self.snapshot(pages, initial);
156 if expected.is_some_and(|revision| revision != current.revision()) {
157 return false;
158 }
159 let resolve = |route| pages.iter().copied().find(|&page| page == route);
160 let mut routes = current.routes.clone();
161 match action {
162 StackNavigation::Push(route) | StackNavigation::Replace(route) => {
163 let Some(page) = resolve(route).filter(|page| !routes.contains(page)) else {
164 return false;
165 };
166 if matches!(action, StackNavigation::Replace(_)) {
167 routes.pop();
168 }
169 routes.push(page);
170 }
171 StackNavigation::Pop if routes.len() > 1 => {
172 routes.pop();
173 }
174 StackNavigation::Pop => return false,
175 StackNavigation::PopTo(route) => {
176 let Some(index) = routes.iter().position(|&page| page == route) else {
177 return false;
178 };
179 routes.truncate(index + 1);
180 }
181 StackNavigation::Reset(route) => {
182 let Some(page) = resolve(route) else {
183 return false;
184 };
185 routes.clear();
186 routes.push(page);
187 }
188 StackNavigation::PushPages(path) | StackNavigation::ResetTo(path) => {
189 if path.is_empty() {
190 return false;
191 }
192 if matches!(action, StackNavigation::ResetTo(_)) {
193 routes.clear();
194 }
195 for route in path {
196 let Some(page) = resolve(route.as_str()).filter(|page| !routes.contains(page))
197 else {
198 return false;
199 };
200 routes.push(page);
201 }
202 }
203 }
204 if routes == current.routes {
205 return false;
206 }
207 let next = Arc::new(StackSnapshot::new(routes));
208 let change = StackChange {
209 before: ¤t,
210 after: &next,
211 };
212 let outgoing = change.deactivated();
213 let leaving = outgoing
214 .into_iter()
215 .chain(change.removed().filter(|route| Some(*route) != outgoing));
216 let destination = next.current().unwrap_or("");
217 for route in leaving {
218 if !can_leave(route, destination, next.index_of(route).is_none()) {
219 return false;
220 }
221 }
222 if !self
224 .snapshot
225 .matches_current(|latest| Arc::ptr_eq(latest, ¤t))
226 {
227 return false;
228 }
229 self.snapshot.set(next.clone());
230 changed(change);
231 true
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn navigation_rejects_stale_actions_and_reentrant_notifications() {
241 let stack = StackState::default();
242 let pages = ["home", "detail", "preview"];
243 let initial = || "home".to_owned();
244 let initial_revision = stack.snapshot(&pages, initial).revision();
245 let calls = Cell::new(0);
246 assert!(stack.navigate(
247 &pages,
248 initial,
249 Some(initial_revision),
250 StackNavigation::Push("detail"),
251 |snapshot| {
252 assert_eq!(snapshot.routes(), ["home", "detail"]);
253 calls.set(calls.get() + 1);
254 assert!(!stack.navigate(
255 &pages,
256 initial,
257 None,
258 StackNavigation::Pop,
259 |_| unreachable!(),
260 ));
261 },
262 ));
263 assert!(!stack.navigate(
264 &pages,
265 initial,
266 Some(initial_revision),
267 StackNavigation::Pop,
268 |_| unreachable!(),
269 ));
270 assert!(!stack.navigate(
271 &pages,
272 initial,
273 None,
274 StackNavigation::Push("home"),
275 |_| unreachable!(),
276 ));
277 assert!(stack.navigate(
278 &pages,
279 initial,
280 None,
281 StackNavigation::Replace("preview"),
282 |_| calls.set(calls.get() + 1),
283 ));
284 assert_eq!(
285 stack.snapshot(&pages, initial).routes(),
286 ["home", "preview"]
287 );
288 assert_eq!(calls.get(), 2);
289 }
290
291 #[test]
292 fn guarded_navigation_keeps_its_revision_when_a_hidden_route_vetoes() {
293 let stack = StackState::default();
294 let pages = ["home", "editor", "preview", "other"];
295 let initial = || "home".to_owned();
296 let open = ["home", "editor", "preview"].map(str::to_owned);
297 assert!(stack.navigate(
298 &pages,
299 initial,
300 None,
301 StackNavigation::ResetTo(&open),
302 |_| {}
303 ));
304 let before = stack.snapshot(&pages, initial);
305 let mut guards = Vec::new();
306 assert!(!stack.navigate_guarded(
307 &pages,
308 initial,
309 Some(before.revision()),
310 StackNavigation::Reset("home"),
311 |route, destination, removing| {
312 assert_eq!(destination, "home");
313 assert!(removing);
314 guards.push(route.to_owned());
315 route != "editor"
316 },
317 |_| panic!("a veto must not emit a change"),
318 ));
319 assert_eq!(guards, ["preview", "editor"]);
320 assert!(Arc::ptr_eq(&before, &stack.snapshot(&pages, initial)));
321
322 let keep_top = ["home", "other", "preview"].map(str::to_owned);
323 assert!(stack.navigate_guarded(
324 &pages,
325 initial,
326 Some(before.revision()),
327 StackNavigation::ResetTo(&keep_top),
328 |route, destination, removing| {
329 assert_eq!((route, destination, removing), ("editor", "preview", true));
330 true
331 },
332 |change| {
333 assert_eq!(change.deactivated(), None);
334 assert_eq!(change.activated(), None);
335 assert_eq!(change.removed().collect::<Vec<_>>(), ["editor"]);
336 assert_eq!(
337 stack.snapshot(&pages, initial).routes(),
338 ["home", "other", "preview"]
339 );
340 },
341 ));
342 }
343
344 #[test]
345 fn a_guard_cannot_commit_against_an_initial_route_it_invalidated() {
346 let stack = StackState::default();
347 let seed = Property::default();
348 let pages = ["home", "editor", "preview"];
349 let initial = || seed.get(|| "home".to_owned());
350 assert!(!stack.navigate_guarded(
351 &pages,
352 initial,
353 None,
354 StackNavigation::Push("preview"),
355 |route, _, _| {
356 assert_eq!(route, "home");
357 seed.set("editor".to_owned());
358 assert_eq!(stack.snapshot(&pages, initial).current(), Some("editor"));
359 true
360 },
361 |_| panic!("the route checked before the guard is stale"),
362 ));
363 assert_eq!(stack.snapshot(&pages, initial).routes(), ["editor"]);
364 }
365
366 #[test]
367 fn navigation_paths_commit_atomically_and_notify_once() {
368 let stack = StackState::default();
369 let pages = ["home", "detail", "preview", "summary"];
370 let initial = || "home".to_owned();
371 let before = stack.snapshot(&pages, initial);
372 let bad = ["detail", "missing"].map(str::to_owned);
373 assert!(!stack.navigate(
374 &pages,
375 initial,
376 None,
377 StackNavigation::PushPages(&bad),
378 |_| unreachable!()
379 ));
380 let duplicate = ["detail", "home", "detail"].map(str::to_owned);
381 assert!(!stack.navigate(
382 &pages,
383 initial,
384 None,
385 StackNavigation::ResetTo(&duplicate),
386 |_| unreachable!()
387 ));
388 assert!(Arc::ptr_eq(&before, &stack.snapshot(&pages, initial)));
389
390 let calls = Cell::new(0);
391 let path = ["detail", "preview"].map(str::to_owned);
392 assert!(stack.navigate(
393 &pages,
394 initial,
395 None,
396 StackNavigation::PushPages(&path),
397 |next| {
398 assert_eq!(next.routes(), ["home", "detail", "preview"]);
399 calls.set(calls.get() + 1);
400 }
401 ));
402 let reset = ["home", "summary"].map(str::to_owned);
403 assert!(stack.navigate(
404 &pages,
405 initial,
406 None,
407 StackNavigation::ResetTo(&reset),
408 |next| {
409 assert_eq!(next.routes(), ["home", "summary"]);
410 calls.set(calls.get() + 1);
411 }
412 ));
413 assert_eq!(calls.get(), 2);
414 }
415}