Compare commits

...
11 Commits
Author SHA1 Message Date
Romulus21andClaude Opus 5.5 1f83787fbd Ajoute 24 pictogrammes et les range par rayon
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:56:30 +01:00
Romulus21andClaude Opus 5.5 28a1a17802 Adapte la feuille de style aux ordinateurs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:50:39 +01:00
Romulus21andClaude Opus 5.5 3afb658b40 Relève la limite de récursion pour le build release du front
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:44:56 +01:00
Romulus21andClaude Opus 5.5 ca42b85f24 Retire les suggestions et le décompte sous le titre de la liste
Les tuiles « + Beurre » disparaissent avec leur requête, leur fonction
SQL et leurs styles. La ligne « Encore N articles à attraper. » est
retirée : le nombre reste affiché dans l'onglet de la liste.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:43:45 +01:00
Romulus21andClaude Opus 5.5 e47db8b070 Remplace Tailwind par une feuille de style classique
style/main.css est désormais servi tel quel par cargo-leptos (style-file) :
remise à zéro des styles du navigateur, couleurs en variables CSS et
classes nommées par composant à la place des classes utilitaires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:39:42 +01:00
Romulus21andClaude Opus 5.5 6b5eaa0ba6 Remplace « + article » par une recherche dans la liste
Le bouton « ajouter » ouvre un champ unique : il retrouve les articles
de la liste et du panier, un appui les fait passer de l'un à l'autre, et
un bouton ajoute le nom saisi s'il n'existe pas encore.

Le fond de la page et la couleur de la barre d'état prennent aussi la
couleur de la liste ouverte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:30:57 +01:00
Romulus21andClaude Opus 5.5 444319f9a5 Masque le choix d'icône à la création d'un article
Un nouvel article prend le panier ; l'icône reste modifiable depuis
l'éditeur de l'article.

Closes #4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:14:41 +01:00
Romulus21andClaude Opus 5.5 a34e86dea6 Retire la ligne « Ticket N° · date » en haut des listes
Le numéro était l'identifiant global de la liste et la date celle de
sa création : ni l'un ni l'autre n'aidait. Le bouton « … » remonte à
côté du titre.

Closes #3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:14:41 +01:00
Romulus21andClaude Opus 5.5 9aa81a22fe Anime le passage d'un article entre la liste et le panier
Le basculement passe par une View Transition : chaque tuile porte un
view-transition-name, la tuile glisse vers sa nouvelle place et les
autres se décalent. Sans support navigateur, rien ne change.

Closes #1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:54:23 +01:00
Romulus21andClaude Opus 5.5 6c593b0201 Enregistre les changements d'articles par lots en arrière-plan
Cocher, ajouter, modifier ou supprimer un article s'affiche aussitôt :
le changement attend dans une file, fusionné avec les précédents, puis
part avec les autres en une seule requête, une à la fois. Le serveur
applique le lot dans une transaction et résout les ids temporaires des
articles ajoutés. Sans réseau, le lot est gardé et renvoyé plus tard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 08:47:25 +02:00
Romulus21andClaude Opus 5.5 f3f5f0cee1 Ajoute un administrateur qui gère les comptes
Le premier compte inscrit devient administrateur. La page /admin lui
permet de lister, créer, modifier et supprimer les comptes, même quand
les inscriptions sont fermées.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:03:47 +02:00
16 changed files with 2753 additions and 561 deletions

No files matched your search

