feat: collections overhaul — reorder, search, edit/delete, tags (v0.53.0)

Seven related improvements to collections:

- Drag-and-drop reorder (dnd-kit, same pattern as the shopping list) — new
  collection_recipes.position column (migration 0049, backfilled from
  existing added_at order so nothing jumps around on upgrade).
- Search collections by name/description (server-side, list page) and
  search recipes within a collection (client-side filter, already loaded).
- Edit collection: name/description/tags/private notes via a new dialog;
  new collections.notes + collections.tags columns.
- Delete collection with a choice to also delete its recipes — only ones
  the deleting user actually owns, never recipes shared in by others.
- Collection detail (both owner and public view) now renders the same
  RecipeGridCard used on /recipes, instead of the older, plainer RecipeCard.
- Collection list cards redesigned — photo-collage preview (first 4 recipe
  covers/placeholders), tag badges, cleaner layout.
- Fixed the recipe count shown on a collection card: the query capped the
  `recipes` relation at 1 for thumbnail purposes and then read `.length`
  off that same capped array, so it never showed more than 1. Now a
  proper grouped count query, separate from the thumbnail fetch.

New/changed endpoints documented in OpenAPI: PATCH /collections/{id}/reorder,
DELETE /collections/{id}?deleteRecipes, PUT /collections/{id}'s new
notes/tags fields.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-19 18:44:08 +02:00
parent 5403a06348
commit e8c687e53a
19 changed files with 6300 additions and 82 deletions
@@ -1,11 +1,28 @@
"use client";
import { useState, useCallback } from "react";
import { useState, useCallback, useMemo } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { ListChecks, X, FolderInput, FolderMinus, Check } from "lucide-react";
import { ListChecks, X, FolderInput, FolderMinus, Check, GripVertical, Search } from "lucide-react";
import {
DndContext,
type DragEndEvent,
PointerSensor,
useSensor,
useSensors,
closestCenter,
} from "@dnd-kit/core";
import {
SortableContext,
useSortable,
verticalListSortingStrategy,
arrayMove,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button, buttonVariants } from "@/components/ui/button";
import { RecipeCard } from "@/components/recipe/recipe-card";
import { Input } from "@/components/ui/input";
import { RecipeGridCard, type GridCardRecipe } from "@/components/recipe/recipe-grid-card";
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
import {
AlertDialog,
@@ -19,21 +36,69 @@ import {
} from "@/components/ui/alert-dialog";
import { cn } from "@/lib/utils";
type Recipe = {
id: string;
title: string;
description: string | null;
baseServings: number;
prepMins: number | null;
cookMins: number | null;
difficulty: "easy" | "medium" | "hard" | null;
visibility: "private" | "unlisted" | "public" | "followers";
updatedAt: Date;
photos?: Array<{ storageKey: string; isCover: boolean }>;
sourceUrl?: string | null;
};
function SortableRecipeCard({
recipe,
selectMode,
selected,
onToggle,
dragDisabled,
}: {
recipe: GridCardRecipe;
selectMode: boolean;
selected: boolean;
onToggle: () => void;
dragDisabled: boolean;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: recipe.id,
disabled: dragDisabled,
});
export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }: { collectionId: string; recipes: Recipe[] }) {
const style = { transform: CSS.Transform.toString(transform), transition };
return (
<div
ref={setNodeRef}
style={style}
className={cn("relative", selectMode && "cursor-pointer", isDragging && "z-10 opacity-70")}
onClick={selectMode ? onToggle : undefined}
>
{selectMode && (
<div
className={cn(
"absolute top-2 left-2 z-10 h-5 w-5 rounded-full border-2 flex items-center justify-center shadow-sm",
selected ? "bg-primary border-primary" : "bg-black/30 border-white/70"
)}
>
{selected && <Check className="h-3 w-3 text-primary-foreground stroke-[3]" />}
</div>
)}
{!selectMode && !dragDisabled && (
<button
type="button"
{...attributes}
{...listeners}
className="absolute top-2 right-2 z-10 h-6 w-6 rounded-md bg-background/90 border shadow-sm flex items-center justify-center text-muted-foreground cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 hover:text-foreground transition-opacity"
onClick={(e) => e.preventDefault()}
aria-label="Drag to reorder"
>
<GripVertical className="h-3.5 w-3.5" />
</button>
)}
<div className={cn("group", selectMode && "pointer-events-none", selectMode && selected && "rounded-xl ring-2 ring-primary")}>
{selectMode ? (
<RecipeGridCard recipe={recipe} />
) : (
<Link href={`/recipes/${recipe.id}`}>
<RecipeGridCard recipe={recipe} />
</Link>
)}
</div>
</div>
);
}
export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }: { collectionId: string; recipes: GridCardRecipe[] }) {
const t = useTranslations("collections");
const tCommon = useTranslations("common");
const [recipes, setRecipes] = useState(initialRecipes);
@@ -42,6 +107,9 @@ export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }:
const [moveOpen, setMoveOpen] = useState(false);
const [removeConfirmOpen, setRemoveConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [search, setSearch] = useState("");
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));
const toggleSelect = useCallback((id: string) => {
setSelected((prev) => {
@@ -75,16 +143,57 @@ export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }:
}
}
async function persistOrder(ordered: GridCardRecipe[]) {
try {
const res = await fetch(`/api/v1/collections/${collectionId}/reorder`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ recipeIds: ordered.map((r) => r.id) }),
});
if (!res.ok) throw new Error();
} catch {
toast.error(t("reorderFailed"));
}
}
function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
if (!over || active.id === over.id) return;
const oldIndex = recipes.findIndex((r) => r.id === active.id);
const newIndex = recipes.findIndex((r) => r.id === over.id);
if (oldIndex === -1 || newIndex === -1) return;
const reordered = arrayMove(recipes, oldIndex, newIndex);
setRecipes(reordered);
void persistOrder(reordered);
}
const filtered = useMemo(() => {
const q = search.trim().toLowerCase();
if (!q) return recipes;
return recipes.filter((r) => r.title.toLowerCase().includes(q));
}, [recipes, search]);
const searchActive = search.trim().length > 0;
if (recipes.length === 0) return null;
return (
<div className="space-y-4">
<div className="flex items-center justify-end">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t("searchRecipesPlaceholder")}
className="pl-9"
/>
</div>
<Button
variant="ghost"
size="sm"
onClick={selectMode ? exitSelect : () => setSelectMode(true)}
className={cn("gap-1.5", selectMode && "text-muted-foreground")}
className={cn("gap-1.5 shrink-0", selectMode && "text-muted-foreground")}
>
{selectMode ? (
<><X className="h-4 w-4" />{tCommon("cancel")}</>
@@ -94,25 +203,26 @@ export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }:
</Button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{recipes.map((recipe) => (
<div key={recipe.id} className={cn("relative", selectMode && "cursor-pointer")} onClick={selectMode ? () => toggleSelect(recipe.id) : undefined}>
{selectMode && (
<div
className={cn(
"absolute top-2 left-2 z-10 h-5 w-5 rounded-full border-2 flex items-center justify-center shadow-sm",
selected.has(recipe.id) ? "bg-primary border-primary" : "bg-black/30 border-white/70"
)}
>
{selected.has(recipe.id) && <Check className="h-3 w-3 text-primary-foreground stroke-[3]" />}
</div>
)}
<div className={cn(selectMode && "pointer-events-none", selectMode && selected.has(recipe.id) && "rounded-xl ring-2 ring-primary")}>
<RecipeCard recipe={recipe} />
{filtered.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">{t("noRecipeSearchResults")}</p>
) : (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={filtered.map((r) => r.id)} strategy={verticalListSortingStrategy}>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{filtered.map((recipe) => (
<SortableRecipeCard
key={recipe.id}
recipe={recipe}
selectMode={selectMode}
selected={selected.has(recipe.id)}
onToggle={() => toggleSelect(recipe.id)}
dragDisabled={selectMode || searchActive}
/>
))}
</div>
</div>
))}
</div>
</SortableContext>
</DndContext>
)}
{selectMode && selected.size > 0 && (
<div className="fixed bottom-4 sm:bottom-8 left-1/2 -translate-x-1/2 z-50 w-[calc(100vw-2rem)] sm:w-auto sm:max-w-none animate-in slide-in-from-bottom-4 duration-200">
@@ -1,27 +1,86 @@
"use client";
import { useState, useTransition } from "react";
import { useTranslations } from "next-intl";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { FolderOpen, Flame } from "lucide-react";
import Image from "next/image";
import { FolderOpen, Flame, Search } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { buttonVariants } from "@/components/ui/button";
import { NewCollectionButton } from "@/components/social/new-collection-button";
import { EmptyState } from "@/components/shared/empty-state";
import { RecipeCoverPlaceholder } from "@/components/recipe/recipe-cover-placeholder";
import { cn } from "@/lib/utils";
type Thumbnail = {
recipeId: string;
recipeType?: "dish" | "drink";
coverIcon: string | null;
coverColor: string | null;
photoUrl: string | null;
};
type Collection = {
id: string;
name: string;
description: string | null;
tags: string[];
isPublic: boolean;
recipeCount: number;
thumbnails: Thumbnail[];
};
type Props = {
collections: Collection[];
query: string;
};
export function CollectionsPageContent({ collections }: Props) {
function CollectionThumbCollage({ thumbnails }: { thumbnails: Thumbnail[] }) {
if (thumbnails.length === 0) {
return (
<div className="w-full h-full flex items-center justify-center bg-muted text-muted-foreground">
<FolderOpen className="h-8 w-8" strokeWidth={1.5} />
</div>
);
}
return (
<div className="grid grid-cols-2 grid-rows-2 gap-0.5 w-full h-full">
{Array.from({ length: 4 }).map((_, i) => {
const thumb = thumbnails[i];
return (
<div key={i} className="relative overflow-hidden bg-muted">
{thumb ? (
thumb.photoUrl ? (
<Image src={thumb.photoUrl} unoptimized alt="" fill className="object-cover" />
) : (
<RecipeCoverPlaceholder
recipe={{ id: thumb.recipeId, recipeType: thumb.recipeType, coverIcon: thumb.coverIcon, coverColor: thumb.coverColor }}
iconClassName="h-5 w-5"
/>
)
) : null}
</div>
);
})}
</div>
);
}
export function CollectionsPageContent({ collections, query }: Props) {
const t = useTranslations("collections");
const router = useRouter();
const pathname = usePathname();
const [search, setSearch] = useState(query);
const [, startTransition] = useTransition();
function handleSearch(value: string) {
setSearch(value);
const params = new URLSearchParams();
if (value.trim()) params.set("q", value.trim());
startTransition(() => router.push(`${pathname}?${params.toString()}`));
}
return (
<div className="space-y-6">
@@ -39,25 +98,51 @@ export function CollectionsPageContent({ collections }: Props) {
</div>
</div>
<div className="relative max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
value={search}
onChange={(e) => handleSearch(e.target.value)}
placeholder={t("searchPlaceholder")}
className="pl-9"
/>
</div>
{collections.length === 0 ? (
<EmptyState
icon={FolderOpen}
title={t("empty")}
description={t("emptyDescription")}
actionSlot={<NewCollectionButton />}
title={query ? t("noSearchResults") : t("empty")}
description={query ? undefined : t("emptyDescription")}
actionSlot={!query ? <NewCollectionButton /> : undefined}
/>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{collections.map((col) => (
<Link key={col.id} href={`/collections/${col.id}`} className="group rounded-xl border p-4 hover:shadow-sm transition-shadow space-y-2">
<div className="flex items-start justify-between gap-2">
<h2 className="font-semibold group-hover:text-primary transition-colors line-clamp-1">{col.name}</h2>
{col.isPublic && <Badge variant="secondary" className="text-xs shrink-0">{t("public")}</Badge>}
<Link
key={col.id}
href={`/collections/${col.id}`}
className="group rounded-xl border overflow-hidden hover:shadow-md hover:border-muted-foreground/30 transition-all duration-200"
>
<div className="aspect-[2/1]">
<CollectionThumbCollage thumbnails={col.thumbnails} />
</div>
<div className="p-4 space-y-2">
<div className="flex items-start justify-between gap-2">
<h2 className="font-semibold group-hover:text-primary transition-colors line-clamp-1">{col.name}</h2>
{col.isPublic && <Badge variant="secondary" className="text-xs shrink-0">{t("public")}</Badge>}
</div>
{col.description && <p className="text-sm text-muted-foreground line-clamp-2">{col.description}</p>}
{col.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{col.tags.slice(0, 4).map((tag) => (
<Badge key={tag} variant="outline" className="text-xs">{tag}</Badge>
))}
</div>
)}
<p className="text-xs text-muted-foreground">
{col.recipeCount !== 1 ? t("recipeCountPlural", { count: col.recipeCount }) : t("recipeCount", { count: col.recipeCount })}
</p>
</div>
{col.description && <p className="text-sm text-muted-foreground line-clamp-2">{col.description}</p>}
<p className="text-xs text-muted-foreground">
{col.recipeCount !== 1 ? t("recipeCountPlural", { count: col.recipeCount }) : t("recipeCount", { count: col.recipeCount })}
</p>
</Link>
))}
</div>
@@ -0,0 +1,80 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
export function DeleteCollectionDialog({ collectionId }: { collectionId: string }) {
const t = useTranslations("collections");
const tCommon = useTranslations("common");
const router = useRouter();
const [open, setOpen] = useState(false);
const [deleteRecipes, setDeleteRecipes] = useState(false);
const [deleting, setDeleting] = useState(false);
async function handleDelete() {
setDeleting(true);
try {
const res = await fetch(`/api/v1/collections/${collectionId}?deleteRecipes=${deleteRecipes}`, { method: "DELETE" });
if (!res.ok) throw new Error();
toast.success(t("deleteSuccess"));
router.push("/collections");
router.refresh();
} catch {
toast.error(t("deleteFailed"));
setDeleting(false);
}
}
return (
<>
<Button variant="outline" size="sm" className="gap-1.5 text-destructive hover:text-destructive" onClick={() => setOpen(true)}>
<Trash2 className="h-4 w-4" />
{tCommon("delete")}
</Button>
<AlertDialog open={open} onOpenChange={setOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle>
<AlertDialogDescription>{t("deleteConfirmDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input
type="checkbox"
checked={deleteRecipes}
onChange={(e) => setDeleteRecipes(e.target.checked)}
className="rounded mt-0.5"
/>
<span>{t("deleteRecipesToo")}</span>
</label>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>{tCommon("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => { e.preventDefault(); void handleDelete(); }}
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? t("deleting") : tCommon("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
@@ -0,0 +1,163 @@
"use client";
import { useRef, useState, type KeyboardEvent } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Pencil, Tag, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
export function EditCollectionDialog({
collectionId,
initialName,
initialDescription,
initialNotes,
initialTags,
initialIsPublic,
}: {
collectionId: string;
initialName: string;
initialDescription: string | null;
initialNotes: string | null;
initialTags: string[];
initialIsPublic: boolean;
}) {
const t = useTranslations("collections");
const tRecipeForm = useTranslations("recipeForm");
const tCommon = useTranslations("common");
const router = useRouter();
const [open, setOpen] = useState(false);
const [name, setName] = useState(initialName);
const [description, setDescription] = useState(initialDescription ?? "");
const [notes, setNotes] = useState(initialNotes ?? "");
const [tags, setTags] = useState<string[]>(initialTags);
const [tagInput, setTagInput] = useState("");
const [isPublic, setIsPublic] = useState(initialIsPublic);
const [saving, setSaving] = useState(false);
const tagInputRef = useRef<HTMLInputElement>(null);
function addTag(raw: string) {
const tag = raw.trim().toLowerCase().slice(0, 50);
if (!tag || tags.includes(tag) || tags.length >= 20) return;
setTags((prev) => [...prev, tag]);
setTagInput("");
}
function removeTag(tag: string) {
setTags((prev) => prev.filter((tg) => tg !== tag));
}
function handleTagKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter") {
e.preventDefault();
addTag(tagInput);
} else if (e.key === "Backspace" && !tagInput && tags.length > 0) {
setTags((prev) => prev.slice(0, -1));
}
}
async function handleSave() {
if (!name.trim()) return;
setSaving(true);
try {
const res = await fetch(`/api/v1/collections/${collectionId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: name.trim(),
description: description.trim() || null,
notes: notes.trim() || null,
tags,
isPublic,
}),
});
if (!res.ok) throw new Error();
toast.success(t("editSuccess"));
setOpen(false);
router.refresh();
} catch {
toast.error(t("editFailed"));
} finally {
setSaving(false);
}
}
return (
<>
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setOpen(true)}>
<Pencil className="h-4 w-4" />
{tCommon("edit")}
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{t("editTitle")}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="edit-col-name">{t("nameLabel")}</Label>
<Input id="edit-col-name" value={name} onChange={(e) => setName(e.target.value)} placeholder={t("namePlaceholder")} maxLength={100} />
</div>
<div className="space-y-2">
<Label htmlFor="edit-col-desc">{t("descriptionLabel")}</Label>
<Textarea id="edit-col-desc" value={description} onChange={(e) => setDescription(e.target.value)} rows={2} placeholder={t("descriptionPlaceholder")} maxLength={500} />
</div>
<div className="space-y-2">
<Label htmlFor="edit-col-notes">{t("notesLabel")}</Label>
<Textarea id="edit-col-notes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} placeholder={t("notesPlaceholder")} maxLength={2000} />
</div>
<div className="space-y-2">
<Label>{t("tagsLabel")}</Label>
<div
className="flex flex-wrap gap-1.5 min-h-9 rounded-lg border border-input bg-transparent px-2.5 py-1.5 cursor-text focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50"
onClick={() => tagInputRef.current?.focus()}
>
{tags.map((tag) => (
<span key={tag} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs bg-muted text-muted-foreground">
<Tag className="h-2.5 w-2.5" />
{tag}
<button type="button" onClick={(e) => { e.stopPropagation(); removeTag(tag); }} className="hover:text-foreground transition-colors" aria-label={tRecipeForm("removeTagAriaLabel", { tag })}>
<X className="h-2.5 w-2.5" />
</button>
</span>
))}
{tags.length < 20 && (
<input
ref={tagInputRef}
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={handleTagKeyDown}
onBlur={() => { if (tagInput.trim()) addTag(tagInput); }}
placeholder={tags.length === 0 ? tRecipeForm("tagsPlaceholder") : ""}
className="flex-1 min-w-[120px] bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
)}
</div>
</div>
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input type="checkbox" checked={isPublic} onChange={(e) => setIsPublic(e.target.checked)} className="rounded" />
{t("makePublic")}
</label>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>{tCommon("cancel")}</Button>
<Button onClick={() => { void handleSave(); }} disabled={!name.trim() || saving}>
{saving ? t("saving") : tCommon("save")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}