use leptos::prelude::*; use leptos_router::components::{A, Redirect}; use super::sheets::Sheet; use super::{Ctx, error_message}; use crate::api::{Login, Logout, Register, get_me}; use crate::model::User; /// Session state shared by the whole app. #[derive(Clone, Copy)] pub struct Auth { pub me: Resource, ServerFnError>>, pub login: ServerAction, pub register: ServerAction, pub logout: ServerAction, } impl Auth { pub fn provide() -> Self { let login = ServerAction::::new(); let register = ServerAction::::new(); let logout = ServerAction::::new(); let me = Resource::new( move || (login.version().get(), register.version().get(), logout.version().get()), |_| get_me(), ); let auth = Auth { me, login, register, logout }; provide_context(auth); auth } } /// Renders `render` with the signed-in user, or redirects to the login page. #[component] pub fn RequireUser(render: F) -> impl IntoView where F: Fn(User) -> V + Send + Sync + 'static, V: IntoView + 'static, { let auth = expect_context::(); let render = StoredValue::new(render); view! { {move || Suspend::new(async move { match auth.me.await { Ok(Some(user)) => render.with_value(|render| render(user)).into_any(), _ => view! { }.into_any(), } })} } } /// Sends a signed-in user away from the login and sign-up pages. #[component] fn RedirectIfSignedIn() -> impl IntoView { let auth = expect_context::(); view! { {move || Suspend::new(async move { matches!(auth.me.await, Ok(Some(_))).then(|| view! { }) })} } } #[component] fn AuthLayout(title: &'static str, children: Children) -> impl IntoView { view! {

"mes"
"listes"

"Lisette · Courses"

{title}

{children()}
} } #[component] fn FormError(#[prop(into)] error: Signal>) -> impl IntoView { move || { error.get().map(|msg| { view! { } }) } } #[component] pub fn LoginPage() -> impl IntoView { let auth = expect_context::(); view! {

"Pas encore de compte ? " "Créer un compte"

} } #[component] pub fn RegisterPage() -> impl IntoView { let auth = expect_context::(); view! {

"Déjà inscrit·e ? " "Se connecter"

} } #[component] fn Field(label: &'static str, children: Children) -> impl IntoView { view! { } } #[component] fn SubmitButton(#[prop(into)] pending: Signal, label: &'static str) -> impl IntoView { view! { } } /// Avatar sheet: who is signed in, and sign out. #[component] pub fn AccountSheet(user: User) -> impl IntoView { let auth = expect_context::(); let ctx = expect_context::(); let close = move || ctx.account_open.set(false); let user = StoredValue::new(user); view! {

{user.with_value(|u| u.email.clone())}

} }