first commit

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

No files matched your search

+382
View File
@@ -0,0 +1,382 @@
use leptos::ev;
use leptos::prelude::*;
use leptos_router::hooks::use_navigate;
use super::Ctx;
use super::icons::{IconSvg, icon_label};
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit};
#[derive(Clone, Debug, PartialEq)]
pub enum ItemEditor {
New,
Edit(Item),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ListEditor {
New,
Edit(ShoppingList),
}
/// Bottom sheet with a backdrop; `on_close` runs on backdrop tap or Escape.
#[component]
fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static, children: Children) -> impl IntoView {
let handle = window_event_listener(ev::keydown, move |ev| {
if ev.key() == "Escape" {
on_close();
}
});
on_cleanup(move || handle.remove());
view! {
<div class="fixed inset-0 z-20 flex items-end justify-center" role="dialog" aria-modal="true">
<div class="absolute inset-0 bg-ink/50" on:click=move |_| on_close()></div>
<div class="relative max-h-[90dvh] w-full max-w-md overflow-y-auto rounded-t-3xl border-2 border-b-0 border-ink bg-paper px-5 pt-3 pb-[max(1.5rem,env(safe-area-inset-bottom))]">
<div class="mx-auto mb-4 h-1.5 w-12 rounded-full bg-ink/20"></div>
<h2 class="font-display text-2xl font-bold">{title}</h2>
{children()}
</div>
</div>
}
}
#[component]
pub fn ItemSheet(#[prop(into)] list_id: Signal<Option<i64>>) -> impl IntoView {
let ctx = expect_context::<Ctx>();
move || {
let editor = ctx.item_editor.get()?;
let list_id = list_id.get()?;
Some(view! { <ItemForm editor list_id /> })
}
}
#[component]
fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let close = move || ctx.item_editor.set(None);
let existing = match &editor {
ItemEditor::Edit(item) => Some(item.clone()),
ItemEditor::New => None,
};
let name = RwSignal::new(existing.as_ref().map(|i| i.name.clone()).unwrap_or_default());
let amount = RwSignal::new(
existing
.as_ref()
.and_then(|i| i.quantity)
.map(|q| q.amount.to_string().replace('.', ","))
.unwrap_or_default(),
);
let unit = RwSignal::new(existing.as_ref().and_then(|i| i.quantity).map_or(Unit::Piece, |q| q.unit));
let icon = RwSignal::new(existing.as_ref().map_or(Icon::Basket, |i| i.icon));
let category = RwSignal::new(existing.as_ref().map_or(Category::Autre, |i| i.category));
let item_id = existing.as_ref().map(|i| i.id);
let invalid_amount = Memo::new(move |_| amount.with(|a| !a.trim().is_empty() && parse_amount(a).is_none()));
let submit = move |ev: ev::SubmitEvent| {
ev.prevent_default();
if invalid_amount.get() {
return;
}
let input = ItemInput {
name: name.get(),
quantity: parse_amount(&amount.get()).map(|amount| Quantity { amount, unit: unit.get() }),
icon: icon.get(),
category: category.get(),
};
match item_id {
Some(id) => ctx.mutate(crate::api::update_item(id, input), move |_| close()),
None => ctx.mutate(crate::api::add_item(list_id, input), move |_| close()),
}
};
let delete = move |_| {
if let Some(id) = item_id {
ctx.mutate(crate::api::delete_item(id), move |_| close());
}
};
let title = if item_id.is_some() { "Modifier l'article" } else { "Nouvel article" };
view! {
<Sheet title=title.to_owned() on_close=close>
<form class="mt-4 flex flex-col gap-5" on:submit=submit>
<label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span>
<input
class="field"
required
maxlength="60"
autofocus
placeholder="Avocats"
bind:value=name
/>
</label>
<div class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Quantité (facultatif)"
</span>
<div class="flex gap-2">
<input
class="field w-28"
inputmode="decimal"
placeholder="3"
aria-label="Quantité"
aria-invalid=move || invalid_amount.get().to_string()
bind:value=amount
/>
<select
class="field flex-1"
aria-label="Unité"
on:change=move |ev| {
if let Some(u) = Unit::parse(&event_target_value(&ev)) {
unit.set(u);
}
}
>
{Unit::ALL
.iter()
.map(|&u| {
view! {
<option value=u.as_str() selected=move || unit.get() == u>
{u.label()}
</option>
}
})
.collect_view()}
</select>
</div>
<Show when=move || invalid_amount.get()>
<p class="text-sm text-red-700">"Quantité invalide."</p>
</Show>
</div>
<fieldset class="flex flex-col gap-1.5">
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Rayon"
</legend>
<div class="flex flex-wrap gap-2">
{Category::ALL
.iter()
.map(|&c| {
view! {
<button
type="button"
class=move || {
format!(
"rounded-full border-2 px-3 py-1.5 text-sm font-semibold {} {}",
c.tile_class(),
if category.get() == c { "border-ink" } else { "border-transparent opacity-70" },
)
}
aria-pressed=move || (category.get() == c).to_string()
on:click=move |_| category.set(c)
>
{c.label()}
</button>
}
})
.collect_view()}
</div>
</fieldset>
<fieldset class="flex flex-col gap-1.5">
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Icône"
</legend>
<div class="grid grid-cols-6 gap-2">
{Icon::ALL
.iter()
.map(|&i| {
view! {
<button
type="button"
class=move || {
format!(
"grid aspect-square place-items-center rounded-xl border-2 {}",
if icon.get() == i {
"border-ink bg-lime"
} else {
"border-ink/10 bg-mist"
},
)
}
title=icon_label(i)
aria-label=icon_label(i)
aria-pressed=move || (icon.get() == i).to_string()
on:click=move |_| icon.set(i)
>
<IconSvg icon=i class="size-7" />
</button>
}
})
.collect_view()}
</div>
</fieldset>
<div class="flex gap-3">
{item_id
.map(|_| {
view! {
<button
type="button"
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
on:click=delete
>
"Supprimer"
</button>
}
})}
<button
type="submit"
class="tile-shadow flex-1 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-display text-lg font-bold active:translate-y-1 active:shadow-none"
>
{if item_id.is_some() { "Enregistrer" } else { "Ajouter" }}
</button>
</div>
</form>
</Sheet>
}
}
/// "1,5" / "1.5" / "3" → Some; empty or non-positive → None.
fn parse_amount(text: &str) -> Option<f64> {
let value = text.trim().replace(',', ".").parse::<f64>().ok()?;
(value.is_finite() && value > 0.0).then_some(value)
}
#[component]
pub fn ListSheet() -> impl IntoView {
let ctx = expect_context::<Ctx>();
move || ctx.list_editor.get().map(|editor| view! { <ListForm editor /> })
}
#[component]
fn ListForm(editor: ListEditor) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let navigate = use_navigate();
let close = move || ctx.list_editor.set(None);
let existing = match &editor {
ListEditor::Edit(list) => Some(list.clone()),
ListEditor::New => None,
};
let list_id = existing.as_ref().map(|l| l.id);
let name = RwSignal::new(existing.map(|l| l.name).unwrap_or_default());
let color = RwSignal::new(ListColor::Pink);
let submit = {
let navigate = navigate.clone();
move |ev: ev::SubmitEvent| {
ev.prevent_default();
match list_id {
Some(id) => ctx.mutate(crate::api::rename_list(id, name.get()), move |_| close()),
None => {
let navigate = navigate.clone();
ctx.mutate(crate::api::create_list(name.get(), color.get()), move |id| {
close();
navigate(&format!("/l/{id}"), Default::default());
})
}
}
}
};
let delete = move |_| {
let Some(id) = list_id else { return };
let confirmed = window()
.confirm_with_message("Supprimer cette liste et tous ses articles ?")
.unwrap_or(false);
if confirmed {
let navigate = navigate.clone();
ctx.mutate(crate::api::delete_list(id), move |_| {
close();
navigate("/", Default::default());
});
}
};
let title = if list_id.is_some() { "Modifier la liste" } else { "Nouvelle liste" };
view! {
<Sheet title=title.to_owned() on_close=close>
<form class="mt-4 flex flex-col gap-5" on:submit=submit>
<label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span>
<input
class="field"
required
maxlength="60"
autofocus
placeholder="Apéro de samedi"
bind:value=name
/>
</label>
<Show when=move || list_id.is_none()>
<fieldset>
<legend class="mb-1.5 font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">
"Couleur"
</legend>
<div class="flex gap-3">
{ListColor::ALL
.iter()
.map(|&c| {
view! {
<button
type="button"
class=move || {
format!(
"size-11 rounded-full border-2 {} {}",
c.dot_class(),
if color.get() == c { "border-ink ring-2 ring-ink ring-offset-2 ring-offset-paper" } else { "border-ink/40" },
)
}
aria-label=c.as_str()
aria-pressed=move || (color.get() == c).to_string()
on:click=move |_| color.set(c)
></button>
}
})
.collect_view()}
</div>
</fieldset>
</Show>
<div class="flex gap-3">
{list_id
.map(|_| {
view! {
<button
type="button"
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
on:click=delete
>
"Supprimer"
</button>
}
})}
<button
type="submit"
class="tile-shadow flex-1 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-display text-lg font-bold active:translate-y-1 active:shadow-none"
>
{if list_id.is_some() { "Enregistrer" } else { "Créer" }}
</button>
</div>
</form>
</Sheet>
}
}
#[cfg(test)]
mod tests {
use super::parse_amount;
#[test]
fn parses_amounts() {
assert_eq!(parse_amount("1,5"), Some(1.5));
assert_eq!(parse_amount(" 3 "), Some(3.0));
assert_eq!(parse_amount("0"), None);
assert_eq!(parse_amount("abc"), None);
}
}