use std::sync::Arc;
use crate::contexts::router::RoutingCallback;
use crate::history::HistoryProvider;
use crate::routable::Routable;
use dioxus::prelude::*;
use crate::prelude::*;
pub struct RouterConfig<R: Routable> {
pub(crate) failure_external_navigation: fn(Scope) -> Element,
pub(crate) history: Option<Box<dyn AnyHistoryProvider>>,
pub(crate) on_update: Option<RoutingCallback<R>>,
}
#[cfg(feature = "serde")]
impl<R: Routable + Clone> Default for RouterConfig<R>
where
<R as std::str::FromStr>::Err: std::fmt::Display,
R: serde::Serialize + serde::de::DeserializeOwned,
{
fn default() -> Self {
Self {
failure_external_navigation: FailureExternalNavigation::<R>,
history: None,
on_update: None,
}
}
}
#[cfg(feature = "serde")]
impl<R: Routable + Clone> RouterConfig<R>
where
<R as std::str::FromStr>::Err: std::fmt::Display,
R: serde::Serialize + serde::de::DeserializeOwned,
{
pub(crate) fn get_history(self) -> Box<dyn HistoryProvider<R>> {
self.history.unwrap_or_else(|| {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
let history = Box::<WebHistory<R>>::default();
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
let history = Box::<MemoryHistory<R>>::default();
history
})
}
}
#[cfg(not(feature = "serde"))]
impl<R: Routable + Clone> Default for RouterConfig<R>
where
<R as std::str::FromStr>::Err: std::fmt::Display,
{
fn default() -> Self {
Self {
failure_external_navigation: FailureExternalNavigation,
history: None,
on_update: None,
}
}
}
#[cfg(not(feature = "serde"))]
impl<R: Routable + Clone> RouterConfig<R>
where
<R as std::str::FromStr>::Err: std::fmt::Display,
{
pub(crate) fn take_history(&mut self) -> Box<dyn AnyHistoryProvider> {
self.history.take().unwrap_or_else(|| {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
let history = Box::<AnyHistoryProviderImplWrapper<R, WebHistory<R>>>::default();
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
let history = Box::<AnyHistoryProviderImplWrapper<R, MemoryHistory<R>>>::default();
history
})
}
}
impl<R> RouterConfig<R>
where
R: Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
{
pub fn on_update(
self,
callback: impl Fn(GenericRouterContext<R>) -> Option<NavigationTarget<R>> + 'static,
) -> Self {
Self {
on_update: Some(Arc::new(callback)),
..self
}
}
pub fn history(self, history: impl HistoryProvider<R> + 'static) -> Self {
Self {
history: Some(Box::new(AnyHistoryProviderImplWrapper::new(history))),
..self
}
}
pub fn failure_external_navigation(self, component: fn(Scope) -> Element) -> Self {
Self {
failure_external_navigation: component,
..self
}
}
}