Files
home_hub/frontend/src/pages/ShoppingPage.tsx
T
gilles a821b27fc6 fix(shopping): champ recherche article — autoComplete off, liste adaptative dvh
- autocomplete/autocorrect/autocapitalize off + spellCheck false sur le
  champ de recherche → supprime la barre de suggestions iOS et le popup autofill
- maxHeight liste: min(240px, 35dvh) → reste visible quand le clavier est ouvert

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 07:42:20 +02:00

636 lines
24 KiB
TypeScript

// frontend/src/pages/ShoppingPage.tsx
import { useState, useEffect, useCallback } from 'react'
import { matchesSearch } from '../utils/search'
import type { ShoppingListDetail, ShoppingList, Store, Product, ShoppingItem } from '../api/shopping'
import {
fetchLists, createList, fetchListDetail, deleteList,
addItem, updateItem, deleteItem, finishShopping, fetchStores, generateMagicList,
searchProducts, createProduct,
} from '../api/shopping'
import Modal from '../components/Modal'
import ItemRow from '../components/shopping/ItemRow'
import CatalogueModal from '../components/shopping/CatalogueModal'
import BoutiquesModal from '../components/shopping/BoutiquesModal'
import { useWakeLock } from '../hooks/useWakeLock'
const inputStyle: React.CSSProperties = {
width: '100%',
background: 'var(--bg-4)',
border: '1px solid var(--bg-5)',
borderRadius: 8,
padding: '10px 12px',
color: 'var(--ink-1)',
fontFamily: 'var(--font-ui)',
fontSize: 14,
boxSizing: 'border-box',
}
const noSelect: React.CSSProperties = { userSelect: 'none' }
export default function ShoppingPage() {
const [currentList, setCurrentList] = useState<ShoppingListDetail | null>(null)
const [allLists, setAllLists] = useState<ShoppingList[]>([])
const [stores, setStores] = useState<Store[]>([])
const [products, setProducts] = useState<Product[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [generating, setGenerating] = useState(false)
const [showAddItemModal, setShowAddItemModal] = useState(false)
const [showHistoryModal, setShowHistoryModal] = useState(false)
const [showCatalogueModal, setShowCatalogueModal] = useState(false)
const [showBoutiquesModal, setShowBoutiquesModal] = useState(false)
const [editingItem, setEditingItem] = useState<ShoppingItem | null>(null)
const [editQty, setEditQty] = useState('')
const [editUnit, setEditUnit] = useState('')
const [itemSearch, setItemSearch] = useState('')
const [selectedProduct, setSelectedProduct] = useState<Product | null>(null)
const [newItemQty, setNewItemQty] = useState('')
const [newItemUnit, setNewItemUnit] = useState('')
const [addToCatalogue, setAddToCatalogue] = useState(true)
useWakeLock(currentList !== null)
const loadData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const [listsData, storesData, productsData] = await Promise.all([fetchLists(), fetchStores(), searchProducts()])
setAllLists(listsData)
setStores(storesData)
setProducts([...productsData].sort((a, b) => a.name.localeCompare(b.name, 'fr')))
const current = listsData.find(l => l.status === 'draft' || l.status === 'active')
if (current) {
setCurrentList(await fetchListDetail(current.id))
} else {
setCurrentList(null)
}
} catch {
setError('Erreur lors du chargement')
} finally {
setLoading(false)
}
}, [])
useEffect(() => { void loadData() }, [loadData])
async function refreshCurrentList() {
if (!currentList) return
try {
setCurrentList(await fetchListDetail(currentList.id))
} catch {
setError('Erreur de rafraîchissement')
}
}
async function handleCreateManualList() {
try {
const detail = await createList({})
setCurrentList(detail)
void loadData()
} catch {
setError('Erreur lors de la création')
}
}
async function handleGenerateMagicList() {
setGenerating(true)
setError(null)
try {
const detail = await generateMagicList()
setCurrentList(detail)
void loadData()
} catch {
setError('Erreur lors de la génération')
} finally {
setGenerating(false)
}
}
function closeAddItemModal() {
setItemSearch('')
setSelectedProduct(null)
setNewItemQty('')
setNewItemUnit('')
setAddToCatalogue(true)
setShowAddItemModal(false)
}
function selectProduct(p: Product) {
setSelectedProduct(p)
setItemSearch(p.name)
setNewItemUnit(p.default_unit ?? '')
}
async function handleAddItem() {
if (!currentList) return
const customName = itemSearch.trim()
if (!selectedProduct && !customName) return
try {
let productId = selectedProduct?.id
// Article libre + case "Ajouter au catalogue" cochée → créer le produit d'abord
if (!selectedProduct && customName && addToCatalogue) {
const newProduct = await createProduct({
name: customName,
default_unit: newItemUnit || undefined,
})
productId = newProduct.id
// Met à jour la liste locale des produits pour les prochains ajouts
setProducts(prev => [...prev, newProduct].sort((a, b) => a.name.localeCompare(b.name, 'fr')))
}
await addItem(currentList.id, {
product_id: productId,
custom_name: !productId ? customName : undefined,
quantity: newItemQty || undefined,
unit: newItemUnit || undefined,
})
closeAddItemModal()
void refreshCurrentList()
} catch {
setError("Erreur lors de l'ajout")
}
}
async function handleCheckItem(itemId: string, checked: boolean) {
if (!currentList) return
try {
await updateItem(currentList.id, itemId, { is_checked: checked })
void refreshCurrentList()
} catch {
setError('Erreur lors du cochage')
}
}
async function handleDeleteItem(itemId: string) {
if (!currentList) return
try {
await deleteItem(currentList.id, itemId)
void refreshCurrentList()
} catch {
setError('Erreur lors de la suppression')
}
}
function openEditItem(item: ShoppingItem) {
setEditingItem(item)
setEditQty(item.quantity ?? '')
setEditUnit(item.unit ?? '')
}
async function handleEditItem() {
if (!currentList || !editingItem) return
try {
await updateItem(currentList.id, editingItem.id, {
quantity: editQty || undefined,
unit: editUnit || undefined,
})
setEditingItem(null)
void refreshCurrentList()
} catch {
setError('Erreur lors de la modification')
}
}
async function handleFinish() {
if (!currentList) return
try {
await finishShopping(currentList.id)
void loadData()
} catch {
setError('Erreur lors de la finalisation')
}
}
async function handleDeleteCurrentList() {
if (!currentList) return
if (!confirm('Supprimer la liste en cours ?')) return
try {
await deleteList(currentList.id)
void loadData()
} catch {
setError('Erreur lors de la suppression')
}
}
async function handleOpenHistoryList(list: ShoppingList) {
try {
const detail = await fetchListDetail(list.id)
setCurrentList(detail)
setShowHistoryModal(false)
} catch {
setError('Erreur lors du chargement')
}
}
// Tri : non cochés alpha, cochés alpha (en bas)
const sortedItems = [...(currentList?.items ?? [])].sort((a, b) => {
if (a.is_checked !== b.is_checked) return a.is_checked ? 1 : -1
return a.display_name.localeCompare(b.display_name, 'fr')
})
const uncheckedItems = sortedItems.filter(i => !i.is_checked)
const checkedItems = sortedItems.filter(i => i.is_checked)
const hasCurrentList = currentList !== null
const pastLists = allLists.filter(l => l.status === 'done')
const filteredProducts = products.filter(p => {
const term = itemSearch.trim()
return !term || matchesSearch(p.name, term) || matchesSearch(p.brand ?? '', term)
})
return (
<div style={{ display: 'flex', flexDirection: 'column', minHeight: '100%' }}>
{/* ── En-tête ── */}
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '12px 16px',
background: 'var(--bg-2)',
borderBottom: '1px solid var(--bg-4)',
position: 'sticky', top: 0, zIndex: 10,
}}>
<h1 style={{ color: 'var(--accent)', fontFamily: 'var(--font-mono)', margin: 0, flex: 1, fontSize: 18, ...noSelect }}>
{hasCurrentList ? (currentList.name ?? 'Courses') : 'Courses'}
</h1>
<button
onClick={() => setShowCatalogueModal(true)}
style={{
background: 'var(--bg-3)', border: '1px solid var(--bg-5)',
borderRadius: 8, color: 'var(--ink-2)', cursor: 'pointer',
padding: '6px 12px', fontFamily: 'var(--font-ui)', fontSize: 12, minHeight: 36,
...noSelect,
}}
>Articles</button>
<button
onClick={() => setShowBoutiquesModal(true)}
style={{
background: 'var(--bg-3)', border: '1px solid var(--bg-5)',
borderRadius: 8, color: 'var(--ink-2)', cursor: 'pointer',
padding: '6px 12px', fontFamily: 'var(--font-ui)', fontSize: 12, minHeight: 36,
...noSelect,
}}
>Boutiques</button>
</div>
{/* ── Erreur ── */}
{error && (
<div style={{ padding: '8px 16px' }}>
<p style={{ color: 'var(--err)', background: 'var(--bg-3)', borderRadius: 8, padding: '8px 12px', margin: 0, fontSize: 13, fontFamily: 'var(--font-ui)' }}>
{error}
</p>
</div>
)}
{loading && (
<p style={{ color: 'var(--ink-3)', textAlign: 'center', padding: 40, fontFamily: 'var(--font-ui)', ...noSelect }}>Chargement</p>
)}
{/* ── Vue : pas de liste en cours ── */}
{!loading && !hasCurrentList && (
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 24, padding: 32 }}>
<p style={{ color: 'var(--ink-3)', fontFamily: 'var(--font-ui)', fontSize: 15, margin: 0, textAlign: 'center', ...noSelect }}>
Aucune liste de courses en cours
</p>
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
<button
onClick={() => void handleCreateManualList()}
style={{
padding: '14px 24px', borderRadius: 12,
background: 'var(--ok)', color: '#1d2021', border: 'none',
cursor: 'pointer', fontFamily: 'var(--font-ui)', fontWeight: 700,
fontSize: 15, minHeight: 56, minWidth: 140,
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
...noSelect,
}}
>+ Nouvelle liste</button>
<button
onClick={() => void handleGenerateMagicList()}
disabled={generating}
style={{
padding: '14px 24px', borderRadius: 12,
background: generating ? 'var(--bg-4)' : 'var(--bg-3)',
color: generating ? 'var(--ink-4)' : 'var(--accent)',
border: '1px solid var(--bg-5)',
cursor: generating ? 'not-allowed' : 'pointer',
fontFamily: 'var(--font-ui)', fontWeight: 600,
fontSize: 15, minHeight: 56, minWidth: 140,
...noSelect,
}}
>
<i className="fa-solid fa-wand-magic-sparkles" style={{ marginRight: 8 }} />
{generating ? 'Génération…' : 'Liste magique'}
</button>
</div>
{pastLists.length > 0 && (
<button
onClick={() => setShowHistoryModal(true)}
style={{
background: 'transparent', border: 'none',
color: 'var(--ink-3)', cursor: 'pointer',
fontFamily: 'var(--font-ui)', fontSize: 13,
textDecoration: 'underline', padding: '4px 8px',
...noSelect,
}}
>Voir l'historique ({pastLists.length})</button>
)}
</div>
)}
{/* ── Vue : liste en cours ── */}
{!loading && hasCurrentList && (
<>
{/* Barre d'info + actions */}
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '8px 16px',
background: 'var(--bg-3)',
borderBottom: '1px solid var(--bg-4)',
}}>
<span style={{ flex: 1, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 12, ...noSelect }}>
{checkedItems.length}/{currentList.item_count} cochés
</span>
{pastLists.length > 0 && (
<button
onClick={() => setShowHistoryModal(true)}
style={{ background: 'transparent', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontSize: 12, padding: '4px 8px', ...noSelect }}
>Historique</button>
)}
<button
onClick={() => void handleDeleteCurrentList()}
style={{ background: 'transparent', border: 'none', color: 'var(--err)', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontSize: 12, padding: '4px 8px', ...noSelect }}
>Supprimer</button>
<button
onClick={() => void handleFinish()}
style={{
background: 'var(--ok)', color: '#1d2021', border: 'none',
borderRadius: 8, padding: '6px 14px',
fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 13,
cursor: 'pointer', minHeight: 36, ...noSelect,
}}
>Terminer </button>
</div>
{/* Articles non cochés */}
{uncheckedItems.length === 0 && checkedItems.length === 0 && (
<p style={{ color: 'var(--ink-3)', textAlign: 'center', margin: '40px 0', fontFamily: 'var(--font-ui)', fontSize: 14, ...noSelect }}>
Liste vide ajoutez des articles avec le bouton +
</p>
)}
<div style={{ flex: 1, overflowY: 'auto', paddingBottom: 80 }}>
{uncheckedItems.map(item => (
<ItemRow
key={item.id}
item={item}
onCheck={() => void handleCheckItem(item.id, true)}
onDelete={() => void handleDeleteItem(item.id)}
onEdit={() => openEditItem(item)}
storeMode
/>
))}
{checkedItems.length > 0 && (
<>
<div style={{
padding: '6px 16px',
color: 'var(--ink-4)', fontSize: 11,
fontFamily: 'var(--font-ui)', textTransform: 'uppercase',
letterSpacing: 1, background: 'var(--bg-2)',
borderTop: '1px solid var(--bg-4)',
borderBottom: '1px solid var(--bg-4)',
...noSelect,
}}>
Cochés ({checkedItems.length})
</div>
{checkedItems.map(item => (
<ItemRow
key={item.id}
item={item}
onCheck={() => void handleCheckItem(item.id, false)}
onDelete={() => void handleDeleteItem(item.id)}
onEdit={() => openEditItem(item)}
storeMode
/>
))}
</>
)}
</div>
{/* FAB + */}
<button
onClick={() => setShowAddItemModal(true)}
aria-label="Ajouter un article"
style={{
position: 'fixed', bottom: 72, right: 20,
width: 56, height: 56, borderRadius: '50%',
background: 'var(--accent)', color: '#1d2021', border: 'none',
fontSize: 28, cursor: 'pointer', boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>+</button>
</>
)}
{/* ── Modals ── */}
{/* Modal édition quantité/unité */}
{editingItem && (
<Modal title={`Modifier — ${editingItem.display_name}`} onClose={() => setEditingItem(null)} width={320}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
<input
style={inputStyle}
placeholder="Quantité"
inputMode="decimal"
value={editQty}
onChange={e => setEditQty(e.target.value)}
autoFocus
onKeyDown={e => e.key === 'Enter' && void handleEditItem()}
/>
<input
style={inputStyle}
placeholder="Unité (kg, L…)"
value={editUnit}
onChange={e => setEditUnit(e.target.value)}
onKeyDown={e => e.key === 'Enter' && void handleEditItem()}
/>
</div>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<button
onClick={() => setEditingItem(null)}
style={{ padding: '10px 16px', borderRadius: 8, border: '1px solid var(--bg-5)', background: 'transparent', color: 'var(--ink-2)', cursor: 'pointer', fontFamily: 'var(--font-ui)', minHeight: 48 }}
>Annuler</button>
<button
onClick={() => void handleEditItem()}
style={{ padding: '10px 20px', borderRadius: 8, border: 'none', background: 'var(--accent)', color: '#1d2021', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontWeight: 600, minHeight: 48 }}
>Enregistrer</button>
</div>
</div>
</Modal>
)}
{showAddItemModal && (
<Modal title="Ajouter un article" onClose={closeAddItemModal} width={420}>
{/* Barre de recherche / nom personnalisé */}
<input
style={{
...inputStyle,
borderColor: selectedProduct ? 'var(--ok)' : 'var(--bg-5)',
borderWidth: selectedProduct ? 2 : 1,
}}
placeholder="Rechercher ou saisir un article…"
value={itemSearch}
onChange={e => { setItemSearch(e.target.value); setSelectedProduct(null) }}
autoFocus
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
onKeyDown={e => e.key === 'Enter' && void handleAddItem()}
/>
{/* Liste scrollable alphabétique du catalogue */}
<div style={{
maxHeight: 'min(240px, 35dvh)', overflowY: 'auto',
border: '1px solid var(--bg-5)', borderRadius: 8,
background: 'var(--bg-3)',
}}>
{filteredProducts.length === 0 && (
<p style={{
color: 'var(--ink-4)', fontFamily: 'var(--font-ui)', fontSize: 13,
textAlign: 'center', padding: '12px 16px', margin: 0, ...noSelect,
}}>
{itemSearch.trim() ? `"${itemSearch}" — article libre` : 'Catalogue vide'}
</p>
)}
{filteredProducts.map((p, idx) => {
const isSelected = selectedProduct?.id === p.id
return (
<div
key={p.id}
onClick={() => isSelected ? (setSelectedProduct(null), setItemSearch('')) : selectProduct(p)}
style={{
padding: '10px 14px',
cursor: 'pointer',
background: isSelected ? 'var(--ok)' : 'transparent',
color: isSelected ? '#1d2021' : 'var(--ink-1)',
borderBottom: idx < filteredProducts.length - 1 ? '1px solid var(--bg-4)' : 'none',
display: 'flex', alignItems: 'center', gap: 10,
userSelect: 'none',
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontFamily: 'var(--font-ui)', fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{p.name}
</div>
{(p.default_unit || p.brand) && (
<div style={{ fontSize: 11, color: isSelected ? '#1d2021' : 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 1 }}>
{[p.brand, p.default_unit].filter(Boolean).join(' · ')}
</div>
)}
</div>
{isSelected && <span style={{ fontSize: 16, fontWeight: 700 }}></span>}
</div>
)
})}
</div>
{/* Case "Ajouter au catalogue" — uniquement si article libre sans correspondance */}
{!selectedProduct && itemSearch.trim() && filteredProducts.length === 0 && (
<label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', userSelect: 'none', padding: '6px 2px' }}>
<input
type="checkbox"
checked={addToCatalogue}
onChange={e => setAddToCatalogue(e.target.checked)}
style={{ width: 18, height: 18, accentColor: 'var(--ok)', cursor: 'pointer', flexShrink: 0 }}
/>
<span style={{ fontFamily: 'var(--font-ui)', fontSize: 13, color: 'var(--ink-2)' }}>
Ajouter <strong style={{ color: 'var(--ink-1)' }}>{itemSearch.trim()}</strong> au catalogue
</span>
</label>
)}
{/* Quantité + Unité */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
<input
style={inputStyle} placeholder="Quantité"
inputMode="decimal"
value={newItemQty}
onChange={e => setNewItemQty(e.target.value)}
/>
<input
style={inputStyle} placeholder="Unité (kg, L…)"
value={newItemUnit}
onChange={e => setNewItemUnit(e.target.value)}
/>
</div>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<button
onClick={closeAddItemModal}
style={{ padding: '10px 16px', borderRadius: 8, border: '1px solid var(--bg-5)', background: 'transparent', color: 'var(--ink-2)', cursor: 'pointer', fontFamily: 'var(--font-ui)', minHeight: 48 }}
>Annuler</button>
<button
onClick={() => void handleAddItem()}
disabled={!selectedProduct && !itemSearch.trim()}
style={{
padding: '10px 20px', borderRadius: 8, border: 'none',
background: (!selectedProduct && !itemSearch.trim()) ? 'var(--bg-5)' : 'var(--accent)',
color: '#1d2021', cursor: 'pointer', fontFamily: 'var(--font-ui)', fontWeight: 600, minHeight: 48,
}}
>Ajouter</button>
</div>
</Modal>
)}
{showHistoryModal && (
<Modal title="Historique des courses" onClose={() => setShowHistoryModal(false)}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{allLists.filter(l => l.status === 'done').map(list => (
<div
key={list.id}
onClick={() => void handleOpenHistoryList(list)}
className="glass interactive"
style={{ borderRadius: 8, padding: '10px 14px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10 }}
>
<div style={{ flex: 1 }}>
<div style={{ color: 'var(--ink-1)', fontFamily: 'var(--font-ui)', fontSize: 14, ...noSelect }}>
{list.name ?? 'Liste terminée'}
</div>
<div style={{ color: 'var(--ink-3)', fontSize: 11, fontFamily: 'var(--font-mono)', ...noSelect }}>
{new Date(list.created_at).toLocaleDateString('fr-FR')} · {list.checked_count}/{list.item_count} articles
</div>
</div>
<span style={{ color: 'var(--ink-3)', fontSize: 16 }}></span>
</div>
))}
{allLists.filter(l => l.status === 'done').length === 0 && (
<p style={{ color: 'var(--ink-3)', textAlign: 'center', padding: 16, fontFamily: 'var(--font-ui)', fontSize: 13, ...noSelect }}>
Aucune liste terminée
</p>
)}
</div>
</Modal>
)}
{showCatalogueModal && (
<CatalogueModal stores={stores} onClose={() => setShowCatalogueModal(false)} />
)}
{showBoutiquesModal && (
<BoutiquesModal
stores={stores}
onClose={() => setShowBoutiquesModal(false)}
onStoresChanged={() => void loadData()}
/>
)}
</div>
)
}