dioxus/packages/fullstack/src/router.rs

101 lines
3.1 KiB
Rust
Raw Normal View History

2023-06-24 01:23:03 +00:00
//! Fullstack router intigration
#![allow(non_snake_case)]
use dioxus::prelude::*;
/// Used by the launch macro
#[doc(hidden)]
pub fn RouteWithCfg<R>(cx: Scope<FullstackRouterConfig<R>>) -> Element
where
R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
{
use dioxus_router::prelude::RouterConfig;
#[cfg(feature = "ssr")]
2023-07-08 19:22:54 +00:00
let context = crate::prelude::server_context();
2023-06-24 01:23:03 +00:00
let cfg = *cx.props;
render! {
2023-07-26 01:14:48 +00:00
dioxus_router::prelude::Router::<R> {
2023-06-24 01:23:03 +00:00
config: move || {
RouterConfig::default()
.failure_external_navigation(cfg.failure_external_navigation)
.history({
#[cfg(feature = "ssr")]
let history = dioxus_router::prelude::MemoryHistory::with_initial_path(
context
2023-07-08 01:25:45 +00:00
.request_parts().unwrap()
2023-06-24 01:23:03 +00:00
.uri
.to_string()
.parse()
.unwrap_or_else(|err| {
2023-09-06 22:47:33 +00:00
tracing::error!("Failed to parse uri: {}", err);
2023-06-24 01:23:03 +00:00
"/"
.parse()
.unwrap_or_else(|err| {
panic!("Failed to parse uri: {}", err);
})
}),
);
#[cfg(not(feature = "ssr"))]
let history = dioxus_router::prelude::WebHistory::new(
None,
cfg.scroll_restoration,
);
history
})
},
}
}
}
2023-07-26 18:29:34 +00:00
fn default_external_navigation_handler() -> fn(Scope) -> Element {
2023-07-26 01:14:48 +00:00
dioxus_router::prelude::FailureExternalNavigation
2023-06-24 01:23:03 +00:00
}
/// The configeration for the router
#[derive(Props, serde::Serialize, serde::Deserialize)]
pub struct FullstackRouterConfig<R>
where
R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
{
#[serde(skip)]
2023-07-26 18:29:34 +00:00
#[serde(default = "default_external_navigation_handler")]
2023-06-24 01:23:03 +00:00
failure_external_navigation: fn(Scope) -> Element,
scroll_restoration: bool,
#[serde(skip)]
phantom: std::marker::PhantomData<R>,
}
impl<R> Clone for FullstackRouterConfig<R>
where
R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
{
fn clone(&self) -> Self {
*self
2023-06-24 01:23:03 +00:00
}
}
impl<R> Copy for FullstackRouterConfig<R>
where
R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
{
}
impl<R> Default for FullstackRouterConfig<R>
where
R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
{
fn default() -> Self {
Self {
2023-07-26 01:14:48 +00:00
failure_external_navigation: dioxus_router::prelude::FailureExternalNavigation,
2023-06-24 01:23:03 +00:00
scroll_restoration: true,
phantom: std::marker::PhantomData,
}
}
}