dioxus_router/contexts/navigator.rs
1use crate::prelude::{ExternalNavigationFailure, NavigationTarget, RouterContext};
2
3/// Acquire the navigator without subscribing to updates.
4///
5/// Can be called anywhere in the application provided a Router has been initialized.
6///
7/// ## Panics
8///
9/// Panics if there is no router present.
10pub fn navigator() -> Navigator {
11 Navigator(
12 dioxus_lib::prelude::try_consume_context::<RouterContext>()
13 .expect("A router must be present to use navigator"),
14 )
15}
16
17/// A view into the navigation state of a router.
18#[derive(Clone, Copy)]
19pub struct Navigator(pub(crate) RouterContext);
20
21impl Navigator {
22 /// Check whether there is a previous page to navigate back to.
23 #[must_use]
24 pub fn can_go_back(&self) -> bool {
25 self.0.can_go_back()
26 }
27
28 /// Check whether there is a future page to navigate forward to.
29 #[must_use]
30 pub fn can_go_forward(&self) -> bool {
31 self.0.can_go_forward()
32 }
33
34 /// Go back to the previous location.
35 ///
36 /// Will fail silently if there is no previous location to go to.
37 pub fn go_back(&self) {
38 self.0.go_back();
39 }
40
41 /// Go back to the next location.
42 ///
43 /// Will fail silently if there is no next location to go to.
44 pub fn go_forward(&self) {
45 self.0.go_forward();
46 }
47
48 /// Push a new location.
49 ///
50 /// The previous location will be available to go back to.
51 pub fn push(&self, target: impl Into<NavigationTarget>) -> Option<ExternalNavigationFailure> {
52 self.0.push(target)
53 }
54
55 /// Replace the current location.
56 ///
57 /// The previous location will **not** be available to go back to.
58 pub fn replace(
59 &self,
60 target: impl Into<NavigationTarget>,
61 ) -> Option<ExternalNavigationFailure> {
62 self.0.replace(target)
63 }
64}