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">