Skip to main content

xrack_runtime/
stack.rs

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