use leptos::ev; use leptos::prelude::*; use super::icons::IconSvg; use super::{Ctx, ItemEditor}; use crate::model::{Item, ItemInput, Suggestion}; const LONG_PRESS_MS: u64 = 450; /// Item still to buy: tap moves it to the basket, long press opens the editor. #[component] pub fn ItemTile(item: Item) -> impl IntoView { let ctx = expect_context::(); let item = StoredValue::new(item); let timer = StoredValue::new(None::); // Set once the long press fired, so the following click is ignored. let long_pressed = StoredValue::new(false); let open_editor = move || { long_pressed.set_value(true); ctx.item_editor.set(Some(ItemEditor::Edit(item.get_value()))); }; let cancel_timer = move |_| { if let Some(handle) = timer.get_value() { handle.clear(); timer.set_value(None); } }; let start_timer = move |_: ev::PointerEvent| { long_pressed.set_value(false); let handle = set_timeout_with_handle(open_editor, std::time::Duration::from_millis(LONG_PRESS_MS)).ok(); timer.set_value(handle); }; let on_click = move |_| { if long_pressed.get_value() { long_pressed.set_value(false); } else { item.with_value(|item| ctx.toggle(item)); } }; let on_context_menu = move |ev: ev::MouseEvent| { ev.prevent_default(); cancel_timer(()); open_editor(); }; let (name, icon, category, badge) = item.with_value(|item| { (item.name.clone(), item.icon, item.category, item.quantity.map(|q| q.label())) }); let aria_label = format!("{name} : mettre dans le panier"); view! { } } /// 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::(); 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! { } } /// Greyed tile in "Déjà dans le panier": tap puts the item back on the list. #[component] pub fn BasketTile(item: Item) -> impl IntoView { let ctx = expect_context::(); let (name, icon) = (item.name.clone(), item.icon); let aria_label = format!("{name} : remettre dans la liste"); let item = StoredValue::new(item); view! { } }