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