use crate::{use_navigate, use_resolved_path, NavigateOptions};
use leptos::{
component, provide_context, signal_prelude::*, use_context, IntoView, Scope,
};
use std::rc::Rc;
#[cfg_attr(
any(debug_assertions, feature = "ssr"),
tracing::instrument(level = "trace", skip_all,)
)]
#[component]
pub fn Redirect<P>(
cx: Scope,
path: P,
#[prop(optional)]
#[allow(unused)]
options: Option<NavigateOptions>,
) -> impl IntoView
where
P: std::fmt::Display + 'static,
{
let path = use_resolved_path(cx, move || path.to_string());
let path = path.get_untracked().unwrap_or_else(|| "/".to_string());
if let Some(redirect_fn) = use_context::<ServerRedirectFunction>(cx) {
(redirect_fn.f)(&path);
}
else {
#[allow(unused)]
let navigate = use_navigate(cx);
#[cfg(any(feature = "csr", feature = "hydrate"))]
leptos::request_animation_frame(move || {
if let Err(e) = navigate(&path, options.unwrap_or_default()) {
leptos::error!("<Redirect/> error: {e:?}");
}
});
#[cfg(not(any(feature = "csr", feature = "hydrate")))]
{
leptos::debug_warn!(
"<Redirect/> is trying to redirect without \
`ServerRedirectFunction` being provided. (If you’re getting \
this on initial server start-up, it’s okay to ignore. It \
just means that your root route is a redirect.)"
);
}
}
}
#[derive(Clone)]
pub struct ServerRedirectFunction {
f: Rc<dyn Fn(&str)>,
}
impl std::fmt::Debug for ServerRedirectFunction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServerRedirectFunction").finish()
}
}
#[cfg_attr(
any(debug_assertions, feature = "ssr"),
tracing::instrument(level = "trace", skip_all,)
)]
pub fn provide_server_redirect(cx: Scope, handler: impl Fn(&str) + 'static) {
provide_context(
cx,
ServerRedirectFunction {
f: Rc::new(handler),
},
)
}