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

+91
View File
@@ -0,0 +1,91 @@
use leptos::prelude::*;
use leptos::server_fn::codec::Json;
use crate::model::{Item, ItemInput, ListColor, ShoppingList, Suggestion};
#[cfg(feature = "ssr")]
mod server {
use leptos::prelude::*;
use sqlx::SqlitePool;
pub fn pool() -> Result<SqlitePool, ServerFnError> {
use_context::<SqlitePool>().ok_or_else(|| ServerFnError::new("database pool missing"))
}
pub fn db_err(err: sqlx::Error) -> ServerFnError {
leptos::logging::error!("database error: {err}");
ServerFnError::new("Erreur de base de données")
}
pub fn clean_name(name: &str) -> Result<String, ServerFnError> {
let name = name.trim();
if name.is_empty() || name.chars().count() > 60 {
return Err(ServerFnError::new("Le nom doit faire entre 1 et 60 caractères"));
}
Ok(name.to_owned())
}
}
#[server]
pub async fn get_lists() -> Result<Vec<ShoppingList>, ServerFnError> {
use server::*;
crate::db::lists(&pool()?).await.map_err(db_err)
}
#[server]
pub async fn create_list(name: String, color: ListColor) -> Result<i64, ServerFnError> {
use server::*;
let name = clean_name(&name)?;
crate::db::create_list(&pool()?, &name, color).await.map_err(db_err)
}
#[server]
pub async fn rename_list(id: i64, name: String) -> Result<(), ServerFnError> {
use server::*;
let name = clean_name(&name)?;
crate::db::rename_list(&pool()?, id, &name).await.map_err(db_err)
}
#[server]
pub async fn delete_list(id: i64) -> Result<(), ServerFnError> {
use server::*;
crate::db::delete_list(&pool()?, id).await.map_err(db_err)
}
#[server]
pub async fn get_items(list_id: i64) -> Result<Vec<Item>, ServerFnError> {
use server::*;
crate::db::items(&pool()?, list_id).await.map_err(db_err)
}
#[server(input = Json)]
pub async fn add_item(list_id: i64, input: ItemInput) -> Result<i64, ServerFnError> {
use server::*;
let input = ItemInput { name: clean_name(&input.name)?, ..input };
crate::db::add_item(&pool()?, list_id, &input).await.map_err(db_err)
}
#[server(input = Json)]
pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> {
use server::*;
let input = ItemInput { name: clean_name(&input.name)?, ..input };
crate::db::update_item(&pool()?, id, &input).await.map_err(db_err)
}
#[server]
pub async fn delete_item(id: i64) -> Result<(), ServerFnError> {
use server::*;
crate::db::delete_item(&pool()?, id).await.map_err(db_err)
}
#[server]
pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> {
use server::*;
crate::db::set_checked(&pool()?, id, checked).await.map_err(db_err)
}
#[server]
pub async fn get_suggestions(list_id: i64) -> Result<Vec<Suggestion>, ServerFnError> {
use server::*;
crate::db::suggestions(&pool()?, list_id, 3).await.map_err(db_err)
}
+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>
}
}
+249
View File
@@ -0,0 +1,249 @@
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRow};
use sqlx::Row;
use std::str::FromStr;
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Suggestion, Unit};
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
let options = SqliteConnectOptions::from_str(url)?
.create_if_missing(true)
.foreign_keys(true);
// Each connection to `:memory:` opens a distinct database.
let max = if url.contains(":memory:") { 1 } else { 5 };
let pool = SqlitePoolOptions::new()
.max_connections(max)
.connect_with(options)
.await?;
sqlx::migrate!().run(&pool).await?;
Ok(pool)
}
fn decode<T>(value: Option<T>, column: &str) -> Result<T, sqlx::Error> {
value.ok_or_else(|| sqlx::Error::Decode(format!("invalid value in column `{column}`").into()))
}
fn list_from_row(row: &SqliteRow) -> Result<ShoppingList, sqlx::Error> {
Ok(ShoppingList {
id: row.try_get("id")?,
name: row.try_get("name")?,
color: decode(ListColor::parse(row.try_get("color")?), "color")?,
created_at: row.try_get("created_at")?,
})
}
fn item_from_row(row: &SqliteRow) -> Result<Item, sqlx::Error> {
let amount: Option<f64> = row.try_get("amount")?;
let unit: Option<String> = row.try_get("unit")?;
let quantity = match (amount, unit) {
(Some(amount), Some(unit)) => Some(Quantity {
amount,
unit: decode(Unit::parse(&unit), "unit")?,
}),
_ => None,
};
Ok(Item {
id: row.try_get("id")?,
list_id: row.try_get("list_id")?,
name: row.try_get("name")?,
quantity,
icon: decode(Icon::parse(row.try_get("icon")?), "icon")?,
category: decode(Category::parse(row.try_get("category")?), "category")?,
checked: row.try_get("checked")?,
})
}
pub async fn lists(pool: &SqlitePool) -> Result<Vec<ShoppingList>, sqlx::Error> {
sqlx::query("SELECT id, name, color, created_at FROM lists ORDER BY id")
.fetch_all(pool)
.await?
.iter()
.map(list_from_row)
.collect()
}
pub async fn create_list(pool: &SqlitePool, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
let row = sqlx::query("INSERT INTO lists (name, color) VALUES (?, ?) RETURNING id")
.bind(name)
.bind(color.as_str())
.fetch_one(pool)
.await?;
row.try_get("id")
}
pub async fn rename_list(pool: &SqlitePool, id: i64, name: &str) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE lists SET name = ? WHERE id = ?")
.bind(name)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM lists WHERE id = ?").bind(id).execute(pool).await?;
Ok(())
}
pub async fn items(pool: &SqlitePool, list_id: i64) -> Result<Vec<Item>, sqlx::Error> {
sqlx::query(
"SELECT id, list_id, name, amount, unit, icon, category, checked
FROM items WHERE list_id = ? ORDER BY id",
)
.bind(list_id)
.fetch_all(pool)
.await?
.iter()
.map(item_from_row)
.collect()
}
/// Remembers the product in the catalog so it can be suggested later.
async fn record_in_catalog(pool: &SqlitePool, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO catalog (name, icon, category, use_count) VALUES (?, ?, ?, 1)
ON CONFLICT(name) DO UPDATE SET
icon = excluded.icon,
category = excluded.category,
use_count = use_count + 1",
)
.bind(&input.name)
.bind(input.icon.as_str())
.bind(input.category.as_str())
.execute(pool)
.await?;
Ok(())
}
pub async fn add_item(pool: &SqlitePool, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
let row = sqlx::query(
"INSERT INTO items (list_id, name, amount, unit, icon, category)
VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
)
.bind(list_id)
.bind(&input.name)
.bind(input.quantity.map(|q| q.amount))
.bind(input.quantity.map(|q| q.unit.as_str()))
.bind(input.icon.as_str())
.bind(input.category.as_str())
.fetch_one(pool)
.await?;
record_in_catalog(pool, input).await?;
row.try_get("id")
}
pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query(
"UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?",
)
.bind(&input.name)
.bind(input.quantity.map(|q| q.amount))
.bind(input.quantity.map(|q| q.unit.as_str()))
.bind(input.icon.as_str())
.bind(input.category.as_str())
.bind(id)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_item(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(pool).await?;
Ok(())
}
pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
.bind(checked)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
/// Most used catalog products not already on the list.
pub async fn suggestions(pool: &SqlitePool, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
sqlx::query(
"SELECT name, icon, category FROM catalog c
WHERE NOT EXISTS (
SELECT 1 FROM items i WHERE i.list_id = ? AND i.name = c.name COLLATE NOCASE
)
ORDER BY use_count DESC, name
LIMIT ?",
)
.bind(list_id)
.bind(limit)
.fetch_all(pool)
.await?
.iter()
.map(|row| {
Ok(Suggestion {
name: row.try_get("name")?,
icon: decode(Icon::parse(row.try_get("icon")?), "icon")?,
category: decode(Category::parse(row.try_get("category")?), "category")?,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
async fn pool() -> SqlitePool {
connect("sqlite::memory:").await.unwrap()
}
fn input(name: &str) -> ItemInput {
ItemInput {
name: name.into(),
quantity: Some(Quantity { amount: 3.0, unit: Unit::Piece }),
icon: Icon::Apple,
category: Category::FruitsLegumes,
}
}
#[tokio::test]
async fn item_crud_and_toggle() {
let pool = pool().await;
let list = lists(&pool).await.unwrap()[0].id;
let id = add_item(&pool, list, &input("Avocats")).await.unwrap();
let mut edited = input("Avocats");
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
update_item(&pool, id, &edited).await.unwrap();
set_checked(&pool, id, true).await.unwrap();
let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1);
assert_eq!(all[0].quantity.unwrap().label(), "×4");
assert!(all[0].checked);
delete_item(&pool, id).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty());
}
#[tokio::test]
async fn suggestions_skip_items_on_list() {
let pool = pool().await;
let list = lists(&pool).await.unwrap()[0].id;
add_item(&pool, list, &input("beurre")).await.unwrap();
let names: Vec<_> = suggestions(&pool, list, 3)
.await
.unwrap()
.into_iter()
.map(|s| s.name)
.collect();
assert!(!names.iter().any(|n| n.eq_ignore_ascii_case("beurre")));
assert_eq!(names.len(), 3);
}
#[tokio::test]
async fn deleting_list_cascades() {
let pool = pool().await;
let list = create_list(&pool, "Apéro", ListColor::Pink).await.unwrap();
add_item(&pool, list, &input("Chips")).await.unwrap();
delete_list(&pool, list).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty());
}
}
+13
View File
@@ -0,0 +1,13 @@
pub mod api;
pub mod app;
pub mod model;
#[cfg(feature = "ssr")]
pub mod db;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(app::App);
}
+44
View File
@@ -0,0 +1,44 @@
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::prelude::*;
use leptos_axum::{LeptosRoutes, generate_route_list};
use lisette::app::{App, shell};
let conf = get_configuration(None).expect("invalid Leptos configuration");
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let database_url =
std::env::var("DATABASE_URL").unwrap_or_else(|_| "sqlite://lisette.db".to_owned());
let pool = lisette::db::connect(&database_url)
.await
.expect("cannot open database");
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes_with_context(
&leptos_options,
routes,
{
let pool = pool.clone();
move || provide_context(pool.clone())
},
{
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
},
)
.fallback(leptos_axum::file_and_error_handler(shell))
.with_state(leptos_options);
// Server functions are registered by `leptos_routes_with_context`; they get the pool
// from the same context closure.
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
leptos::logging::log!("listening on http://{addr}");
axum::serve(listener, app.into_make_service()).await.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {}
+243
View File
@@ -0,0 +1,243 @@
use serde::{Deserialize, Serialize};
/// Generates `as_str` / `from_str` / `ALL` for a fieldless enum stored as TEXT.
macro_rules! text_enum {
($name:ident { $($variant:ident => $text:literal),+ $(,)? }) => {
impl $name {
pub const ALL: &'static [$name] = &[$($name::$variant),+];
pub fn as_str(self) -> &'static str {
match self {
$($name::$variant => $text),+
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
$($text => Some($name::$variant),)+
_ => None,
}
}
}
};
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ShoppingList {
pub id: i64,
pub name: String,
pub color: ListColor,
pub created_at: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ListColor {
Lime,
Pink,
Sky,
Peach,
}
text_enum!(ListColor {
Lime => "lime",
Pink => "pink",
Sky => "sky",
Peach => "peach",
});
impl ListColor {
pub fn dot_class(self) -> &'static str {
match self {
ListColor::Lime => "bg-lime",
ListColor::Pink => "bg-pink",
ListColor::Sky => "bg-sky",
ListColor::Peach => "bg-peach",
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Item {
pub id: i64,
pub list_id: i64,
pub name: String,
pub quantity: Option<Quantity>,
pub icon: Icon,
pub category: Category,
pub checked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Quantity {
pub amount: f64,
pub unit: Unit,
}
impl Quantity {
/// Short label for the tile badge: "×3", "500 g", "1,5 L".
pub fn label(&self) -> String {
let amount = if self.amount.fract() == 0.0 {
format!("{}", self.amount as i64)
} else {
format!("{}", self.amount).replace('.', ",")
};
match self.unit {
Unit::Piece => format!("×{amount}"),
unit => format!("{amount} {}", unit.label()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Unit {
Piece,
Gram,
Kilogram,
Millilitre,
Litre,
}
text_enum!(Unit {
Piece => "pc",
Gram => "g",
Kilogram => "kg",
Millilitre => "ml",
Litre => "l",
});
impl Unit {
pub fn label(self) -> &'static str {
match self {
Unit::Piece => "pièce(s)",
Unit::Gram => "g",
Unit::Kilogram => "kg",
Unit::Millilitre => "mL",
Unit::Litre => "L",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Category {
FruitsLegumes,
Frais,
Epicerie,
Viande,
Boulangerie,
Autre,
}
text_enum!(Category {
FruitsLegumes => "fruits_legumes",
Frais => "frais",
Epicerie => "epicerie",
Viande => "viande",
Boulangerie => "boulangerie",
Autre => "autre",
});
impl Category {
pub fn label(self) -> &'static str {
match self {
Category::FruitsLegumes => "Fruits & légumes",
Category::Frais => "Frais",
Category::Epicerie => "Épicerie",
Category::Viande => "Viande & poisson",
Category::Boulangerie => "Boulangerie",
Category::Autre => "Autre",
}
}
/// Tailwind background class for the item tile.
pub fn tile_class(self) -> &'static str {
match self {
Category::FruitsLegumes => "bg-lime",
Category::Frais => "bg-sky",
Category::Epicerie => "bg-peach",
Category::Viande => "bg-rose",
Category::Boulangerie => "bg-sand",
Category::Autre => "bg-lilac",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Icon {
Apple,
Banana,
Carrot,
Lemon,
Glass,
Milk,
IceCream,
Cheese,
Egg,
Coffee,
Bread,
Croissant,
Pasta,
Meat,
Fish,
Bottle,
Basket,
}
text_enum!(Icon {
Apple => "apple",
Banana => "banana",
Carrot => "carrot",
Lemon => "lemon",
Glass => "glass",
Milk => "milk",
IceCream => "ice_cream",
Cheese => "cheese",
Egg => "egg",
Coffee => "coffee",
Bread => "bread",
Croissant => "croissant",
Pasta => "pasta",
Meat => "meat",
Fish => "fish",
Bottle => "bottle",
Basket => "basket",
});
/// A frequently bought product, offered as a dashed "+ Beurre" tile.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Suggestion {
pub name: String,
pub icon: Icon,
pub category: Category,
}
/// Payload for creating or editing an item.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ItemInput {
pub name: String,
pub quantity: Option<Quantity>,
pub icon: Icon,
pub category: Category,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quantity_labels() {
let q = |amount, unit| Quantity { amount, unit }.label();
assert_eq!(q(3.0, Unit::Piece), "×3");
assert_eq!(q(500.0, Unit::Gram), "500 g");
assert_eq!(q(1.5, Unit::Litre), "1,5 L");
}
#[test]
fn text_roundtrip() {
for icon in Icon::ALL {
assert_eq!(Icon::parse(icon.as_str()), Some(*icon));
}
for cat in Category::ALL {
assert_eq!(Category::parse(cat.as_str()), Some(*cat));
}
}
}