dioxus_router/
router_cfg.rs

1use crate::{components::FailureExternalNavigation, prelude::*};
2use dioxus_lib::prelude::*;
3use std::sync::Arc;
4
5/// Global configuration options for the router.
6///
7/// This implements [`Default`] and follows the builder pattern, so you can use it like this:
8/// ```rust,no_run
9/// # use dioxus_router::prelude::*;
10/// # use dioxus::prelude::*;
11/// # #[component]
12/// # fn Index() -> Element {
13/// #     VNode::empty()
14/// # }
15/// #[derive(Clone, Routable)]
16/// enum Route {
17///     #[route("/")]
18///     Index {},
19/// }
20///
21/// fn ExternalNavigationFailure() -> Element {
22///     rsx! {
23///         "Failed to navigate to external URL"
24///     }
25/// }
26///
27/// let cfg = RouterConfig::<Route>::default().failure_external_navigation(ExternalNavigationFailure);
28/// ```
29pub struct RouterConfig<R> {
30    pub(crate) failure_external_navigation: fn() -> Element,
31    pub(crate) on_update: Option<RoutingCallback<R>>,
32}
33
34impl<R> Default for RouterConfig<R> {
35    fn default() -> Self {
36        Self {
37            failure_external_navigation: FailureExternalNavigation,
38            on_update: None,
39        }
40    }
41}
42
43impl<R> RouterConfig<R>
44where
45    R: Routable,
46    <R as std::str::FromStr>::Err: std::fmt::Display,
47{
48    /// A function to be called whenever the routing is updated.
49    ///
50    /// The callback is invoked after the routing is updated, but before components and hooks are
51    /// updated.
52    ///
53    /// If the callback returns a [`NavigationTarget`] the router will replace the current location
54    /// with it. If no navigation failure was triggered, the router will then updated dependent
55    /// components and hooks.
56    ///
57    /// The callback is called no more than once per rerouting. It will not be called if a
58    /// navigation failure occurs.
59    ///
60    /// Defaults to [`None`].
61    pub fn on_update(
62        self,
63        callback: impl Fn(GenericRouterContext<R>) -> Option<NavigationTarget<R>> + 'static,
64    ) -> Self {
65        Self {
66            on_update: Some(Arc::new(callback)),
67            ..self
68        }
69    }
70
71    /// A component to render when an external navigation fails.
72    ///
73    /// Defaults to a router-internal component called [`FailureExternalNavigation`]
74    pub fn failure_external_navigation(self, component: fn() -> Element) -> Self {
75        Self {
76            failure_external_navigation: component,
77            ..self
78        }
79    }
80}