first commit
This commit is contained in:
commit
9536cf0dbe
16 files changed
+5170
No files matched your search
+446
@@ -0,0 +1,446 @@
|
||||
mod icons;
|
||||
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};
|
||||
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
|
||||
use tiles::{BasketTile, ItemTile, SuggestionTile};
|
||||
|
||||
pub fn shell(options: LeptosOptions) -> impl IntoView {
|
||||
view! {
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, viewport-fit=cover"
|
||||
/>
|
||||
<AutoReload options=options.clone() />
|
||||
<HydrationScripts options />
|
||||
<MetaTags />
|
||||
</head>
|
||||
<body class="bg-lime text-ink font-sans antialiased">
|
||||
<App />
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn App() -> impl IntoView {
|
||||
provide_meta_context();
|
||||
|
||||
view! {
|
||||
<Stylesheet id="leptos" href="/pkg/lisette.css" />
|
||||
<Link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<Link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" />
|
||||
<Link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@500&family=Unbounded:wght@700;800&display=swap"
|
||||
/>
|
||||
<Link rel="manifest" href="/manifest.webmanifest" />
|
||||
<Link rel="icon" href="/favicon.svg" type_="image/svg+xml" />
|
||||
<Meta name="theme-color" content="#bfe383" />
|
||||
<Title text="Lisette" />
|
||||
|
||||
<Router>
|
||||
<Routes fallback=|| view! { <p class="p-4">"Page introuvable."</p> }>
|
||||
<Route path=path!("/") view=ListsPage />
|
||||
<Route path=path!("/l/:id") view=ListsPage />
|
||||
</Routes>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
/// Page-wide state shared by tiles and sheets.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Ctx {
|
||||
/// Bumped after every mutation so resources refetch.
|
||||
refresh: RwSignal<u32>,
|
||||
error: RwSignal<Option<String>>,
|
||||
/// Checked state applied before the server confirms it.
|
||||
optimistic: RwSignal<HashMap<i64, bool>>,
|
||||
item_editor: RwSignal<Option<ItemEditor>>,
|
||||
list_editor: RwSignal<Option<ListEditor>>,
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
/// Runs a server call, then refreshes data or reports the error.
|
||||
fn mutate<T: 'static>(
|
||||
self,
|
||||
call: impl Future<Output = Result<T, ServerFnError>> + '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.error.set(Some(error_message(err))),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn toggle(self, item: &Item) {
|
||||
let (id, checked) = (item.id, !item.checked);
|
||||
self.optimistic.update(|map| {
|
||||
map.insert(id, checked);
|
||||
});
|
||||
spawn_local(async move {
|
||||
if let Err(err) = crate::api::set_checked(id, checked).await {
|
||||
self.optimistic.update(|map| {
|
||||
map.remove(&id);
|
||||
});
|
||||
self.error.set(Some(error_message(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 {
|
||||
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),
|
||||
};
|
||||
provide_context(ctx);
|
||||
|
||||
let params = use_params_map();
|
||||
let active_id = Memo::new(move |_| params.read().get("id").and_then(|id| id.parse::<i64>().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! {
|
||||
<main class="mx-auto flex min-h-dvh max-w-md flex-col px-4 pt-[max(1.5rem,env(safe-area-inset-top))] pb-32">
|
||||
<header class="flex items-start justify-between gap-4">
|
||||
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight">
|
||||
"mes"<br />"listes"
|
||||
</h1>
|
||||
<div
|
||||
class="grid size-14 shrink-0 place-items-center rounded-2xl bg-ink font-display text-lg font-bold text-lime"
|
||||
aria-label="Profil"
|
||||
>
|
||||
"CL"
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<ErrorBanner />
|
||||
|
||||
<Transition fallback=|| view! { <TicketSkeleton /> }>
|
||||
<ErrorBoundary fallback=|errors| {
|
||||
view! {
|
||||
<p class="mt-6 rounded-2xl bg-paper p-4">
|
||||
"Oups : "
|
||||
{move || {
|
||||
errors.get().into_iter().map(|(_, e)| e.to_string()).collect::<Vec<_>>().join(", ")
|
||||
}}
|
||||
</p>
|
||||
}
|
||||
}>
|
||||
{move || Suspend::new(async move {
|
||||
let lists = lists.await?;
|
||||
let items = items.await?;
|
||||
let suggestions = suggestions.await?;
|
||||
Ok::<_, ServerFnError>(view! {
|
||||
<ListsContent lists items suggestions active_id=active_id.get() />
|
||||
})
|
||||
})}
|
||||
</ErrorBoundary>
|
||||
</Transition>
|
||||
</main>
|
||||
|
||||
<ItemSheet list_id=active_id />
|
||||
<ListSheet />
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ListsContent(
|
||||
lists: Vec<ShoppingList>,
|
||||
items: Vec<Item>,
|
||||
suggestions: Vec<Suggestion>,
|
||||
active_id: Option<i64>,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<Ctx>();
|
||||
|
||||
let Some(active_id) = active_id else {
|
||||
return match lists.first() {
|
||||
Some(first) => view! { <Redirect path=format!("/l/{}", first.id) /> }.into_any(),
|
||||
None => view! {
|
||||
<ListTabs lists active=None remaining=0 />
|
||||
<EmptyState />
|
||||
}
|
||||
.into_any(),
|
||||
};
|
||||
};
|
||||
let Some(list) = lists.iter().find(|l| l.id == active_id).cloned() else {
|
||||
return view! {
|
||||
<ListTabs lists active=None remaining=0 />
|
||||
<p class="mt-6 rounded-2xl bg-paper p-4">"Cette liste n'existe plus."</p>
|
||||
}
|
||||
.into_any();
|
||||
};
|
||||
|
||||
// Items with pending checkbox changes applied.
|
||||
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::<Vec<_>>()
|
||||
})
|
||||
});
|
||||
let to_get = Memo::new(move |_| current.with(|items| items.iter().filter(|i| !i.checked).cloned().collect::<Vec<_>>()));
|
||||
let in_basket = Memo::new(move |_| current.with(|items| items.iter().filter(|i| i.checked).cloned().collect::<Vec<_>>()));
|
||||
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! {
|
||||
<ListTabs lists active=Some(active_id) remaining />
|
||||
|
||||
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<p class="font-mono text-sm tracking-[0.2em] text-ink/60 uppercase">
|
||||
{format!("Ticket N°{:03} · {}", list.id, ticket_date(&list.created_at))}
|
||||
</p>
|
||||
<button
|
||||
class="-mt-2 -mr-2 grid size-11 place-items-center rounded-full text-ink/60 active:bg-ink/5"
|
||||
aria-label="Modifier la liste"
|
||||
on:click=edit_list
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" class="size-6" aria-hidden="true">
|
||||
<circle cx="5" cy="12" r="2" />
|
||||
<circle cx="12" cy="12" r="2" />
|
||||
<circle cx="19" cy="12" r="2" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">
|
||||
{list.name.clone()}
|
||||
</h2>
|
||||
<p class="mt-1 text-lg text-ink/70">{move || remaining_text(remaining.get(), total())}</p>
|
||||
|
||||
<div class="mt-5 grid grid-cols-3 gap-3">
|
||||
<For each=move || to_get.get() key=|item| (item.id, item.quantity.map(|q| q.label()), item.name.clone(), item.icon, item.category) let:item>
|
||||
<ItemTile item />
|
||||
</For>
|
||||
{suggestions
|
||||
.into_iter()
|
||||
.map(|suggestion| view! { <SuggestionTile suggestion list_id=active_id /> })
|
||||
.collect_view()}
|
||||
</div>
|
||||
|
||||
<Show when=move || !in_basket.with(Vec::is_empty)>
|
||||
<div class="mt-6 border-t-2 border-dashed border-ink/15 pt-5">
|
||||
<div class="flex justify-between font-mono text-sm tracking-[0.2em] text-ink/60 uppercase">
|
||||
<span>"Déjà dans le panier"</span>
|
||||
<span>{move || format!("{}/{}", in_basket.with(Vec::len), total())}</span>
|
||||
</div>
|
||||
<div class="mt-4 grid grid-cols-4 gap-2">
|
||||
<For each=move || in_basket.get() key=|item| (item.id, item.name.clone(), item.icon) let:item>
|
||||
<BasketTile item />
|
||||
</For>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</section>
|
||||
|
||||
<button
|
||||
class="tile-shadow fixed right-[max(1rem,calc(50vw-14rem+1rem))] bottom-[max(1.25rem,env(safe-area-inset-bottom))] z-10 rounded-2xl border-2 border-ink bg-pink px-6 py-4 font-display text-xl font-bold active:translate-y-1 active:shadow-none"
|
||||
on:click=move |_| ctx.item_editor.set(Some(ItemEditor::New))
|
||||
>
|
||||
"+ article"
|
||||
</button>
|
||||
}
|
||||
.into_any()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ListTabs(lists: Vec<ShoppingList>, active: Option<i64>, #[prop(into)] remaining: Signal<usize>) -> impl IntoView {
|
||||
let ctx = expect_context::<Ctx>();
|
||||
view! {
|
||||
<nav class="-mx-4 mt-5 flex gap-3 overflow-x-auto px-4 pb-1 [scrollbar-width:none]">
|
||||
{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! {
|
||||
<A
|
||||
href=format!("/l/{}", list.id)
|
||||
attr:class=format!(
|
||||
"flex shrink-0 items-center gap-2 rounded-2xl border-2 px-5 py-3 text-lg font-semibold whitespace-nowrap {class}",
|
||||
)
|
||||
>
|
||||
{(!is_active)
|
||||
.then(|| {
|
||||
view! {
|
||||
<span class=format!(
|
||||
"size-4 rounded-full border-2 border-ink {}",
|
||||
list.color.dot_class(),
|
||||
) />
|
||||
}
|
||||
})}
|
||||
{list.name.clone()}
|
||||
{is_active.then_some(move || format!(" · {}", remaining.get()))}
|
||||
</A>
|
||||
}
|
||||
})
|
||||
.collect_view()}
|
||||
<button
|
||||
class="shrink-0 rounded-2xl border-2 border-dashed border-ink/50 px-5 py-3 text-lg font-semibold text-ink/70"
|
||||
aria-label="Nouvelle liste"
|
||||
on:click=move |_| ctx.list_editor.set(Some(ListEditor::New))
|
||||
>
|
||||
"+"
|
||||
</button>
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ErrorBanner() -> impl IntoView {
|
||||
let ctx = expect_context::<Ctx>();
|
||||
view! {
|
||||
{move || {
|
||||
ctx.error
|
||||
.get()
|
||||
.map(|msg| {
|
||||
view! {
|
||||
<div
|
||||
role="alert"
|
||||
class="mt-4 flex items-center justify-between gap-3 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-medium"
|
||||
>
|
||||
<span>{msg}</span>
|
||||
<button class="font-bold" on:click=move |_| ctx.error.set(None)>
|
||||
"OK"
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
})
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn EmptyState() -> impl IntoView {
|
||||
let ctx = expect_context::<Ctx>();
|
||||
view! {
|
||||
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8 text-center">
|
||||
<p class="text-lg text-ink/70">"Aucune liste pour l'instant."</p>
|
||||
<button
|
||||
class="tile-shadow mt-4 rounded-2xl border-2 border-ink bg-pink px-5 py-3 font-display font-bold"
|
||||
on:click=move |_| ctx.list_editor.set(Some(ListEditor::New))
|
||||
>
|
||||
"Créer une liste"
|
||||
</button>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn TicketSkeleton() -> impl IntoView {
|
||||
view! { <div class="ticket mt-20 h-96 animate-pulse bg-paper/60"></div> }
|
||||
}
|
||||
|
||||
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::<i32>().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 !");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user