1use crate::Property;
2use std::{
3 borrow::Cow,
4 cell::Cell,
5 sync::{
6 Arc,
7 atomic::{AtomicU64, Ordering},
8 },
9};
10
11static NEXT_REVISION: AtomicU64 = AtomicU64::new(1);
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum StackNavigation<'a> {
15 Push(&'a str),
16 Pop,
17 Replace(&'a str),
18 PopTo(&'a str),
19 Reset(&'a str),
20 PushPages(&'a [String]),
21 ResetTo(&'a [String]),
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[doc(hidden)]
26pub enum StackNavigationMethod {
27 Push,
28 Pop,
29 Replace,
30 PopTo,
31 Reset,
32 PushPages,
33 ResetTo,
34}
35
36#[doc(hidden)]
37pub enum StackNavigationArgument<'a> {
38 None,
39 Route(&'a str),
40 Path(&'a [String]),
41}
42
43impl StackNavigationMethod {
44 pub fn parse(name: &str) -> Option<Self> {
45 Some(match name {
46 "push" => Self::Push,
47 "pop" => Self::Pop,
48 "replace" => Self::Replace,
49 "pop-to" => Self::PopTo,
50 "reset" => Self::Reset,
51 "push-pages" => Self::PushPages,
52 "reset-to" => Self::ResetTo,
53 _ => return None,
54 })
55 }
56
57 pub fn uses_path(self) -> bool {
58 matches!(self, Self::PushPages | Self::ResetTo)
59 }
60
61 pub fn action(self, argument: StackNavigationArgument<'_>) -> Option<StackNavigation<'_>> {
62 use StackNavigationArgument::{Path, Route};
63 Some(match (self, argument) {
64 (Self::Push, Route(route)) => StackNavigation::Push(route),
65 (Self::Pop, StackNavigationArgument::None) => StackNavigation::Pop,
66 (Self::Replace, Route(route)) => StackNavigation::Replace(route),
67 (Self::PopTo, Route(route)) => StackNavigation::PopTo(route),
68 (Self::Reset, Route(route)) => StackNavigation::Reset(route),
69 (Self::PushPages, Path(path)) => StackNavigation::PushPages(path),
70 (Self::ResetTo, Path(path)) => StackNavigation::ResetTo(path),
71 _ => return None,
72 })
73 }
74}
75
76#[derive(Debug, PartialEq, Eq)]
77pub struct StackSnapshot {
78 routes: Vec<Cow<'static, str>>,
79 revision: u64,
80}
81
82impl StackSnapshot {
83 #[expect(
84 clippy::expect_used,
85 reason = "navigation revision IDs must stay unique even if the counter reaches its limit"
86 )]
87 fn new(routes: Vec<Cow<'static, str>>) -> Self {
88 let revision = NEXT_REVISION
89 .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
90 value.checked_add(1)
91 })
92 .expect("navigation revision exhausted");
93 Self { routes, revision }
94 }
95
96 pub fn routes(&self) -> &[Cow<'static, str>] {
97 &self.routes
98 }
99
100 pub fn current(&self) -> Option<&str> {
101 self.routes.last().map(Cow::as_ref)
102 }
103
104 pub fn index_of(&self, route: &str) -> Option<usize> {
105 self.routes.iter().position(|page| page == route)
106 }
107
108 pub fn depth(&self) -> usize {
109 self.routes.len()
110 }
111
112 #[doc(hidden)]
113 pub fn current_page(&self) -> String {
114 self.current().unwrap_or_default().to_owned()
115 }
116
117 #[doc(hidden)]
118 pub fn can_go_back(&self) -> bool {
119 self.depth() > 1
120 }
121
122 #[doc(hidden)]
123 pub fn page_active(&self, route: &str) -> bool {
124 self.current() == Some(route)
125 }
126
127 #[doc(hidden)]
128 pub fn page_index(&self, route: &str) -> i64 {
129 self.index_of(route).map_or(-1, |index| index as i64)
130 }
131
132 pub fn revision(&self) -> u64 {
133 self.revision
134 }
135}
136
137#[doc(hidden)]
139pub struct StackChange<'a> {
140 pub before: &'a StackSnapshot,
141 pub after: &'a StackSnapshot,
142}
143
144#[doc(hidden)]
145pub enum StackEvent<'a> {
146 Deactivated(&'a str),
147 Removed(&'a str),
148 Activated(&'a str),
149 Changed { current: &'a str, depth: i64 },
150}
151
152impl StackChange<'_> {
153 pub fn deactivated(&self) -> Option<&str> {
154 self.before
155 .current()
156 .filter(|page| Some(*page) != self.after.current())
157 }
158
159 pub fn activated(&self) -> Option<&str> {
160 self.after
161 .current()
162 .filter(|page| Some(*page) != self.before.current())
163 }
164
165 pub fn removed(&self) -> impl Iterator<Item = &str> + '_ {
166 self.before
167 .routes
168 .iter()
169 .map(Cow::as_ref)
170 .rev()
171 .filter(|route| self.after.index_of(route).is_none())
172 }
173
174 pub fn try_notify<E>(
175 &self,
176 mut notify: impl FnMut(StackEvent<'_>) -> Result<(), E>,
177 ) -> Result<(), E> {
178 if let Some(route) = self.deactivated() {
179 notify(StackEvent::Deactivated(route))?;
180 }
181 for route in self.removed() {
182 notify(StackEvent::Removed(route))?;
183 }
184 if let Some(route) = self.activated() {
185 notify(StackEvent::Activated(route))?;
186 }
187 notify(StackEvent::Changed {
188 current: self.after.current().unwrap_or(""),
189 depth: self.after.depth() as i64,
190 })
191 }
192
193 pub fn notify(&self, mut notify: impl FnMut(StackEvent<'_>)) {
194 self.try_notify(|event| {
195 notify(event);
196 Ok::<_, std::convert::Infallible>(())
197 })
198 .unwrap_or_else(|error| match error {})
199 }
200}
201
202#[derive(Default)]
203#[doc(hidden)]
204pub struct StackState {
205 snapshot: Property<Arc<StackSnapshot>>,
206 notifying: Cell<bool>,
207}
208
209struct NavigationGuard<'a>(&'a Cell<bool>);
210
211impl Drop for NavigationGuard<'_> {
212 fn drop(&mut self) {
213 self.0.set(false);
214 }
215}
216
217impl StackState {
218 pub fn snapshot(
219 &self,
220 pages: &[&'static str],
221 initial: impl FnOnce() -> String,
222 ) -> Arc<StackSnapshot> {
223 self.try_snapshot(pages, || Ok::<_, std::convert::Infallible>(initial()))
224 .unwrap_or_else(|error| match error {})
225 }
226
227 pub fn try_snapshot<R, E>(
228 &self,
229 pages: &[R],
230 initial: impl FnOnce() -> Result<String, E>,
231 ) -> Result<Arc<StackSnapshot>, E>
232 where
233 R: Clone + AsRef<str> + Into<Cow<'static, str>>,
234 {
235 self.snapshot.try_get(|| {
236 let initial = initial()?;
237 let route = pages
238 .iter()
239 .find(|page| page.as_ref() == initial)
240 .or_else(|| pages.first())
241 .cloned()
242 .map(Into::into);
243 Ok(Arc::new(StackSnapshot::new(route.into_iter().collect())))
244 })
245 }
246
247 pub fn navigate(
248 &self,
249 pages: &[&'static str],
250 initial: impl FnOnce() -> String,
251 expected: Option<u64>,
252 action: StackNavigation<'_>,
253 changed: impl FnOnce(&StackSnapshot),
254 ) -> bool {
255 self.navigate_guarded(
256 pages,
257 initial,
258 expected,
259 action,
260 |_, _, _| true,
261 |change| {
262 changed(change.after);
263 },
264 )
265 }
266
267 pub fn navigate_guarded(
268 &self,
269 pages: &[&'static str],
270 initial: impl FnOnce() -> String,
271 expected: Option<u64>,
272 action: StackNavigation<'_>,
273 mut can_leave: impl FnMut(&str, &str, bool) -> bool,
274 changed: impl FnOnce(StackChange<'_>),
275 ) -> bool {
276 self.try_navigate_guarded(
277 pages,
278 || Ok::<_, std::convert::Infallible>(initial()),
279 expected,
280 action,
281 |route, destination, removing| Ok(can_leave(route, destination, removing)),
282 |change| {
283 changed(change);
284 Ok(())
285 },
286 )
287 .unwrap_or_else(|error| match error {})
288 }
289
290 pub fn try_navigate_guarded<R, E>(
291 &self,
292 pages: &[R],
293 initial: impl FnOnce() -> Result<String, E>,
294 expected: Option<u64>,
295 action: StackNavigation<'_>,
296 mut can_leave: impl FnMut(&str, &str, bool) -> Result<bool, E>,
297 changed: impl FnOnce(StackChange<'_>) -> Result<(), E>,
298 ) -> Result<bool, E>
299 where
300 R: Clone + AsRef<str> + Into<Cow<'static, str>>,
301 {
302 if self.notifying.replace(true) {
303 return Ok(false);
304 }
305 let _guard = NavigationGuard(&self.notifying);
306 let current = self.try_snapshot(pages, initial)?;
307 if expected.is_some_and(|revision| revision != current.revision()) {
308 return Ok(false);
309 }
310 let resolve = |route| {
311 pages
312 .iter()
313 .find(|page| page.as_ref() == route)
314 .cloned()
315 .map(Into::into)
316 };
317 let mut routes = current.routes.clone();
318 match action {
319 StackNavigation::Push(route) | StackNavigation::Replace(route) => {
320 let Some(page) = resolve(route).filter(|page| !routes.contains(page)) else {
321 return Ok(false);
322 };
323 if matches!(action, StackNavigation::Replace(_)) {
324 routes.pop();
325 }
326 routes.push(page);
327 }
328 StackNavigation::Pop if routes.len() > 1 => {
329 routes.pop();
330 }
331 StackNavigation::Pop => return Ok(false),
332 StackNavigation::PopTo(route) => {
333 let Some(index) = routes.iter().position(|page| page == route) else {
334 return Ok(false);
335 };
336 routes.truncate(index + 1);
337 }
338 StackNavigation::Reset(route) => {
339 let Some(page) = resolve(route) else {
340 return Ok(false);
341 };
342 routes.clear();
343 routes.push(page);
344 }
345 StackNavigation::PushPages(path) | StackNavigation::ResetTo(path) => {
346 if path.is_empty() {
347 return Ok(false);
348 }
349 if matches!(action, StackNavigation::ResetTo(_)) {
350 routes.clear();
351 }
352 for route in path {
353 let Some(page) = resolve(route.as_str()).filter(|page| !routes.contains(page))
354 else {
355 return Ok(false);
356 };
357 routes.push(page);
358 }
359 }
360 }
361 if routes == current.routes {
362 return Ok(false);
363 }
364 let next = Arc::new(StackSnapshot::new(routes));
365 let change = StackChange {
366 before: ¤t,
367 after: &next,
368 };
369 let outgoing = change.deactivated();
370 let leaving = outgoing
371 .into_iter()
372 .chain(change.removed().filter(|route| Some(*route) != outgoing));
373 let destination = next.current().unwrap_or("");
374 for route in leaving {
375 if !can_leave(route, destination, next.index_of(route).is_none())? {
376 return Ok(false);
377 }
378 }
379 if !self
381 .snapshot
382 .matches_current(|latest| Arc::ptr_eq(latest, ¤t))
383 {
384 return Ok(false);
385 }
386 self.snapshot.set(next.clone());
387 changed(change)?;
388 Ok(true)
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395
396 #[test]
397 fn owned_routes_recover_from_initialization_and_guard_errors() {
398 let pages = ["home".to_owned(), "editor".to_owned()];
399 let state = StackState::default();
400 assert!(matches!(
401 state.try_snapshot(&pages, || Err("initial route")),
402 Err("initial route")
403 ));
404 let initial = || Ok::<_, &str>("home".to_owned());
405 let before = state.try_snapshot(&pages, initial).unwrap();
406 assert!(matches!(
407 state.try_navigate_guarded(
408 &pages,
409 initial,
410 Some(before.revision()),
411 StackNavigation::Push("editor"),
412 |_, _, _| Err("guard failed"),
413 |_| unreachable!(),
414 ),
415 Err("guard failed")
416 ));
417 assert!(Arc::ptr_eq(
418 &before,
419 &state.try_snapshot(&pages, initial).unwrap()
420 ));
421 assert!(
422 state
423 .try_navigate_guarded(
424 &pages,
425 initial,
426 Some(before.revision()),
427 StackNavigation::Push("editor"),
428 |_, _, _| Ok(true),
429 |_| Ok(()),
430 )
431 .unwrap()
432 );
433 assert_eq!(
434 state.try_snapshot(&pages, initial).unwrap().routes(),
435 ["home", "editor"]
436 );
437 }
438
439 #[test]
440 fn navigation_rejects_stale_actions_and_reentrant_notifications() {
441 let stack = StackState::default();
442 let pages = ["home", "detail", "preview"];
443 let initial = || "home".to_owned();
444 let initial_revision = stack.snapshot(&pages, initial).revision();
445 let calls = Cell::new(0);
446 assert!(stack.navigate(
447 &pages,
448 initial,
449 Some(initial_revision),
450 StackNavigation::Push("detail"),
451 |snapshot| {
452 assert_eq!(snapshot.routes(), ["home", "detail"]);
453 calls.set(calls.get() + 1);
454 assert!(!stack.navigate(
455 &pages,
456 initial,
457 None,
458 StackNavigation::Pop,
459 |_| unreachable!(),
460 ));
461 },
462 ));
463 assert!(!stack.navigate(
464 &pages,
465 initial,
466 Some(initial_revision),
467 StackNavigation::Pop,
468 |_| unreachable!(),
469 ));
470 assert!(!stack.navigate(
471 &pages,
472 initial,
473 None,
474 StackNavigation::Push("home"),
475 |_| unreachable!(),
476 ));
477 assert!(stack.navigate(
478 &pages,
479 initial,
480 None,
481 StackNavigation::Replace("preview"),
482 |_| calls.set(calls.get() + 1),
483 ));
484 assert_eq!(
485 stack.snapshot(&pages, initial).routes(),
486 ["home", "preview"]
487 );
488 assert_eq!(calls.get(), 2);
489 }
490
491 #[test]
492 fn guarded_navigation_keeps_its_revision_when_a_hidden_route_vetoes() {
493 let stack = StackState::default();
494 let pages = ["home", "editor", "preview", "other"];
495 let initial = || "home".to_owned();
496 let open = ["home", "editor", "preview"].map(str::to_owned);
497 assert!(stack.navigate(
498 &pages,
499 initial,
500 None,
501 StackNavigation::ResetTo(&open),
502 |_| {}
503 ));
504 let before = stack.snapshot(&pages, initial);
505 let mut guards = Vec::new();
506 assert!(!stack.navigate_guarded(
507 &pages,
508 initial,
509 Some(before.revision()),
510 StackNavigation::Reset("home"),
511 |route, destination, removing| {
512 assert_eq!(destination, "home");
513 assert!(removing);
514 guards.push(route.to_owned());
515 route != "editor"
516 },
517 |_| panic!("a veto must not emit a change"),
518 ));
519 assert_eq!(guards, ["preview", "editor"]);
520 assert!(Arc::ptr_eq(&before, &stack.snapshot(&pages, initial)));
521
522 let keep_top = ["home", "other", "preview"].map(str::to_owned);
523 assert!(stack.navigate_guarded(
524 &pages,
525 initial,
526 Some(before.revision()),
527 StackNavigation::ResetTo(&keep_top),
528 |route, destination, removing| {
529 assert_eq!((route, destination, removing), ("editor", "preview", true));
530 true
531 },
532 |change| {
533 assert_eq!(change.deactivated(), None);
534 assert_eq!(change.activated(), None);
535 assert_eq!(change.removed().collect::<Vec<_>>(), ["editor"]);
536 assert_eq!(
537 stack.snapshot(&pages, initial).routes(),
538 ["home", "other", "preview"]
539 );
540 },
541 ));
542 }
543
544 #[test]
545 fn a_guard_cannot_commit_against_an_initial_route_it_invalidated() {
546 let stack = StackState::default();
547 let seed = Property::default();
548 let pages = ["home", "editor", "preview"];
549 let initial = || seed.get(|| "home".to_owned());
550 assert!(!stack.navigate_guarded(
551 &pages,
552 initial,
553 None,
554 StackNavigation::Push("preview"),
555 |route, _, _| {
556 assert_eq!(route, "home");
557 seed.set("editor".to_owned());
558 assert_eq!(stack.snapshot(&pages, initial).current(), Some("editor"));
559 true
560 },
561 |_| panic!("the route checked before the guard is stale"),
562 ));
563 assert_eq!(stack.snapshot(&pages, initial).routes(), ["editor"]);
564 }
565
566 #[test]
567 fn navigation_paths_commit_atomically_and_notify_once() {
568 let stack = StackState::default();
569 let pages = ["home", "detail", "preview", "summary"];
570 let initial = || "home".to_owned();
571 let before = stack.snapshot(&pages, initial);
572 let bad = ["detail", "missing"].map(str::to_owned);
573 assert!(!stack.navigate(
574 &pages,
575 initial,
576 None,
577 StackNavigation::PushPages(&bad),
578 |_| unreachable!()
579 ));
580 let duplicate = ["detail", "home", "detail"].map(str::to_owned);
581 assert!(!stack.navigate(
582 &pages,
583 initial,
584 None,
585 StackNavigation::ResetTo(&duplicate),
586 |_| unreachable!()
587 ));
588 assert!(Arc::ptr_eq(&before, &stack.snapshot(&pages, initial)));
589
590 let calls = Cell::new(0);
591 let path = ["detail", "preview"].map(str::to_owned);
592 assert!(stack.navigate(
593 &pages,
594 initial,
595 None,
596 StackNavigation::PushPages(&path),
597 |next| {
598 assert_eq!(next.routes(), ["home", "detail", "preview"]);
599 calls.set(calls.get() + 1);
600 }
601 ));
602 let reset = ["home", "summary"].map(str::to_owned);
603 assert!(stack.navigate(
604 &pages,
605 initial,
606 None,
607 StackNavigation::ResetTo(&reset),
608 |next| {
609 assert_eq!(next.routes(), ["home", "summary"]);
610 calls.set(calls.get() + 1);
611 }
612 ));
613 assert_eq!(calls.get(), 2);
614 }
615}