dioxus_router/
router_cfg.rs

1use crate::{GenericRouterContext, NavigationTarget, Routable, RoutingCallback};
2use dioxus_core::Element;
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::prelude::*;
10/// # use dioxus_router::RouterConfig;
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
34#[cfg(not(feature = "html"))]
35impl<R> Default for RouterConfig<R> {
36    fn default() -> Self {
37        Self {
38            failure_external_navigation: || VNode::empty(),
39            on_update: None,
40        }
41    }
42}
43
44#[cfg(feature = "html")]
45impl<R> Default for RouterConfig<R> {
46    fn default() -> Self {
47        Self {
48            failure_external_navigation: crate::components::FailureExternalNavigation,
49            on_update: None,
50        }
51    }
52}
53
54impl<R> RouterConfig<R>
55where
56    R: Routable,
57{
58    /// A function to be called whenever the routing is updated.
59    ///
60    /// The callback is invoked after the routing is updated, but before components and hooks are
61    /// updated.
62    ///
63    /// If the callback returns a [`NavigationTarget`] the router will replace the current location
64    /// with it. If no navigation failure was triggered, the router will then updated dependent
65    /// components and hooks.
66    ///
67    /// The callback is called no more than once per rerouting. It will not be called if a
68    /// navigation failure occurs.
69    ///
70    /// Defaults to [`None`].
71    pub fn on_update(
72        self,
73        callback: impl Fn(GenericRouterContext<R>) -> Option<NavigationTarget<R>> + 'static,
74    ) -> Self {
75        Self {
76            on_update: Some(Arc::new(callback)),
77            ..self
78        }
79    }
80
81    /// A component to render when an external navigation fails.
82    ///
83    #[cfg_attr(
84        feature = "html",
85        doc = "Defaults to [`crate::components::FailureExternalNavigation`]."
86    )]
87    pub fn failure_external_navigation(self, component: fn() -> Element) -> Self {
88        Self {
89            failure_external_navigation: component,
90            ..self
91        }
92    }
93}