mod account;
mod admin;
mod icons;
mod live;
mod sheets;
mod tiles;
use std::collections::HashMap;
use std::future::Future;
use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_meta::{Link, Meta, MetaTags, Stylesheet, Title, provide_meta_context};
use leptos_router::components::{A, Redirect, Route, Router, Routes};
use leptos_router::hooks::use_params_map;
use leptos_router::path;
use crate::api::{get_items, get_lists, get_suggestions};
use crate::model::{Item, ShoppingList, Suggestion, User};
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
use admin::AdminPage;
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
use tiles::{BasketTile, ItemTile, SuggestionTile};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
}
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
Auth::provide();
view! {
"Page introuvable." }>
}
}
/// Page-wide state shared by tiles and sheets.
#[derive(Clone, Copy)]
pub struct Ctx {
/// Bumped after every mutation so resources refetch.
refresh: RwSignal,
error: RwSignal>,
/// Checked state applied before fresh data shows it, with the number of
/// calls still in flight for that item.
optimistic: RwSignal>,
item_editor: RwSignal>,
list_editor: RwSignal >,
account_open: RwSignal,
user_id: i64,
auth: Auth,
}
impl Ctx {
/// Runs a server call, then refreshes data or reports the error.
fn mutate(
self,
call: impl Future> + 'static,
on_ok: impl FnOnce(T) + 'static,
) {
spawn_local(async move {
match call.await {
Ok(value) => {
on_ok(value);
self.refresh.update(|n| *n += 1);
}
Err(err) => self.report(err),
}
});
}
fn report(self, err: ServerFnError) {
let msg = error_message(err);
if msg == crate::api::NOT_LOGGED_IN {
// The guard sends the user back to the login page.
self.auth.me.refetch();
}
self.error.set(Some(msg));
}
fn toggle(self, item: &Item) {
let (id, checked) = (item.id, !item.checked);
self.optimistic.update(|map| {
let in_flight = map.get(&id).map_or(0, |&(_, n)| n);
map.insert(id, (checked, in_flight + 1));
});
spawn_local(async move {
match crate::api::set_checked(id, checked).await {
Ok(()) => self.optimistic.update_untracked(|map| {
if let Some((_, in_flight)) = map.get_mut(&id) {
*in_flight -= 1;
}
}),
Err(err) => {
self.optimistic.update(|map| {
map.remove(&id);
});
self.report(err);
}
}
});
}
}
fn error_message(err: ServerFnError) -> String {
match err {
ServerFnError::ServerError(msg) => msg,
_ => "Impossible de joindre le serveur.".to_owned(),
}
}
#[component]
fn ListsPage() -> impl IntoView {
view! { } /> }
}
#[component]
fn ListsView(user: User) -> impl IntoView {
let ctx = Ctx {
refresh: RwSignal::new(0),
error: RwSignal::new(None),
optimistic: RwSignal::new(HashMap::new()),
item_editor: RwSignal::new(None),
list_editor: RwSignal::new(None),
account_open: RwSignal::new(false),
user_id: user.id,
auth: expect_context::(),
};
provide_context(ctx);
live::subscribe(ctx.refresh);
let params = use_params_map();
let active_id = Memo::new(move |_| {
params
.read()
.get("id")
.and_then(|id| id.parse::().ok())
});
let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists());
let items = Resource::new(
move || (active_id.get(), ctx.refresh.get()),
|(id, _)| async move {
match id {
Some(id) => get_items(id).await,
None => Ok(Vec::new()),
}
},
);
let suggestions = Resource::new(
move || (active_id.get(), ctx.refresh.get()),
|(id, _)| async move {
match id {
Some(id) => get_suggestions(id).await,
None => Ok(Vec::new()),
}
},
);
view! {
}>
"Oups : "
{move || {
errors.get().into_iter().map(|(_, e)| e.to_string()).collect::>().join(", ")
}}
}
}>
{move || Suspend::new(async move {
let lists = lists.await?;
let items = items.await?;
let suggestions = suggestions.await?;
Ok::<_, ServerFnError>(view! {
})
})}
}
}
#[component]
fn ListsContent(
lists: Vec,
items: Vec- ,
suggestions: Vec
,
active_id: Option,
) -> impl IntoView {
let ctx = expect_context::();
let Some(active_id) = active_id else {
return match lists.first() {
Some(first) => view! { }.into_any(),
None => view! {
}
.into_any(),
};
};
let Some(list) = lists.iter().find(|l| l.id == active_id).cloned() else {
return view! {
"Cette liste n'existe plus."
}
.into_any();
};
// Fresh data includes every confirmed toggle: only keep pending ones, so
// changes made by others since are not masked.
ctx.optimistic
.update_untracked(|map| map.retain(|_, &mut (_, in_flight)| in_flight > 0));
// Items with pending checkbox changes applied, by category then name.
let mut items = items;
items.sort_by_cached_key(Item::sort_key);
let items = StoredValue::new(items);
let current = Memo::new(move |_| {
let optimistic = ctx.optimistic.get();
items.with_value(|items| {
items
.iter()
.cloned()
.map(|mut item| {
if let Some(&(checked, _)) = optimistic.get(&item.id) {
item.checked = checked;
}
item
})
.collect::>()
})
});
let to_get = Memo::new(move |_| {
current.with(|items| {
items
.iter()
.filter(|i| !i.checked)
.cloned()
.collect::>()
})
});
let in_basket = Memo::new(move |_| {
current.with(|items| {
items
.iter()
.filter(|i| i.checked)
.cloned()
.collect::>()
})
});
let total = move || current.with(Vec::len);
let remaining = Signal::derive(move || to_get.with(Vec::len));
let edit_list = {
let list = list.clone();
move |_| ctx.list_editor.set(Some(ListEditor::Edit(list.clone())))
};
view! {
{format!("Ticket N°{:03} · {}", list.id, ticket_date(&list.created_at))}
{list.name.clone()}
{(!list.is_owner)
.then(|| {
view! {
{format!("Partagée par {}", list.owner_name)}
}
})}
{move || remaining_text(remaining.get(), total())}
{suggestions
.into_iter()
.map(|suggestion| view! { })
.collect_view()}
"Déjà dans le panier"
{move || format!("{}/{}", in_basket.with(Vec::len), total())}
"+ article"
}
.into_any()
}
#[component]
fn ListTabs(
lists: Vec,
active: Option,
#[prop(into)] remaining: Signal,
) -> impl IntoView {
let ctx = expect_context::();
view! {
{lists
.into_iter()
.map(|list| {
let is_active = active == Some(list.id);
let class = if is_active {
"border-ink bg-ink text-paper"
} else {
"border-ink bg-paper"
};
view! {
{(!is_active)
.then(|| {
view! {
}
})}
{list.name.clone()}
{is_active.then_some(move || format!(" · {}", remaining.get()))}
}
})
.collect_view()}
"+"
}
}
#[component]
fn ErrorBanner() -> impl IntoView {
let ctx = expect_context::();
view! {
{move || {
ctx.error
.get()
.map(|msg| {
view! {
{msg}
"OK"
}
})
}}
}
}
#[component]
fn EmptyState() -> impl IntoView {
let ctx = expect_context::();
view! {
"Aucune liste pour l'instant."
"Créer une liste"
}
}
#[component]
fn TicketSkeleton() -> impl IntoView {
view! {
}
}
fn remaining_text(remaining: usize, total: usize) -> String {
match (remaining, total) {
(_, 0) => "Liste vide : ajoute ton premier article.".to_owned(),
(0, _) => "Tout est dans le panier !".to_owned(),
(1, _) => "Encore 1 article à attraper.".to_owned(),
(n, _) => format!("Encore {n} articles à attraper."),
}
}
/// "2026-10-07" → "mer. 07/10" (upper-cased by CSS).
fn ticket_date(iso: &str) -> String {
const DAYS: [&str; 7] = ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."];
const OFFSETS: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
let mut parts = iso.split('-').map(|p| p.parse::().ok());
let (Some(Some(y)), Some(Some(m @ 1..=12)), Some(Some(d))) =
(parts.next(), parts.next(), parts.next())
else {
return String::new();
};
// Sakamoto's algorithm, 0 = Sunday.
let y_adj = if m < 3 { y - 1 } else { y };
let weekday =
(y_adj + y_adj / 4 - y_adj / 100 + y_adj / 400 + OFFSETS[(m - 1) as usize] + d) % 7;
format!("{} {d:02}/{m:02}", DAYS[weekday as usize])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_ticket_date() {
assert_eq!(ticket_date("2026-10-07"), "mer. 07/10");
assert_eq!(ticket_date("2024-02-29"), "jeu. 29/02");
assert_eq!(ticket_date("garbage"), "");
}
#[test]
fn remaining_wording() {
assert_eq!(remaining_text(5, 7), "Encore 5 articles à attraper.");
assert_eq!(remaining_text(1, 2), "Encore 1 article à attraper.");
assert_eq!(remaining_text(0, 2), "Tout est dans le panier !");
}
}