feat: pantry drag-to-recategorize, always-show categories, auto-categorize; fix category label + merge quantity mismatch (v0.84.0)

Pantry items can now be dragged between category sections (dnd-kit, cross-category drop only — no sortOrder column to persist within-category reorder). All 9 categories always render as sections, even empty ones, instead of only ones with items. Added an "Auto-categorize" action mirroring the shopping list's guessAisle heuristic.

Fixed: the edit dialog's category dropdown displayed the raw stored slug/"__other__" instead of its translated label (SelectValue needs a value->label render function, same pattern shopping-list-view.tsx already used elsewhere). Fixed: merge-duplicates now merges by ingredient identity alone, not identity+unit — two rows merge even with mismatched, missing, or different-unit quantities, only summing when safe to do so.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-24 15:51:05 +02:00
parent 93936eae10
commit ebe3216c04
11 changed files with 218 additions and 69 deletions
+160 -50
View File
@@ -3,12 +3,13 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { Plus, Trash2, AlertTriangle, Package, Pencil, ChevronDown, Merge } from "lucide-react";
import { Plus, Trash2, AlertTriangle, Package, Pencil, ChevronDown, Merge, Sparkles, Loader2, GripVertical } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { formatQuantity, hasQuantity } from "@/lib/fractions";
import { guessAisle, GROCERY_CATEGORIES, type GroceryCategory } from "@/lib/grocery-categories";
import { PantryScanDialog } from "@/components/pantry/pantry-scan-dialog";
import { PantryItemDialog, type PantryItem } from "@/components/pantry/pantry-item-dialog";
import { EmptyState } from "@/components/shared/empty-state";
@@ -22,14 +23,46 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
DndContext,
type DragEndEvent,
PointerSensor,
useSensor,
useSensors,
useDraggable,
useDroppable,
} from "@dnd-kit/core";
const OTHER_KEY = "__other__";
const ALL_CATEGORY_KEYS: string[] = [...GROCERY_CATEGORIES, OTHER_KEY];
function daysUntilExpiry(dateStr: string): number {
const diff = new Date(dateStr).getTime() - Date.now();
return Math.ceil(diff / (1000 * 60 * 60 * 24));
}
function DroppableCategory({ groupKey, children }: { groupKey: string; children: React.ReactNode }) {
const { setNodeRef, isOver } = useDroppable({ id: groupKey });
return (
<div ref={setNodeRef} className={cn(isOver && "bg-primary/5 outline-2 outline-dashed outline-primary/40 -outline-offset-2")}>
{children}
</div>
);
}
function DraggableItemRow({ item, children }: { item: PantryItem; children: React.ReactNode }) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: item.id });
const style = transform ? { transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`, zIndex: 10 } : undefined;
return (
<div ref={setNodeRef} style={style} className={cn("flex items-center gap-2 px-4 py-3 hover:bg-muted/30 bg-background", isDragging && "opacity-50")}>
<button {...attributes} {...listeners} className="text-muted-foreground/50 hover:text-muted-foreground cursor-grab touch-none shrink-0" aria-hidden>
<GripVertical className="h-4 w-4" />
</button>
{children}
</div>
);
}
export function PantryManager({ initialItems }: { initialItems: PantryItem[] }) {
const t = useTranslations("pantry");
const tShopping = useTranslations("shoppingLists");
@@ -43,8 +76,17 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
const [adding, setAdding] = useState(false);
const [confirmId, setConfirmId] = useState<string | null>(null);
const [editingItem, setEditingItem] = useState<PantryItem | null>(null);
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const [merging, setMerging] = useState(false);
const [autoCategorizing, setAutoCategorizing] = useState(false);
const [collapsed, setCollapsed] = useState<Set<string>>(() => {
const initialByKey = new Map<string, number>();
for (const item of initialItems) {
const key = item.aisle ?? OTHER_KEY;
initialByKey.set(key, (initialByKey.get(key) ?? 0) + 1);
}
return new Set(ALL_CATEGORY_KEYS.filter((key) => !initialByKey.get(key)));
});
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));
async function mergeDuplicates() {
setMerging(true);
@@ -60,6 +102,39 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
}
}
async function autoCategorize() {
const targets = items.filter((i) => !i.aisle);
const updates = targets
.map((i) => ({ id: i.id, aisle: guessAisle(i.rawName) }))
.filter((u): u is { id: string; aisle: GroceryCategory } => u.aisle !== null);
if (updates.length === 0) {
toast.error(tShopping("autoCategorizeNoneFound"));
return;
}
setAutoCategorizing(true);
try {
await Promise.all(updates.map((u) =>
fetch(`/api/v1/pantry/${u.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ aisle: u.aisle }),
})
));
const byId = new Map(updates.map((u) => [u.id, u.aisle]));
setItems((prev) => prev.map((i) => (byId.has(i.id) ? { ...i, aisle: byId.get(i.id)! } : i)));
setCollapsed((prev) => {
const next = new Set(prev);
for (const u of updates) next.delete(u.aisle);
return next;
});
toast.success(tShopping("autoCategorizeSuccess", { count: updates.length }));
} finally {
setAutoCategorizing(false);
}
}
async function add() {
if (!name.trim()) return;
setAdding(true);
@@ -80,6 +155,7 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
...prev,
{ id, rawName: name.trim(), quantity: quantity || null, unit: unit || null, notes: null, aisle: null, expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null },
]);
setCollapsed((prev) => { const next = new Set(prev); next.delete(OTHER_KEY); return next; });
setName(""); setQuantity(""); setUnit(""); setExpiresAt("");
} finally {
setAdding(false);
@@ -92,6 +168,29 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
else toast.error(t("removeFailed"));
}
async function moveToCategory(id: string, newKey: string) {
const newAisle = newKey === OTHER_KEY ? null : newKey;
setItems((prev) => prev.map((i) => (i.id === id ? { ...i, aisle: newAisle } : i)));
const res = await fetch(`/api/v1/pantry/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ aisle: newAisle }),
});
if (!res.ok) toast.error(t("editFailed"));
}
function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
if (!over) return;
const item = items.find((i) => i.id === active.id);
if (!item) return;
const currentKey = item.aisle ?? OTHER_KEY;
const destKey = String(over.id);
if (currentKey === destKey) return;
setCollapsed((prev) => { const next = new Set(prev); next.delete(destKey); return next; });
void moveToCategory(item.id, destKey);
}
function toggleCollapsed(key: string) {
setCollapsed((prev) => {
const next = new Set(prev);
@@ -110,11 +209,11 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
};
const grouped = new Map<string, PantryItem[]>();
for (const key of ALL_CATEGORY_KEYS) grouped.set(key, []);
for (const item of items) {
const key = item.aisle ?? OTHER_KEY;
const group = grouped.get(key) ?? [];
group.push(item);
grouped.set(key, group);
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key)!.push(item);
}
for (const group of grouped.values()) group.sort(sortWithinGroup);
@@ -123,7 +222,7 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
}
const sortedGroupKeys = [...grouped.keys()].sort((a, b) => categoryLabel(a).localeCompare(categoryLabel(b)));
const showGroupHeaders = grouped.size > 1;
const uncategorizedCount = items.filter((i) => !i.aisle).length;
return (
<div className="space-y-6 max-w-2xl">
@@ -137,6 +236,11 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
<Plus className="h-4 w-4" /> {t("add")}
</Button>
<PantryScanDialog onAdded={() => router.refresh()} />
{uncategorizedCount > 0 && (
<Button variant="ghost" size="sm" onClick={() => { void autoCategorize(); }} disabled={autoCategorizing}>
{autoCategorizing ? <Loader2 className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />} {tShopping("autoCategorize")}
</Button>
)}
<Button variant="outline" size="sm" onClick={() => { void mergeDuplicates(); }} disabled={merging}>
<Merge className="h-4 w-4" /> {t("mergeDuplicates")}
</Button>
@@ -146,13 +250,13 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
{items.length === 0 ? (
<EmptyState icon={Package} title={t("empty")} description={t("emptyDescription")} compact />
) : (
<div className="space-y-4">
{sortedGroupKeys.map((key) => {
const groupItems = grouped.get(key)!;
const isCollapsed = collapsed.has(key);
return (
<div key={key} className="rounded-xl border overflow-hidden">
{showGroupHeaders && (
<DndContext sensors={sensors} onDragEnd={handleDragEnd}>
<div className="space-y-4">
{sortedGroupKeys.map((key) => {
const groupItems = grouped.get(key)!;
const isCollapsed = collapsed.has(key);
return (
<div key={key} className="rounded-xl border overflow-hidden">
<button
type="button"
onClick={() => toggleCollapsed(key)}
@@ -164,44 +268,50 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
<ChevronDown className={cn("h-4 w-4 text-muted-foreground transition-transform", isCollapsed && "-rotate-90")} />
</span>
</button>
)}
{!isCollapsed && (
<div className="divide-y">
{groupItems.map((item) => {
const days = item.expiresAt ? daysUntilExpiry(item.expiresAt) : null;
const expiring = days !== null && days <= 3;
const expired = days !== null && days < 0;
return (
<div key={item.id} className="flex items-center gap-3 px-4 py-3 hover:bg-muted/30">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm">{item.rawName}</span>
{hasQuantity(item.quantity) && (
<span className="text-xs text-muted-foreground">{formatQuantity(parseFloat(item.quantity!))}{item.unit ? ` ${item.unit}` : ""}</span>
)}
{expired && <span className="text-xs text-destructive flex items-center gap-1"><AlertTriangle className="h-3 w-3" />{t("expired")}</span>}
{expiring && !expired && <span className="text-xs text-orange-500 flex items-center gap-1"><AlertTriangle className="h-3 w-3" />{t("expiresInDays", { days })}</span>}
</div>
{item.expiresAt && !expired && !expiring && (
<p className="text-xs text-muted-foreground">{t("expiresOn", { date: new Date(item.expiresAt).toLocaleDateString() })}</p>
)}
{item.notes && <p className="text-xs text-muted-foreground italic mt-0.5">{item.notes}</p>}
</div>
<button onClick={() => setEditingItem(item)} aria-label={t("editItem")} className="text-muted-foreground hover:text-foreground transition-colors">
<Pencil className="h-4 w-4" />
</button>
<button onClick={() => setConfirmId(item.id)} className="text-muted-foreground hover:text-destructive transition-colors">
<Trash2 className="h-4 w-4" />
</button>
{!isCollapsed && (
<DroppableCategory groupKey={key}>
{groupItems.length === 0 ? (
<p className="px-4 py-3 text-xs text-muted-foreground italic">{t("categoryEmptyDropHint")}</p>
) : (
<div className="divide-y">
{groupItems.map((item) => {
const days = item.expiresAt ? daysUntilExpiry(item.expiresAt) : null;
const expiring = days !== null && days <= 3;
const expired = days !== null && days < 0;
return (
<DraggableItemRow key={item.id} item={item}>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm">{item.rawName}</span>
{hasQuantity(item.quantity) && (
<span className="text-xs text-muted-foreground">{formatQuantity(parseFloat(item.quantity!))}{item.unit ? ` ${item.unit}` : ""}</span>
)}
{expired && <span className="text-xs text-destructive flex items-center gap-1"><AlertTriangle className="h-3 w-3" />{t("expired")}</span>}
{expiring && !expired && <span className="text-xs text-orange-500 flex items-center gap-1"><AlertTriangle className="h-3 w-3" />{t("expiresInDays", { days })}</span>}
</div>
{item.expiresAt && !expired && !expiring && (
<p className="text-xs text-muted-foreground">{t("expiresOn", { date: new Date(item.expiresAt).toLocaleDateString() })}</p>
)}
{item.notes && <p className="text-xs text-muted-foreground italic mt-0.5">{item.notes}</p>}
</div>
<button onClick={() => setEditingItem(item)} aria-label={t("editItem")} className="text-muted-foreground hover:text-foreground transition-colors shrink-0">
<Pencil className="h-4 w-4" />
</button>
<button onClick={() => setConfirmId(item.id)} className="text-muted-foreground hover:text-destructive transition-colors shrink-0">
<Trash2 className="h-4 w-4" />
</button>
</DraggableItemRow>
);
})}
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
)}
</DroppableCategory>
)}
</div>
);
})}
</div>
</DndContext>
)}
<AlertDialog open={confirmId !== null} onOpenChange={(open) => !open && setConfirmId(null)}>