feat(recipes): full recipe CRUD with photos, print, version history
List, detail, new, edit pages. Server-side pagination, dietary tags, difficulty. Photo upload to S3-compatible storage. Version history. Multi-select grid with bulk delete/visibility. Print view. Delete confirmation dialog.
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Sparkles, Loader2, Camera, Type, Upload, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
|
||||
|
||||
const LANGUAGES = [
|
||||
{ code: "en", label: "English" },
|
||||
{ code: "fr", label: "French" },
|
||||
{ code: "es", label: "Spanish" },
|
||||
{ code: "de", label: "German" },
|
||||
{ code: "it", label: "Italian" },
|
||||
{ code: "pt", label: "Portuguese" },
|
||||
{ code: "ja", label: "Japanese" },
|
||||
{ code: "zh", label: "Chinese" },
|
||||
{ code: "ar", label: "Arabic" },
|
||||
];
|
||||
|
||||
type Tab = "describe" | "photo";
|
||||
|
||||
type GeneratedRecipe = {
|
||||
title: string;
|
||||
description?: string;
|
||||
baseServings?: number;
|
||||
prepMins?: number;
|
||||
cookMins?: number;
|
||||
difficulty?: "easy" | "medium" | "hard";
|
||||
dietaryTags?: Record<string, boolean>;
|
||||
ingredients: Array<{ rawName: string; quantity?: string; unit?: string; note?: string }>;
|
||||
steps: Array<{ instruction: string; timerSeconds?: number }>;
|
||||
};
|
||||
|
||||
export function AiGenerateDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [tab, setTab] = useState<Tab>("describe");
|
||||
|
||||
// describe tab
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [language, setLanguage] = useState("en");
|
||||
|
||||
// photo tab
|
||||
const [photoPreview, setPhotoPreview] = useState<string | null>(null);
|
||||
const [photoBase64, setPhotoBase64] = useState<string | null>(null);
|
||||
const [photoMime, setPhotoMime] = useState<string>("image/jpeg");
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
function handleClose() {
|
||||
if (busy) return;
|
||||
onOpenChange(false);
|
||||
setTimeout(() => {
|
||||
setPrompt("");
|
||||
setPhotoPreview(null);
|
||||
setPhotoBase64(null);
|
||||
setTab("describe");
|
||||
}, 200);
|
||||
}
|
||||
|
||||
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setPhotoMime(file.type);
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => {
|
||||
const dataUrl = ev.target?.result as string;
|
||||
setPhotoPreview(dataUrl);
|
||||
// strip the data:mime;base64, prefix
|
||||
setPhotoBase64(dataUrl.split(",")[1] ?? null);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
e.target.value = "";
|
||||
}
|
||||
|
||||
async function handleDescribeGenerate() {
|
||||
if (!prompt.trim()) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/ai/generate", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ prompt: prompt.trim(), language }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json() as { error?: string };
|
||||
toast.error(err.error ?? "Failed to generate recipe");
|
||||
return;
|
||||
}
|
||||
const generated = await res.json() as GeneratedRecipe;
|
||||
const saveRes = await fetch("/api/v1/recipes", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true }),
|
||||
});
|
||||
if (!saveRes.ok) { toast.error("Failed to save generated recipe"); return; }
|
||||
const saved = await saveRes.json() as { id: string };
|
||||
toast.success("Recipe generated! Review and edit before publishing.");
|
||||
handleClose();
|
||||
router.push(`/recipes/${saved.id}/edit`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePhotoGenerate() {
|
||||
if (!photoBase64) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/ai/import-photo", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ imageBase64: photoBase64, mimeType: photoMime }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let msg = "Failed to analyze photo";
|
||||
try { msg = ((await res.json()) as { error?: string }).error ?? msg; } catch { /* non-JSON body */ }
|
||||
toast.error(msg);
|
||||
return;
|
||||
}
|
||||
const { id } = await res.json() as { id: string };
|
||||
toast.success("Recipe recognized! Review and edit before publishing.");
|
||||
handleClose();
|
||||
router.push(`/recipes/${id}/edit`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const canSubmit = tab === "describe" ? !!prompt.trim() : !!photoBase64;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5 text-primary" />
|
||||
Generate recipe with AI
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Describe a dish in words or snap a photo — AI builds the full recipe.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Tab switcher */}
|
||||
<div className="flex gap-1 p-1 bg-muted rounded-lg">
|
||||
{([
|
||||
{ key: "describe", label: "Describe", icon: Type },
|
||||
{ key: "photo", label: "From photo", icon: Camera },
|
||||
] as { key: Tab; label: string; icon: React.ElementType }[]).map(({ key, label, icon: Icon }) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setTab(key)}
|
||||
disabled={busy}
|
||||
className={cn(
|
||||
"flex-1 flex items-center justify-center gap-2 py-2 px-3 rounded-md text-sm font-medium transition-all",
|
||||
tab === key
|
||||
? "bg-background shadow-sm text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Describe tab */}
|
||||
{tab === "describe" && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="ai-prompt">What do you want to cook?</Label>
|
||||
<Textarea
|
||||
id="ai-prompt"
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
placeholder="e.g. A creamy mushroom risotto with parmesan, serves 4, easy difficulty"
|
||||
rows={4}
|
||||
disabled={busy}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Recipe language</Label>
|
||||
<Select value={language} onValueChange={(v) => v && setLanguage(v)} disabled={busy}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANGUAGES.map((l) => (
|
||||
<SelectItem key={l.code} value={l.code}>{l.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Photo tab */}
|
||||
{tab === "photo" && (
|
||||
<div className="space-y-3">
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
{photoPreview ? (
|
||||
<div className="relative rounded-xl overflow-hidden border bg-muted">
|
||||
<img
|
||||
src={photoPreview}
|
||||
alt="Dish preview"
|
||||
className="w-full max-h-64 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={() => { setPhotoPreview(null); setPhotoBase64(null); }}
|
||||
className="absolute top-2 right-2 h-7 w-7 rounded-full bg-black/60 flex items-center justify-center text-white hover:bg-black/80 transition-colors"
|
||||
disabled={busy}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={busy}
|
||||
className="w-full border-2 border-dashed rounded-xl p-10 flex flex-col items-center gap-3 text-muted-foreground hover:border-primary/50 hover:text-foreground transition-colors"
|
||||
>
|
||||
<Upload className="h-8 w-8" />
|
||||
<div className="text-sm text-center">
|
||||
<span className="font-medium text-foreground">Click to upload</span> or drag a food photo
|
||||
<p className="text-xs mt-1">JPEG, PNG or WebP · AI will reverse-engineer the recipe</p>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
{photoPreview && (
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
AI will analyze this dish and infer ingredients, quantities, and cooking steps.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FakeProgressBar
|
||||
active={busy}
|
||||
durationMs={tab === "photo" ? 12000 : 10000}
|
||||
label={busy ? (tab === "photo" ? "Analyzing dish photo…" : "Generating recipe…") : undefined}
|
||||
/>
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 justify-end pt-1">
|
||||
<Button variant="outline" onClick={handleClose} disabled={busy}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={tab === "describe" ? () => { void handleDescribeGenerate(); } : () => { void handlePhotoGenerate(); }}
|
||||
disabled={!canSubmit || busy}
|
||||
>
|
||||
{busy ? (
|
||||
<><Loader2 className="h-4 w-4 animate-spin" />Analyzing…</>
|
||||
) : (
|
||||
<><Sparkles className="h-4 w-4" />{tab === "photo" ? "Recognize dish" : "Generate"}</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user