feat: bulk tag editing, bulk export, and move recipes between collections

Extends the existing bulk-select infra: recipes list gets tag add/remove
and multi-recipe Markdown export; collection pages get a select mode to
move recipes to another collection or remove them from the current one.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-13 11:57:07 +02:00
parent 4960dfc7c6
commit 70eb565eec
14 changed files with 533 additions and 18 deletions
@@ -0,0 +1,164 @@
"use client";
import { useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { ListChecks, X, FolderInput, FolderMinus, Check } from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";
import { RecipeCard } from "@/components/recipe/recipe-card";
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} 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";
updatedAt: Date;
photos?: Array<{ storageKey: string; isCover: boolean }>;
sourceUrl?: string | null;
};
export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }: { collectionId: string; recipes: Recipe[] }) {
const t = useTranslations("collections");
const tCommon = useTranslations("common");
const [recipes, setRecipes] = useState(initialRecipes);
const [selectMode, setSelectMode] = useState(false);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [moveOpen, setMoveOpen] = useState(false);
const [removeConfirmOpen, setRemoveConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
const toggleSelect = useCallback((id: string) => {
setSelected((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
}, []);
const exitSelect = () => {
setSelectMode(false);
setSelected(new Set());
};
async function removeFromCollection() {
setBusy(true);
try {
const res = await fetch(`/api/v1/collections/${collectionId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ removeRecipeIds: [...selected] }),
});
if (!res.ok) throw new Error();
setRecipes((prev) => prev.filter((r) => !selected.has(r.id)));
toast.success(t("removedFromCollection", { count: selected.size }));
exitSelect();
} catch {
toast.error(t("removeFromCollectionFailed"));
} finally {
setBusy(false);
}
}
if (recipes.length === 0) return null;
return (
<div className="space-y-4">
<div className="flex items-center justify-end">
<Button
variant="ghost"
size="sm"
onClick={selectMode ? exitSelect : () => setSelectMode(true)}
className={cn("gap-1.5", selectMode && "text-muted-foreground")}
>
{selectMode ? (
<><X className="h-4 w-4" />{tCommon("cancel")}</>
) : (
<><ListChecks className="h-4 w-4" />{t("selectRecipes")}</>
)}
</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} />
</div>
</div>
))}
</div>
{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">
<div className="flex items-center gap-1 sm:gap-2 bg-popover border shadow-2xl rounded-2xl px-2 sm:px-5 py-2 sm:py-3 overflow-x-auto sm:overflow-visible [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
<span className="text-sm font-semibold tabular-nums mr-1 shrink-0">{selected.size}</span>
<div className="w-px h-5 bg-border mx-1 shrink-0" />
<Button variant="ghost" size="sm" onClick={() => setMoveOpen(true)} disabled={busy} className={buttonVariants({ variant: "ghost", size: "sm" }) + " gap-1.5 shrink-0"} aria-label={t("moveToCollection")}>
<FolderInput className="h-4 w-4" />
<span className="hidden sm:inline">{t("moveToCollection")}</span>
</Button>
<Button variant="destructive" size="sm" onClick={() => setRemoveConfirmOpen(true)} disabled={busy} className="gap-1.5 shrink-0" aria-label={t("removeFromCollection")}>
<FolderMinus className="h-4 w-4" />
<span className="hidden sm:inline">{t("removeFromCollection")}</span>
</Button>
</div>
</div>
)}
<AddToCollectionDialog
open={moveOpen}
onOpenChange={setMoveOpen}
recipeIds={[...selected]}
sourceCollectionId={collectionId}
onDone={() => {
setRecipes((prev) => prev.filter((r) => !selected.has(r.id)));
exitSelect();
}}
/>
<AlertDialog open={removeConfirmOpen} onOpenChange={setRemoveConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("removeFromCollectionConfirmTitle", { count: selected.size })}</AlertDialogTitle>
<AlertDialogDescription>{t("removeFromCollectionConfirmDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => { setRemoveConfirmOpen(false); void removeFromCollection(); }}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t("removeFromCollection")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
@@ -20,11 +20,14 @@ export function AddToCollectionDialog({
onOpenChange,
recipeIds,
onDone,
sourceCollectionId,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
recipeIds: string[];
onDone: () => void;
/** When set, this is a "move" — after adding to the target, the recipes are removed from this collection. */
sourceCollectionId?: string;
}) {
const t = useTranslations("recipe");
const [collections, setCollections] = useState<CollectionSummary[]>([]);
@@ -42,10 +45,10 @@ export function AddToCollectionDialog({
fetch("/api/v1/collections?limit=50")
.then((res) => (res.ok ? res.json() : null))
.then((data: { data: CollectionSummary[] } | null) => {
setCollections(data?.data ?? []);
setCollections((data?.data ?? []).filter((c) => c.id !== sourceCollectionId));
})
.finally(() => setLoading(false));
}, [open]);
}, [open, sourceCollectionId]);
async function addTo(collectionId: string, collectionName: string) {
setBusyId(collectionId);
@@ -56,7 +59,20 @@ export function AddToCollectionDialog({
body: JSON.stringify({ addRecipeIds: recipeIds }),
});
if (!res.ok) throw new Error();
toast.success(t("addToCollectionSuccess", { count: recipeIds.length, name: collectionName }));
if (sourceCollectionId) {
await fetch(`/api/v1/collections/${sourceCollectionId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ removeRecipeIds: recipeIds }),
});
}
toast.success(
sourceCollectionId
? t("moveToCollectionSuccess", { count: recipeIds.length, name: collectionName })
: t("addToCollectionSuccess", { count: recipeIds.length, name: collectionName })
);
onOpenChange(false);
onDone();
} catch {
@@ -91,7 +107,9 @@ export function AddToCollectionDialog({
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<FolderPlus className="h-5 w-5 text-primary" />
{t("addToCollectionTitle", { count: recipeIds.length })}
{sourceCollectionId
? t("moveToCollectionTitle", { count: recipeIds.length })
: t("addToCollectionTitle", { count: recipeIds.length })}
</DialogTitle>
</DialogHeader>
@@ -0,0 +1,143 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Tag, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
export function BulkTagsDialog({
open,
onOpenChange,
recipeIds,
availableTags,
onDone,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
recipeIds: string[];
availableTags: string[];
onDone: (addTags: string[], removeTags: string[]) => void;
}) {
const t = useTranslations("recipe");
const tCommon = useTranslations("common");
const [addInput, setAddInput] = useState("");
const [toAdd, setToAdd] = useState<string[]>([]);
const [toRemove, setToRemove] = useState<string[]>([]);
const [saving, setSaving] = useState(false);
function commitAddInput() {
const tag = addInput.trim();
if (tag && !toAdd.includes(tag)) setToAdd((prev) => [...prev, tag]);
setAddInput("");
}
function toggleRemove(tag: string) {
setToRemove((prev) => (prev.includes(tag) ? prev.filter((x) => x !== tag) : [...prev, tag]));
}
async function save() {
if (toAdd.length === 0 && toRemove.length === 0) {
onOpenChange(false);
return;
}
setSaving(true);
try {
const res = await fetch("/api/v1/recipes/bulk", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: recipeIds, addTags: toAdd, removeTags: toRemove }),
});
if (!res.ok) throw new Error();
toast.success(t("bulkTagsUpdated", { count: recipeIds.length }));
onOpenChange(false);
onDone(toAdd, toRemove);
setToAdd([]);
setToRemove([]);
} catch {
toast.error(t("bulkUpdateFailed"));
} finally {
setSaving(false);
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Tag className="h-5 w-5 text-primary" />
{t("bulkTagsTitle", { count: recipeIds.length })}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<p className="text-sm font-medium">{t("bulkTagsAddLabel")}</p>
<div className="flex gap-2">
<Input
value={addInput}
onChange={(e) => setAddInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
commitAddInput();
}
}}
placeholder={t("bulkTagsAddPlaceholder")}
/>
<Button type="button" variant="outline" onClick={commitAddInput} disabled={!addInput.trim()}>
{t("bulkTagsAddButton")}
</Button>
</div>
{toAdd.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{toAdd.map((tag) => (
<Badge key={tag} variant="secondary" className="gap-1 pr-1">
{tag}
<button onClick={() => setToAdd((prev) => prev.filter((x) => x !== tag))} className="rounded-full hover:bg-muted-foreground/20 p-0.5">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
</div>
{availableTags.length > 0 && (
<div className="space-y-2">
<p className="text-sm font-medium">{t("bulkTagsRemoveLabel")}</p>
<div className="flex flex-wrap gap-1.5">
{availableTags.map((tag) => (
<button key={tag} onClick={() => toggleRemove(tag)}>
<Badge variant={toRemove.includes(tag) ? "destructive" : "outline"} className="cursor-pointer">
{tag}
</Badge>
</button>
))}
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}>
{tCommon("cancel")}
</Button>
<Button onClick={() => { void save(); }} disabled={saving || (toAdd.length === 0 && toRemove.length === 0)}>
{tCommon("save")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+58 -1
View File
@@ -3,8 +3,9 @@
import { useState, useCallback, useEffect } from "react";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3, FolderPlus, ChefHat, ExternalLink } from "lucide-react";
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3, FolderPlus, ChefHat, ExternalLink, Tag, Download } from "lucide-react";
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
import { BulkTagsDialog } from "@/components/recipe/bulk-tags-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import {
DropdownMenu,
@@ -407,6 +408,8 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
const [viewMode, setViewMode] = useState<ViewMode>("grid");
const [addToCollectionOpen, setAddToCollectionOpen] = useState(false);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [bulkTagsOpen, setBulkTagsOpen] = useState(false);
const [exporting, setExporting] = useState(false);
useEffect(() => {
const stored = localStorage.getItem(VIEW_STORAGE_KEY) as ViewMode | null;
@@ -473,9 +476,47 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
}
}
function applyBulkTags(addTags: string[], removeTags: string[]) {
setRecipes((prev) =>
prev.map((r) =>
selected.has(r.id)
? { ...r, tags: [...new Set([...r.tags.filter((tag) => !removeTags.includes(tag)), ...addTags])] }
: r
)
);
exitSelect();
}
async function bulkExport() {
setExporting(true);
try {
const res = await fetch("/api/v1/recipes/bulk/export", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: [...selected] }),
});
if (!res.ok) throw new Error();
const { markdown } = (await res.json()) as { markdown: string };
const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "recipes.md";
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch {
toast.error(t("bulkExportFailed"));
} finally {
setExporting(false);
}
}
if (recipes.length === 0) return null;
const allSelected = selected.size === recipes.length;
const availableTagsForRemoval = [...new Set(recipes.filter((r) => selected.has(r.id)).flatMap((r) => r.tags))];
return (
<div className="space-y-4">
@@ -555,6 +596,14 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
<FolderPlus className="h-4 w-4" />
<span className="hidden sm:inline">{t("addToCollection")}</span>
</Button>
<Button variant="ghost" size="sm" onClick={() => setBulkTagsOpen(true)} disabled={busy} className="gap-1.5 shrink-0" aria-label={t("bulkTagsButton")}>
<Tag className="h-4 w-4" />
<span className="hidden sm:inline">{t("bulkTagsButton")}</span>
</Button>
<Button variant="ghost" size="sm" onClick={() => { void bulkExport(); }} disabled={exporting || busy} className="gap-1.5 shrink-0" aria-label={t("bulkExportButton")}>
<Download className="h-4 w-4" />
<span className="hidden sm:inline">{t("bulkExportButton")}</span>
</Button>
<Button variant="destructive" size="sm" onClick={() => setDeleteConfirmOpen(true)} disabled={busy} className="gap-1.5 shrink-0" aria-label={tCommon("delete")}>
<Trash2 className="h-4 w-4" />
<span className="hidden sm:inline">{tCommon("delete")}</span>
@@ -570,6 +619,14 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
onDone={exitSelect}
/>
<BulkTagsDialog
open={bulkTagsOpen}
onOpenChange={setBulkTagsOpen}
recipeIds={[...selected]}
availableTags={availableTagsForRemoval}
onDone={applyBulkTags}
/>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>