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>
This commit is contained in:
Romulus21andClaude Opus 5.5 committed 2026-11-05 22:30:57 +01:00
1 parent 444319f9a5
commit 6b5eaa0ba6
4 files changed
+235 -84

No files matched your search

+202 -80
View File
@@ -5,7 +5,7 @@ use leptos_router::hooks::use_navigate;
use super::Ctx;
use super::icons::{IconSvg, icon_label};
use crate::api::get_members;
use crate::model::{Category, Icon, Item, ItemInput, ItemOp, ListColor, Quantity, ShoppingList, Unit};
use crate::model::{Category, Icon, Item, ItemInput, ItemOp, ListColor, Quantity, ShoppingList, Unit, fold_name};
#[derive(Clone, Debug, PartialEq)]
pub enum ItemEditor {
@@ -42,36 +42,177 @@ pub fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static,
}
#[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>();
move || {
let editor = ctx.item_editor.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="mt-4 flex flex-col gap-4" 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="grid grid-cols-3 gap-3">
<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="tile-shadow rounded-2xl border-2 border-ink bg-pink px-4 py-3 text-left font-display text-lg font-bold active:translate-y-1 active:shadow-none"
>
{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, label_class) = if selected {
(
format!("tile-shadow border-ink active:translate-y-1 active:shadow-none {}", item.category.tile_class()),
"font-semibold",
)
} else {
("border-transparent bg-mist text-ink/45 active:bg-ink/10".to_owned(), "font-medium line-through decoration-ink/30")
};
let aria_label = format!("{name} : {}", if selected { "mettre dans le panier" } else { "remettre dans la liste" });
view! {
<li>
<button
type="button"
class=format!("flex aspect-square w-full flex-col items-center gap-1 rounded-2xl border-2 p-2 pb-2.5 text-center {class}")
aria-label=aria_label
aria-pressed=selected.to_string()
on:click=move |_| {
ctx.change(ItemOp::SetChecked { id, checked: selected });
on_pick();
}
>
<IconSvg icon class="min-h-0 w-full flex-1" />
<span class=format!("line-clamp-2 text-[0.95rem] leading-tight break-words hyphens-auto {label_class}")>
{name}
</span>
</button>
</li>
}
}
#[component]
fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
fn ItemForm(item: Item) -> 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 name = RwSignal::new(item.name.clone());
let amount = RwSignal::new(
existing
.as_ref()
.and_then(|i| i.quantity)
item.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 unit = RwSignal::new(item.quantity.map_or(Unit::Piece, |q| q.unit));
let icon = RwSignal::new(item.icon);
let category = RwSignal::new(item.category);
let item_id = item.id;
let invalid_amount = Memo::new(move |_| amount.with(|a| !a.trim().is_empty() && parse_amount(a).is_none()));
@@ -86,23 +227,16 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
icon: icon.get(),
category: category.get(),
};
ctx.change(match item_id {
Some(id) => ItemOp::Update { id, input },
None => ItemOp::Add { id: 0, list_id, input },
});
ctx.change(ItemOp::Update { id: item_id, input });
close();
};
let delete = move |_| {
if let Some(id) = item_id {
ctx.change(ItemOp::Delete { id });
close();
}
ctx.change(ItemOp::Delete { id: item_id });
close();
};
let title = if item_id.is_some() { "Modifier l'article" } else { "Nouvel article" };
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>
<label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Nom"</span>
@@ -110,7 +244,6 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
class="field"
required
maxlength="60"
autofocus
placeholder="Avocats"
bind:value=name
/>
@@ -184,64 +317,53 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
</div>
</fieldset>
// New items keep the basket: the icon can be changed when editing.
{item_id
.map(|_| {
view! {
<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>
}
})}
<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="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" }}
"Enregistrer"
</button>
</div>
</form>