Generated
+1
View File
@@ -1397,6 +1397,7 @@ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",
"dotenvy", "dotenvy",
"hex", "hex",
"js-sys",
"leptos", "leptos",
"leptos_axum", "leptos_axum",
"leptos_meta", "leptos_meta",
+4 -2
View File
@@ -21,7 +21,8 @@ hex = { version = "0.4", optional = true }
dotenvy = { version = "0.15", optional = true } dotenvy = { version = "0.15", optional = true }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
wasm-bindgen = { version = "=0.2.128", optional = true } wasm-bindgen = { version = "=0.2.128", optional = true }
web-sys = { version = "0.3", features = ["CloseEvent", "Document", "Location", "MessageEvent", "VisibilityState", "WebSocket", "Window"], optional = true } js-sys = { version = "0.3", optional = true }
web-sys = { version = "0.3", features = ["CloseEvent", "Document", "Element", "Location", "MessageEvent", "VisibilityState", "WebSocket", "Window"], optional = true }
send_wrapper = { version = "0.6", optional = true } send_wrapper = { version = "0.6", optional = true }
console_error_panic_hook = { version = "0.1", optional = true } console_error_panic_hook = { version = "0.1", optional = true }
@@ -30,6 +31,7 @@ hydrate = [
"leptos/hydrate", "leptos/hydrate",
"dep:console_error_panic_hook", "dep:console_error_panic_hook",
"dep:wasm-bindgen", "dep:wasm-bindgen",
"dep:js-sys",
"dep:web-sys", "dep:web-sys",
"dep:send_wrapper", "dep:send_wrapper",
] ]
@@ -59,7 +61,7 @@ panic = "abort"
output-name = "lisette" output-name = "lisette"
site-root = "target/site" site-root = "target/site"
site-pkg-dir = "pkg" site-pkg-dir = "pkg"
tailwind-input-file = "style/main.css" style-file = "style/main.css"
assets-dir = "public" assets-dir = "public"
site-addr = "127.0.0.1:3002" site-addr = "127.0.0.1:3002"
reload-port = 3001 reload-port = 3001
+4
View File
@@ -0,0 +1,4 @@
ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0;
-- The first account to register administers the others.
UPDATE users SET is_admin = 1 WHERE id = (SELECT MIN(id) FROM users);
+203 -70
View File
@@ -1,7 +1,7 @@
use leptos::prelude::*; use leptos::prelude::*;
use leptos::server_fn::codec::Json; use leptos::server_fn::codec::Json;
use crate::model::{Item, ItemInput, ListColor, Member, ShoppingList, Suggestion, User}; use crate::model::{Account, Item, ItemOp, ListColor, Member, ShoppingList, SyncReport, User};
pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi."; pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi.";
@@ -29,6 +29,20 @@ mod server {
.ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN)) .ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN))
} }
pub async fn require_admin(pool: &SqlitePool) -> Result<User, ServerFnError> {
let user = require_user(pool).await?;
if !user.is_admin {
return Err(ServerFnError::new("Réservé aux administrateurs."));
}
Ok(user)
}
/// Sign-ups follow `REGISTRATION_ENABLED`, but stay open until the first
/// account (the admin) exists.
pub async fn registration_open(pool: &SqlitePool) -> Result<bool, ServerFnError> {
Ok(crate::auth::registration_enabled() || !crate::db::has_users(pool).await.map_err(db_err)?)
}
fn not_found() -> ServerFnError { fn not_found() -> ServerFnError {
ServerFnError::new("Liste introuvable.") ServerFnError::new("Liste introuvable.")
} }
@@ -48,16 +62,6 @@ mod server {
} }
} }
/// Fails unless the item belongs to a list the user can access; returns that list.
pub async fn require_item(pool: &SqlitePool, user: &User, item_id: i64) -> Result<i64, ServerFnError> {
let list_id = crate::db::item_list_id(pool, item_id)
.await
.map_err(db_err)?
.ok_or_else(|| ServerFnError::new("Article introuvable."))?;
require_list(pool, user, list_id).await?;
Ok(list_id)
}
/// Everyone who can see the list, to pass to [`notify`] once it changed. /// Everyone who can see the list, to pass to [`notify`] once it changed.
pub async fn audience(pool: &SqlitePool, list_id: i64) -> Result<Vec<i64>, ServerFnError> { pub async fn audience(pool: &SqlitePool, list_id: i64) -> Result<Vec<i64>, ServerFnError> {
crate::db::list_audience(pool, list_id).await.map_err(db_err) crate::db::list_audience(pool, list_id).await.map_err(db_err)
@@ -76,6 +80,13 @@ mod server {
Ok(()) Ok(())
} }
pub fn message(err: ServerFnError) -> String {
match err {
ServerFnError::ServerError(msg) => msg,
err => err.to_string(),
}
}
pub fn clean_name(name: &str, max: usize) -> Result<String, ServerFnError> { pub fn clean_name(name: &str, max: usize) -> Result<String, ServerFnError> {
let name = name.trim(); let name = name.trim();
if name.is_empty() || name.chars().count() > max { if name.is_empty() || name.chars().count() > max {
@@ -96,6 +107,29 @@ mod server {
Ok(email) Ok(email)
} }
pub fn check_password(password: &str) -> Result<(), ServerFnError> {
if !(8..=128).contains(&password.chars().count()) {
return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères."));
}
Ok(())
}
pub async fn hash(password: String) -> Result<String, ServerFnError> {
blocking(move || crate::auth::hash_password(&password))
.await?
.map_err(|_| ServerFnError::new("Erreur interne"))
}
/// Maps a duplicate email to a readable error.
pub fn email_err(err: sqlx::Error) -> ServerFnError {
match err {
sqlx::Error::Database(err) if err.is_unique_violation() => {
ServerFnError::new("Un compte existe déjà avec cet email.")
}
err => db_err(err),
}
}
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> { pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> {
tokio::task::spawn_blocking(f) tokio::task::spawn_blocking(f)
.await .await
@@ -113,32 +147,23 @@ pub async fn get_me() -> Result<Option<User>, ServerFnError> {
#[server] #[server]
pub async fn registration_enabled() -> Result<bool, ServerFnError> { pub async fn registration_enabled() -> Result<bool, ServerFnError> {
Ok(crate::auth::registration_enabled()) use server::*;
registration_open(&pool()?).await
} }
#[server] #[server]
pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> { pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> {
use server::*; use server::*;
if !crate::auth::registration_enabled() { let pool = pool()?;
if !registration_open(&pool).await? {
return Err(ServerFnError::new("Les inscriptions sont fermées.")); return Err(ServerFnError::new("Les inscriptions sont fermées."));
} }
let pool = pool()?;
let name = clean_name(&name, 40)?; let name = clean_name(&name, 40)?;
let email = clean_email(&email)?; let email = clean_email(&email)?;
if !(8..=128).contains(&password.chars().count()) { check_password(&password)?;
return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères."));
}
let hash = blocking(move || crate::auth::hash_password(&password)) let hash = hash(password).await?;
.await? let user_id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?;
.map_err(|_| ServerFnError::new("Erreur interne"))?;
let user_id = match crate::db::register(&pool, &email, &name, &hash).await {
Ok(id) => id,
Err(sqlx::Error::Database(err)) if err.is_unique_violation() => {
return Err(ServerFnError::new("Un compte existe déjà avec cet email."));
}
Err(err) => return Err(db_err(err)),
};
crate::auth::start_session(&pool, user_id).await.map_err(db_err)?; crate::auth::start_session(&pool, user_id).await.map_err(db_err)?;
leptos_axum::redirect("/"); leptos_axum::redirect("/");
Ok(()) Ok(())
@@ -170,6 +195,89 @@ pub async fn logout() -> Result<(), ServerFnError> {
Ok(()) Ok(())
} }
// --- Administration ---------------------------------------------------------
#[server]
pub async fn get_accounts() -> Result<Vec<Account>, ServerFnError> {
use server::*;
let pool = pool()?;
require_admin(&pool).await?;
crate::db::accounts(&pool).await.map_err(db_err)
}
/// Creates an account even when sign-ups are closed.
#[server]
pub async fn create_account(name: String, email: String, password: String, is_admin: bool) -> Result<(), ServerFnError> {
use server::*;
let pool = pool()?;
require_admin(&pool).await?;
let name = clean_name(&name, 40)?;
let email = clean_email(&email)?;
check_password(&password)?;
let hash = hash(password).await?;
let id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?;
if is_admin {
crate::db::update_user(&pool, id, &name, &email, true).await.map_err(db_err)?;
}
Ok(())
}
/// An empty `password` keeps the current one.
#[server]
pub async fn update_account(
id: i64,
name: String,
email: String,
password: String,
is_admin: bool,
) -> Result<(), ServerFnError> {
use server::*;
let pool = pool()?;
let admin = require_admin(&pool).await?;
if id == admin.id && !is_admin {
return Err(ServerFnError::new("Tu ne peux pas retirer tes propres droits d'administration."));
}
let name = clean_name(&name, 40)?;
let email = clean_email(&email)?;
if !password.is_empty() {
check_password(&password)?;
}
crate::db::update_user(&pool, id, &name, &email, is_admin).await.map_err(email_err)?;
if !password.is_empty() {
let hash = hash(password).await?;
crate::db::set_password(&pool, id, &hash).await.map_err(db_err)?;
if id == admin.id {
// set_password signed every session out, this one included.
crate::auth::start_session(&pool, id).await.map_err(db_err)?;
}
}
Ok(())
}
/// Deletes the account and the lists it owns.
#[server]
pub async fn delete_account(id: i64) -> Result<(), ServerFnError> {
use server::*;
let pool = pool()?;
let admin = require_admin(&pool).await?;
if id == admin.id {
return Err(ServerFnError::new("Tu ne peux pas supprimer ton propre compte."));
}
// Members of the lists it owns or shares see them change.
let mut users = Vec::new();
for list in crate::db::lists(&pool, id).await.map_err(db_err)? {
users.extend(audience(&pool, list.id).await?);
}
crate::db::delete_user(&pool, id).await.map_err(db_err)?;
users.sort_unstable();
users.dedup();
notify(users);
Ok(())
}
// --- Lists ------------------------------------------------------------------ // --- Lists ------------------------------------------------------------------
#[server] #[server]
@@ -268,54 +376,79 @@ pub async fn get_items(list_id: i64) -> Result<Vec<Item>, ServerFnError> {
crate::db::items(&pool, list_id).await.map_err(db_err) crate::db::items(&pool, list_id).await.map_err(db_err)
} }
/// Applies a batch of item changes queued by the browser. Changes to items
/// deleted meanwhile are dropped; invalid ones are skipped and reported.
#[server(input = Json)] #[server(input = Json)]
pub async fn add_item(list_id: i64, input: ItemInput) -> Result<i64, ServerFnError> { pub async fn sync_items(ops: Vec<ItemOp>) -> Result<SyncReport, ServerFnError> {
use crate::model::ItemInput;
use server::*; use server::*;
let pool = pool()?; let pool = pool()?;
let user = require_user(&pool).await?; let user = require_user(&pool).await?;
require_list(&pool, &user, list_id).await?;
let input = ItemInput { name: clean_name(&input.name, 60)?, ..input };
let id = crate::db::add_item(&pool, user.id, list_id, &input).await.map_err(db_err)?;
notify_list(&pool, list_id).await?;
Ok(id)
}
#[server(input = Json)] // Lists checked so far, and whether the user can access them.
pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> { let mut access: Vec<(i64, bool)> = Vec::new();
use server::*; // Temporary ids added in this batch, with their list.
let pool = pool()?; let mut added: Vec<(i64, i64)> = Vec::new();
let user = require_user(&pool).await?; let mut accepted = Vec::with_capacity(ops.len());
let list_id = require_item(&pool, &user, id).await?; let mut rejected = None;
let input = ItemInput { name: clean_name(&input.name, 60)?, ..input }; for op in ops {
crate::db::update_item(&pool, id, &input).await.map_err(db_err)?; let list_id = match &op {
notify_list(&pool, list_id).await ItemOp::Add { id, list_id, .. } if *id < 0 => Some(*list_id),
} ItemOp::Add { .. } => None,
op if op.id() < 0 => added.iter().find(|&&(temp, _)| temp == op.id()).map(|&(_, list)| list),
op => crate::db::item_list_id(&pool, op.id()).await.map_err(db_err)?,
};
let Some(list_id) = list_id else { continue };
let allowed = match access.iter().find(|&&(list, _)| list == list_id) {
Some(&(_, allowed)) => allowed,
None => {
let allowed = crate::db::list_role(&pool, user.id, list_id).await.map_err(db_err)?.is_some();
access.push((list_id, allowed));
allowed
}
};
if !allowed {
if matches!(op, ItemOp::Add { .. }) {
rejected.get_or_insert_with(|| "Liste introuvable.".to_owned());
}
continue;
}
#[server] let op = match op {
pub async fn delete_item(id: i64) -> Result<(), ServerFnError> { ItemOp::Add { id, list_id, input } => match clean_name(&input.name, 60) {
use server::*; Ok(name) => ItemOp::Add { id, list_id, input: ItemInput { name, ..input } },
let pool = pool()?; Err(err) => {
let user = require_user(&pool).await?; rejected.get_or_insert(message(err));
let list_id = require_item(&pool, &user, id).await?; continue;
crate::db::delete_item(&pool, id).await.map_err(db_err)?; }
notify_list(&pool, list_id).await },
} ItemOp::Update { id, input } => match clean_name(&input.name, 60) {
Ok(name) => ItemOp::Update { id, input: ItemInput { name, ..input } },
Err(err) => {
rejected.get_or_insert(message(err));
continue;
}
},
op => op,
};
if let ItemOp::Add { id, list_id, .. } = op {
added.push((id, list_id));
}
accepted.push(op);
}
#[server] if accepted.is_empty() {
pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> { return Ok(SyncReport { created: Vec::new(), rejected });
use server::*; }
let pool = pool()?; let created = crate::db::apply_item_ops(&pool, user.id, &accepted).await.map_err(db_err)?;
let user = require_user(&pool).await?; let mut users = Vec::new();
let list_id = require_item(&pool, &user, id).await?; for &(list_id, allowed) in &access {
crate::db::set_checked(&pool, id, checked).await.map_err(db_err)?; if allowed {
notify_list(&pool, list_id).await users.extend(audience(&pool, list_id).await?);
} }
}
#[server] users.sort_unstable();
pub async fn get_suggestions(list_id: i64) -> Result<Vec<Suggestion>, ServerFnError> { users.dedup();
use server::*; notify(users);
let pool = pool()?; Ok(SyncReport { created, rejected })
let user = require_user(&pool).await?;
require_list(&pool, &user, list_id).await?;
crate::db::suggestions(&pool, user.id, list_id, 3).await.map_err(db_err)
} }
+33 -21
View File
@@ -83,13 +83,13 @@ fn RedirectIfSignedIn() -> impl IntoView {
fn AuthLayout(title: &'static str, children: Children) -> impl IntoView { fn AuthLayout(title: &'static str, children: Children) -> impl IntoView {
view! { view! {
<RedirectIfSignedIn /> <RedirectIfSignedIn />
<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-16"> <main class="page page-auth">
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight"> <h1 class="page-title">
"mes listes" "mes listes"
</h1> </h1>
<section class="ticket relative mt-8 bg-paper px-5 pt-6 pb-8"> <section class="ticket">
<p class="font-mono text-sm tracking-[0.2em] text-ink/60 uppercase">"Lisette · Courses"</p> <p class="eyebrow">"Lisette · Courses"</p>
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">{title}</h2> <h2 class="ticket-title">{title}</h2>
{children()} {children()}
</section> </section>
</main> </main>
@@ -97,11 +97,11 @@ fn AuthLayout(title: &'static str, children: Children) -> impl IntoView {
} }
#[component] #[component]
fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView { pub fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView {
move || { move || {
error.get().map(|msg| { error.get().map(|msg| {
view! { view! {
<p role="alert" class="rounded-xl border-2 border-ink bg-pink px-3 py-2 font-medium"> <p role="alert" class="form-error">
{msg} {msg}
</p> </p>
} }
@@ -114,7 +114,7 @@ pub fn LoginPage() -> impl IntoView {
let auth = expect_context::<Auth>(); let auth = expect_context::<Auth>();
view! { view! {
<AuthLayout title="Connexion"> <AuthLayout title="Connexion">
<ActionForm action=auth.login attr:class="mt-5 flex flex-col gap-4"> <ActionForm action=auth.login attr:class="form form-compact">
<FormError error=Signal::derive(move || auth.login.value().get().and_then(Result::err).map(error_message)) /> <FormError error=Signal::derive(move || auth.login.value().get().and_then(Result::err).map(error_message)) />
<Field label="Email"> <Field label="Email">
<input class="field" type="email" name="email" required autocomplete="email" /> <input class="field" type="email" name="email" required autocomplete="email" />
@@ -135,9 +135,9 @@ pub fn LoginPage() -> impl IntoView {
matches!(auth.registration.await, Ok(true)) matches!(auth.registration.await, Ok(true))
.then(|| { .then(|| {
view! { view! {
<p class="mt-6 text-center text-ink/70"> <p class="footnote">
"Pas encore de compte ? " "Pas encore de compte ? "
<A href="/inscription" attr:class="font-semibold text-ink underline"> <A href="/inscription">
"Créer un compte" "Créer un compte"
</A> </A>
</p> </p>
@@ -158,14 +158,14 @@ pub fn RegisterPage() -> impl IntoView {
{move || Suspend::new(async move { {move || Suspend::new(async move {
if !matches!(auth.registration.await, Ok(true)) { if !matches!(auth.registration.await, Ok(true)) {
return view! { return view! {
<p class="mt-4 text-lg text-ink/70"> <p class="lead">
"Les inscriptions sont fermées pour le moment." "Les inscriptions sont fermées pour le moment."
</p> </p>
} }
.into_any(); .into_any();
} }
view! { view! {
<ActionForm action=auth.register attr:class="mt-5 flex flex-col gap-4"> <ActionForm action=auth.register attr:class="form form-compact">
<FormError error=Signal::derive(move || auth.register.value().get().and_then(Result::err).map(error_message)) /> <FormError error=Signal::derive(move || auth.register.value().get().and_then(Result::err).map(error_message)) />
<Field label="Prénom ou pseudo"> <Field label="Prénom ou pseudo">
<input <input
@@ -196,9 +196,9 @@ pub fn RegisterPage() -> impl IntoView {
.into_any() .into_any()
})} })}
</Suspense> </Suspense>
<p class="mt-6 text-center text-ink/70"> <p class="footnote">
"Déjà inscrit·e ? " "Déjà inscrit·e ? "
<A href="/connexion" attr:class="font-semibold text-ink underline"> <A href="/connexion">
"Se connecter" "Se connecter"
</A> </A>
</p> </p>
@@ -207,10 +207,10 @@ pub fn RegisterPage() -> impl IntoView {
} }
#[component] #[component]
fn Field(label: &'static str, children: Children) -> impl IntoView { pub fn Field(label: &'static str, children: Children) -> impl IntoView {
view! { view! {
<label class="flex flex-col gap-1.5"> <label class="field-group">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">{label}</span> <span class="label">{label}</span>
{children()} {children()}
</label> </label>
} }
@@ -221,7 +221,7 @@ fn SubmitButton(#[prop(into)] pending: Signal<bool>, label: &'static str) -> imp
view! { view! {
<button <button
type="submit" type="submit"
class="tile-shadow mt-2 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 disabled:opacity-60" class="button button-primary"
disabled=move || pending.get() disabled=move || pending.get()
> >
{label} {label}
@@ -240,11 +240,23 @@ pub fn AccountSheet(user: User) -> impl IntoView {
view! { view! {
<Show when=move || ctx.account_open.get()> <Show when=move || ctx.account_open.get()>
<Sheet title=user.with_value(|u| u.name.clone()) on_close=close> <Sheet title=user.with_value(|u| u.name.clone()) on_close=close>
<p class="mt-1 text-ink/70">{user.with_value(|u| u.email.clone())}</p> <p class="sheet-text">{user.with_value(|u| u.email.clone())}</p>
<ActionForm action=auth.logout attr:class="mt-6"> {user
.with_value(|u| u.is_admin)
.then(|| {
view! {
<A
href="/admin"
attr:class="button button-lime button-block"
>
"Gérer les utilisateurs"
</A>
}
})}
<ActionForm action=auth.logout>
<button <button
type="submit" type="submit"
class="w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold" class="button button-block"
> >
"Se déconnecter" "Se déconnecter"
</button> </button>
+309
View File
@@ -0,0 +1,309 @@
use leptos::ev;
use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::components::A;
use super::account::{Auth, Field, FormError, RequireUser};
use super::error_message;
use super::sheets::Sheet;
use crate::api::{create_account, delete_account, get_accounts, update_account};
use crate::model::{Account, User};
#[derive(Clone, Debug, PartialEq)]
enum AccountEditor {
New,
Edit(User),
}
#[component]
pub fn AdminPage() -> impl IntoView {
view! { <RequireUser render=|user| view! { <AdminView me=user /> } /> }
}
#[component]
fn AdminView(me: User) -> impl IntoView {
if !me.is_admin {
return view! {
<AdminLayout>
<section class="ticket">
<p class="lead">"Cette page est réservée aux administrateurs."</p>
</section>
</AdminLayout>
}
.into_any();
}
let version = RwSignal::new(0);
let editor = RwSignal::new(None::<AccountEditor>);
let accounts = Resource::new(move || version.get(), |_| get_accounts());
let me_id = me.id;
view! {
<AdminLayout>
<section class="ticket">
<p class="eyebrow">"Lisette · Comptes"</p>
<h2 class="ticket-title">
"Utilisateurs"
</h2>
<Transition fallback=|| view! { <p class="loading">"…"</p> }>
{move || Suspend::new(async move {
match accounts.await {
Ok(accounts) => view! { <AccountRows accounts me_id editor /> }.into_any(),
Err(err) => {
view! { <p class="lead">{error_message(err)}</p> }.into_any()
}
}
})}
</Transition>
</section>
<button
class="fab"
on:click=move |_| editor.set(Some(AccountEditor::New))
>
"+ compte"
</button>
</AdminLayout>
{move || {
editor
.get()
.map(|current| {
view! {
<AccountForm
editor=current
me_id
on_close=move || editor.set(None)
on_saved=move || version.update(|v| *v += 1)
/>
}
})
}}
}
.into_any()
}
#[component]
fn AdminLayout(children: Children) -> impl IntoView {
view! {
<main class="page">
<header class="page-header">
<h1 class="page-title">"admin"</h1>
<A
href="/"
attr:class="button button-paper"
>
"← mes listes"
</A>
</header>
{children()}
</main>
}
}
#[component]
fn AccountRows(
accounts: Vec<Account>,
me_id: i64,
editor: RwSignal<Option<AccountEditor>>,
) -> impl IntoView {
view! {
<p class="lead">
{match accounts.len() {
1 => "1 compte.".to_owned(),
n => format!("{n} comptes."),
}}
</p>
<ul class="people">
{accounts
.into_iter()
.map(|Account { user, created_at }| {
let is_me = user.id == me_id;
let edited = user.clone();
view! {
<li>
<button
class="person"
on:click=move |_| editor.set(Some(AccountEditor::Edit(edited.clone())))
>
<div class="person-info">
<p class="person-name">
{user.name.clone()}
{is_me.then_some(" (toi)")}
</p>
<p class="person-email">{user.email.clone()}</p>
<p class="person-date">{format!("Inscrit·e le {}", french_date(&created_at))}</p>
</div>
{user
.is_admin
.then(|| {
view! {
<span class="badge">
"admin"
</span>
}
})}
</button>
</li>
}
})
.collect_view()}
</ul>
}
}
#[component]
fn AccountForm(
editor: AccountEditor,
me_id: i64,
on_close: impl Fn() + Copy + Send + Sync + 'static,
on_saved: impl Fn() + Copy + Send + Sync + 'static,
) -> impl IntoView {
let auth = expect_context::<Auth>();
let existing = match editor {
AccountEditor::Edit(user) => Some(user),
AccountEditor::New => None,
};
let user_id = existing.as_ref().map(|u| u.id);
let is_me = user_id == Some(me_id);
let name = RwSignal::new(
existing
.as_ref()
.map(|u| u.name.clone())
.unwrap_or_default(),
);
let email = RwSignal::new(
existing
.as_ref()
.map(|u| u.email.clone())
.unwrap_or_default(),
);
let password = RwSignal::new(String::new());
let is_admin = RwSignal::new(existing.as_ref().is_some_and(|u| u.is_admin));
let error = RwSignal::new(None::<String>);
let pending = RwSignal::new(false);
let run = move |call: std::pin::Pin<Box<dyn Future<Output = Result<(), ServerFnError>>>>| {
pending.set(true);
spawn_local(async move {
let result = call.await;
pending.set(false);
match result {
Ok(()) => {
if is_me {
// Name shown on the avatar.
auth.me.refetch();
}
on_saved();
on_close();
}
Err(err) => error.set(Some(error_message(err))),
}
});
};
let submit = move |ev: ev::SubmitEvent| {
ev.prevent_default();
let (name, email, password, is_admin) =
(name.get(), email.get(), password.get(), is_admin.get());
run(match user_id {
Some(id) => Box::pin(update_account(id, name, email, password, is_admin)),
None => Box::pin(create_account(name, email, password, is_admin)),
});
};
let delete = move |_| {
let Some(id) = user_id else { return };
let confirmed = window()
.confirm_with_message("Supprimer ce compte et toutes les listes qu'il possède ?")
.unwrap_or(false);
if confirmed {
run(Box::pin(delete_account(id)));
}
};
let title = if user_id.is_some() {
"Modifier le compte"
} else {
"Nouveau compte"
};
let password_label = if user_id.is_some() {
"Nouveau mot de passe (facultatif)"
} else {
"Mot de passe (8 caractères min.)"
};
view! {
<Sheet title=title.to_owned() on_close>
<form class="form form-compact" on:submit=submit>
<FormError error=error />
<Field label="Prénom ou pseudo">
<input class="field" required maxlength="40" autocomplete="off" bind:value=name />
</Field>
<Field label="Email">
<input class="field" type="email" required autocomplete="off" bind:value=email />
</Field>
<Field label=password_label>
<input
class="field"
type="password"
required=user_id.is_none()
minlength="8"
maxlength="128"
autocomplete="new-password"
bind:value=password
/>
</Field>
<label class="checkbox">
<input
type="checkbox"
disabled=is_me
bind:checked=is_admin
/>
"Administrateur"
</label>
<div class="actions">
{(user_id.is_some() && !is_me)
.then(|| {
view! {
<button
type="button"
class="button"
disabled=move || pending.get()
on:click=delete
>
"Supprimer"
</button>
}
})}
<button
type="submit"
class="button button-primary"
disabled=move || pending.get()
>
{if user_id.is_some() { "Enregistrer" } else { "Créer" }}
</button>
</div>
</form>
</Sheet>
}
}
/// "2026-10-07" → "07/10/2026".
fn french_date(iso: &str) -> String {
match iso.split('-').collect::<Vec<_>>().as_slice() {
[y, m, d] => format!("{d}/{m}/{y}"),
_ => iso.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::french_date;
#[test]
fn formats_french_date() {
assert_eq!(french_date("2026-10-07"), "07/10/2026");
assert_eq!(french_date("garbage"), "garbage");
}
}
+172 -24
View File
@@ -14,32 +14,101 @@ fn paths(icon: Icon) -> &'static [&'static str] {
"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", "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", "M3.4 4.6 5.6 4l.5 2.4-1.9.5Z",
], ],
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::Pear => &[
"M12 5.5c-1.8 0-3 1.4-3 3.3 0 1.6-.6 2.6-1.6 3.8A5.6 5.6 0 0 0 6 16.3C6 19.5 8.7 22 12 22s6-2.5 6-5.7c0-1.4-.5-2.7-1.4-3.7-1-1.2-1.6-2.2-1.6-3.8 0-1.9-1.2-3.3-3-3.3Z",
"M11.4 1.8h1.3l-.1 2.9h-1.2Z",
"M13.4 4c.9-1.4 2.5-2 4.1-1.5-.6 1.6-2.3 2.3-4.1 1.5Z",
],
Icon::Grapes => &[
"M5.1 8.5a2.1 2.1 0 1 0 4.2 0 2.1 2.1 0 1 0-4.2 0Z",
"M9.9 8.5a2.1 2.1 0 1 0 4.2 0 2.1 2.1 0 1 0-4.2 0Z",
"M14.7 8.5a2.1 2.1 0 1 0 4.2 0 2.1 2.1 0 1 0-4.2 0Z",
"M7.5 12.7a2.1 2.1 0 1 0 4.2 0 2.1 2.1 0 1 0-4.2 0Z",
"M12.3 12.7a2.1 2.1 0 1 0 4.2 0 2.1 2.1 0 1 0-4.2 0Z",
"M9.9 16.9a2.1 2.1 0 1 0 4.2 0 2.1 2.1 0 1 0-4.2 0Z",
"M11.4 2h1.3v4.1h-1.3Z",
"M13.2 5c1-1.7 3-2.5 5-2-.8 1.8-2.8 2.7-5 2Z",
],
Icon::Strawberry => &[
"M5 9.6c0-1 1-1.6 2.6-1.6h8.8c1.6 0 2.6.6 2.6 1.6 0 4.6-3.4 10.6-7 11.9-3.6-1.3-7-7.3-7-11.9Zm4 1.9a.7.7 0 1 0 0-.01Zm6 0a.7.7 0 1 0 0-.01ZM12 13a.7.7 0 1 0 0-.01Zm-2.2 2.8a.7.7 0 1 0 0-.01Zm4.4 0a.7.7 0 1 0 0-.01Z",
"M6.8 6.9c1.4-.9 3-1 4.3-.4L12 3.8l.9 2.7c1.3-.6 2.9-.5 4.3.4-1.4.5-3.2.8-5.2.8s-3.8-.3-5.2-.8Z",
],
Icon::Cherries => &[
"M3.9 17a3.6 3.6 0 1 0 7.2 0 3.6 3.6 0 1 0-7.2 0Z",
"M12.4 17.4a3.6 3.6 0 1 0 7.2 0 3.6 3.6 0 1 0-7.2 0Z",
"M7 13.4c.6-3.6 2.4-7 5.6-9.6l.9 1c-3 2.4-4.6 5.5-5.2 8.8Z",
"M13.2 4.4c1.4 2.6 2.4 6 2.7 9.5l-1.3.1c-.3-3.3-1.2-6.5-2.5-8.9Z",
"M13.6 4c1.4-1.6 3.8-2.2 6-1.4-1.2 1.9-3.6 2.6-6 1.4Z",
],
Icon::Avocado => &[
"M12 2.5c-2.5 0-3.6 2.4-4.2 5-.5 2-2.3 3.5-2.3 6.5a6.5 6.5 0 0 0 13 0c0-3-1.8-4.5-2.3-6.5-.6-2.6-1.7-5-4.2-5Zm-3 12a3 3 0 1 0 6 0 3 3 0 1 0-6 0Z",
],
Icon::Tomato => &[
"M4.5 14.5a7.5 6.5 0 1 0 15 0 7.5 6.5 0 1 0-15 0Z",
"M11.3 2h1.4v3.5h-1.4Z",
"M6.5 7c1.8-1.6 3.8-2 5.5-1.2C13.7 5 15.7 5.4 17.5 7c-2 .6-3.9.5-5.5-.2-1.6.7-3.5.8-5.5.2Z",
],
Icon::Carrot => &[ 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", "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", "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 => &[ Icon::Salad => &[
"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", "M3.5 20.5c0-9.5 5.3-16.5 17-16.5 0 11.5-7.4 16.5-17 16.5Zm2.6-1.6 9.6-10.6-.9-.8-9.6 10.6Z",
], ],
Icon::Glass => &[ Icon::Onion => &[
"M5 3h14l-1.6 16.2A2 2 0 0 1 15.4 21H8.6a2 2 0 0 1-2-1.8Z", "M12 2.5c.4 2 2 3.3 3.9 4.6 2.3 1.6 4.1 3.6 4.1 6.7 0 4-3.6 6.7-8 6.7s-8-2.7-8-6.7c0-3.1 1.8-5.1 4.1-6.7C10 5.8 11.6 4.5 12 2.5Zm-.9 8.5c-.6 2.8-.6 5.5 0 8h1c-.5-2.5-.5-5.2 0-8Z",
"M9.5 21.2h5V22h-5Z",
],
Icon::Potato => &[
"M6.2 6.4C8.7 3.9 13 3.5 16.4 5.2c3.6 1.8 5 5.4 3.8 8.8-1.3 3.7-5 6.4-9.3 6.5-4.4.1-7.6-2.5-7.7-6.2-.1-2.7 1-5.8 3-7.9ZM9 9.2a.9.9 0 1 0 0-.01Zm6.2-.6a.8.8 0 1 0 0-.01Zm-1.8 6.2a.9.9 0 1 0 0-.01ZM8 15a.7.7 0 1 0 0-.01Z",
],
Icon::Mushroom => &[
"M3 12C3 6.8 7 3.5 12 3.5s9 3.3 9 8.5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1Z",
"M9 14.5h6l.8 5.2a1.6 1.6 0 0 1-1.6 1.8H9.8a1.6 1.6 0 0 1-1.6-1.8Z",
], ],
Icon::Milk => &[ Icon::Milk => &[
"M8 2h8v3l2 3.5V20a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V8.5L8 5Z", "M8 2h8v3l2 3.5V20a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V8.5L8 5Z",
], ],
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::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::Yogurt => &[
"M4 3h16v2.2H4Z",
"M5 6.5h14l-1.5 13a2 2 0 0 1-2 1.8h-7a2 2 0 0 1-2-1.8Z",
],
Icon::IceCream => &[ 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", "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", "M8 14h8l-3.3 7.4a.8.8 0 0 1-1.4 0Z",
], ],
Icon::Cheese => &[ Icon::Frozen => &[
"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", "M11.2 2 12.8 2 12.8 22 11.2 22Z",
"M20.26 6.31 21.06 7.69 3.74 17.69 2.94 16.31Z",
"M21.06 16.31 20.26 17.69 2.94 7.69 3.74 6.31Z",
"M12 5.6 15.4 3 16.2 4.1 12 7.4Z",
"M12 7.4 7.8 4.1 8.6 3 12 5.6Z",
"M17.54 8.8 21.49 10.44 20.94 11.69 15.98 9.7Z",
"M15.98 9.7 16.74 4.41 18.09 4.56 17.54 8.8Z",
"M17.54 15.2 18.09 19.44 16.74 19.59 15.98 14.3Z",
"M15.98 14.3 20.94 12.31 21.49 13.56 17.54 15.2Z",
"M12 18.4 8.6 21 7.8 19.9 12 16.6Z",
"M12 16.6 16.2 19.9 15.4 21 12 18.4Z",
"M6.46 15.2 2.51 13.56 3.06 12.31 8.02 14.3Z",
"M8.02 14.3 7.26 19.59 5.91 19.44 6.46 15.2Z",
"M6.46 8.8 5.91 4.56 7.26 4.41 8.02 9.7Z",
"M8.02 9.7 3.06 11.69 2.51 10.44 6.46 8.8Z",
], ],
Icon::Egg => &[ Icon::Meat => &[
"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", "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::Coffee => &[ Icon::Fish => &[
"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", "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",
"M3 20h13v1.8H3Z", "M20.5 12 23 8v8Z",
], ],
Icon::Bread => &[ 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", "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",
@@ -49,20 +118,75 @@ fn paths(icon: Icon) -> &'static [&'static str] {
"M8.3 6.6 6.8 15H4.5L3 9.6Zm7.4 0 5.3 3-1.5 5.4h-2.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", "M2 11.5 4 17H2.5L1 13Zm20 0L23 13l-1.5 4H20Z",
], ],
Icon::Cake => &[
"M12 1c1 1.2 1.5 2 1.5 2.7a1.5 1.5 0 0 1-3 0c0-.7.5-1.5 1.5-2.7Z",
"M11.2 6h1.6v3.2h-1.6Z",
"M6 10.5h12a2 2 0 0 1 2 2V15H4v-2.5a2 2 0 0 1 2-2Z",
"M4 16.5h16V21H4Z",
],
Icon::Cookie => &[
"M3 12a9 9 0 1 0 18 0 9 9 0 1 0-18 0Zm5-2.5a1.3 1.3 0 1 0 0-.01Zm6-3a1.1 1.1 0 1 0 0-.01Zm2.5 6a1.3 1.3 0 1 0 0-.01Zm-5.5 3a1.2 1.2 0 1 0 0-.01Zm.5-5a.9.9 0 1 0 0-.01Z",
],
Icon::Pizza => &[
"M3 6c5.8-3 12.2-3 18 0l-9 16Zm1.3 2.2c5.1-2.4 10.3-2.4 15.4 0l.5-.9c-5.4-2.6-11-2.6-16.4 0ZM10 11.2a1.3 1.3 0 1 0 0-.01Zm4.2.4a1.1 1.1 0 1 0 0-.01ZM12 15.5a1.1 1.1 0 1 0 0-.01Z",
],
Icon::Pasta => &[ Icon::Pasta => &[
"M4 10h16v2a8 8 0 0 1-16 0Z", "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", "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 => &[ Icon::Can => &[
"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", "M5 5.5C5 4 8.1 3 12 3s7 1 7 2.5v13C19 20 15.9 21 12 21s-7-1-7-2.5Zm0 1.2c1.6 1 4 1.5 7 1.5s5.4-.5 7-1.5V8c-1.6 1-4 1.5-7 1.5S6.6 9 5 8Zm0 9c1.6 1 4 1.5 7 1.5s5.4-.5 7-1.5V17c-1.6 1-4 1.5-7 1.5S6.6 18 5 17Z",
], ],
Icon::Fish => &[ Icon::Jar => &[
"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", "M7 2.5h10v3H7Z",
"M20.5 12 23 8v8Z", "M7.5 6.5h9L18 9v10a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 6 19V9Zm1 5v5h7v-5Z",
],
Icon::Chocolate => &[
"M6 3h5.3v5.3H5V4a1 1 0 0 1 1-1Z",
"M12.7 3H18a1 1 0 0 1 1 1v4.3h-6.3Z",
"M5 9.6h6.3v5.3H5Z",
"M12.7 9.6H19v5.3h-6.3Z",
"M5 16.2h6.3V21H6a1 1 0 0 1-1-1Z",
"M12.7 16.2H19V20a1 1 0 0 1-1 1h-5.3Z",
],
Icon::Candy => &[
"M7.5 12a4.5 4.5 0 1 0 9 0 4.5 4.5 0 1 0-9 0Z",
"M2 8l5.2 2.4v3.2L2 16Z",
"M22 8l-5.2 2.4v3.2L22 16Z",
],
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::Water => &[
"M12 2.5C9 7 5.5 10.7 5.5 14.5a6.5 6.5 0 0 0 13 0C18.5 10.7 15 7 12 2.5Z",
],
Icon::Glass => &[
"M5 3h14l-1.6 16.2A2 2 0 0 1 15.4 21H8.6a2 2 0 0 1-2-1.8Z",
], ],
Icon::Bottle => &[ 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", "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::Wine => &[
"M6.5 2h11l.4 4.5c.5 3.6-2 6.6-5.2 7V19H16v2H8v-2h3.3v-5.5c-3.2-.4-5.7-3.4-5.2-7Z",
],
Icon::Spray => &[
"M7.5 3h8.5l3 2v2h-3v1.2H8Z",
"M15.3 8.8l2.7 3-1 .8-2.5-2.7Z",
"M8 9.5h6.5l1 2.5V20a1.5 1.5 0 0 1-1.5 1.5H8.5A1.5 1.5 0 0 1 7 20v-8Z",
],
Icon::BabyBottle => &[
"M10.5 5c0-1.5.6-3 1.5-3s1.5 1.5 1.5 3Z",
"M8.5 6h7v2.5h-7Z",
"M9 9.5h6l.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5h-4A1.5 1.5 0 0 1 8.5 20v-9Zm-.5 3.5h3v.9h-3Zm0 3h3v.9h-3Z",
],
Icon::Paw => &[
"M12 11.5c-2.6 0-5.5 3.2-5.5 6 0 1.8 1.3 3 3 3 1 0 1.6-.4 2.5-.4s1.5.4 2.5.4c1.7 0 3-1.2 3-3 0-2.8-2.9-6-5.5-6Z",
"M3.2 10.5a1.8 2.3 0 1 0 3.6 0 1.8 2.3 0 1 0-3.6 0Z",
"M7.1 6.2a1.9 2.5 0 1 0 3.8 0 1.9 2.5 0 1 0-3.8 0Z",
"M13.1 6.2a1.9 2.5 0 1 0 3.8 0 1.9 2.5 0 1 0-3.8 0Z",
"M17.2 10.5a1.8 2.3 0 1 0 3.6 0 1.8 2.3 0 1 0-3.6 0Z",
],
Icon::Basket => &[ 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", "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",
], ],
@@ -73,20 +197,44 @@ pub fn icon_label(icon: Icon) -> &'static str {
match icon { match icon {
Icon::Apple => "Pomme", Icon::Apple => "Pomme",
Icon::Banana => "Banane", Icon::Banana => "Banane",
Icon::Carrot => "Carotte",
Icon::Lemon => "Citron", Icon::Lemon => "Citron",
Icon::Glass => "Verre", Icon::Pear => "Poire",
Icon::Grapes => "Raisin",
Icon::Strawberry => "Fraise",
Icon::Cherries => "Cerises",
Icon::Avocado => "Avocat",
Icon::Tomato => "Tomate",
Icon::Carrot => "Carotte",
Icon::Salad => "Salade",
Icon::Onion => "Oignon",
Icon::Potato => "Pomme de terre",
Icon::Mushroom => "Champignon",
Icon::Milk => "Brique de lait", Icon::Milk => "Brique de lait",
Icon::IceCream => "Glace",
Icon::Cheese => "Fromage",
Icon::Egg => "Œuf", Icon::Egg => "Œuf",
Icon::Coffee => "Café", Icon::Cheese => "Fromage",
Icon::Bread => "Pain", Icon::Yogurt => "Yaourt",
Icon::Croissant => "Viennoiserie", Icon::IceCream => "Glace",
Icon::Pasta => "Pâtes", Icon::Frozen => "Surgelés",
Icon::Meat => "Viande", Icon::Meat => "Viande",
Icon::Fish => "Poisson", Icon::Fish => "Poisson",
Icon::Bread => "Pain",
Icon::Croissant => "Viennoiserie",
Icon::Cake => "Gâteau",
Icon::Cookie => "Biscuit",
Icon::Pizza => "Pizza",
Icon::Pasta => "Pâtes",
Icon::Can => "Conserve",
Icon::Jar => "Bocal",
Icon::Chocolate => "Chocolat",
Icon::Candy => "Bonbon",
Icon::Coffee => "Café",
Icon::Water => "Eau",
Icon::Glass => "Verre",
Icon::Bottle => "Bouteille", Icon::Bottle => "Bouteille",
Icon::Wine => "Vin",
Icon::Spray => "Produit ménager",
Icon::BabyBottle => "Bébé",
Icon::Paw => "Animaux",
Icon::Basket => "Panier", Icon::Basket => "Panier",
} }
} }
+96 -162
View File
@@ -1,10 +1,12 @@
mod account; mod account;
mod admin;
mod icons; mod icons;
mod live; mod live;
mod sheets; mod sheets;
mod sync;
mod tiles; mod tiles;
mod transition;
use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use leptos::prelude::*; use leptos::prelude::*;
@@ -14,11 +16,13 @@ use leptos_router::components::{A, Redirect, Route, Router, Routes};
use leptos_router::hooks::use_params_map; use leptos_router::hooks::use_params_map;
use leptos_router::path; use leptos_router::path;
use crate::api::{get_items, get_lists, get_suggestions}; use crate::api::{get_items, get_lists};
use crate::model::{Item, ShoppingList, Suggestion, User}; use crate::model::{Item, ItemOp, ShoppingList, User};
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser}; use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
use admin::AdminPage;
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet}; use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
use tiles::{BasketTile, ItemTile, SuggestionTile}; use sync::Sync;
use tiles::{BasketTile, ItemTile};
pub fn shell(options: LeptosOptions) -> impl IntoView { pub fn shell(options: LeptosOptions) -> impl IntoView {
view! { view! {
@@ -37,7 +41,7 @@ pub fn shell(options: LeptosOptions) -> impl IntoView {
"if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js');" "if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js');"
</script> </script>
</head> </head>
<body class="bg-lime text-ink font-sans antialiased"> <body>
<App /> <App />
</body> </body>
</html> </html>
@@ -67,11 +71,12 @@ pub fn App() -> impl IntoView {
<Title text="Lisette" /> <Title text="Lisette" />
<Router> <Router>
<Routes fallback=|| view! { <p class="p-4">"Page introuvable."</p> }> <Routes fallback=|| view! { <p class="page-not-found">"Page introuvable."</p> }>
<Route path=path!("/") view=ListsPage /> <Route path=path!("/") view=ListsPage />
<Route path=path!("/l/:id") view=ListsPage /> <Route path=path!("/l/:id") view=ListsPage />
<Route path=path!("/connexion") view=LoginPage /> <Route path=path!("/connexion") view=LoginPage />
<Route path=path!("/inscription") view=RegisterPage /> <Route path=path!("/inscription") view=RegisterPage />
<Route path=path!("/admin") view=AdminPage />
</Routes> </Routes>
</Router> </Router>
} }
@@ -83,9 +88,8 @@ pub struct Ctx {
/// Bumped after every mutation so resources refetch. /// Bumped after every mutation so resources refetch.
refresh: RwSignal<u32>, refresh: RwSignal<u32>,
error: RwSignal<Option<String>>, error: RwSignal<Option<String>>,
/// Checked state applied before fresh data shows it, with the number of /// Item changes waiting to be saved.
/// calls still in flight for that item. sync: Sync,
optimistic: RwSignal<HashMap<i64, (bool, u32)>>,
item_editor: RwSignal<Option<ItemEditor>>, item_editor: RwSignal<Option<ItemEditor>>,
list_editor: RwSignal<Option<ListEditor>>, list_editor: RwSignal<Option<ListEditor>>,
account_open: RwSignal<bool>, account_open: RwSignal<bool>,
@@ -120,27 +124,15 @@ impl Ctx {
self.error.set(Some(msg)); self.error.set(Some(msg));
} }
/// Shows the item change at once and saves it in the background.
fn change(self, op: ItemOp) {
self.sync.push(self, op);
}
/// Moves the item between the list and the basket, with an animation.
fn toggle(self, item: &Item) { fn toggle(self, item: &Item) {
let (id, checked) = (item.id, !item.checked); let op = ItemOp::SetChecked { id: item.id, checked: !item.checked };
self.optimistic.update(|map| { transition::animate(move || self.change(op));
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);
}
}
});
} }
} }
@@ -161,7 +153,7 @@ fn ListsView(user: User) -> impl IntoView {
let ctx = Ctx { let ctx = Ctx {
refresh: RwSignal::new(0), refresh: RwSignal::new(0),
error: RwSignal::new(None), error: RwSignal::new(None),
optimistic: RwSignal::new(HashMap::new()), sync: Sync::new(),
item_editor: RwSignal::new(None), item_editor: RwSignal::new(None),
list_editor: RwSignal::new(None), list_editor: RwSignal::new(None),
account_open: RwSignal::new(false), account_open: RwSignal::new(false),
@@ -170,6 +162,7 @@ fn ListsView(user: User) -> impl IntoView {
}; };
provide_context(ctx); provide_context(ctx);
live::subscribe(ctx.refresh); live::subscribe(ctx.refresh);
ctx.sync.flush_on_hide(ctx);
let params = use_params_map(); let params = use_params_map();
let active_id = Memo::new(move |_| { let active_id = Memo::new(move |_| {
@@ -182,31 +175,36 @@ fn ListsView(user: User) -> impl IntoView {
let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists()); let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists());
let items = Resource::new( let items = Resource::new(
move || (active_id.get(), ctx.refresh.get()), move || (active_id.get(), ctx.refresh.get()),
|(id, _)| async move { move |(id, _)| {
match id { // What the data will include, to drop the changes it shows.
Some(id) => get_items(id).await, let saved = ctx.sync.saved();
None => Ok(Vec::new()), async move {
} match id {
}, Some(id) => get_items(id).await.map(|items| (items, saved)),
); None => Ok((Vec::new(), saved)),
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()),
} }
}, },
); );
// Items of the open list with unsaved changes, for the add sheet.
let list_items = Memo::new(move |_| match (active_id.get(), items.get()) {
(Some(id), Some(Ok((items, _)))) => {
let mut items = ctx.sync.apply(id, &items);
items.sort_by_cached_key(|item| crate::model::fold_name(&item.name));
items
}
_ => Vec::new(),
});
view! { 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"> <main class="page">
<header class="flex items-start justify-between gap-4"> <header class="page-header">
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight"> <h1 class="page-title">
"mes listes" "mes listes"
</h1> </h1>
<button <button
class="grid size-14 shrink-0 place-items-center rounded-2xl bg-ink font-display text-lg font-bold text-lime" class="avatar"
aria-label="Mon compte" aria-label="Mon compte"
on:click=move |_| ctx.account_open.set(true) on:click=move |_| ctx.account_open.set(true)
> >
@@ -215,11 +213,16 @@ fn ListsView(user: User) -> impl IntoView {
</header> </header>
<ErrorBanner /> <ErrorBanner />
<Show when=move || ctx.sync.offline()>
<p class="notice">
"Réseau indisponible : tes changements partiront dès que possible."
</p>
</Show>
<Transition fallback=|| view! { <TicketSkeleton /> }> <Transition fallback=|| view! { <TicketSkeleton /> }>
<ErrorBoundary fallback=|errors| { <ErrorBoundary fallback=|errors| {
view! { view! {
<p class="mt-6 rounded-2xl bg-paper p-4"> <p class="panel">
"Oups : " "Oups : "
{move || { {move || {
errors.get().into_iter().map(|(_, e)| e.to_string()).collect::<Vec<_>>().join(", ") errors.get().into_iter().map(|(_, e)| e.to_string()).collect::<Vec<_>>().join(", ")
@@ -229,17 +232,16 @@ fn ListsView(user: User) -> impl IntoView {
}> }>
{move || Suspend::new(async move { {move || Suspend::new(async move {
let lists = lists.await?; let lists = lists.await?;
let items = items.await?; let (items, saved) = items.await?;
let suggestions = suggestions.await?;
Ok::<_, ServerFnError>(view! { Ok::<_, ServerFnError>(view! {
<ListsContent lists items suggestions active_id=active_id.get() /> <ListsContent lists items saved active_id=active_id.get() />
}) })
})} })}
</ErrorBoundary> </ErrorBoundary>
</Transition> </Transition>
</main> </main>
<ItemSheet list_id=active_id /> <ItemSheet list_id=active_id items=list_items />
<ListSheet /> <ListSheet />
<AccountSheet user /> <AccountSheet user />
} }
@@ -249,7 +251,8 @@ fn ListsView(user: User) -> impl IntoView {
fn ListsContent( fn ListsContent(
lists: Vec<ShoppingList>, lists: Vec<ShoppingList>,
items: Vec<Item>, items: Vec<Item>,
suggestions: Vec<Suggestion>, /// Batches of changes saved when `items` was fetched.
saved: u32,
active_id: Option<i64>, active_id: Option<i64>,
) -> impl IntoView { ) -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
@@ -267,34 +270,19 @@ fn ListsContent(
let Some(list) = lists.iter().find(|l| l.id == active_id).cloned() else { let Some(list) = lists.iter().find(|l| l.id == active_id).cloned() else {
return view! { return view! {
<ListTabs lists active=None remaining=0 /> <ListTabs lists active=None remaining=0 />
<p class="mt-6 rounded-2xl bg-paper p-4">"Cette liste n'existe plus."</p> <p class="panel">"Cette liste n'existe plus."</p>
} }
.into_any(); .into_any();
}; };
// Fresh data includes every confirmed toggle: only keep pending ones, so ctx.sync.settle(saved);
// 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. // Items with unsaved changes applied, by category then name.
let mut items = items;
items.sort_by_cached_key(Item::sort_key);
let items = StoredValue::new(items); let items = StoredValue::new(items);
let current = Memo::new(move |_| { let current = Memo::new(move |_| {
let optimistic = ctx.optimistic.get(); let mut items = items.with_value(|items| ctx.sync.apply(active_id, items));
items.with_value(|items| { items.sort_by_cached_key(Item::sort_key);
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 |_| { let to_get = Memo::new(move |_| {
current.with(|items| { current.with(|items| {
@@ -317,61 +305,62 @@ fn ListsContent(
let total = move || current.with(Vec::len); let total = move || current.with(Vec::len);
let remaining = Signal::derive(move || to_get.with(Vec::len)); let remaining = Signal::derive(move || to_get.with(Vec::len));
// The page takes the color of the open list.
let color = list.color;
Effect::new(move |_| {
if let Ok(Some(meta)) = document().query_selector("meta[name=theme-color]") {
_ = meta.set_attribute("content", color.hex());
}
});
let edit_list = { let edit_list = {
let list = list.clone(); let list = list.clone();
move |_| ctx.list_editor.set(Some(ListEditor::Edit(list.clone()))) move |_| ctx.list_editor.set(Some(ListEditor::Edit(list.clone())))
}; };
view! { view! {
<div class=format!("page-bg {}", color.dot_class()) aria-hidden="true"></div>
<ListTabs lists active=Some(active_id) remaining /> <ListTabs lists active=Some(active_id) remaining />
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8"> <section class="ticket">
<div class="flex items-start justify-between gap-2"> <div class="ticket-head">
<p class="font-mono text-sm tracking-[0.2em] text-ink/60 uppercase"> <h2 class="ticket-title">
{format!("Ticket N°{:03} · {}", list.id, ticket_date(&list.created_at))} {list.name.clone()}
</p> </h2>
<button <button
class="-mt-2 -mr-2 grid size-11 place-items-center rounded-full text-ink/60 active:bg-ink/5" class="icon-button"
aria-label="Modifier la liste" aria-label="Modifier la liste"
on:click=edit_list on:click=edit_list
> >
<svg viewBox="0 0 24 24" fill="currentColor" class="size-6" aria-hidden="true"> <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<circle cx="5" cy="12" r="2" /> <circle cx="5" cy="12" r="2" />
<circle cx="12" cy="12" r="2" /> <circle cx="12" cy="12" r="2" />
<circle cx="19" cy="12" r="2" /> <circle cx="19" cy="12" r="2" />
</svg> </svg>
</button> </button>
</div> </div>
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">
{list.name.clone()}
</h2>
{(!list.is_owner) {(!list.is_owner)
.then(|| { .then(|| {
view! { view! {
<p class="mt-1 font-medium text-ink/60"> <p class="ticket-owner">
{format!("Partagée par {}", list.owner_name)} {format!("Partagée par {}", list.owner_name)}
</p> </p>
} }
})} })}
<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"> <div class="tiles">
<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> <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 /> <ItemTile item />
</For> </For>
{suggestions
.into_iter()
.map(|suggestion| view! { <SuggestionTile suggestion list_id=active_id /> })
.collect_view()}
</div> </div>
<Show when=move || !in_basket.with(Vec::is_empty)> <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="basket">
<div class="flex justify-between font-mono text-sm tracking-[0.2em] text-ink/60 uppercase"> <div class="basket-head">
<span>"Déjà dans le panier"</span> <span>"Déjà dans le panier"</span>
<span>{move || format!("{}/{}", in_basket.with(Vec::len), total())}</span> <span>{move || format!("{}/{}", in_basket.with(Vec::len), total())}</span>
</div> </div>
<div class="mt-4 grid grid-cols-4 gap-2"> <div class="tiles">
<For each=move || in_basket.get() key=|item| (item.id, item.name.clone(), item.icon) let:item> <For each=move || in_basket.get() key=|item| (item.id, item.name.clone(), item.icon) let:item>
<BasketTile item /> <BasketTile item />
</For> </For>
@@ -381,10 +370,10 @@ fn ListsContent(
</section> </section>
<button <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" class="fab"
on:click=move |_| ctx.item_editor.set(Some(ItemEditor::New)) on:click=move |_| ctx.item_editor.set(Some(ItemEditor::New))
> >
"+ article" "ajouter"
</button> </button>
} }
.into_any() .into_any()
@@ -398,30 +387,21 @@ fn ListTabs(
) -> impl IntoView { ) -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
view! { view! {
<nav class="-mx-4 mt-5 flex gap-3 overflow-x-auto px-4 pb-1 [scrollbar-width:none]"> <nav class="tabs">
{lists {lists
.into_iter() .into_iter()
.map(|list| { .map(|list| {
let is_active = active == Some(list.id); let is_active = active == Some(list.id);
let class = if is_active { let class = if is_active { "tab tab-active" } else { "tab" };
"border-ink bg-ink text-paper"
} else {
"border-ink bg-paper"
};
view! { view! {
<A <A
href=format!("/l/{}", list.id) href=format!("/l/{}", list.id)
attr:class=format!( attr:class=class
"flex shrink-0 items-center gap-2 rounded-2xl border-2 px-5 py-3 text-lg font-semibold whitespace-nowrap {class}",
)
> >
{(!is_active) {(!is_active)
.then(|| { .then(|| {
view! { view! {
<span class=format!( <span class=format!("dot {}", list.color.dot_class()) />
"size-4 rounded-full border-2 border-ink {}",
list.color.dot_class(),
) />
} }
})} })}
{list.name.clone()} {list.name.clone()}
@@ -431,7 +411,7 @@ fn ListTabs(
}) })
.collect_view()} .collect_view()}
<button <button
class="shrink-0 rounded-2xl border-2 border-dashed border-ink/50 px-5 py-3 text-lg font-semibold text-ink/70" class="tab tab-new"
aria-label="Nouvelle liste" aria-label="Nouvelle liste"
on:click=move |_| ctx.list_editor.set(Some(ListEditor::New)) on:click=move |_| ctx.list_editor.set(Some(ListEditor::New))
> >
@@ -452,10 +432,10 @@ fn ErrorBanner() -> impl IntoView {
view! { view! {
<div <div
role="alert" 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" class="alert"
> >
<span>{msg}</span> <span>{msg}</span>
<button class="font-bold" on:click=move |_| ctx.error.set(None)> <button on:click=move |_| ctx.error.set(None)>
"OK" "OK"
</button> </button>
</div> </div>
@@ -469,10 +449,10 @@ fn ErrorBanner() -> impl IntoView {
fn EmptyState() -> impl IntoView { fn EmptyState() -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
view! { view! {
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8 text-center"> <section class="ticket ticket-empty">
<p class="text-lg text-ink/70">"Aucune liste pour l'instant."</p> <p class="lead">"Aucune liste pour l'instant."</p>
<button <button
class="tile-shadow mt-4 rounded-2xl border-2 border-ink bg-pink px-5 py-3 font-display font-bold" class="button button-primary"
on:click=move |_| ctx.list_editor.set(Some(ListEditor::New)) on:click=move |_| ctx.list_editor.set(Some(ListEditor::New))
> >
"Créer une liste" "Créer une liste"
@@ -483,51 +463,5 @@ fn EmptyState() -> impl IntoView {
#[component] #[component]
fn TicketSkeleton() -> impl IntoView { fn TicketSkeleton() -> impl IntoView {
view! { <div class="ticket mt-20 h-96 animate-pulse bg-paper/60"></div> } view! { <div class="ticket ticket-skeleton"></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 !");
}
} }
+217 -111
View File
@@ -5,7 +5,7 @@ use leptos_router::hooks::use_navigate;
use super::Ctx; use super::Ctx;
use super::icons::{IconSvg, icon_label}; use super::icons::{IconSvg, icon_label};
use crate::api::get_members; use crate::api::get_members;
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit}; use crate::model::{Category, Icon, Item, ItemInput, ItemOp, ListColor, Quantity, ShoppingList, Unit, fold_name};
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum ItemEditor { pub enum ItemEditor {
@@ -30,11 +30,11 @@ pub fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static,
on_cleanup(move || handle.remove()); on_cleanup(move || handle.remove());
view! { view! {
<div class="fixed inset-0 z-20 flex items-end justify-center" role="dialog" aria-modal="true"> <div class="sheet" role="dialog" aria-modal="true">
<div class="absolute inset-0 bg-ink/50" on:click=move |_| on_close()></div> <div class="sheet-backdrop" 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="sheet-panel">
<div class="mx-auto mb-4 h-1.5 w-12 rounded-full bg-ink/20"></div> <div class="sheet-handle"></div>
<h2 class="font-display text-2xl font-bold">{title}</h2> <h2 class="sheet-title">{title}</h2>
{children()} {children()}
</div> </div>
</div> </div>
@@ -42,36 +42,174 @@ pub fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static,
} }
#[component] #[component]
pub fn ItemSheet(#[prop(into)] list_id: Signal<Option<i64>>) -> impl IntoView { pub fn ItemSheet(
#[prop(into)] list_id: Signal<Option<i64>>,
/// Items of the open list, searched by the add sheet.
items: Memo<Vec<Item>>,
) -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
move || { move || {
let editor = ctx.item_editor.get()?; let editor = ctx.item_editor.get()?;
let list_id = list_id.get()?; let list_id = list_id.get()?;
Some(view! { <ItemForm editor list_id /> }) Some(match editor {
ItemEditor::New => view! { <AddForm list_id items /> }.into_any(),
ItemEditor::Edit(item) => view! { <ItemForm item /> }.into_any(),
})
}
}
/// Search box over the list: a match is tapped to put it on the list or in
/// the basket, and an unknown name is added.
#[component]
fn AddForm(list_id: i64, items: Memo<Vec<Item>>) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let close = move || ctx.item_editor.set(None);
let query = RwSignal::new(String::new());
let input = NodeRef::<leptos::html::Input>::new();
let refocus = move || {
query.set(String::new());
if let Some(input) = input.get_untracked() {
_ = input.focus();
}
};
// `autofocus` is ignored on elements added after page load.
Effect::new(move |_| {
if let Some(input) = input.get() {
_ = input.focus();
}
});
let needle = Memo::new(move |_| fold_name(query.read().trim()));
let matches = Memo::new(move |_| {
let needle = needle.get();
if needle.is_empty() {
return Vec::new();
}
items.with(|items| {
items
.iter()
.filter(|item| fold_name(&item.name).contains(&needle))
.cloned()
.collect::<Vec<_>>()
})
});
let exact = move || {
let needle = needle.get();
matches.with(|items| items.iter().find(|item| fold_name(&item.name) == needle).cloned())
};
let can_add = move || !needle.with(String::is_empty) && exact().is_none();
let submit = move |ev: ev::SubmitEvent| {
ev.prevent_default();
match exact() {
// Enter on a name already in the basket puts it back on the list.
Some(item) => {
if item.checked {
ctx.change(ItemOp::SetChecked { id: item.id, checked: false });
}
}
None if can_add() => {
let input = ItemInput {
name: query.get_untracked().trim().to_owned(),
quantity: None,
icon: Icon::Basket,
category: Category::Autre,
};
ctx.change(ItemOp::Add { id: 0, list_id, input });
}
None => return,
}
refocus();
};
view! {
<Sheet title="Ajouter".to_owned() on_close=close>
<form class="form form-compact" on:submit=submit>
<input
class="field"
type="search"
enterkeyhint="done"
maxlength="60"
placeholder="Avocats, pain…"
aria-label="Article"
node_ref=input
bind:value=query
/>
<Show when=move || !matches.with(Vec::is_empty)>
<ul class="tiles">
<For
each=move || matches.get()
key=|item| (item.id, item.checked, item.name.clone(), item.icon)
let:item
>
<SearchResult item on_pick=refocus />
</For>
</ul>
</Show>
<Show when=can_add>
<button
type="submit"
class="button button-primary button-add"
>
{move || format!("+ Ajouter « {} »", query.read().trim())}
</button>
</Show>
</form>
</Sheet>
}
}
/// A list item found by the search: tap moves it between the list and the basket.
#[component]
fn SearchResult(item: Item, on_pick: impl Fn() + Copy + Send + Sync + 'static) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let selected = !item.checked;
let (id, icon, name) = (item.id, item.icon, item.name);
// Same looks as the tiles of the list and of the basket.
let class = if selected {
format!("tile tile-item {}", item.category.tile_class())
} else {
"tile tile-off".to_owned()
};
let aria_label = format!("{name} : {}", if selected { "mettre dans le panier" } else { "remettre dans la liste" });
view! {
<li>
<button
type="button"
class=class
aria-label=aria_label
aria-pressed=selected.to_string()
on:click=move |_| {
ctx.change(ItemOp::SetChecked { id, checked: selected });
on_pick();
}
>
<IconSvg icon />
<span class="tile-label">
{name}
</span>
</button>
</li>
} }
} }
#[component] #[component]
fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView { fn ItemForm(item: Item) -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
let close = move || ctx.item_editor.set(None); let close = move || ctx.item_editor.set(None);
let existing = match &editor { let name = RwSignal::new(item.name.clone());
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( let amount = RwSignal::new(
existing item.quantity
.as_ref()
.and_then(|i| i.quantity)
.map(|q| q.amount.to_string().replace('.', ",")) .map(|q| q.amount.to_string().replace('.', ","))
.unwrap_or_default(), .unwrap_or_default(),
); );
let unit = RwSignal::new(existing.as_ref().and_then(|i| i.quantity).map_or(Unit::Piece, |q| q.unit)); let unit = RwSignal::new(item.quantity.map_or(Unit::Piece, |q| q.unit));
let icon = RwSignal::new(existing.as_ref().map_or(Icon::Basket, |i| i.icon)); let icon = RwSignal::new(item.icon);
let category = RwSignal::new(existing.as_ref().map_or(Category::Autre, |i| i.category)); let category = RwSignal::new(item.category);
let item_id = existing.as_ref().map(|i| i.id); let item_id = item.id;
let invalid_amount = Memo::new(move |_| amount.with(|a| !a.trim().is_empty() && parse_amount(a).is_none())); let invalid_amount = Memo::new(move |_| amount.with(|a| !a.trim().is_empty() && parse_amount(a).is_none()));
@@ -86,41 +224,35 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
icon: icon.get(), icon: icon.get(),
category: category.get(), category: category.get(),
}; };
match item_id { ctx.change(ItemOp::Update { id: item_id, input });
Some(id) => ctx.mutate(crate::api::update_item(id, input), move |_| close()), close();
None => ctx.mutate(crate::api::add_item(list_id, input), move |_| close()),
}
}; };
let delete = move |_| { let delete = move |_| {
if let Some(id) = item_id { ctx.change(ItemOp::Delete { id: item_id });
ctx.mutate(crate::api::delete_item(id), move |_| close()); close();
}
}; };
let title = if item_id.is_some() { "Modifier l'article" } else { "Nouvel article" };
view! { view! {
<Sheet title=title.to_owned() on_close=close> <Sheet title="Modifier l'article".to_owned() on_close=close>
<form class="mt-4 flex flex-col gap-5" on:submit=submit> <form class="form" on:submit=submit>
<label class="flex flex-col gap-1.5"> <label class="field-group">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span> <span class="label">"Nom"</span>
<input <input
class="field" class="field"
required required
maxlength="60" maxlength="60"
autofocus
placeholder="Avocats" placeholder="Avocats"
bind:value=name bind:value=name
/> />
</label> </label>
<div class="flex flex-col gap-1.5"> <div class="field-group">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase"> <span class="label">
"Quantité (facultatif)" "Quantité (facultatif)"
</span> </span>
<div class="flex gap-2"> <div class="quantity">
<input <input
class="field w-28" class="field"
inputmode="decimal" inputmode="decimal"
placeholder="3" placeholder="3"
aria-label="Quantité" aria-label="Quantité"
@@ -128,7 +260,7 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
bind:value=amount bind:value=amount
/> />
<select <select
class="field flex-1" class="field"
aria-label="Unité" aria-label="Unité"
on:change=move |ev| { on:change=move |ev| {
if let Some(u) = Unit::parse(&event_target_value(&ev)) { if let Some(u) = Unit::parse(&event_target_value(&ev)) {
@@ -149,28 +281,22 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
</select> </select>
</div> </div>
<Show when=move || invalid_amount.get()> <Show when=move || invalid_amount.get()>
<p class="text-sm text-red-700">"Quantité invalide."</p> <p class="field-error">"Quantité invalide."</p>
</Show> </Show>
</div> </div>
<fieldset class="flex flex-col gap-1.5"> <fieldset class="field-group">
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase"> <legend class="label">
"Rayon" "Rayon"
</legend> </legend>
<div class="flex flex-wrap gap-2"> <div class="chips">
{Category::ALL {Category::ALL
.iter() .iter()
.map(|&c| { .map(|&c| {
view! { view! {
<button <button
type="button" type="button"
class=move || { class=format!("chip {}", c.tile_class())
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() aria-pressed=move || (category.get() == c).to_string()
on:click=move |_| category.set(c) on:click=move |_| category.set(c)
> >
@@ -182,33 +308,24 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
</div> </div>
</fieldset> </fieldset>
<fieldset class="flex flex-col gap-1.5"> <fieldset class="field-group">
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase"> <legend class="label">
"Icône" "Icône"
</legend> </legend>
<div class="grid grid-cols-6 gap-2"> <div class="icon-grid">
{Icon::ALL {Icon::ALL
.iter() .iter()
.map(|&i| { .map(|&i| {
view! { view! {
<button <button
type="button" type="button"
class=move || { class="icon-choice"
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) title=icon_label(i)
aria-label=icon_label(i) aria-label=icon_label(i)
aria-pressed=move || (icon.get() == i).to_string() aria-pressed=move || (icon.get() == i).to_string()
on:click=move |_| icon.set(i) on:click=move |_| icon.set(i)
> >
<IconSvg icon=i class="size-7" /> <IconSvg icon=i />
</button> </button>
} }
}) })
@@ -216,24 +333,19 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
</div> </div>
</fieldset> </fieldset>
<div class="flex gap-3"> <div class="actions">
{item_id <button
.map(|_| { type="button"
view! { class="button"
<button on:click=delete
type="button" >
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold" "Supprimer"
on:click=delete </button>
>
"Supprimer"
</button>
}
})}
<button <button
type="submit" 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" class="button button-primary"
> >
{if item_id.is_some() { "Enregistrer" } else { "Ajouter" }} "Enregistrer"
</button> </button>
</div> </div>
</form> </form>
@@ -306,9 +418,9 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
view! { view! {
<Sheet title=title.to_owned() on_close=close> <Sheet title=title.to_owned() on_close=close>
<form class="mt-4 flex flex-col gap-5" on:submit=submit> <form class="form" on:submit=submit>
<label class="flex flex-col gap-1.5"> <label class="field-group">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span> <span class="label">"Nom"</span>
<input <input
class="field" class="field"
required required
@@ -321,23 +433,17 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
<Show when=move || list_id.is_none()> <Show when=move || list_id.is_none()>
<fieldset> <fieldset>
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase"> <legend class="label">
"Couleur" "Couleur"
</legend> </legend>
<div class="flex gap-3"> <div class="swatches">
{ListColor::ALL {ListColor::ALL
.iter() .iter()
.map(|&c| { .map(|&c| {
view! { view! {
<button <button
type="button" type="button"
class=move || { class=format!("swatch {}", c.dot_class())
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-label=c.as_str()
aria-pressed=move || (color.get() == c).to_string() aria-pressed=move || (color.get() == c).to_string()
on:click=move |_| color.set(c) on:click=move |_| color.set(c)
@@ -349,13 +455,13 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
</fieldset> </fieldset>
</Show> </Show>
<div class="flex gap-3"> <div class="actions">
{list_id {list_id
.map(|_| { .map(|_| {
view! { view! {
<button <button
type="button" type="button"
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold" class="button"
on:click=delete on:click=delete
> >
"Supprimer" "Supprimer"
@@ -364,7 +470,7 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
})} })}
<button <button
type="submit" 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" class="button button-primary"
> >
{if list_id.is_some() { "Enregistrer" } else { "Créer" }} {if list_id.is_some() { "Enregistrer" } else { "Créer" }}
</button> </button>
@@ -393,29 +499,29 @@ fn SharePanel(list_id: i64) -> impl IntoView {
}; };
view! { view! {
<section class="mt-6 border-t-2 border-dashed border-ink/15 pt-5"> <section class="section">
<h3 class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Partagée avec"</h3> <h3 class="label">"Partagée avec"</h3>
<Transition fallback=|| view! { <p class="mt-2 text-ink/50">"…"</p> }> <Transition fallback=|| view! { <p class="section-text">"…"</p> }>
{move || Suspend::new(async move { {move || Suspend::new(async move {
let members = members.await.unwrap_or_default(); let members = members.await.unwrap_or_default();
if members.is_empty() { if members.is_empty() {
return view! { <p class="mt-2 text-ink/60">"Personne pour l'instant."</p> }.into_any(); return view! { <p class="section-text">"Personne pour l'instant."</p> }.into_any();
} }
view! { view! {
<ul class="mt-2 flex flex-col gap-2"> <ul class="people">
{members {members
.into_iter() .into_iter()
.map(|member| { .map(|member| {
let user_id = member.user_id; let user_id = member.user_id;
view! { view! {
<li class="flex items-center justify-between gap-3 rounded-xl bg-mist px-3 py-2"> <li class="person">
<div class="min-w-0"> <div class="person-info">
<p class="truncate font-semibold">{member.name}</p> <p class="person-name">{member.name}</p>
<p class="truncate text-sm text-ink/60">{member.email}</p> <p class="person-email">{member.email}</p>
</div> </div>
<button <button
type="button" type="button"
class="shrink-0 rounded-lg px-2 py-1 text-sm font-semibold underline" class="link-button"
on:click=move |_| { on:click=move |_| {
ctx.mutate(crate::api::remove_member(list_id, user_id), move |_| bump()) ctx.mutate(crate::api::remove_member(list_id, user_id), move |_| bump())
} }
@@ -431,16 +537,16 @@ fn SharePanel(list_id: i64) -> impl IntoView {
.into_any() .into_any()
})} })}
</Transition> </Transition>
<form class="mt-3 flex gap-2" on:submit=share> <form class="share-form" on:submit=share>
<input <input
class="field min-w-0 flex-1" class="field"
type="email" type="email"
required required
placeholder="email@exemple.fr" placeholder="email@exemple.fr"
aria-label="Email de la personne" aria-label="Email de la personne"
bind:value=email bind:value=email
/> />
<button type="submit" class="shrink-0 rounded-2xl border-2 border-ink bg-lime px-4 font-semibold"> <button type="submit" class="button button-lime">
"Partager" "Partager"
</button> </button>
</form> </form>
@@ -469,10 +575,10 @@ fn SharedListInfo(list: ShoppingList) -> impl IntoView {
view! { view! {
<Sheet title=list.name.clone() on_close=close> <Sheet title=list.name.clone() on_close=close>
<p class="mt-1 text-ink/70">{format!("Liste de {}, partagée avec toi.", list.owner_name)}</p> <p class="sheet-text">{format!("Liste de {}, partagée avec toi.", list.owner_name)}</p>
<button <button
type="button" type="button"
class="mt-6 w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold" class="button button-block"
on:click=leave on:click=leave
> >
"Quitter la liste" "Quitter la liste"
+323
View File
@@ -0,0 +1,323 @@
//! Item changes are shown at once and saved in the background: they wait in a
//! queue and leave in batches, one request at a time, so a slow mobile
//! connection never holds the interface back.
use std::time::Duration;
use leptos::ev;
use leptos::prelude::*;
use leptos::task::spawn_local;
use super::Ctx;
use crate::model::{Item, ItemOp, SyncReport};
/// Changes made within this delay leave together.
const DEBOUNCE: Duration = Duration::from_millis(400);
const MAX_RETRY_DELAY: Duration = Duration::from_secs(30);
#[derive(Clone, Copy)]
pub struct Sync(RwSignal<State>);
#[derive(Default)]
struct State {
/// Changes not sent yet.
queue: Vec<ItemOp>,
/// Sent changes, shown until data fetched after they were saved has them.
sent: Vec<Batch>,
/// Batches saved so far.
saved: u32,
/// Real ids of items added here, by temporary id.
ids: Vec<(i64, i64)>,
/// Last temporary id handed out.
last_temp: i64,
/// A flush is planned.
scheduled: bool,
/// A batch is on its way; the next one waits for its answer.
sending: bool,
/// Failed attempts since the last batch got through.
retries: u32,
}
struct Batch {
ops: Vec<ItemOp>,
/// Value of `saved` once this batch was saved.
saved_as: Option<u32>,
}
enum Outcome {
Saved(SyncReport),
Refused(ServerFnError),
Retry(Duration),
}
impl Sync {
pub fn new() -> Self {
Self(RwSignal::new(State::default()))
}
/// Sends what is left when the page is hidden: the phone may freeze it next.
pub fn flush_on_hide(self, ctx: Ctx) {
let handle = window_event_listener(ev::visibilitychange, move |_| {
if document().hidden() {
self.flush(ctx);
}
});
on_cleanup(move || handle.remove());
}
pub fn push(self, ctx: Ctx, op: ItemOp) {
let schedule = self.0.try_update(|state| {
state.push(op);
!std::mem::replace(&mut state.scheduled, true)
});
if schedule == Some(true) {
set_timeout(move || self.flush(ctx), DEBOUNCE);
}
}
/// Saved batches so far: data fetched from now on includes them.
pub fn saved(self) -> u32 {
self.0.try_with_untracked(|state| state.saved).unwrap_or_default()
}
/// Forgets saved changes that data fetched when `saved` batches were
/// saved already shows, so changes made by others since are not masked.
pub fn settle(self, saved: u32) {
self.0.try_update_untracked(|state| {
state.sent.retain(|batch| batch.saved_as.is_none_or(|n| n > saved));
});
}
/// The list's items with the changes not saved or not fetched yet.
pub fn apply(self, list_id: i64, items: &[Item]) -> Vec<Item> {
let mut items = items.to_vec();
self.0.with(|state| {
let ops = state.sent.iter().flat_map(|batch| &batch.ops).chain(&state.queue);
for op in ops {
apply(&mut items, list_id, op);
}
});
items
}
/// The last attempt failed for lack of network; changes are kept.
pub fn offline(self) -> bool {
self.0.with(|state| state.retries > 0)
}
fn flush(self, ctx: Ctx) {
let ops = self.0.try_update(|state| {
state.scheduled = false;
if state.sending || state.queue.is_empty() {
return None;
}
let ops = std::mem::take(&mut state.queue);
state.sent.push(Batch { ops: ops.clone(), saved_as: None });
state.sending = true;
Some(ops)
});
let Some(Some(ops)) = ops else { return };
spawn_local(async move {
let result = crate::api::sync_items(ops).await;
self.answered(ctx, result);
});
}
fn answered(self, ctx: Ctx, result: Result<SyncReport, ServerFnError>) {
let outcome = self.0.try_update(|state| {
state.sending = false;
let mut batch = state.sent.pop().expect("the batch sent is the last one");
match result {
Ok(report) => {
state.saved += 1;
batch.saved_as = Some(state.saved);
state.sent.push(batch);
state.resolve(&report.created);
state.retries = 0;
Outcome::Saved(report)
}
// Refused by the server: retrying would not help.
Err(err @ ServerFnError::ServerError(_)) => {
state.retries = 0;
Outcome::Refused(err)
}
// Not delivered, or the answer was lost: send it again later.
Err(_) => {
state.queue.splice(0..0, batch.ops);
state.retries += 1;
let delay = Duration::from_secs(1 << state.retries.min(5)).min(MAX_RETRY_DELAY);
Outcome::Retry(delay)
}
}
});
match outcome {
None => {}
Some(Outcome::Saved(report)) => {
if let Some(msg) = report.rejected {
ctx.error.set(Some(msg));
}
ctx.refresh.update(|n| *n += 1);
self.flush(ctx);
}
Some(Outcome::Refused(err)) => {
ctx.report(err);
ctx.refresh.update(|n| *n += 1);
self.flush(ctx);
}
Some(Outcome::Retry(delay)) => set_timeout(move || self.flush(ctx), delay),
}
}
}
impl State {
/// Queues the change, merged with the queued ones for the same item.
fn push(&mut self, mut op: ItemOp) {
if let ItemOp::Add { id, .. } = &mut op {
self.last_temp -= 1;
*id = self.last_temp;
} else if let Some(&(_, real)) = self.ids.iter().find(|&&(temp, _)| temp == op.id()) {
// Still open in an editor from before the item was saved.
*op.id_mut() = real;
}
let id = op.id();
let queued_add = self.queue.iter().position(|q| matches!(q, ItemOp::Add { id: added, .. } if *added == id));
match (op, queued_add) {
(ItemOp::Delete { .. }, Some(_)) => self.queue.retain(|q| q.id() != id),
(ItemOp::Update { input, .. }, Some(index)) => {
if let ItemOp::Add { input: added, .. } = &mut self.queue[index] {
*added = input;
}
}
(op @ ItemOp::Delete { .. }, None) => {
self.queue.retain(|q| q.id() != id);
self.queue.push(op);
}
(op @ (ItemOp::Update { .. } | ItemOp::SetChecked { .. }), _) => {
let same_kind = std::mem::discriminant(&op);
self.queue.retain(|q| q.id() != id || std::mem::discriminant(q) != same_kind);
self.queue.push(op);
}
(op, _) => self.queue.push(op),
}
}
/// Swaps temporary ids for the ones the server gave.
fn resolve(&mut self, created: &[(i64, i64)]) {
let ops = self.queue.iter_mut().chain(self.sent.iter_mut().flat_map(|batch| &mut batch.ops));
for op in ops {
if let Some(&(_, real)) = created.iter().find(|&&(temp, _)| temp == op.id()) {
*op.id_mut() = real;
}
}
self.ids.extend_from_slice(created);
}
}
fn apply(items: &mut Vec<Item>, list_id: i64, op: &ItemOp) {
fn find(items: &mut [Item], id: i64) -> Option<&mut Item> {
items.iter_mut().find(|item| item.id == id)
}
match op {
ItemOp::Add { id, list_id: list, input } => {
if *list == list_id && !items.iter().any(|item| item.id == *id) {
items.push(Item {
id: *id,
list_id,
name: input.name.clone(),
quantity: input.quantity,
icon: input.icon,
category: input.category,
checked: false,
});
}
}
ItemOp::Update { id, input } => {
if let Some(item) = find(items, *id) {
item.name = input.name.clone();
item.quantity = input.quantity;
item.icon = input.icon;
item.category = input.category;
}
}
ItemOp::Delete { id } => items.retain(|item| item.id != *id),
ItemOp::SetChecked { id, checked } => {
if let Some(item) = find(items, *id) {
item.checked = *checked;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{Category, Icon, ItemInput};
fn input(name: &str) -> ItemInput {
ItemInput { name: name.into(), quantity: None, icon: Icon::Basket, category: Category::Autre }
}
fn add(name: &str) -> ItemOp {
ItemOp::Add { id: 0, list_id: 1, input: input(name) }
}
#[test]
fn merges_queued_changes() {
let mut state = State::default();
state.push(ItemOp::SetChecked { id: 5, checked: true });
state.push(ItemOp::SetChecked { id: 5, checked: false });
state.push(add("Pain"));
state.push(ItemOp::Update { id: -1, input: input("Pain complet") });
assert_eq!(
state.queue,
[
ItemOp::SetChecked { id: 5, checked: false },
ItemOp::Add { id: -1, list_id: 1, input: input("Pain complet") },
]
);
state.push(ItemOp::Delete { id: -1 });
state.push(ItemOp::Delete { id: 5 });
assert_eq!(state.queue, [ItemOp::Delete { id: 5 }]);
}
#[test]
fn resolves_temporary_ids() {
let mut state = State::default();
state.push(add("Pain"));
state.sent.push(Batch { ops: std::mem::take(&mut state.queue), saved_as: None });
state.push(ItemOp::SetChecked { id: -1, checked: true });
state.resolve(&[(-1, 42)]);
assert_eq!(state.queue, [ItemOp::SetChecked { id: 42, checked: true }]);
assert_eq!(state.sent[0].ops[0].id(), 42);
// An editor opened on the temporary item.
state.push(ItemOp::Delete { id: -1 });
assert_eq!(state.queue, [ItemOp::Delete { id: 42 }]);
}
#[test]
fn applies_changes_to_fetched_items() {
let item = Item {
id: 7,
list_id: 1,
name: "Lait".into(),
quantity: None,
icon: Icon::Milk,
category: Category::Frais,
checked: false,
};
let mut items = vec![item];
apply(&mut items, 1, &ItemOp::SetChecked { id: 7, checked: true });
apply(&mut items, 1, &ItemOp::Add { id: -1, list_id: 1, input: input("Pain") });
apply(&mut items, 1, &ItemOp::Add { id: -2, list_id: 2, input: input("Ailleurs") });
assert!(items[0].checked);
assert_eq!(items.len(), 2);
// Already in the fetched data.
apply(&mut items, 1, &ItemOp::Add { id: 7, list_id: 1, input: input("Lait") });
apply(&mut items, 1, &ItemOp::Delete { id: -1 });
assert_eq!(items.len(), 1);
}
}
+14 -37
View File
@@ -2,8 +2,9 @@ use leptos::ev;
use leptos::prelude::*; use leptos::prelude::*;
use super::icons::IconSvg; use super::icons::IconSvg;
use super::transition;
use super::{Ctx, ItemEditor}; use super::{Ctx, ItemEditor};
use crate::model::{Item, ItemInput, Suggestion}; use crate::model::Item;
const LONG_PRESS_MS: u64 = 450; const LONG_PRESS_MS: u64 = 450;
@@ -44,17 +45,15 @@ pub fn ItemTile(item: Item) -> impl IntoView {
open_editor(); open_editor();
}; };
let (name, icon, category, badge) = item.with_value(|item| { let (id, name, icon, category, badge) = item.with_value(|item| {
(item.name.clone(), item.icon, item.category, item.quantity.map(|q| q.label())) (item.id, item.name.clone(), item.icon, item.category, item.quantity.map(|q| q.label()))
}); });
let aria_label = format!("{name} : mettre dans le panier"); let aria_label = format!("{name} : mettre dans le panier");
view! { view! {
<button <button
class=format!( class=format!("tile tile-item {}", category.tile_class())
"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] {}", style:view-transition-name=transition::item_name(id)
category.tile_class(),
)
aria-label=aria_label aria-label=aria_label
on:click=on_click on:click=on_click
on:contextmenu=on_context_menu on:contextmenu=on_context_menu
@@ -66,58 +65,36 @@ pub fn ItemTile(item: Item) -> impl IntoView {
{badge {badge
.map(|badge| { .map(|badge| {
view! { view! {
<span class="absolute top-2 right-2 rounded-lg bg-ink px-1.5 py-0.5 font-mono text-xs text-paper"> <span class="tile-badge">
{badge} {badge}
</span> </span>
} }
})} })}
<IconSvg icon class="min-h-0 w-full flex-1 text-ink" /> <IconSvg icon />
<span class="line-clamp-2 text-[0.95rem] leading-tight font-semibold break-words hyphens-auto"> <span class="tile-label">
{name} {name}
</span> </span>
</button> </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. /// Greyed tile in "Déjà dans le panier": tap puts the item back on the list.
#[component] #[component]
pub fn BasketTile(item: Item) -> impl IntoView { pub fn BasketTile(item: Item) -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
let (name, icon) = (item.name.clone(), item.icon); let (id, name, icon) = (item.id, item.name.clone(), item.icon);
let aria_label = format!("{name} : remettre dans la liste"); let aria_label = format!("{name} : remettre dans la liste");
let item = StoredValue::new(item); let item = StoredValue::new(item);
view! { view! {
<button <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" class="tile tile-off"
style:view-transition-name=transition::item_name(id)
aria-label=aria_label aria-label=aria_label
on:click=move |_| item.with_value(|item| ctx.toggle(item)) on:click=move |_| item.with_value(|item| ctx.toggle(item))
> >
<IconSvg icon class="min-h-0 w-full flex-1" /> <IconSvg icon />
<span class="line-clamp-2 text-xs leading-tight font-medium line-through decoration-ink/30"> <span class="tile-label">
{name} {name}
</span> </span>
</button> </button>
+43
View File
@@ -0,0 +1,43 @@
//! Animated DOM updates: tiles carrying a `view-transition-name` glide from
//! their old place to their new one, even across lists.
/// Runs `update` inside a view transition, or right away when the browser
/// does not support them.
pub fn animate(update: impl FnOnce() + 'static) {
#[cfg(feature = "hydrate")]
browser::animate(update);
#[cfg(not(feature = "hydrate"))]
update();
}
/// `view-transition-name` of an item tile, the same in both lists.
pub fn item_name(id: i64) -> String {
format!("item-{id}")
}
#[cfg(feature = "hydrate")]
mod browser {
use js_sys::{Function, Promise, Reflect};
use leptos::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
pub fn animate(update: impl FnOnce() + 'static) {
let document = document();
let start = Reflect::get(&document, &"startViewTransition".into())
.ok()
.and_then(|start| start.dyn_into::<Function>().ok());
let Some(start) = start else {
return update();
};
let callback = Closure::once_into_js(move || {
update();
// Leptos patches the DOM in a microtask: the new state is
// ready by the next timeout.
Promise::new(&mut |resolve, _| {
let _ = window().set_timeout_with_callback(&resolve);
})
});
let _ = start.call1(&document, &callback);
}
}
+129 -63
View File
@@ -3,7 +3,7 @@ use sqlx::{Row, SqliteConnection};
use std::str::FromStr; use std::str::FromStr;
use crate::model::{ use crate::model::{
Category, Icon, Item, ItemInput, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User, Account, Category, Icon, Item, ItemInput, ItemOp, ListColor, Member, Quantity, ShoppingList, Unit, User,
}; };
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> { pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
@@ -61,6 +61,7 @@ fn user_from_row(row: &SqliteRow) -> Result<User, sqlx::Error> {
id: row.try_get("id")?, id: row.try_get("id")?,
name: row.try_get("name")?, name: row.try_get("name")?,
email: row.try_get("email")?, email: row.try_get("email")?,
is_admin: row.try_get("is_admin")?,
}) })
} }
@@ -76,17 +77,20 @@ const STARTER_CATALOG: &[(&str, Icon, Category)] = &[
("Café en grains", Icon::Coffee, Category::Epicerie), ("Café en grains", Icon::Coffee, Category::Epicerie),
]; ];
/// Creates the account with a first list and starter suggestions. /// Creates the account with a first list and starter suggestions; the very
/// Fails with a unique violation if the email is taken. /// first account is an admin. Fails with a unique violation if the email is taken.
pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> { pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> {
let mut tx = pool.begin().await?; let mut tx = pool.begin().await?;
let user_id: i64 = sqlx::query("INSERT INTO users (email, name, password_hash) VALUES (?, ?, ?) RETURNING id") let user_id: i64 = sqlx::query(
.bind(email) "INSERT INTO users (email, name, password_hash, is_admin)
.bind(name) VALUES (?, ?, ?, NOT EXISTS (SELECT 1 FROM users)) RETURNING id",
.bind(password_hash) )
.fetch_one(&mut *tx) .bind(email)
.await? .bind(name)
.try_get("id")?; .bind(password_hash)
.fetch_one(&mut *tx)
.await?
.try_get("id")?;
// Lists created before accounts existed go to the first user. // Lists created before accounts existed go to the first user.
let claimed = sqlx::query("UPDATE lists SET owner_id = ? WHERE owner_id IS NULL") let claimed = sqlx::query("UPDATE lists SET owner_id = ? WHERE owner_id IS NULL")
@@ -113,7 +117,7 @@ pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash:
/// The user and their password hash. /// The user and their password hash.
pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, sqlx::Error> { pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, sqlx::Error> {
sqlx::query("SELECT id, name, email, password_hash FROM users WHERE email = ?") sqlx::query("SELECT id, name, email, is_admin, password_hash FROM users WHERE email = ?")
.bind(email) .bind(email)
.fetch_optional(pool) .fetch_optional(pool)
.await? .await?
@@ -136,7 +140,7 @@ pub async fn create_session(pool: &SqlitePool, token_hash: &str, user_id: i64, d
pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> { pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> {
sqlx::query( sqlx::query(
"SELECT u.id, u.name, u.email FROM sessions s JOIN users u ON u.id = s.user_id "SELECT u.id, u.name, u.email, u.is_admin FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = ? AND s.expires_at > datetime('now')", WHERE s.token_hash = ? AND s.expires_at > datetime('now')",
) )
.bind(token_hash) .bind(token_hash)
@@ -155,6 +159,57 @@ pub async fn delete_session(pool: &SqlitePool, token_hash: &str) -> Result<(), s
Ok(()) Ok(())
} }
// --- Administration ---------------------------------------------------------
pub async fn has_users(pool: &SqlitePool) -> Result<bool, sqlx::Error> {
sqlx::query("SELECT EXISTS (SELECT 1 FROM users) AS has_users")
.fetch_one(pool)
.await?
.try_get("has_users")
}
pub async fn accounts(pool: &SqlitePool) -> Result<Vec<Account>, sqlx::Error> {
sqlx::query("SELECT id, name, email, is_admin, date(created_at) AS created_at FROM users ORDER BY id")
.fetch_all(pool)
.await?
.iter()
.map(|row| Ok(Account { user: user_from_row(row)?, created_at: row.try_get("created_at")? }))
.collect()
}
/// Fails with a unique violation if the email is taken.
pub async fn update_user(pool: &SqlitePool, id: i64, name: &str, email: &str, is_admin: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE users SET name = ?, email = ?, is_admin = ? WHERE id = ?")
.bind(name)
.bind(email)
.bind(is_admin)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
/// Changes the password and signs the user out everywhere.
pub async fn set_password(pool: &SqlitePool, id: i64, password_hash: &str) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
sqlx::query("UPDATE users SET password_hash = ? WHERE id = ?")
.bind(password_hash)
.bind(id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM sessions WHERE user_id = ?")
.bind(id)
.execute(&mut *tx)
.await?;
tx.commit().await
}
/// Deletes the account with its sessions, suggestions and the lists it owns.
pub async fn delete_user(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM users WHERE id = ?").bind(id).execute(pool).await?;
Ok(())
}
// --- Lists & sharing -------------------------------------------------------- // --- Lists & sharing --------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -226,7 +281,7 @@ pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error>
pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> { pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> {
sqlx::query( sqlx::query(
"SELECT u.id, u.name, u.email FROM list_members m JOIN users u ON u.id = m.user_id "SELECT u.id, u.name, u.email, u.is_admin FROM list_members m JOIN users u ON u.id = m.user_id
WHERE m.list_id = ? ORDER BY u.name", WHERE m.list_id = ? ORDER BY u.name",
) )
.bind(list_id) .bind(list_id)
@@ -297,7 +352,7 @@ pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> Result<Option<i64>
} }
/// Remembers the product in the user's catalog so it can be suggested later. /// Remembers the product in the user's catalog so it can be suggested later.
async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> { async fn record_in_catalog(conn: &mut SqliteConnection, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query( sqlx::query(
"INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1) "INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)
ON CONFLICT(user_id, name) DO UPDATE SET ON CONFLICT(user_id, name) DO UPDATE SET
@@ -309,12 +364,12 @@ async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -
.bind(&input.name) .bind(&input.name)
.bind(input.icon.as_str()) .bind(input.icon.as_str())
.bind(input.category.as_str()) .bind(input.category.as_str())
.execute(pool) .execute(&mut *conn)
.await?; .await?;
Ok(()) Ok(())
} }
pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> { async fn add_item(conn: &mut SqliteConnection, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
let row = sqlx::query( let row = sqlx::query(
"INSERT INTO items (list_id, name, amount, unit, icon, category) "INSERT INTO items (list_id, name, amount, unit, icon, category)
VALUES (?, ?, ?, ?, ?, ?) RETURNING id", VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
@@ -325,13 +380,13 @@ pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &Ite
.bind(input.quantity.map(|q| q.unit.as_str())) .bind(input.quantity.map(|q| q.unit.as_str()))
.bind(input.icon.as_str()) .bind(input.icon.as_str())
.bind(input.category.as_str()) .bind(input.category.as_str())
.fetch_one(pool) .fetch_one(&mut *conn)
.await?; .await?;
record_in_catalog(pool, user_id, input).await?; record_in_catalog(conn, user_id, input).await?;
row.try_get("id") row.try_get("id")
} }
pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> { async fn update_item(conn: &mut SqliteConnection, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query( sqlx::query(
"UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?", "UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?",
) )
@@ -341,49 +396,47 @@ pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Resul
.bind(input.icon.as_str()) .bind(input.icon.as_str())
.bind(input.category.as_str()) .bind(input.category.as_str())
.bind(id) .bind(id)
.execute(pool) .execute(conn)
.await?; .await?;
Ok(()) Ok(())
} }
pub async fn delete_item(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> { async fn delete_item(conn: &mut SqliteConnection, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(pool).await?; sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(conn).await?;
Ok(()) Ok(())
} }
pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<(), sqlx::Error> { async fn set_checked(conn: &mut SqliteConnection, id: i64, checked: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE items SET checked = ? WHERE id = ?") sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
.bind(checked) .bind(checked)
.bind(id) .bind(id)
.execute(pool) .execute(conn)
.await?; .await?;
Ok(()) Ok(())
} }
/// The user's most used products not already on the list. /// Applies the changes, in order, in one transaction. Ops may target items
pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> { /// added earlier in the batch by their temporary id; returns the
sqlx::query( /// (temporary id, real id) of each added item.
"SELECT name, icon, category FROM catalog c pub async fn apply_item_ops(pool: &SqlitePool, user_id: i64, ops: &[ItemOp]) -> Result<Vec<(i64, i64)>, sqlx::Error> {
WHERE c.user_id = ? AND NOT EXISTS ( let mut tx = pool.begin().await?;
SELECT 1 FROM items i WHERE i.list_id = ? AND i.name = c.name COLLATE NOCASE let mut created: Vec<(i64, i64)> = Vec::new();
) for op in ops {
ORDER BY use_count DESC, name let id = created
LIMIT ?", .iter()
) .find(|&&(temp, _)| temp == op.id())
.bind(user_id) .map_or(op.id(), |&(_, real)| real);
.bind(list_id) match op {
.bind(limit) ItemOp::Add { id: temp, list_id, input } => {
.fetch_all(pool) created.push((*temp, add_item(&mut tx, user_id, *list_id, input).await?));
.await? }
.iter() ItemOp::Update { input, .. } => update_item(&mut tx, id, input).await?,
.map(|row| { ItemOp::Delete { .. } => delete_item(&mut tx, id).await?,
Ok(Suggestion { ItemOp::SetChecked { checked, .. } => set_checked(&mut tx, id, *checked).await?,
name: row.try_get("name")?, }
icon: decode(Icon::parse(row.try_get("icon")?), "icon")?, }
category: decode(Category::parse(row.try_get("category")?), "category")?, tx.commit().await?;
}) Ok(created)
})
.collect()
} }
#[cfg(test)] #[cfg(test)]
@@ -394,6 +447,11 @@ mod tests {
connect("sqlite::memory:").await.unwrap() connect("sqlite::memory:").await.unwrap()
} }
/// The in-memory pool has a single connection: drop it before using the pool.
async fn conn(pool: &SqlitePool) -> sqlx::pool::PoolConnection<sqlx::Sqlite> {
pool.acquire().await.unwrap()
}
async fn user(pool: &SqlitePool, email: &str) -> i64 { async fn user(pool: &SqlitePool, email: &str) -> i64 {
register(pool, email, "Test", "hash").await.unwrap() register(pool, email, "Test", "hash").await.unwrap()
} }
@@ -462,37 +520,45 @@ mod tests {
let me = user(&pool, "a@x.fr").await; let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id; let list = lists(&pool, me).await.unwrap()[0].id;
let id = add_item(&pool, me, list, &input("Avocats")).await.unwrap(); let id = add_item(&mut *conn(&pool).await, me, list, &input("Avocats")).await.unwrap();
assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list)); assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list));
let mut edited = input("Avocats"); let mut edited = input("Avocats");
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece }); edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
update_item(&pool, id, &edited).await.unwrap(); update_item(&mut *conn(&pool).await, id, &edited).await.unwrap();
set_checked(&pool, id, true).await.unwrap(); set_checked(&mut *conn(&pool).await, id, true).await.unwrap();
let all = items(&pool, list).await.unwrap(); let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1); assert_eq!(all.len(), 1);
assert_eq!(all[0].quantity.unwrap().label(), "×4"); assert_eq!(all[0].quantity.unwrap().label(), "×4");
assert!(all[0].checked); assert!(all[0].checked);
delete_item(&pool, id).await.unwrap(); delete_item(&mut *conn(&pool).await, id).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty()); assert!(items(&pool, list).await.unwrap().is_empty());
} }
#[tokio::test] #[tokio::test]
async fn suggestions_skip_items_on_list() { async fn batch_resolves_temporary_ids() {
let pool = pool().await; let pool = pool().await;
let me = user(&pool, "a@x.fr").await; let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id; let list = lists(&pool, me).await.unwrap()[0].id;
add_item(&pool, me, list, &input("beurre")).await.unwrap();
let names: Vec<_> = suggestions(&pool, me, list, 3) let mut edited = input("Pommes");
.await edited.quantity = None;
.unwrap() let ops = [
.into_iter() ItemOp::Add { id: -1, list_id: list, input: input("Pommes") },
.map(|s| s.name) ItemOp::Add { id: -2, list_id: list, input: input("Poires") },
.collect(); ItemOp::Update { id: -1, input: edited },
assert!(!names.iter().any(|n| n.eq_ignore_ascii_case("beurre"))); ItemOp::SetChecked { id: -1, checked: true },
assert_eq!(names.len(), 3); ItemOp::Delete { id: -2 },
];
let created = apply_item_ops(&pool, me, &ops).await.unwrap();
assert_eq!(created.len(), 2);
let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1);
assert_eq!(all[0].id, created[0].1);
assert_eq!(all[0].quantity, None);
assert!(all[0].checked);
} }
#[tokio::test] #[tokio::test]
@@ -500,7 +566,7 @@ mod tests {
let pool = pool().await; let pool = pool().await;
let me = user(&pool, "a@x.fr").await; let me = user(&pool, "a@x.fr").await;
let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap(); let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap();
add_item(&pool, me, list, &input("Chips")).await.unwrap(); add_item(&mut *conn(&pool).await, me, list, &input("Chips")).await.unwrap();
delete_list(&pool, list).await.unwrap(); delete_list(&pool, list).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty()); assert!(items(&pool, list).await.unwrap().is_empty());
} }
+3
View File
@@ -1,3 +1,6 @@
// Leptos view types nest deeply: the add sheet exceeds the default limit.
#![recursion_limit = "256"]
pub mod api; pub mod api;
pub mod app; pub mod app;
pub mod model; pub mod model;
+121 -27
View File
@@ -38,6 +38,8 @@ pub struct User {
pub id: i64, pub id: i64,
pub name: String, pub name: String,
pub email: String, pub email: String,
/// Can see and manage every account.
pub is_admin: bool,
} }
impl User { impl User {
@@ -53,6 +55,14 @@ impl User {
} }
} }
/// An account as listed on the admin page.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Account {
pub user: User,
/// "2026-10-07".
pub created_at: String,
}
/// Someone a list is shared with. /// Someone a list is shared with.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Member { pub struct Member {
@@ -85,6 +95,16 @@ impl ListColor {
ListColor::Peach => "bg-peach", ListColor::Peach => "bg-peach",
} }
} }
/// Same color as `dot_class`, for the browser's `theme-color`.
pub fn hex(self) -> &'static str {
match self {
ListColor::Lime => "#bfe383",
ListColor::Pink => "#ffadd6",
ListColor::Sky => "#7fdffb",
ListColor::Peach => "#ffbd76",
}
}
} }
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -107,7 +127,7 @@ impl Item {
/// Lowercases and strips French accents so "Œufs" sorts with "o" and /// Lowercases and strips French accents so "Œufs" sorts with "o" and
/// "Épinards" with "e". /// "Épinards" with "e".
fn fold_name(name: &str) -> String { pub fn fold_name(name: &str) -> String {
let mut folded = String::with_capacity(name.len()); let mut folded = String::with_capacity(name.len());
for c in name.chars().flat_map(char::to_lowercase) { for c in name.chars().flat_map(char::to_lowercase) {
match c { match c {
@@ -208,7 +228,7 @@ impl Category {
} }
} }
/// Tailwind background class for the item tile. /// Background class for the item tile (see style/main.css).
pub fn tile_class(self) -> &'static str { pub fn tile_class(self) -> &'static str {
match self { match self {
Category::FruitsLegumes => "bg-lime", Category::FruitsLegumes => "bg-lime",
@@ -225,51 +245,91 @@ impl Category {
pub enum Icon { pub enum Icon {
Apple, Apple,
Banana, Banana,
Carrot,
Lemon, Lemon,
Glass, Pear,
Grapes,
Strawberry,
Cherries,
Avocado,
Tomato,
Carrot,
Salad,
Onion,
Potato,
Mushroom,
Milk, Milk,
IceCream,
Cheese,
Egg, Egg,
Coffee, Cheese,
Bread, Yogurt,
Croissant, IceCream,
Pasta, Frozen,
Meat, Meat,
Fish, Fish,
Bread,
Croissant,
Cake,
Cookie,
Pizza,
Pasta,
Can,
Jar,
Chocolate,
Candy,
Coffee,
Water,
Glass,
Bottle, Bottle,
Wine,
Spray,
BabyBottle,
Paw,
Basket, Basket,
} }
text_enum!(Icon { text_enum!(Icon {
Apple => "apple", Apple => "apple",
Banana => "banana", Banana => "banana",
Carrot => "carrot",
Lemon => "lemon", Lemon => "lemon",
Glass => "glass", Pear => "pear",
Grapes => "grapes",
Strawberry => "strawberry",
Cherries => "cherries",
Avocado => "avocado",
Tomato => "tomato",
Carrot => "carrot",
Salad => "salad",
Onion => "onion",
Potato => "potato",
Mushroom => "mushroom",
Milk => "milk", Milk => "milk",
IceCream => "ice_cream",
Cheese => "cheese",
Egg => "egg", Egg => "egg",
Coffee => "coffee", Cheese => "cheese",
Bread => "bread", Yogurt => "yogurt",
Croissant => "croissant", IceCream => "ice_cream",
Pasta => "pasta", Frozen => "frozen",
Meat => "meat", Meat => "meat",
Fish => "fish", Fish => "fish",
Bread => "bread",
Croissant => "croissant",
Cake => "cake",
Cookie => "cookie",
Pizza => "pizza",
Pasta => "pasta",
Can => "can",
Jar => "jar",
Chocolate => "chocolate",
Candy => "candy",
Coffee => "coffee",
Water => "water",
Glass => "glass",
Bottle => "bottle", Bottle => "bottle",
Wine => "wine",
Spray => "spray",
BabyBottle => "baby_bottle",
Paw => "paw",
Basket => "basket", 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. /// Payload for creating or editing an item.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ItemInput { pub struct ItemInput {
@@ -279,6 +339,40 @@ pub struct ItemInput {
pub category: Category, pub category: Category,
} }
/// A change to items, queued in the browser and sent to the server in batches.
/// Items added in the browser carry a negative temporary `id` until the
/// server gives them a real one.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ItemOp {
Add { id: i64, list_id: i64, input: ItemInput },
Update { id: i64, input: ItemInput },
Delete { id: i64 },
SetChecked { id: i64, checked: bool },
}
impl ItemOp {
pub fn id(&self) -> i64 {
match self {
ItemOp::Add { id, .. } | ItemOp::Update { id, .. } | ItemOp::Delete { id } | ItemOp::SetChecked { id, .. } => *id,
}
}
pub fn id_mut(&mut self) -> &mut i64 {
match self {
ItemOp::Add { id, .. } | ItemOp::Update { id, .. } | ItemOp::Delete { id } | ItemOp::SetChecked { id, .. } => id,
}
}
}
/// What the server did with a batch of [`ItemOp`]s.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SyncReport {
/// (temporary id, real id) of each item added.
pub created: Vec<(i64, i64)>,
/// Why some changes were refused, if any; the others were applied.
pub rejected: Option<String>,
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -293,7 +387,7 @@ mod tests {
#[test] #[test]
fn initials() { fn initials() {
let user = |name: &str| User { id: 1, name: name.into(), email: String::new() }; let user = |name: &str| User { id: 1, name: name.into(), email: String::new(), is_admin: false };
assert_eq!(user("Camille Lefèvre").initials(), "CL"); assert_eq!(user("Camille Lefèvre").initials(), "CL");
assert_eq!(user("romain").initials(), "RO"); assert_eq!(user("romain").initials(), "RO");
assert_eq!(user("élise").initials(), "ÉL"); assert_eq!(user("élise").initials(), "ÉL");
+1081 -44
View File
File diff suppressed because it is too large. Load diff