first commit

This commit is contained in:
Romulus21 committed 2026-10-09 12:33:27 +02:00
commit 9536cf0dbe
16 files changed
+5170

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
use leptos::prelude::*;
use crate::model::Icon;
/// SVG path data (24×24 viewBox, filled with `currentColor`).
fn paths(icon: Icon) -> &'static [&'static str] {
match icon {
Icon::Apple => &[
"M12 7.5c-1.6-1.2-4.2-1.5-6 .2C3.9 9.6 4 13.4 5.6 16.4 7 19 8.9 21 11 20.5c.6-.1.9-.4 1-.4s.4.3 1 .4c2.1.5 4-1.5 5.4-4.1 1.6-3 1.7-6.8-.4-8.7-1.8-1.7-4.4-1.4-6 0Z",
"M11.4 7.2c-.2-1.7.3-3.4 1.3-4.6l1.1.9c-.8 1-1.1 2.3-.9 3.6Z",
"M13.2 5.6c.8-1.6 2.5-2.4 4.3-2.1-.4 1.7-2 2.8-4.3 2.1Z",
],
Icon::Banana => &[
"M4 6.5c1.3-.3 2.2.4 2.4 1.5.7 4.4 4 7.6 8.5 8.1 1.6.2 3.3 0 4.8-.6l.6 1.3c-2.2 1.9-5.1 2.8-8 2.4C7 18.5 3.4 13.8 3.3 8.2c0-.8.3-1.5.7-1.7Z",
"M3.4 4.6 5.6 4l.5 2.4-1.9.5Z",
],
Icon::Carrot => &[
"M14.8 9.2c-1.3-1.3-3.4-1.3-4.7 0L3.3 19.4c-.4.6.3 1.3.9.9l10.2-6.8c1.6-1.1 1.8-3.3.4-4.3Z",
"M15.5 8.5c.2-2 1.2-4.2 3-5.3l.8 1.2c-1.2.8-2 2.3-2.3 3.8 1.5-.3 3-1 3.9-2.2l1.1.9c-1.2 1.8-3.8 2.8-6.5 1.6Z",
],
Icon::Lemon => &[
"M19.6 6.5c.9-.4 1.1-1.6.4-2.3-.7-.7-1.9-.5-2.3.4-3.4-1.6-8-.4-10.9 2.5S2.6 13.8 4.2 17.2c-.9.4-1.1 1.6-.4 2.3.7.7 1.9.5 2.3-.4 3.4 1.6 8 .4 10.9-2.5s4.2-6.7 2.6-10.1Z",
],
Icon::Glass => &[
"M5 3h14l-1.6 16.2A2 2 0 0 1 15.4 21H8.6a2 2 0 0 1-2-1.8Z",
],
Icon::Milk => &[
"M8 2h8v3l2 3.5V20a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V8.5L8 5Z",
],
Icon::IceCream => &[
"M12 2a5 5 0 0 0-4.9 4A3.5 3.5 0 0 0 7.5 13h9a3.5 3.5 0 0 0 .4-7A5 5 0 0 0 12 2Z",
"M8 14h8l-3.3 7.4a.8.8 0 0 1-1.4 0Z",
],
Icon::Cheese => &[
"M2.5 11 14 4.5c2.8.3 5.7 2.5 7.5 6.5v8a1 1 0 0 1-1 1h-17a1 1 0 0 1-1-1Zm6 4a1.5 1.5 0 1 0 0-.01Zm8-1.5a1 1 0 1 0 0-.01Z",
],
Icon::Egg => &[
"M12 2.5c-3.6 0-7 6.3-7 11.2A7 7 0 0 0 12 21a7 7 0 0 0 7-7.3c0-4.9-3.4-11.2-7-11.2Z",
],
Icon::Coffee => &[
"M3 6h13v6a6 6 0 0 1-6 6H9a6 6 0 0 1-6-6Zm13 1.5h1.5a3 3 0 0 1 0 6h-1.8l.3-2h1.5a1 1 0 0 0 0-2H16Z",
"M3 20h13v1.8H3Z",
],
Icon::Bread => &[
"M12 3C6.5 3 3 5.3 3 8.3c0 1.4 1 2.4 2 2.7V19a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8c1-.3 2-1.3 2-2.7C21 5.3 17.5 3 12 3Z",
],
Icon::Croissant => &[
"M9.5 5.5 12 4l2.5 1.5-1 9h-3Z",
"M8.3 6.6 6.8 15H4.5L3 9.6Zm7.4 0 5.3 3-1.5 5.4h-2.3Z",
"M2 11.5 4 17H2.5L1 13Zm20 0L23 13l-1.5 4H20Z",
],
Icon::Pasta => &[
"M4 10h16v2a8 8 0 0 1-16 0Z",
"M7 9c0-3 1.5-6 3-7l1 .6C9.8 4 9 6.4 9 9Zm4 0c0-3 1.5-6 3-7l1 .6c-1.2 1.4-2 3.8-2 6.4Z",
],
Icon::Meat => &[
"M14.5 3.5c3.6 0 6 2.7 6 6 0 4.4-4.6 8-8.5 8-1.1 0-2 .4-2.6 1.1l-1.7 2a1.8 1.8 0 1 1-2.6-2.4l.3-.3a1.8 1.8 0 1 1 1.1-3.3c.9-.6 1.4-1.6 1.4-2.7 0-4 3-8.4 6.6-8.4Z",
],
Icon::Fish => &[
"M2 12c2.5-3.6 6-5.5 9.6-5.5 3.7 0 6.6 2.4 8 5.5-1.4 3.1-4.3 5.5-8 5.5C8 17.5 4.5 15.6 2 12Zm14.5-1.2a1.2 1.2 0 1 0 0 .01Z",
"M20.5 12 23 8v8Z",
],
Icon::Bottle => &[
"M10 2h4v4.5c2 1 3 2.7 3 4.8V20a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2v-8.7c0-2.1 1-3.8 3-4.8Z",
],
Icon::Basket => &[
"M7.6 9 11 3.4l1.3.8L9.3 9h5.4l-3-4.8 1.3-.8L16.4 9H22l-2 10.5a2 2 0 0 1-2 1.5H6a2 2 0 0 1-2-1.5L2 9Z",
],
}
}
pub fn icon_label(icon: Icon) -> &'static str {
match icon {
Icon::Apple => "Pomme",
Icon::Banana => "Banane",
Icon::Carrot => "Carotte",
Icon::Lemon => "Citron",
Icon::Glass => "Verre",
Icon::Milk => "Brique de lait",
Icon::IceCream => "Glace",
Icon::Cheese => "Fromage",
Icon::Egg => "Œuf",
Icon::Coffee => "Café",
Icon::Bread => "Pain",
Icon::Croissant => "Viennoiserie",
Icon::Pasta => "Pâtes",
Icon::Meat => "Viande",
Icon::Fish => "Poisson",
Icon::Bottle => "Bouteille",
Icon::Basket => "Panier",
}
}
#[component]
pub fn IconSvg(icon: Icon, #[prop(into, optional)] class: String) -> impl IntoView {
view! {
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class=class>
{paths(icon).iter().map(|d| view! { <path d=*d fill-rule="evenodd" /> }).collect_view()}
</svg>
}
}
+446
View File
@@ -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 !");
}
}
+382
View File
@@ -0,0 +1,382 @@
use leptos::ev;
use leptos::prelude::*;
use leptos_router::hooks::use_navigate;
use super::Ctx;
use super::icons::{IconSvg, icon_label};
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit};
#[derive(Clone, Debug, PartialEq)]
pub enum ItemEditor {
New,
Edit(Item),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ListEditor {
New,
Edit(ShoppingList),
}
/// Bottom sheet with a backdrop; `on_close` runs on backdrop tap or Escape.
#[component]
fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static, children: Children) -> impl IntoView {
let handle = window_event_listener(ev::keydown, move |ev| {
if ev.key() == "Escape" {
on_close();
}
});
on_cleanup(move || handle.remove());
view! {
<div class="fixed inset-0 z-20 flex items-end justify-center" role="dialog" aria-modal="true">
<div class="absolute inset-0 bg-ink/50" on:click=move |_| on_close()></div>
<div class="relative max-h-[90dvh] w-full max-w-md overflow-y-auto rounded-t-3xl border-2 border-b-0 border-ink bg-paper px-5 pt-3 pb-[max(1.5rem,env(safe-area-inset-bottom))]">
<div class="mx-auto mb-4 h-1.5 w-12 rounded-full bg-ink/20"></div>
<h2 class="font-display text-2xl font-bold">{title}</h2>
{children()}
</div>
</div>
}
}
#[component]
pub fn ItemSheet(#[prop(into)] list_id: Signal<Option<i64>>) -> impl IntoView {
let ctx = expect_context::<Ctx>();
move || {
let editor = ctx.item_editor.get()?;
let list_id = list_id.get()?;
Some(view! { <ItemForm editor list_id /> })
}
}
#[component]
fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let close = move || ctx.item_editor.set(None);
let existing = match &editor {
ItemEditor::Edit(item) => Some(item.clone()),
ItemEditor::New => None,
};
let name = RwSignal::new(existing.as_ref().map(|i| i.name.clone()).unwrap_or_default());
let amount = RwSignal::new(
existing
.as_ref()
.and_then(|i| i.quantity)
.map(|q| q.amount.to_string().replace('.', ","))
.unwrap_or_default(),
);
let unit = RwSignal::new(existing.as_ref().and_then(|i| i.quantity).map_or(Unit::Piece, |q| q.unit));
let icon = RwSignal::new(existing.as_ref().map_or(Icon::Basket, |i| i.icon));
let category = RwSignal::new(existing.as_ref().map_or(Category::Autre, |i| i.category));
let item_id = existing.as_ref().map(|i| i.id);
let invalid_amount = Memo::new(move |_| amount.with(|a| !a.trim().is_empty() && parse_amount(a).is_none()));
let submit = move |ev: ev::SubmitEvent| {
ev.prevent_default();
if invalid_amount.get() {
return;
}
let input = ItemInput {
name: name.get(),
quantity: parse_amount(&amount.get()).map(|amount| Quantity { amount, unit: unit.get() }),
icon: icon.get(),
category: category.get(),
};
match item_id {
Some(id) => ctx.mutate(crate::api::update_item(id, input), move |_| close()),
None => ctx.mutate(crate::api::add_item(list_id, input), move |_| close()),
}
};
let delete = move |_| {
if let Some(id) = item_id {
ctx.mutate(crate::api::delete_item(id), move |_| close());
}
};
let title = if item_id.is_some() { "Modifier l'article" } else { "Nouvel article" };
view! {
<Sheet title=title.to_owned() on_close=close>
<form class="mt-4 flex flex-col gap-5" on:submit=submit>
<label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span>
<input
class="field"
required
maxlength="60"
autofocus
placeholder="Avocats"
bind:value=name
/>
</label>
<div class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Quantité (facultatif)"
</span>
<div class="flex gap-2">
<input
class="field w-28"
inputmode="decimal"
placeholder="3"
aria-label="Quantité"
aria-invalid=move || invalid_amount.get().to_string()
bind:value=amount
/>
<select
class="field flex-1"
aria-label="Unité"
on:change=move |ev| {
if let Some(u) = Unit::parse(&event_target_value(&ev)) {
unit.set(u);
}
}
>
{Unit::ALL
.iter()
.map(|&u| {
view! {
<option value=u.as_str() selected=move || unit.get() == u>
{u.label()}
</option>
}
})
.collect_view()}
</select>
</div>
<Show when=move || invalid_amount.get()>
<p class="text-sm text-red-700">"Quantité invalide."</p>
</Show>
</div>
<fieldset class="flex flex-col gap-1.5">
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Rayon"
</legend>
<div class="flex flex-wrap gap-2">
{Category::ALL
.iter()
.map(|&c| {
view! {
<button
type="button"
class=move || {
format!(
"rounded-full border-2 px-3 py-1.5 text-sm font-semibold {} {}",
c.tile_class(),
if category.get() == c { "border-ink" } else { "border-transparent opacity-70" },
)
}
aria-pressed=move || (category.get() == c).to_string()
on:click=move |_| category.set(c)
>
{c.label()}
</button>
}
})
.collect_view()}
</div>
</fieldset>
<fieldset class="flex flex-col gap-1.5">
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Icône"
</legend>
<div class="grid grid-cols-6 gap-2">
{Icon::ALL
.iter()
.map(|&i| {
view! {
<button
type="button"
class=move || {
format!(
"grid aspect-square place-items-center rounded-xl border-2 {}",
if icon.get() == i {
"border-ink bg-lime"
} else {
"border-ink/10 bg-mist"
},
)
}
title=icon_label(i)
aria-label=icon_label(i)
aria-pressed=move || (icon.get() == i).to_string()
on:click=move |_| icon.set(i)
>
<IconSvg icon=i class="size-7" />
</button>
}
})
.collect_view()}
</div>
</fieldset>
<div class="flex gap-3">
{item_id
.map(|_| {
view! {
<button
type="button"
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
on:click=delete
>
"Supprimer"
</button>
}
})}
<button
type="submit"
class="tile-shadow flex-1 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-display text-lg font-bold active:translate-y-1 active:shadow-none"
>
{if item_id.is_some() { "Enregistrer" } else { "Ajouter" }}
</button>
</div>
</form>
</Sheet>
}
}
/// "1,5" / "1.5" / "3" → Some; empty or non-positive → None.
fn parse_amount(text: &str) -> Option<f64> {
let value = text.trim().replace(',', ".").parse::<f64>().ok()?;
(value.is_finite() && value > 0.0).then_some(value)
}
#[component]
pub fn ListSheet() -> impl IntoView {
let ctx = expect_context::<Ctx>();
move || ctx.list_editor.get().map(|editor| view! { <ListForm editor /> })
}
#[component]
fn ListForm(editor: ListEditor) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let navigate = use_navigate();
let close = move || ctx.list_editor.set(None);
let existing = match &editor {
ListEditor::Edit(list) => Some(list.clone()),
ListEditor::New => None,
};
let list_id = existing.as_ref().map(|l| l.id);
let name = RwSignal::new(existing.map(|l| l.name).unwrap_or_default());
let color = RwSignal::new(ListColor::Pink);
let submit = {
let navigate = navigate.clone();
move |ev: ev::SubmitEvent| {
ev.prevent_default();
match list_id {
Some(id) => ctx.mutate(crate::api::rename_list(id, name.get()), move |_| close()),
None => {
let navigate = navigate.clone();
ctx.mutate(crate::api::create_list(name.get(), color.get()), move |id| {
close();
navigate(&format!("/l/{id}"), Default::default());
})
}
}
}
};
let delete = move |_| {
let Some(id) = list_id else { return };
let confirmed = window()
.confirm_with_message("Supprimer cette liste et tous ses articles ?")
.unwrap_or(false);
if confirmed {
let navigate = navigate.clone();
ctx.mutate(crate::api::delete_list(id), move |_| {
close();
navigate("/", Default::default());
});
}
};
let title = if list_id.is_some() { "Modifier la liste" } else { "Nouvelle liste" };
view! {
<Sheet title=title.to_owned() on_close=close>
<form class="mt-4 flex flex-col gap-5" on:submit=submit>
<label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span>
<input
class="field"
required
maxlength="60"
autofocus
placeholder="Apéro de samedi"
bind:value=name
/>
</label>
<Show when=move || list_id.is_none()>
<fieldset>
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Couleur"
</legend>
<div class="flex gap-3">
{ListColor::ALL
.iter()
.map(|&c| {
view! {
<button
type="button"
class=move || {
format!(
"size-11 rounded-full border-2 {} {}",
c.dot_class(),
if color.get() == c { "border-ink ring-2 ring-ink ring-offset-2 ring-offset-paper" } else { "border-ink/40" },
)
}
aria-label=c.as_str()
aria-pressed=move || (color.get() == c).to_string()
on:click=move |_| color.set(c)
></button>
}
})
.collect_view()}
</div>
</fieldset>
</Show>
<div class="flex gap-3">
{list_id
.map(|_| {
view! {
<button
type="button"
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
on:click=delete
>
"Supprimer"
</button>
}
})}
<button
type="submit"
class="tile-shadow flex-1 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-display text-lg font-bold active:translate-y-1 active:shadow-none"
>
{if list_id.is_some() { "Enregistrer" } else { "Créer" }}
</button>
</div>
</form>
</Sheet>
}
}
#[cfg(test)]
mod tests {
use super::parse_amount;
#[test]
fn parses_amounts() {
assert_eq!(parse_amount("1,5"), Some(1.5));
assert_eq!(parse_amount(" 3 "), Some(3.0));
assert_eq!(parse_amount("0"), None);
assert_eq!(parse_amount("abc"), None);
}
}
+125
View File
@@ -0,0 +1,125 @@
use leptos::ev;
use leptos::prelude::*;
use super::icons::IconSvg;
use super::{Ctx, ItemEditor};
use crate::model::{Item, ItemInput, Suggestion};
const LONG_PRESS_MS: u64 = 450;
/// Item still to buy: tap moves it to the basket, long press opens the editor.
#[component]
pub fn ItemTile(item: Item) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let item = StoredValue::new(item);
let timer = StoredValue::new(None::<TimeoutHandle>);
// Set once the long press fired, so the following click is ignored.
let long_pressed = StoredValue::new(false);
let open_editor = move || {
long_pressed.set_value(true);
ctx.item_editor.set(Some(ItemEditor::Edit(item.get_value())));
};
let cancel_timer = move |_| {
if let Some(handle) = timer.get_value() {
handle.clear();
timer.set_value(None);
}
};
let start_timer = move |_: ev::PointerEvent| {
long_pressed.set_value(false);
let handle = set_timeout_with_handle(open_editor, std::time::Duration::from_millis(LONG_PRESS_MS)).ok();
timer.set_value(handle);
};
let on_click = move |_| {
if long_pressed.get_value() {
long_pressed.set_value(false);
} else {
item.with_value(|item| ctx.toggle(item));
}
};
let on_context_menu = move |ev: ev::MouseEvent| {
ev.prevent_default();
cancel_timer(());
open_editor();
};
let (name, icon, category, badge) = item.with_value(|item| {
(item.name.clone(), item.icon, item.category, item.quantity.map(|q| q.label()))
});
let aria_label = format!("{name} : mettre dans le panier");
view! {
<button
class=format!(
"tile-shadow relative flex aspect-square touch-manipulation flex-col items-center gap-1 rounded-2xl border-2 border-ink p-2 pb-2.5 text-center select-none active:translate-y-1 active:shadow-none [-webkit-touch-callout:none] {}",
category.tile_class(),
)
aria-label=aria_label
on:click=on_click
on:contextmenu=on_context_menu
on:pointerdown=start_timer
on:pointerup=move |_| cancel_timer(())
on:pointerleave=move |_| cancel_timer(())
on:pointercancel=move |_| cancel_timer(())
>
{badge
.map(|badge| {
view! {
<span class="absolute top-2 right-2 rounded-lg bg-ink px-1.5 py-0.5 font-mono text-xs text-paper">
{badge}
</span>
}
})}
<IconSvg icon class="min-h-0 w-full flex-1 text-ink" />
<span class="line-clamp-2 text-[0.95rem] leading-tight font-semibold break-words hyphens-auto">
{name}
</span>
</button>
}
}
/// Dashed "+ Beurre" tile: one tap adds a frequently bought product.
#[component]
pub fn SuggestionTile(suggestion: Suggestion, list_id: i64) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let Suggestion { name, icon, category } = suggestion;
let label = format!("+ {name}");
let add = move |_| {
let input = ItemInput { name: name.clone(), quantity: None, icon, category };
ctx.mutate(crate::api::add_item(list_id, input), |_| ());
};
view! {
<button
class="relative flex aspect-square flex-col items-center gap-1 rounded-2xl border-2 border-dashed border-ink/35 p-2 pb-2.5 text-center text-ink/55 active:bg-ink/5"
on:click=add
>
<IconSvg icon class="min-h-0 w-full flex-1 opacity-60" />
<span class="line-clamp-2 text-[0.95rem] leading-tight font-semibold">{label}</span>
</button>
}
}
/// Greyed tile in "Déjà dans le panier": tap puts the item back on the list.
#[component]
pub fn BasketTile(item: Item) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let (name, icon) = (item.name.clone(), item.icon);
let aria_label = format!("{name} : remettre dans la liste");
let item = StoredValue::new(item);
view! {
<button
class="flex aspect-square flex-col items-center gap-0.5 rounded-2xl bg-mist p-1.5 text-center text-ink/45 active:bg-ink/10"
aria-label=aria_label
on:click=move |_| item.with_value(|item| ctx.toggle(item))
>
<IconSvg icon class="min-h-0 w-full flex-1" />
<span class="line-clamp-2 text-xs leading-tight font-medium line-through decoration-ink/30">
{name}
</span>
</button>
}
}