use crate::{use_navigate, use_resolved_path, NavigateOptions};
use leptos::{
component, provide_context, signal_prelude::*, use_context, IntoView, Scope,
};
use std::rc::Rc;
#[component]
pub fn Redirect<P>(
cx: Scope,
path: P,
#[prop(optional)]
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().unwrap_or_else(|| "/".to_string());
if let Some(redirect_fn) = use_context::<ServerRedirectFunction>(cx) {
(redirect_fn.f)(&path);
}
let navigate = use_navigate(cx);
navigate(&path, options.unwrap_or_default())
}
#[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()
}
}
pub fn provide_server_redirect(cx: Scope, handler: impl Fn(&str) + 'static) {
provide_context(
cx,
ServerRedirectFunction {
f: Rc::new(handler),
},
)
}