feat(i18n): translate hardcoded strings across print, public recipe, and recipe management UI

Wires dozens of components and server pages to next-intl instead of hardcoded
English text, and adds a lightweight getMessages/formatMessage helper for
server components (print pages, public recipe page, cook metadata) since
next-intl/server isn't wired into this app's routing. Backfills missing
en/fr message keys that existing code already referenced but fr.json lacked.
This commit is contained in:
Arnaud
2026-07-02 07:58:18 +02:00
parent afff6cf9eb
commit 01fdbb880b
32 changed files with 515 additions and 187 deletions
@@ -3,13 +3,16 @@ import { headers } from "next/headers";
import { auth } from "@/lib/auth/server"; import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db"; import { db, recipes, eq, and } from "@epicure/db";
import { CookingMode } from "@/components/cooking-mode/cooking-mode"; import { CookingMode } from "@/components/cooking-mode/cooking-mode";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> }; type Params = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Params) { export async function generateMetadata({ params }: Params) {
const { id } = await params; const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() });
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) }); const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
return { title: recipe ? `Cooking: ${recipe.title}` : "Cooking Mode" }; return { title: recipe ? formatMessage(m.cookingMode.pageTitle, { title: recipe.title }) : m.cookingMode.pageTitleFallback };
} }
export default async function CookPage({ params }: Params) { export default async function CookPage({ params }: Params) {
+9 -15
View File
@@ -28,6 +28,7 @@ import { CommentsSection } from "@/components/social/comments-section";
import { getPublicUrl } from "@/lib/storage"; import { getPublicUrl } from "@/lib/storage";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { RecipeChatPanel } from "@/components/recipe/recipe-chat-panel"; import { RecipeChatPanel } from "@/components/recipe/recipe-chat-panel";
import { getMessages } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> }; type Params = { params: Promise<{ id: string }> };
@@ -37,25 +38,18 @@ export async function generateMetadata({ params }: Params): Promise<Metadata> {
return { title: recipe?.title ?? "Recipe" }; return { title: recipe?.title ?? "Recipe" };
} }
const VISIBILITY_LABEL = { private: "Private", unlisted: "Unlisted", public: "Public" };
const VISIBILITY_ICON = { private: Lock, unlisted: Link2, public: Globe }; const VISIBILITY_ICON = { private: Lock, unlisted: Link2, public: Globe };
const DIFFICULTY_COLOR = { easy: "default", medium: "secondary", hard: "destructive" } as const; const DIFFICULTY_COLOR = { easy: "default", medium: "secondary", hard: "destructive" } as const;
const DIETARY_LABELS: Record<string, string> = {
vegan: "Vegan",
vegetarian: "Vegetarian",
glutenFree: "Gluten-free",
dairyFree: "Dairy-free",
nutFree: "Nut-free",
halal: "Halal",
kosher: "Kosher",
};
export default async function RecipePage({ params }: Params) { export default async function RecipePage({ params }: Params) {
const { id } = await params; const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null; if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const VISIBILITY_LABEL = m.recipe.visibility;
const DIETARY_LABELS = m.recipe.dietary;
const [recipe, ratingData, favoriteData] = await Promise.all([ const [recipe, ratingData, favoriteData] = await Promise.all([
db.query.recipes.findFirst({ db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)), where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
@@ -79,7 +73,7 @@ export default async function RecipePage({ params }: Params) {
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0); const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const activeDietaryTags = Object.entries(recipe.dietaryTags ?? {}) const activeDietaryTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v) .filter(([, v]) => v)
.map(([k]) => DIETARY_LABELS[k]) .map(([k]) => DIETARY_LABELS[k as keyof typeof DIETARY_LABELS])
.filter(Boolean); .filter(Boolean);
const VisibilityIcon = VISIBILITY_ICON[recipe.visibility]; const VisibilityIcon = VISIBILITY_ICON[recipe.visibility];
@@ -98,7 +92,7 @@ export default async function RecipePage({ params }: Params) {
<Play className="h-4 w-4" /> <Play className="h-4 w-4" />
</Link> </Link>
} /> } />
<TooltipContent>Cook</TooltipContent> <TooltipContent>{m.recipe.cookAction}</TooltipContent>
</Tooltip> </Tooltip>
)} )}
<FavoriteButton recipeId={id} initialFavorited={isFavorited} /> <FavoriteButton recipeId={id} initialFavorited={isFavorited} />
@@ -251,7 +245,7 @@ export default async function RecipePage({ params }: Params) {
{/* Serving scaler + ingredients */} {/* Serving scaler + ingredients */}
{recipe.ingredients.length > 0 && ( {recipe.ingredients.length > 0 && (
<div className="space-y-4"> <div className="space-y-4">
<h2 className="text-xl font-semibold">Ingredients</h2> <h2 className="text-xl font-semibold">{m.recipe.ingredients}</h2>
<ServingScaler <ServingScaler
baseServings={recipe.baseServings} baseServings={recipe.baseServings}
recipeTitle={recipe.title} recipeTitle={recipe.title}
@@ -272,7 +266,7 @@ export default async function RecipePage({ params }: Params) {
<> <>
<Separator /> <Separator />
<div className="space-y-6"> <div className="space-y-6">
<h2 className="text-xl font-semibold">Instructions</h2> <h2 className="text-xl font-semibold">{m.recipe.instructions}</h2>
<ol className="space-y-6"> <ol className="space-y-6">
{recipe.steps.map((step, i) => ( {recipe.steps.map((step, i) => (
<li key={step.id} className="flex gap-4"> <li key={step.id} className="flex gap-4">
+11 -18
View File
@@ -4,6 +4,7 @@ import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db"; import { db, recipes, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger"; import { PrintTrigger } from "@/components/recipe/print-trigger";
import { hasQuantity } from "@/lib/fractions"; import { hasQuantity } from "@/lib/fractions";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> }; type Params = { params: Promise<{ id: string }> };
@@ -12,6 +13,8 @@ export default async function RecipePrintPage({ params }: Params) {
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null; if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const recipe = await db.query.recipes.findFirst({ const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)), where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
with: { with: {
@@ -24,19 +27,9 @@ export default async function RecipePrintPage({ params }: Params) {
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0); const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const DIETARY_LABELS: Record<string, string> = {
vegan: "Vegan",
vegetarian: "Vegetarian",
glutenFree: "Gluten-free",
dairyFree: "Dairy-free",
nutFree: "Nut-free",
halal: "Halal",
kosher: "Kosher",
};
const activeTags = Object.entries(recipe.dietaryTags ?? {}) const activeTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v) .filter(([, v]) => v)
.map(([k]) => DIETARY_LABELS[k]) .map(([k]) => m.recipe.dietary[k as keyof typeof m.recipe.dietary])
.filter(Boolean); .filter(Boolean);
return ( return (
@@ -88,10 +81,10 @@ export default async function RecipePrintPage({ params }: Params) {
)} )}
<div className="meta"> <div className="meta">
{recipe.baseServings && <span>Serves {recipe.baseServings}</span>} {recipe.baseServings && <span>{formatMessage(m.recipe.servings, { count: recipe.baseServings })}</span>}
{recipe.prepMins && <span>Prep {recipe.prepMins} min</span>} {recipe.prepMins && <span>{formatMessage(m.recipe.prep, { mins: recipe.prepMins })}</span>}
{recipe.cookMins && <span>Cook {recipe.cookMins} min</span>} {recipe.cookMins && <span>{formatMessage(m.recipe.cook, { mins: recipe.cookMins })}</span>}
{totalMins > 0 && <span>Total {totalMins} min</span>} {totalMins > 0 && <span>{formatMessage(m.recipe.total, { mins: totalMins })}</span>}
{recipe.difficulty && <span>{recipe.difficulty.charAt(0).toUpperCase() + recipe.difficulty.slice(1)}</span>} {recipe.difficulty && <span>{recipe.difficulty.charAt(0).toUpperCase() + recipe.difficulty.slice(1)}</span>}
</div> </div>
@@ -105,7 +98,7 @@ export default async function RecipePrintPage({ params }: Params) {
{recipe.ingredients.length > 0 && ( {recipe.ingredients.length > 0 && (
<> <>
<h2>Ingredients</h2> <h2>{m.recipe.ingredients}</h2>
<ul className="ingredients"> <ul className="ingredients">
{recipe.ingredients.map((ing) => ( {recipe.ingredients.map((ing) => (
<li key={ing.id}> <li key={ing.id}>
@@ -122,7 +115,7 @@ export default async function RecipePrintPage({ params }: Params) {
{recipe.steps.length > 0 && ( {recipe.steps.length > 0 && (
<> <>
<h2>Instructions</h2> <h2>{m.recipe.instructions}</h2>
<ol className="steps"> <ol className="steps">
{recipe.steps.map((step) => ( {recipe.steps.map((step) => (
<li key={step.id}> <li key={step.id}>
@@ -137,7 +130,7 @@ export default async function RecipePrintPage({ params }: Params) {
)} )}
</article> </article>
<footer>Printed from Epicure</footer> <footer>{m.print.footer}</footer>
</> </>
); );
} }
+10 -14
View File
@@ -2,16 +2,10 @@ import { headers } from "next/headers";
import { auth } from "@/lib/auth/server"; import { auth } from "@/lib/auth/server";
import { db, mealPlans, eq, and } from "@epicure/db"; import { db, mealPlans, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger"; import { PrintTrigger } from "@/components/recipe/print-trigger";
import { getMessages, formatMessage } from "@/lib/i18n/server";
const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const; const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
const DAY_LABELS: Record<string, string> = {
mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday",
fri: "Friday", sat: "Saturday", sun: "Sunday",
};
const MEAL_ORDER = ["breakfast", "lunch", "dinner", "snack"] as const; const MEAL_ORDER = ["breakfast", "lunch", "dinner", "snack"] as const;
const MEAL_LABELS: Record<string, string> = {
breakfast: "Breakfast", lunch: "Lunch", dinner: "Dinner", snack: "Snack",
};
function getMonday(dateStr?: string): Date { function getMonday(dateStr?: string): Date {
const d = dateStr ? new Date(dateStr) : new Date(); const d = dateStr ? new Date(dateStr) : new Date();
@@ -31,6 +25,8 @@ export default async function MealPlanPrintPage({
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null; if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const monday = getMonday(week); const monday = getMonday(week);
const weekStart = monday.toISOString().slice(0, 10); const weekStart = monday.toISOString().slice(0, 10);
const sunday = new Date(monday); const sunday = new Date(monday);
@@ -82,22 +78,22 @@ export default async function MealPlanPrintPage({
<PrintTrigger /> <PrintTrigger />
<h1>Meal Plan</h1> <h1>{m.mealPlan.title}</h1>
<p className="subtitle">{label}</p> <p className="subtitle">{label}</p>
<table> <table>
<thead> <thead>
<tr> <tr>
<th style={{ width: "100px" }}>Day</th> <th style={{ width: "100px" }}>{m.print.day}</th>
{MEAL_ORDER.map((m) => ( {MEAL_ORDER.map((meal) => (
<th key={m}>{MEAL_LABELS[m]}</th> <th key={meal}>{m.mealPlan.meals[meal]}</th>
))} ))}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{DAYS.map((day) => ( {DAYS.map((day) => (
<tr key={day}> <tr key={day}>
<td style={{ fontWeight: 600, color: "#555" }}>{DAY_LABELS[day]}</td> <td style={{ fontWeight: 600, color: "#555" }}>{m.print.days[day]}</td>
{MEAL_ORDER.map((mealType) => { {MEAL_ORDER.map((mealType) => {
const entry = entries.find((e) => e.day === day && e.mealType === mealType); const entry = entries.find((e) => e.day === day && e.mealType === mealType);
return ( return (
@@ -106,7 +102,7 @@ export default async function MealPlanPrintPage({
<> <>
<span className="recipe-title">{entry.recipe?.title ?? entry.note ?? "—"}</span> <span className="recipe-title">{entry.recipe?.title ?? entry.note ?? "—"}</span>
{entry.servings && ( {entry.servings && (
<span className="servings"> · {entry.servings} srv</span> <span className="servings">{formatMessage(m.print.srv, { count: entry.servings })}</span>
)} )}
</> </>
) : ( ) : (
@@ -120,7 +116,7 @@ export default async function MealPlanPrintPage({
</tbody> </tbody>
</table> </table>
<footer>Printed from Epicure</footer> <footer>{m.print.footer}</footer>
</> </>
); );
} }
+12 -5
View File
@@ -3,6 +3,7 @@ import { headers } from "next/headers";
import { auth } from "@/lib/auth/server"; import { auth } from "@/lib/auth/server";
import { db, shoppingLists, eq, and } from "@epicure/db"; import { db, shoppingLists, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger"; import { PrintTrigger } from "@/components/recipe/print-trigger";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> }; type Params = { params: Promise<{ id: string }> };
@@ -11,6 +12,9 @@ export default async function ShoppingListPrintPage({ params }: Params) {
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null; if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const OTHER = m.mealPlan.aisleOther;
const list = await db.query.shoppingLists.findFirst({ const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session.user.id)), where: and(eq(shoppingLists.id, id), eq(shoppingLists.userId, session.user.id)),
with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.rawName)] } }, with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.rawName)] } },
@@ -19,13 +23,13 @@ export default async function ShoppingListPrintPage({ params }: Params) {
if (!list) notFound(); if (!list) notFound();
const byAisle = list.items.reduce<Record<string, typeof list.items>>((acc, item) => { const byAisle = list.items.reduce<Record<string, typeof list.items>>((acc, item) => {
const key = item.aisle ?? "Other"; const key = item.aisle ?? OTHER;
(acc[key] ??= []).push(item); (acc[key] ??= []).push(item);
return acc; return acc;
}, {}); }, {});
const aisles = Object.keys(byAisle).sort((a, b) => const aisles = Object.keys(byAisle).sort((a, b) =>
a === "Other" ? 1 : b === "Other" ? -1 : a.localeCompare(b) a === OTHER ? 1 : b === OTHER ? -1 : a.localeCompare(b)
); );
return ( return (
@@ -67,8 +71,11 @@ export default async function ShoppingListPrintPage({ params }: Params) {
<h1>{list.name}</h1> <h1>{list.name}</h1>
<p className="subtitle"> <p className="subtitle">
{list.items.filter(i => i.checked).length}/{list.items.length} items checked {formatMessage(m.shoppingLists.itemsChecked, {
{list.generatedAt ? " · From meal plan" : ""} checked: list.items.filter((i) => i.checked).length,
total: list.items.length,
})}
{list.generatedAt ? m.shoppingLists.fromMealPlan : ""}
</p> </p>
{aisles.map((aisle) => ( {aisles.map((aisle) => (
@@ -88,7 +95,7 @@ export default async function ShoppingListPrintPage({ params }: Params) {
</section> </section>
))} ))}
<footer>Printed from Epicure</footer> <footer>{m.print.footer}</footer>
</> </>
); );
} }
+19 -19
View File
@@ -13,6 +13,7 @@ import { ServingScaler } from "@/components/recipe/serving-scaler";
import { getPublicUrl } from "@/lib/storage"; import { getPublicUrl } from "@/lib/storage";
import { hasQuantity } from "@/lib/fractions"; import { hasQuantity } from "@/lib/fractions";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> }; type Params = { params: Promise<{ id: string }> };
@@ -33,15 +34,12 @@ export async function generateMetadata({ params }: Params): Promise<Metadata> {
}; };
} }
const DIETARY_LABELS: Record<string, string> = {
vegan: "Vegan", vegetarian: "Vegetarian", glutenFree: "Gluten-free",
dairyFree: "Dairy-free", nutFree: "Nut-free", halal: "Halal", kosher: "Kosher",
};
export default async function PublicRecipePage({ params }: Params) { export default async function PublicRecipePage({ params }: Params) {
const { id } = await params; const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() }).catch(() => null); const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
const recipe = await db.query.recipes.findFirst({ const recipe = await db.query.recipes.findFirst({
where: (r, { and, eq, ne }) => and(eq(r.id, id), ne(r.visibility, "private")), where: (r, { and, eq, ne }) => and(eq(r.id, id), ne(r.visibility, "private")),
with: { with: {
@@ -57,7 +55,9 @@ export default async function PublicRecipePage({ params }: Params) {
const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0]; const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0];
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0); const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const activeTags = Object.entries(recipe.dietaryTags ?? {}) const activeTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v).map(([k]) => DIETARY_LABELS[k]).filter(Boolean); .filter(([, v]) => v)
.map(([k]) => m.recipe.dietary[k as keyof typeof m.recipe.dietary])
.filter(Boolean);
const jsonLd = { const jsonLd = {
"@context": "https://schema.org", "@context": "https://schema.org",
@@ -85,21 +85,21 @@ export default async function PublicRecipePage({ params }: Params) {
{/* Breadcrumb-style nav */} {/* Breadcrumb-style nav */}
<div className="flex items-center gap-2 text-sm text-muted-foreground"> <div className="flex items-center gap-2 text-sm text-muted-foreground">
<Globe className="h-3.5 w-3.5" /> <Globe className="h-3.5 w-3.5" />
<span>Public recipe by</span> <span>{m.publicRecipe.publicRecipeBy}</span>
<Link href={`/u/${recipe.author.username ?? recipe.author.id}`} className="hover:text-foreground font-medium"> <Link href={`/u/${recipe.author.username ?? recipe.author.id}`} className="hover:text-foreground font-medium">
{recipe.author.name} {recipe.author.name}
</Link> </Link>
{session && ( {session && (
<div className="ml-auto"> <div className="ml-auto">
<Link href={`/recipes/${id}`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}> <Link href={`/recipes/${id}`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
View in your library {m.publicRecipe.viewInLibrary}
</Link> </Link>
</div> </div>
)} )}
{!session && ( {!session && (
<div className="ml-auto flex items-center gap-2"> <div className="ml-auto flex items-center gap-2">
<Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>Sign up free</Link> <Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>{m.publicRecipe.signUpFree}</Link>
<Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>Log in</Link> <Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>{m.publicRecipe.logIn}</Link>
</div> </div>
)} )}
</div> </div>
@@ -111,10 +111,10 @@ export default async function PublicRecipePage({ params }: Params) {
)} )}
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground"> <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{recipe.difficulty && <Badge>{recipe.difficulty}</Badge>} {recipe.difficulty && <Badge>{recipe.difficulty}</Badge>}
<span className="flex items-center gap-1"><Users className="h-4 w-4" />{recipe.baseServings} servings</span> <span className="flex items-center gap-1"><Users className="h-4 w-4" />{formatMessage(m.recipe.servings, { count: recipe.baseServings })}</span>
{recipe.prepMins && <span className="flex items-center gap-1"><Clock className="h-4 w-4" />{recipe.prepMins}m prep</span>} {recipe.prepMins && <span className="flex items-center gap-1"><Clock className="h-4 w-4" />{formatMessage(m.recipe.prep, { mins: recipe.prepMins })}</span>}
{recipe.cookMins && <span className="flex items-center gap-1"><ChefHat className="h-4 w-4" />{recipe.cookMins}m cook</span>} {recipe.cookMins && <span className="flex items-center gap-1"><ChefHat className="h-4 w-4" />{formatMessage(m.recipe.cook, { mins: recipe.cookMins })}</span>}
{totalMins > 0 && recipe.prepMins && recipe.cookMins && <span>({totalMins}m total)</span>} {totalMins > 0 && recipe.prepMins && recipe.cookMins && <span>({formatMessage(m.recipe.total, { mins: totalMins })})</span>}
</div> </div>
{activeTags.length > 0 && ( {activeTags.length > 0 && (
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
@@ -133,7 +133,7 @@ export default async function PublicRecipePage({ params }: Params) {
{recipe.ingredients.length > 0 && ( {recipe.ingredients.length > 0 && (
<div className="space-y-4"> <div className="space-y-4">
<h2 className="text-xl font-semibold">Ingredients</h2> <h2 className="text-xl font-semibold">{m.recipe.ingredients}</h2>
<ServingScaler <ServingScaler
baseServings={recipe.baseServings} baseServings={recipe.baseServings}
ingredients={recipe.ingredients.map((ing) => ({ ingredients={recipe.ingredients.map((ing) => ({
@@ -147,7 +147,7 @@ export default async function PublicRecipePage({ params }: Params) {
<> <>
<Separator /> <Separator />
<div className="space-y-6"> <div className="space-y-6">
<h2 className="text-xl font-semibold">Instructions</h2> <h2 className="text-xl font-semibold">{m.recipe.instructions}</h2>
<ol className="space-y-6"> <ol className="space-y-6">
{recipe.steps.map((step, i) => ( {recipe.steps.map((step, i) => (
<li key={step.id} className="flex gap-4"> <li key={step.id} className="flex gap-4">
@@ -162,9 +162,9 @@ export default async function PublicRecipePage({ params }: Params) {
{!session && ( {!session && (
<div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3"> <div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3">
<p className="font-semibold">Want to save this recipe?</p> <p className="font-semibold">{m.publicRecipe.wantToSave}</p>
<p className="text-sm text-muted-foreground">Create a free account to save recipes, scale servings, and build your own library.</p> <p className="text-sm text-muted-foreground">{m.publicRecipe.wantToSaveDescription}</p>
<Link href="/signup" className={cn(buttonVariants())}>Get started free</Link> <Link href="/signup" className={cn(buttonVariants())}>{m.publicRecipe.getStartedFree}</Link>
</div> </div>
)} )}
</div> </div>
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Check, Package, Loader2 } from "lucide-react"; import { Check, Package, Loader2 } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -23,6 +24,8 @@ export function ShoppingListView({
listId: string; listId: string;
initialItems: Item[]; initialItems: Item[];
}) { }) {
const t = useTranslations("mealPlan");
const tShopping = useTranslations("shoppingLists");
const [items, setItems] = useState<Item[]>(initialItems); const [items, setItems] = useState<Item[]>(initialItems);
const [movingToPantry, setMovingToPantry] = useState(false); const [movingToPantry, setMovingToPantry] = useState(false);
@@ -43,8 +46,8 @@ export function ShoppingListView({
})), })),
}), }),
}); });
if (!res.ok) { toast.error("Failed to move items to pantry"); return; } if (!res.ok) { toast.error(t("moveToPantryFailed")); return; }
toast.success(`${checkedItems.length} item${checkedItems.length !== 1 ? "s" : ""} added to pantry`); toast.success(t("addedToPantry", { count: checkedItems.length }));
} finally { } finally {
setMovingToPantry(false); setMovingToPantry(false);
} }
@@ -61,7 +64,7 @@ export function ShoppingListView({
} }
const grouped = items.reduce<Record<string, Item[]>>((acc, item) => { const grouped = items.reduce<Record<string, Item[]>>((acc, item) => {
const key = item.aisle ?? "Other"; const key = item.aisle ?? t("aisleOther");
(acc[key] ??= []).push(item); (acc[key] ??= []).push(item);
return acc; return acc;
}, {}); }, {});
@@ -69,17 +72,17 @@ export function ShoppingListView({
const checkedCount = items.filter((i) => i.checked).length; const checkedCount = items.filter((i) => i.checked).length;
if (items.length === 0) { if (items.length === 0) {
return <p className="text-muted-foreground text-sm">This list is empty.</p>; return <p className="text-muted-foreground text-sm">{t("listEmptyState")}</p>;
} }
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">{checkedCount}/{items.length} checked</p> <p className="text-sm text-muted-foreground">{tShopping("checkedCount", { checked: checkedCount, total: items.length })}</p>
{checkedCount > 0 && ( {checkedCount > 0 && (
<Button size="sm" variant="outline" onClick={moveToPantry} disabled={movingToPantry}> <Button size="sm" variant="outline" onClick={moveToPantry} disabled={movingToPantry}>
{movingToPantry ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Package className="h-3.5 w-3.5" />} {movingToPantry ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Package className="h-3.5 w-3.5" />}
Move {checkedCount} to pantry {t("moveToPantry", { count: checkedCount })}
</Button> </Button>
)} )}
</div> </div>
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Wand2, Loader2, X } from "lucide-react"; import { Wand2, Loader2, X } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -26,6 +27,7 @@ export function AdaptRecipeButton({
recipeId: string; recipeId: string;
ingredients: Ingredient[]; ingredients: Ingredient[];
}) { }) {
const t = useTranslations("recipe");
const router = useRouter(); const router = useRouter();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [excluded, setExcluded] = useState<Set<string>>(new Set()); const [excluded, setExcluded] = useState<Set<string>>(new Set());
@@ -50,7 +52,7 @@ export function AdaptRecipeButton({
async function handleAdapt() { async function handleAdapt() {
if (excluded.size === 0 && !extraConstraints.trim()) { if (excluded.size === 0 && !extraConstraints.trim()) {
toast.error("Select at least one ingredient to exclude or add a constraint"); toast.error(t("adaptConstraintRequired"));
return; return;
} }
@@ -68,7 +70,7 @@ export function AdaptRecipeButton({
if (!res.ok) { if (!res.ok) {
const err = await res.json() as { error?: string }; const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to adapt recipe"); toast.error(err.error ?? t("adaptFailed"));
return; return;
} }
@@ -154,7 +156,7 @@ export function AdaptRecipeButton({
id="extra-constraints" id="extra-constraints"
value={extraConstraints} value={extraConstraints}
onChange={(e) => setExtraConstraints(e.target.value)} onChange={(e) => setExtraConstraints(e.target.value)}
placeholder="e.g. Make it vegan, lower the calories, use pantry staples only, gluten-free…" placeholder={t("adaptConstraintPlaceholder")}
rows={2} rows={2}
disabled={adapting} disabled={adapting}
/> />
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { ShoppingCart, Loader2, Plus, Check } from "lucide-react"; import { ShoppingCart, Loader2, Plus, Check } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -45,6 +46,10 @@ export function AddToShoppingListButton({
baseServings: number; baseServings: number;
ingredients: Ingredient[]; ingredients: Ingredient[];
}) { }) {
const t = useTranslations("recipe");
const tShopping = useTranslations("shoppingLists");
const tCommon = useTranslations("common");
const tForm = useTranslations("recipeForm");
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [lists, setLists] = useState<ShoppingList[]>([]); const [lists, setLists] = useState<ShoppingList[]>([]);
const [loadingLists, setLoadingLists] = useState(false); const [loadingLists, setLoadingLists] = useState(false);
@@ -91,7 +96,7 @@ export function AddToShoppingListButton({
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newListName.trim() || recipeTitle }), body: JSON.stringify({ name: newListName.trim() || recipeTitle }),
}); });
if (!res.ok) { toast.error("Failed to create list"); return; } if (!res.ok) { toast.error(t("shoppingListCreateFailed")); return; }
const created = await res.json() as { id: string }; const created = await res.json() as { id: string };
listId = created.id; listId = created.id;
} }
@@ -102,9 +107,9 @@ export function AddToShoppingListButton({
body: JSON.stringify({ items }), body: JSON.stringify({ items }),
}); });
if (!res.ok) { toast.error("Failed to add ingredients"); return; } if (!res.ok) { toast.error(t("shoppingListAddFailed")); return; }
toast.success(`${items.length} ingredients added to list`); toast.success(tShopping("addedCount", { count: items.length }));
setOpen(false); setOpen(false);
} finally { } finally {
setAdding(false); setAdding(false);
@@ -120,7 +125,7 @@ export function AddToShoppingListButton({
<ShoppingCart className="h-4 w-4" /> <ShoppingCart className="h-4 w-4" />
</Button> </Button>
} /> } />
<TooltipContent>Add to list</TooltipContent> <TooltipContent>{tShopping("addToList")}</TooltipContent>
</Tooltip> </Tooltip>
</TooltipProvider> </TooltipProvider>
@@ -129,17 +134,20 @@ export function AddToShoppingListButton({
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
<ShoppingCart className="h-5 w-5 text-primary" /> <ShoppingCart className="h-5 w-5 text-primary" />
Add to shopping list {tShopping("dialogTitle")}
</DialogTitle> </DialogTitle>
<DialogDescription> <DialogDescription>
Add the ingredients of <strong>{recipeTitle}</strong> to a shopping list. {tShopping.rich("dialogDescription", {
title: recipeTitle,
strong: (chunks) => <strong>{chunks}</strong>,
})}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4"> <div className="space-y-4">
{/* Servings scaler */} {/* Servings scaler */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Label className="shrink-0">Servings</Label> <Label className="shrink-0">{tForm("servings")}</Label>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
type="button" variant="ghost" size="icon" className="h-7 w-7" type="button" variant="ghost" size="icon" className="h-7 w-7"
@@ -153,7 +161,7 @@ export function AddToShoppingListButton({
>+</Button> >+</Button>
</div> </div>
{scale !== 1 && ( {scale !== 1 && (
<span className="text-xs text-muted-foreground">({scale > 1 ? "×" : "÷"}{Math.abs(scale) !== 1 ? (scale > 1 ? scale.toFixed(2).replace(/\.?0+$/, "") : (1 / scale).toFixed(2).replace(/\.?0+$/, "")) : ""} scaled)</span> <span className="text-xs text-muted-foreground">({scale > 1 ? "×" : "÷"}{Math.abs(scale) !== 1 ? (scale > 1 ? scale.toFixed(2).replace(/\.?0+$/, "") : (1 / scale).toFixed(2).replace(/\.?0+$/, "")) : ""} {tShopping("scaledSuffix")}</span>
)} )}
</div> </div>
@@ -162,7 +170,7 @@ export function AddToShoppingListButton({
{/* List picker */} {/* List picker */}
{loadingLists ? ( {loadingLists ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground py-2"> <div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
<Loader2 className="h-4 w-4 animate-spin" /> Loading your lists <Loader2 className="h-4 w-4 animate-spin" /> {tShopping("loadingLists")}
</div> </div>
) : ( ) : (
<div className="space-y-3"> <div className="space-y-3">
@@ -170,7 +178,7 @@ export function AddToShoppingListButton({
<RadioGroup value={mode} onValueChange={(v: string) => setMode(v as "existing" | "new")}> <RadioGroup value={mode} onValueChange={(v: string) => setMode(v as "existing" | "new")}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<RadioGroupItem value="existing" id="mode-existing" /> <RadioGroupItem value="existing" id="mode-existing" />
<Label htmlFor="mode-existing">Add to existing list</Label> <Label htmlFor="mode-existing">{tShopping("modeExisting")}</Label>
</div> </div>
{mode === "existing" && ( {mode === "existing" && (
<div className="ml-6 space-y-1.5"> <div className="ml-6 space-y-1.5">
@@ -192,7 +200,7 @@ export function AddToShoppingListButton({
)} )}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<RadioGroupItem value="new" id="mode-new" /> <RadioGroupItem value="new" id="mode-new" />
<Label htmlFor="mode-new">Create new list</Label> <Label htmlFor="mode-new">{tShopping("modeNew")}</Label>
</div> </div>
</RadioGroup> </RadioGroup>
)} )}
@@ -202,7 +210,7 @@ export function AddToShoppingListButton({
<Input <Input
value={newListName} value={newListName}
onChange={(e) => setNewListName(e.target.value)} onChange={(e) => setNewListName(e.target.value)}
placeholder="List name" placeholder={tShopping("listNamePlaceholder")}
/> />
</div> </div>
)} )}
@@ -211,13 +219,13 @@ export function AddToShoppingListButton({
<Separator /> <Separator />
<p className="text-xs text-muted-foreground">{items.length} ingredient{items.length !== 1 ? "s" : ""} will be added.</p> <p className="text-xs text-muted-foreground">{tShopping("ingredientsWillBeAdded", { count: items.length })}</p>
<div className="flex gap-2 justify-end"> <div className="flex gap-2 justify-end">
<Button variant="ghost" onClick={() => setOpen(false)} disabled={adding}>Cancel</Button> <Button variant="ghost" onClick={() => setOpen(false)} disabled={adding}>{tCommon("cancel")}</Button>
<Button onClick={handleAdd} disabled={adding || loadingLists || (mode === "existing" && !selectedListId)}> <Button onClick={handleAdd} disabled={adding || loadingLists || (mode === "existing" && !selectedListId)}>
{adding ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />} {adding ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
{adding ? "Adding" : "Add ingredients"} {adding ? tShopping("adding") : tShopping("addIngredients")}
</Button> </Button>
</div> </div>
</div> </div>
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState, useRef } from "react"; import { useState, useRef } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Sparkles, Loader2, Camera, Type, Upload, X, Shuffle } from "lucide-react"; import { Sparkles, Loader2, Camera, Type, Upload, X, Shuffle } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -69,6 +70,7 @@ export function AiGenerateDialog({
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
}) { }) {
const t = useTranslations("ai.generate");
const router = useRouter(); const router = useRouter();
const [tab, setTab] = useState<Tab>("describe"); const [tab, setTab] = useState<Tab>("describe");
@@ -122,7 +124,7 @@ export function AiGenerateDialog({
}); });
if (!res.ok) { if (!res.ok) {
const err = await res.json() as { error?: string }; const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to generate recipe"); toast.error(err.error ?? t("error"));
return; return;
} }
const generated = await res.json() as GeneratedRecipe; const generated = await res.json() as GeneratedRecipe;
@@ -131,9 +133,9 @@ export function AiGenerateDialog({
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true, language }), body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true, language }),
}); });
if (!saveRes.ok) { toast.error("Failed to save generated recipe"); return; } if (!saveRes.ok) { toast.error(t("saveError")); return; }
const saved = await saveRes.json() as { id: string }; const saved = await saveRes.json() as { id: string };
toast.success("Recipe generated! Review and edit before publishing."); toast.success(t("success"));
handleClose(); handleClose();
router.push(`/recipes/${saved.id}/edit`); router.push(`/recipes/${saved.id}/edit`);
} finally { } finally {
@@ -151,13 +153,13 @@ export function AiGenerateDialog({
body: JSON.stringify({ imageBase64: photoBase64, mimeType: photoMime }), body: JSON.stringify({ imageBase64: photoBase64, mimeType: photoMime }),
}); });
if (!res.ok) { if (!res.ok) {
let msg = "Failed to analyze photo"; let msg = t("photoError");
try { msg = ((await res.json()) as { error?: string }).error ?? msg; } catch { /* non-JSON body */ } try { msg = ((await res.json()) as { error?: string }).error ?? msg; } catch { /* non-JSON body */ }
toast.error(msg); toast.error(msg);
return; return;
} }
const { id } = await res.json() as { id: string }; const { id } = await res.json() as { id: string };
toast.success("Recipe recognized! Review and edit before publishing."); toast.success(t("photoSuccess"));
handleClose(); handleClose();
router.push(`/recipes/${id}/edit`); router.push(`/recipes/${id}/edit`);
} finally { } finally {
@@ -226,7 +228,7 @@ export function AiGenerateDialog({
id="ai-prompt" id="ai-prompt"
value={prompt} value={prompt}
onChange={(e) => setPrompt(e.target.value)} onChange={(e) => setPrompt(e.target.value)}
placeholder="e.g. A creamy mushroom risotto with parmesan, serves 4, easy difficulty" placeholder={t("placeholder")}
rows={4} rows={4}
disabled={busy} disabled={busy}
/> />
@@ -249,7 +251,7 @@ export function AiGenerateDialog({
<Label>Difficulty</Label> <Label>Difficulty</Label>
<Select value={difficulty} onValueChange={(v) => setDifficulty(v as typeof difficulty)} disabled={busy}> <Select value={difficulty} onValueChange={(v) => setDifficulty(v as typeof difficulty)} disabled={busy}>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Any" /> <SelectValue placeholder={t("anyDifficulty")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="">Any</SelectItem> <SelectItem value="">Any</SelectItem>
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Trash2 } from "lucide-react"; import { Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -19,6 +20,7 @@ import { toast } from "sonner";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export function DeleteRecipeButton({ recipeId }: { recipeId: string }) { export function DeleteRecipeButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("recipe");
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
const router = useRouter(); const router = useRouter();
@@ -31,10 +33,10 @@ export function DeleteRecipeButton({ recipeId }: { recipeId: string }) {
const data = await res.json() as { error?: string }; const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Delete failed"); throw new Error(data.error ?? "Delete failed");
} }
toast.success("Recipe deleted"); toast.success(t("deleted"));
router.push("/recipes"); router.push("/recipes");
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Delete failed"); toast.error(err instanceof Error ? err.message : t("deleteFailed"));
setDeleting(false); setDeleting(false);
} }
} }
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Sparkles, Loader2 } from "lucide-react"; import { Sparkles, Loader2 } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -21,6 +22,7 @@ export function GenerateContentButton({
title: string; title: string;
description?: string | null; description?: string | null;
}) { }) {
const t = useTranslations("ai.generate");
const router = useRouter(); const router = useRouter();
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@@ -38,8 +40,7 @@ export function GenerateContentButton({
}); });
if (!genRes.ok) { if (!genRes.ok) {
const err = await genRes.json() as { error?: string }; toast.error(t("contentGenerateFailed"));
toast.error(err.error ?? "Generation failed");
return; return;
} }
@@ -65,11 +66,11 @@ export function GenerateContentButton({
}); });
if (!saveRes.ok) { if (!saveRes.ok) {
toast.error("Failed to save generated content"); toast.error(t("contentSaveFailed"));
return; return;
} }
toast.success("Ingredients and steps generated!"); toast.success(t("contentGenerated"));
router.refresh(); router.refresh();
} finally { } finally {
setBusy(false); setBusy(false);
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar"; import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { UtensilsCrossed, Sparkles, Loader2, ChefHat, Salad, Wine, Cake, Sandwich, Soup, Check } from "lucide-react"; import { UtensilsCrossed, Sparkles, Loader2, ChefHat, Salad, Wine, Cake, Sandwich, Soup, Check } from "lucide-react";
@@ -54,6 +55,7 @@ const DIFFICULTY_VARIANT = {
} as const; } as const;
export function MealPairingButton({ recipeId }: { recipeId: string }) { export function MealPairingButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("recipe");
const router = useRouter(); const router = useRouter();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -71,7 +73,7 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ count: 4 }), body: JSON.stringify({ count: 4 }),
}); });
if (!res.ok) { toast.error("Failed to suggest pairings"); return; } if (!res.ok) { toast.error(t("pairingMealFailed")); return; }
const data = await res.json() as { pairings: Pairing[] }; const data = await res.json() as { pairings: Pairing[] };
setPairings(data.pairings); setPairings(data.pairings);
} finally { } finally {
@@ -101,7 +103,7 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: pairing.name }), body: JSON.stringify({ prompt: pairing.name }),
}); });
if (!genRes.ok) { toast.error(`Failed to generate "${pairing.name}"`); continue; } if (!genRes.ok) { toast.error(t("pairingGenerateFailed", { name: pairing.name })); continue; }
const generated = await genRes.json() as { const generated = await genRes.json() as {
title: string; description?: string; baseServings?: number; prepMins?: number; title: string; description?: string; baseServings?: number; prepMins?: number;
cookMins?: number; difficulty?: string; dietaryTags?: Record<string, boolean>; cookMins?: number; difficulty?: string; dietaryTags?: Record<string, boolean>;
@@ -113,11 +115,11 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true }), body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true }),
}); });
if (!saveRes.ok) { toast.error(`Failed to save "${pairing.name}"`); continue; } if (!saveRes.ok) { toast.error(t("pairingSaveFailed", { name: pairing.name })); continue; }
const saved = await saveRes.json() as { id: string }; const saved = await saveRes.json() as { id: string };
savedIds.push(saved.id); savedIds.push(saved.id);
} catch { } catch {
toast.error(`Error generating "${pairing.name}"`); toast.error(t("pairingGenerateFailed", { name: pairing.name }));
} }
} }
@@ -126,10 +128,10 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
setOpen(false); setOpen(false);
if (savedIds.length === 1) { if (savedIds.length === 1) {
toast.success("Recipe generated — review before publishing"); toast.success(t("pairingSuccess"));
router.push(`/recipes/${savedIds[0]}/edit`); router.push(`/recipes/${savedIds[0]}/edit`);
} else if (savedIds.length > 1) { } else if (savedIds.length > 1) {
toast.success(`${savedIds.length} recipes generated — find them in your library`); toast.success(t("pairingBulkSuccess", { count: savedIds.length }));
router.push("/recipes"); router.push("/recipes");
} }
} }
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Camera, Loader2 } from "lucide-react"; import { Camera, Loader2 } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -8,6 +9,7 @@ import { Button } from "@/components/ui/button";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar"; import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
export function PhotoImportButton() { export function PhotoImportButton() {
const t = useTranslations("recipe");
const router = useRouter(); const router = useRouter();
const fileRef = useRef<HTMLInputElement>(null); const fileRef = useRef<HTMLInputElement>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -52,7 +54,7 @@ export function PhotoImportButton() {
const { id } = await res.json() as { id: string }; const { id } = await res.json() as { id: string };
router.push(`/recipes/${id}/edit`); router.push(`/recipes/${id}/edit`);
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to import recipe from photo."); toast.error(err instanceof Error ? err.message : t("photoImportFailed"));
} finally { } finally {
setLoading(false); setLoading(false);
// Reset input so the same file can be re-selected // Reset input so the same file can be re-selected
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState, useRef } from "react"; import { useState, useRef } from "react";
import { useTranslations } from "next-intl";
import { Upload, X, Star } from "lucide-react"; import { Upload, X, Star } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { getPublicUrl } from "@/lib/storage"; import { getPublicUrl } from "@/lib/storage";
@@ -20,6 +21,7 @@ export function PhotoUploader({
photos: PhotoEntry[]; photos: PhotoEntry[];
onChange: (photos: PhotoEntry[]) => void; onChange: (photos: PhotoEntry[]) => void;
}) { }) {
const t = useTranslations("recipeForm");
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
@@ -72,7 +74,7 @@ export function PhotoUploader({
type="button" type="button"
onClick={() => setCover(photo.key)} onClick={() => setCover(photo.key)}
className="rounded-full bg-white/20 p-1 hover:bg-white/40 transition-colors" className="rounded-full bg-white/20 p-1 hover:bg-white/40 transition-colors"
title="Set as cover" title={t("setCover")}
> >
<Star className={`h-3 w-3 ${photo.isCover ? "text-yellow-400" : "text-white"}`} /> <Star className={`h-3 w-3 ${photo.isCover ? "text-yellow-400" : "text-white"}`} />
</button> </button>
@@ -80,7 +82,7 @@ export function PhotoUploader({
type="button" type="button"
onClick={() => remove(photo.key)} onClick={() => remove(photo.key)}
className="rounded-full bg-white/20 p-1 hover:bg-red-500/80 transition-colors" className="rounded-full bg-white/20 p-1 hover:bg-red-500/80 transition-colors"
title="Remove" title={t("removePhoto")}
> >
<X className="h-3 w-3 text-white" /> <X className="h-3 w-3 text-white" />
</button> </button>
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState, useRef, useEffect } from "react"; import { useState, useRef, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet"; import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
@@ -19,6 +20,7 @@ type Props = {
}; };
export function RecipeChatPanel({ recipeId, recipeTitle }: Props) { export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
const t = useTranslations("recipeChat");
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [messages, setMessages] = useState<Message[]>([]); const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState(""); const [input, setInput] = useState("");
@@ -49,12 +51,12 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
const data = await res.json() as { answer?: string; error?: string }; const data = await res.json() as { answer?: string; error?: string };
setMessages((prev) => [ setMessages((prev) => [
...prev, ...prev,
{ role: "assistant", content: data.answer ?? "Sorry, I couldn't answer that." }, { role: "assistant", content: data.answer ?? t("sorry") },
]); ]);
} catch { } catch {
setMessages((prev) => [ setMessages((prev) => [
...prev, ...prev,
{ role: "assistant", content: "Something went wrong. Please try again." }, { role: "assistant", content: t("error") },
]); ]);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -62,10 +64,10 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
}; };
const suggestions = [ const suggestions = [
"Can I substitute any ingredients?", t("suggestion1"),
"How do I know when it's done?", t("suggestion2"),
"Can I make this ahead of time?", t("suggestion3"),
"What can I serve with this?", t("suggestion4"),
]; ];
return ( return (
@@ -75,7 +77,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
size="icon" size="icon"
className="fixed bottom-6 right-6 h-12 w-12 rounded-full shadow-lg z-40" className="fixed bottom-6 right-6 h-12 w-12 rounded-full shadow-lg z-40"
onClick={() => setOpen(true)} onClick={() => setOpen(true)}
aria-label="Ask AI about this recipe" aria-label={t("ariaLabel")}
> >
<MessageCircle className="h-5 w-5" /> <MessageCircle className="h-5 w-5" />
</Button> </Button>
@@ -85,7 +87,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0"> <SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
<SheetTitle className="text-base flex items-center gap-2"> <SheetTitle className="text-base flex items-center gap-2">
<Bot className="h-4 w-4 text-primary" /> <Bot className="h-4 w-4 text-primary" />
Ask about this recipe {t("title")}
</SheetTitle> </SheetTitle>
<p className="text-xs text-muted-foreground text-left">{recipeTitle}</p> <p className="text-xs text-muted-foreground text-left">{recipeTitle}</p>
</SheetHeader> </SheetHeader>
@@ -94,7 +96,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
{messages.length === 0 && ( {messages.length === 0 && (
<div className="space-y-3"> <div className="space-y-3">
<p className="text-sm text-muted-foreground text-center py-4"> <p className="text-sm text-muted-foreground text-center py-4">
Ask anything about this recipe ingredients, techniques, substitutions, timing {t("intro")}
</p> </p>
<div className="space-y-2"> <div className="space-y-2">
{suggestions.map((s) => ( {suggestions.map((s) => (
@@ -163,7 +165,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
<Input <Input
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={(e) => setInput(e.target.value)}
placeholder="Ask a question…" placeholder={t("inputPlaceholder")}
disabled={loading} disabled={loading}
className="flex-1" className="flex-1"
autoComplete="off" autoComplete="off"
+6 -4
View File
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState, useCallback } from "react"; import { useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks } from "lucide-react"; import { Trash2, Globe, Lock, Link2, X, Check, ListChecks } from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button"; import { Button, buttonVariants } from "@/components/ui/button";
import { import {
@@ -173,6 +174,7 @@ function SelectableRecipeCard({
} }
export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] }) { export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] }) {
const t = useTranslations("recipe");
const [recipes, setRecipes] = useState(initialRecipes); const [recipes, setRecipes] = useState(initialRecipes);
const [selectMode, setSelectMode] = useState(false); const [selectMode, setSelectMode] = useState(false);
const [selected, setSelected] = useState<Set<string>>(new Set()); const [selected, setSelected] = useState<Set<string>>(new Set());
@@ -208,10 +210,10 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
}); });
if (!res.ok) throw new Error("Delete failed"); if (!res.ok) throw new Error("Delete failed");
setRecipes((prev) => prev.filter((r) => !selected.has(r.id))); setRecipes((prev) => prev.filter((r) => !selected.has(r.id)));
toast.success(`${selected.size} recipe${selected.size !== 1 ? "s" : ""} deleted`); toast.success(t("bulkDeleted", { count: selected.size }));
exitSelect(); exitSelect();
} catch { } catch {
toast.error("Delete failed"); toast.error(t("bulkDeleteFailed"));
} finally { } finally {
setBusy(false); setBusy(false);
} }
@@ -229,10 +231,10 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
setRecipes((prev) => setRecipes((prev) =>
prev.map((r) => selected.has(r.id) ? { ...r, visibility } : r) prev.map((r) => selected.has(r.id) ? { ...r, visibility } : r)
); );
toast.success(`${selected.size} recipe${selected.size !== 1 ? "s" : ""} set to ${visibility}`); toast.success(t("bulkVisibility", { count: selected.size, visibility }));
exitSelect(); exitSelect();
} catch { } catch {
toast.error("Update failed"); toast.error(t("bulkUpdateFailed"));
} finally { } finally {
setBusy(false); setBusy(false);
} }
@@ -22,13 +22,14 @@ import { UrlImportDialog } from "./url-import-dialog";
function TagFilterInput({ value, onChange }: { value: string; onChange: (v: string) => void }) { function TagFilterInput({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const [local, setLocal] = useState(value); const [local, setLocal] = useState(value);
const t = useTranslations("recipes");
return ( return (
<input <input
value={local} value={local}
onChange={(e) => setLocal(e.target.value)} onChange={(e) => setLocal(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") onChange(local); }} onKeyDown={(e) => { if (e.key === "Enter") onChange(local); }}
onBlur={() => onChange(local)} onBlur={() => onChange(local)}
placeholder="Filter by tag…" placeholder={t("filterByTag")}
className="w-full h-7 px-2 text-sm rounded-md border border-input bg-background focus:outline-none focus:ring-1 focus:ring-ring" className="w-full h-7 px-2 text-sm rounded-md border border-input bg-background focus:outline-none focus:ring-1 focus:ring-ring"
/> />
); );
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { Minus, Plus, Sparkles, X } from "lucide-react"; import { Minus, Plus, Sparkles, X } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { scaleQuantity, hasQuantity } from "@/lib/fractions"; import { scaleQuantity, hasQuantity } from "@/lib/fractions";
@@ -35,6 +36,7 @@ export function ServingScaler({
recipeId?: string; recipeId?: string;
onAiScale?: (ingredients: ScaledIngredient[] | null) => void; onAiScale?: (ingredients: ScaledIngredient[] | null) => void;
}) { }) {
const t = useTranslations("servingScaler");
const [servings, setServings] = useState(baseServings); const [servings, setServings] = useState(baseServings);
const [aiScaledIngredients, setAiScaledIngredients] = useState<ScaledIngredient[] | null>(null); const [aiScaledIngredients, setAiScaledIngredients] = useState<ScaledIngredient[] | null>(null);
const [aiScaling, setAiScaling] = useState(false); const [aiScaling, setAiScaling] = useState(false);
@@ -67,7 +69,7 @@ export function ServingScaler({
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="flex items-center gap-3 flex-wrap"> <div className="flex items-center gap-3 flex-wrap">
<span className="text-sm font-medium text-muted-foreground">Servings</span> <span className="text-sm font-medium text-muted-foreground">{t("servings")}</span>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
variant="outline" variant="outline"
@@ -94,7 +96,7 @@ export function ServingScaler({
className="text-xs text-muted-foreground hover:text-foreground underline" className="text-xs text-muted-foreground hover:text-foreground underline"
onClick={() => setServings(baseServings)} onClick={() => setServings(baseServings)}
> >
reset {t("reset")}
</button> </button>
)} )}
{recipeId && servings !== baseServings && ( {recipeId && servings !== baseServings && (
@@ -106,7 +108,7 @@ export function ServingScaler({
disabled={aiScaling} disabled={aiScaling}
> >
<Sparkles className="h-3 w-3" /> <Sparkles className="h-3 w-3" />
{aiScaling ? "Scaling" : "AI Scale"} {aiScaling ? t("scaling") : t("aiScale")}
</Button> </Button>
)} )}
</div> </div>
@@ -114,7 +116,7 @@ export function ServingScaler({
{aiScaledIngredients && ( {aiScaledIngredients && (
<div className="flex items-center gap-2 text-xs text-muted-foreground"> <div className="flex items-center gap-2 text-xs text-muted-foreground">
<Sparkles className="h-3 w-3 shrink-0" /> <Sparkles className="h-3 w-3 shrink-0" />
<span>AI-scaled quantities shown below</span> <span>{t("aiScaledNote")}</span>
<button <button
className="ml-auto hover:text-foreground" className="ml-auto hover:text-foreground"
onClick={dismissAiScale} onClick={dismissAiScale}
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { Shuffle, Loader2 } from "lucide-react"; import { Shuffle, Loader2 } from "lucide-react";
import { import {
Popover, Popover,
@@ -29,6 +30,7 @@ export function SubstituteIngredientPopover({
ingredient: string; ingredient: string;
recipeTitle: string; recipeTitle: string;
}) { }) {
const t = useTranslations("substitute");
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [substitutions, setSubstitutions] = useState<Substitution[]>([]); const [substitutions, setSubstitutions] = useState<Substitution[]>([]);
@@ -47,14 +49,14 @@ export function SubstituteIngredientPopover({
}); });
if (!res.ok) { if (!res.ok) {
const body = await res.json().catch(() => null) as { error?: string } | null; const body = await res.json().catch(() => null) as { error?: string } | null;
setError(body?.error ?? "Couldn't fetch substitutes."); setError(body?.error ?? t("fetchError"));
return; return;
} }
const data = await res.json() as { substitutions: Substitution[] }; const data = await res.json() as { substitutions: Substitution[] };
setSubstitutions(data.substitutions); setSubstitutions(data.substitutions);
setFetched(true); setFetched(true);
} catch { } catch {
setError("Couldn't fetch substitutes."); setError(t("fetchError"));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -69,18 +71,18 @@ export function SubstituteIngredientPopover({
<Popover open={open} onOpenChange={handleOpen}> <Popover open={open} onOpenChange={handleOpen}>
<PopoverTrigger <PopoverTrigger
className="h-5 w-5 opacity-0 group-hover:opacity-60 hover:opacity-100 transition-opacity shrink-0 inline-flex items-center justify-center rounded hover:bg-accent" className="h-5 w-5 opacity-0 group-hover:opacity-60 hover:opacity-100 transition-opacity shrink-0 inline-flex items-center justify-center rounded hover:bg-accent"
title={`Substitute for ${ingredient}`} title={t("titleFor", { ingredient })}
> >
<Shuffle className="h-3 w-3" /> <Shuffle className="h-3 w-3" />
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-80 p-3 space-y-3" align="start"> <PopoverContent className="w-80 p-3 space-y-3" align="start">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide"> <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
Substitutes for <span className="text-foreground normal-case">{ingredient}</span> {t("substitutesFor")} <span className="text-foreground normal-case">{ingredient}</span>
</p> </p>
{loading && ( {loading && (
<div className="flex items-center gap-2 py-2 text-sm text-muted-foreground"> <div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" /> <Loader2 className="h-3.5 w-3.5 animate-spin" />
Finding substitutes {t("finding")}
</div> </div>
)} )}
{!loading && substitutions.length > 0 && ( {!loading && substitutions.length > 0 && (
@@ -103,7 +105,7 @@ export function SubstituteIngredientPopover({
<p className="text-sm text-destructive py-1">{error}</p> <p className="text-sm text-destructive py-1">{error}</p>
)} )}
{!loading && fetched && substitutions.length === 0 && ( {!loading && fetched && substitutions.length === 0 && (
<p className="text-sm text-muted-foreground py-1">No substitutions found.</p> <p className="text-sm text-muted-foreground py-1">{t("noneFound")}</p>
)} )}
</PopoverContent> </PopoverContent>
</Popover> </Popover>
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Languages, Loader2 } from "lucide-react"; import { Languages, Loader2 } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -32,6 +33,7 @@ const LANGUAGES = [
]; ];
export function TranslateButton({ recipeId }: { recipeId: string }) { export function TranslateButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("ai.translate");
const router = useRouter(); const router = useRouter();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [targetLanguage, setTargetLanguage] = useState("French"); const [targetLanguage, setTargetLanguage] = useState("French");
@@ -48,12 +50,12 @@ export function TranslateButton({ recipeId }: { recipeId: string }) {
if (!res.ok) { if (!res.ok) {
const err = await res.json() as { error?: string }; const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to translate recipe"); toast.error(err.error ?? t("error"));
return; return;
} }
const { id } = await res.json() as { id: string }; const { id } = await res.json() as { id: string };
toast.success("Translation saved as new draft recipe"); toast.success(t("success"));
setOpen(false); setOpen(false);
router.push(`/recipes/${id}/edit`); router.push(`/recipes/${id}/edit`);
} finally { } finally {
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar"; import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { Sparkles, Loader2, ChevronRight, Replace } from "lucide-react"; import { Sparkles, Loader2, ChevronRight, Replace } from "lucide-react";
@@ -61,6 +62,7 @@ export function VariationsDialog({
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
}) { }) {
const t = useTranslations("recipe");
const router = useRouter(); const router = useRouter();
const [generating, setGenerating] = useState(false); const [generating, setGenerating] = useState(false);
const [applying, setApplying] = useState<number | null>(null); const [applying, setApplying] = useState<number | null>(null);
@@ -170,7 +172,7 @@ export function VariationsDialog({
<Label htmlFor="directions">Directions <span className="text-muted-foreground font-normal">(optional)</span></Label> <Label htmlFor="directions">Directions <span className="text-muted-foreground font-normal">(optional)</span></Label>
<Textarea <Textarea
id="directions" id="directions"
placeholder="e.g. make it vegan, use only pantry staples, reduce sugar…" placeholder={t("variationsDirectionsPlaceholder")}
value={directions} value={directions}
onChange={(e) => setDirections(e.target.value)} onChange={(e) => setDirections(e.target.value)}
disabled={generating} disabled={generating}
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { History, RotateCcw, ChevronDown } from "lucide-react"; import { History, RotateCcw, ChevronDown } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -39,6 +40,8 @@ function formatDate(dateStr: string): string {
} }
export function VersionHistoryButton({ recipeId }: { recipeId: string }) { export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("recipe");
const tForm = useTranslations("recipeForm");
const router = useRouter(); const router = useRouter();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [versions, setVersions] = useState<VersionSummary[]>([]); const [versions, setVersions] = useState<VersionSummary[]>([]);
@@ -91,7 +94,7 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
setOpen(false); setOpen(false);
router.refresh(); router.refresh();
} else { } else {
toast.error("Failed to restore version"); toast.error(t("historyRestoreFailed"));
} }
} finally { } finally {
setRestoringId(null); setRestoringId(null);
@@ -143,7 +146,7 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
variant="ghost" variant="ghost"
size="icon" size="icon"
className="h-7 w-7 shrink-0" className="h-7 w-7 shrink-0"
title="Expand" title={tForm("expand")}
onClick={() => void handleExpand(v)} onClick={() => void handleExpand(v)}
> >
<ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`} /> <ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`} />
@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Flame, Clock, ChefHat, Search, Sparkles, Wand2, ArrowRight } from "lucide-react"; import { Flame, Clock, ChefHat, Search, Sparkles, Wand2, ArrowRight } from "lucide-react";
import { useTranslations } from "next-intl";
import type { RecipeResult as ExploreRecipeResult } from "@/app/(app)/explore/page"; import type { RecipeResult as ExploreRecipeResult } from "@/app/(app)/explore/page";
const DIFFICULTY_COLORS: Record<string, string> = { const DIFFICULTY_COLORS: Record<string, string> = {
@@ -100,6 +101,8 @@ type Props = {
export function ExplorePageContent({ trending, recent, initialQuery }: Props) { export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const t = useTranslations("explore");
const tCommon = useTranslations("common");
const [inputValue, setInputValue] = useState(initialQuery); const [inputValue, setInputValue] = useState(initialQuery);
const [query, setQuery] = useState(initialQuery); const [query, setQuery] = useState(initialQuery);
@@ -243,7 +246,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
ref={inputRef} ref={inputRef}
value={inputValue} value={inputValue}
onChange={(e) => handleInputChange(e.target.value)} onChange={(e) => handleInputChange(e.target.value)}
placeholder="Search public recipes…" placeholder={t("searchPlaceholder")}
className="pl-10 h-12 text-base" className="pl-10 h-12 text-base"
autoFocus={!!initialQuery} autoFocus={!!initialQuery}
/> />
@@ -253,7 +256,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
<Select value={difficulty} onValueChange={handleDifficultyChange}> <Select value={difficulty} onValueChange={handleDifficultyChange}>
<SelectTrigger className="w-40"> <SelectTrigger className="w-40">
<SelectValue placeholder="Difficulty" /> <SelectValue placeholder={tCommon("difficulty")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="any">Any difficulty</SelectItem> <SelectItem value="any">Any difficulty</SelectItem>
@@ -265,7 +268,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
<Input <Input
type="number" type="number"
min={1} min={1}
placeholder="Max minutes" placeholder={t("maxMinutes")}
value={maxMins} value={maxMins}
onChange={(e) => handleMaxMinsChange(e.target.value)} onChange={(e) => handleMaxMinsChange(e.target.value)}
className="w-36" className="w-36"
@@ -342,7 +345,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
<Input <Input
value={ideasPrompt} value={ideasPrompt}
onChange={(e) => setIdeasPrompt(e.target.value)} onChange={(e) => setIdeasPrompt(e.target.value)}
placeholder="e.g. quick weeknight dinners, Italian comfort food…" placeholder={t("aiSearchPlaceholder")}
className="bg-background" className="bg-background"
/> />
<Button type="submit" disabled={ideasLoading} variant="secondary" className="shrink-0"> <Button type="submit" disabled={ideasLoading} variant="secondary" className="shrink-0">
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -30,6 +31,7 @@ function formatDate(iso: string) {
} }
export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) { export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
const t = useTranslations("settingsForm");
const [keys, setKeys] = useState<ApiKey[]>(initialKeys); const [keys, setKeys] = useState<ApiKey[]>(initialKeys);
const [name, setName] = useState(""); const [name, setName] = useState("");
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
@@ -48,7 +50,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
}); });
if (!res.ok) { if (!res.ok) {
const data = await res.json() as { error?: string }; const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to create API key"); throw new Error(data.error ?? t("apiKeyCreateFailed"));
} }
const data = await res.json() as CreateApiKeyResponse; const data = await res.json() as CreateApiKeyResponse;
setNewKey(data.key); setNewKey(data.key);
@@ -58,7 +60,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
]); ]);
setName(""); setName("");
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create API key"); toast.error(err instanceof Error ? err.message : t("apiKeyCreateFailed"));
} finally { } finally {
setCreating(false); setCreating(false);
} }
@@ -69,11 +71,11 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
const res = await fetch(`/api/v1/api-keys/${id}`, { method: "DELETE" }); const res = await fetch(`/api/v1/api-keys/${id}`, { method: "DELETE" });
if (!res.ok) { if (!res.ok) {
const data = await res.json() as { error?: string }; const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to revoke API key"); throw new Error(data.error ?? t("apiKeyRevokeFailed"));
} }
setKeys((prev) => prev.filter((k) => k.id !== id)); setKeys((prev) => prev.filter((k) => k.id !== id));
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to revoke API key"); toast.error(err instanceof Error ? err.message : t("apiKeyRevokeFailed"));
} }
} }
@@ -84,7 +86,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
setCopied(true); setCopied(true);
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
} catch { } catch {
toast.error("Failed to copy to clipboard"); toast.error(t("copyFailed"));
} }
} }
@@ -97,7 +99,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
<div className="flex gap-2"> <div className="flex gap-2">
<Input <Input
id="key-name" id="key-name"
placeholder="e.g. My app" placeholder={t("apiKeyNamePlaceholder")}
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
maxLength={100} maxLength={100}
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner"; import { toast } from "sonner";
import { Key, Trash2, Check } from "lucide-react"; import { Key, Trash2, Check } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -17,6 +18,7 @@ const PROVIDERS: { id: Provider; label: string; placeholder: string }[] = [
]; ];
export function ByokManager({ initialKeys }: { initialKeys: string[] }) { export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
const t = useTranslations("settingsForm");
const [configuredKeys, setConfiguredKeys] = useState<Set<string>>(new Set(initialKeys)); const [configuredKeys, setConfiguredKeys] = useState<Set<string>>(new Set(initialKeys));
const [inputs, setInputs] = useState<Partial<Record<Provider, string>>>({}); const [inputs, setInputs] = useState<Partial<Record<Provider, string>>>({});
const [saving, setSaving] = useState<Provider | null>(null); const [saving, setSaving] = useState<Provider | null>(null);
@@ -35,9 +37,9 @@ export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
if (res.ok) { if (res.ok) {
setConfiguredKeys((prev) => new Set([...prev, provider])); setConfiguredKeys((prev) => new Set([...prev, provider]));
setInputs((prev) => ({ ...prev, [provider]: "" })); setInputs((prev) => ({ ...prev, [provider]: "" }));
toast.success(`${provider} key saved`); toast.success(t("byokSaved", { provider }));
} else { } else {
toast.error("Failed to save key"); toast.error(t("byokSaveFailed"));
} }
} finally { } finally {
setSaving(null); setSaving(null);
@@ -50,9 +52,9 @@ export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
const res = await fetch(`/api/v1/ai-keys/${provider}`, { method: "DELETE" }); const res = await fetch(`/api/v1/ai-keys/${provider}`, { method: "DELETE" });
if (res.ok) { if (res.ok) {
setConfiguredKeys((prev) => { const s = new Set(prev); s.delete(provider); return s; }); setConfiguredKeys((prev) => { const s = new Set(prev); s.delete(provider); return s; });
toast.success(`${provider} key removed`); toast.success(t("byokRemoved", { provider }));
} else { } else {
toast.error("Failed to remove key"); toast.error(t("byokRemoveFailed"));
} }
} finally { } finally {
setRemoving(null); setRemoving(null);
@@ -14,6 +14,7 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { toast } from "sonner"; import { toast } from "sonner";
import { useTranslations } from "next-intl";
type Provider = "openai" | "anthropic" | "openrouter" | "ollama" | ""; type Provider = "openai" | "anthropic" | "openrouter" | "ollama" | "";
@@ -59,6 +60,7 @@ type Prefs = {
}; };
export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null }) { export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null }) {
const t = useTranslations("settingsForm");
const [prefs, setPrefs] = useState<Prefs>(initialPrefs ?? {}); const [prefs, setPrefs] = useState<Prefs>(initialPrefs ?? {});
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -75,9 +77,9 @@ export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null })
body: JSON.stringify(prefs), body: JSON.stringify(prefs),
}); });
if (!res.ok) throw new Error("Save failed"); if (!res.ok) throw new Error("Save failed");
toast.success("Model preferences saved"); toast.success(t("modelSaved"));
} catch { } catch {
toast.error("Failed to save"); toast.error(t("modelSaveFailed"));
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -132,7 +134,7 @@ export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null })
onValueChange={(v) => setField(modelKey, v === "default" ? null : v)} onValueChange={(v) => setField(modelKey, v === "default" ? null : v)}
> >
<SelectTrigger className="h-8 text-sm"> <SelectTrigger className="h-8 text-sm">
<SelectValue placeholder="Default" /> <SelectValue placeholder={t("modelDefaultPlaceholder")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="default"> <SelectItem value="default">
@@ -149,7 +151,7 @@ export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null })
) : ( ) : (
<Input <Input
className="h-8 text-sm" className="h-8 text-sm"
placeholder={provider ? "e.g. llama3.2" : "—"} placeholder={provider ? t("modelNamePlaceholder") : "—"}
value={model} value={model}
onChange={(e) => setField(modelKey, e.target.value)} onChange={(e) => setField(modelKey, e.target.value)}
disabled={!provider} disabled={!provider}
@@ -2,6 +2,7 @@
import { useState } from "react"; import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { useTranslations } from "next-intl";
import { toast } from "sonner"; import { toast } from "sonner";
import { ChevronDown, ChevronUp, RotateCcw } from "lucide-react"; import { ChevronDown, ChevronUp, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -65,6 +66,7 @@ function formatDateTime(iso: string) {
} }
export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) { export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
const t = useTranslations("settingsForm");
const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks); const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
const [url, setUrl] = useState(""); const [url, setUrl] = useState("");
const [selectedEvents, setSelectedEvents] = useState<WebhookEventType[]>([]); const [selectedEvents, setSelectedEvents] = useState<WebhookEventType[]>([]);
@@ -94,7 +96,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
}); });
if (!res.ok) { if (!res.ok) {
const data = await res.json() as { error?: string }; const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to create webhook"); throw new Error(data.error ?? t("webhookCreateFailed"));
} }
const data = await res.json() as CreateWebhookResponse; const data = await res.json() as CreateWebhookResponse;
setNewSecret({ id: data.id, secret: data.secret }); setNewSecret({ id: data.id, secret: data.secret });
@@ -105,7 +107,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
setUrl(""); setUrl("");
setSelectedEvents([]); setSelectedEvents([]);
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create webhook"); toast.error(err instanceof Error ? err.message : t("webhookCreateFailed"));
} finally { } finally {
setCreating(false); setCreating(false);
} }
@@ -116,12 +118,12 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
const res = await fetch(`/api/v1/webhooks/${id}`, { method: "DELETE" }); const res = await fetch(`/api/v1/webhooks/${id}`, { method: "DELETE" });
if (!res.ok && res.status !== 204) { if (!res.ok && res.status !== 204) {
const data = await res.json() as { error?: string }; const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to delete webhook"); throw new Error(data.error ?? t("webhookDeleteFailed"));
} }
setWebhookList((prev) => prev.filter((w) => w.id !== id)); setWebhookList((prev) => prev.filter((w) => w.id !== id));
if (newSecret?.id === id) setNewSecret(null); if (newSecret?.id === id) setNewSecret(null);
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to delete webhook"); toast.error(err instanceof Error ? err.message : t("webhookDeleteFailed"));
} }
} }
@@ -134,13 +136,13 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
}); });
if (!res.ok) { if (!res.ok) {
const data = await res.json() as { error?: string }; const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Failed to update webhook"); throw new Error(data.error ?? t("webhookUpdateFailed"));
} }
setWebhookList((prev) => setWebhookList((prev) =>
prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w)) prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w))
); );
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to update webhook"); toast.error(err instanceof Error ? err.message : t("webhookUpdateFailed"));
} }
} }
@@ -151,7 +153,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
setCopied(true); setCopied(true);
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
} catch { } catch {
toast.error("Failed to copy to clipboard"); toast.error(t("copyFailed"));
} }
} }
@@ -186,9 +188,9 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
body: JSON.stringify({ deliveryId }), body: JSON.stringify({ deliveryId }),
}); });
if (res.ok) { if (res.ok) {
toast.success("Redelivery queued"); toast.success(t("redeliverySuccess"));
} else { } else {
toast.error("Failed to redeliver"); toast.error(t("redeliveryFailed"));
} }
} finally { } finally {
setRedelivering(null); setRedelivering(null);
@@ -210,7 +212,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
<Input <Input
id="webhook-url" id="webhook-url"
type="url" type="url"
placeholder="https://example.com/webhook" placeholder={t("webhookUrlPlaceholder")}
value={url} value={url}
onChange={(e) => setUrl(e.target.value)} onChange={(e) => setUrl(e.target.value)}
maxLength={2048} maxLength={2048}
@@ -242,7 +244,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
</div> </div>
<Button type="submit" disabled={creating || !url.trim()}> <Button type="submit" disabled={creating || !url.trim()}>
{creating ? "Adding" : "Add webhook"} {creating ? t("webhookAdding") : t("webhookAddButton")}
</Button> </Button>
</form> </form>
@@ -3,6 +3,7 @@
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
import { MessageCircle, Reply, Trash2 } from "lucide-react"; import { MessageCircle, Reply, Trash2 } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
@@ -97,6 +98,7 @@ function CommentItem({
}) { }) {
const [showReply, setShowReply] = useState(false); const [showReply, setShowReply] = useState(false);
const isOwn = comment.userId === currentUserId; const isOwn = comment.userId === currentUserId;
const t = useTranslations("social");
async function deleteComment() { async function deleteComment() {
const res = await fetch(`/api/v1/comments/${comment.id}`, { method: "DELETE" }); const res = await fetch(`/api/v1/comments/${comment.id}`, { method: "DELETE" });
@@ -141,7 +143,7 @@ function CommentItem({
recipeId={recipeId} recipeId={recipeId}
parentId={comment.id} parentId={comment.id}
onSubmit={() => { setShowReply(false); onRefresh(); }} onSubmit={() => { setShowReply(false); onRefresh(); }}
placeholder="Reply…" placeholder={t("replyPlaceholder")}
onCancel={() => setShowReply(false)} onCancel={() => setShowReply(false)}
/> />
)} )}
@@ -191,6 +193,7 @@ export function CommentsSection({
}) { }) {
const [comments, setComments] = useState<Comment[]>([]); const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const t = useTranslations("social");
const load = useCallback(async () => { const load = useCallback(async () => {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments`); const res = await fetch(`/api/v1/recipes/${recipeId}/comments`);
@@ -212,7 +215,7 @@ export function CommentsSection({
</div> </div>
{currentUserId && ( {currentUserId && (
<CommentForm recipeId={recipeId} onSubmit={load} placeholder="Share your thoughts…" /> <CommentForm recipeId={recipeId} onSubmit={load} placeholder={t("commentPlaceholder")} />
)} )}
{loading ? ( {loading ? (
+14
View File
@@ -0,0 +1,14 @@
import en from "@/messages/en.json";
import fr from "@/messages/fr.json";
const catalogs = { en, fr } as const;
export type Locale = keyof typeof catalogs;
export function getMessages(locale: string | undefined | null) {
return catalogs[locale as Locale] ?? catalogs.en;
}
export function formatMessage(template: string, vars: Record<string, string | number>) {
return template.replace(/\{(\w+)\}/g, (_, key) => String(vars[key] ?? ""));
}
+96 -3
View File
@@ -44,6 +44,10 @@
"pairingGenerateFailed": "Failed to generate \"{name}\"", "pairingGenerateFailed": "Failed to generate \"{name}\"",
"pairingSaveFailed": "Failed to save \"{name}\"", "pairingSaveFailed": "Failed to save \"{name}\"",
"pairingSuccess": "Recipe generated — review before publishing", "pairingSuccess": "Recipe generated — review before publishing",
"pairingBulkSuccess": "{count} recipes generated — find them in your library",
"cookAction": "Cook",
"adaptConstraintPlaceholder": "e.g. Make it vegan, lower the calories, use pantry staples only, gluten-free…",
"photoImportFailed": "Failed to import recipe from photo.",
"shoppingListCreateFailed": "Failed to create list", "shoppingListCreateFailed": "Failed to create list",
"shoppingListAddFailed": "Failed to add ingredients", "shoppingListAddFailed": "Failed to add ingredients",
"bulkDeleted": "{count, plural, one {1 recipe deleted} other {{count} recipes deleted}}", "bulkDeleted": "{count, plural, one {1 recipe deleted} other {{count} recipes deleted}}",
@@ -136,6 +140,60 @@
"metric": "Metric", "metric": "Metric",
"imperial": "Imperial" "imperial": "Imperial"
}, },
"print": {
"footer": "Printed from Epicure",
"day": "Day",
"srv": " · {count} srv",
"days": {
"mon": "Monday",
"tue": "Tuesday",
"wed": "Wednesday",
"thu": "Thursday",
"fri": "Friday",
"sat": "Saturday",
"sun": "Sunday"
}
},
"publicRecipe": {
"publicRecipeBy": "Public recipe by",
"viewInLibrary": "View in your library",
"signUpFree": "Sign up free",
"logIn": "Log in",
"wantToSave": "Want to save this recipe?",
"wantToSaveDescription": "Create a free account to save recipes, scale servings, and build your own library.",
"getStartedFree": "Get started free"
},
"substitute": {
"fetchError": "Couldn't fetch substitutes.",
"titleFor": "Substitute for {ingredient}",
"substitutesFor": "Substitutes for",
"finding": "Finding substitutes…",
"noneFound": "No substitutions found."
},
"recipeChat": {
"sorry": "Sorry, I couldn't answer that.",
"error": "Something went wrong. Please try again.",
"suggestion1": "Can I substitute any ingredients?",
"suggestion2": "How do I know when it's done?",
"suggestion3": "Can I make this ahead of time?",
"suggestion4": "What can I serve with this?",
"ariaLabel": "Ask AI about this recipe",
"title": "Ask about this recipe",
"intro": "Ask anything about this recipe — ingredients, techniques, substitutions, timing…",
"inputPlaceholder": "Ask a question…"
},
"servingScaler": {
"servings": "Servings",
"reset": "Reset",
"aiScale": "AI Scale",
"scaling": "Scaling…",
"aiScaledNote": "AI-scaled quantities shown below"
},
"explore": {
"searchPlaceholder": "Search public recipes…",
"maxMinutes": "Max minutes",
"aiSearchPlaceholder": "e.g. quick weeknight dinners, Italian comfort food…"
},
"common": { "common": {
"loading": "Loading…", "loading": "Loading…",
"error": "Something went wrong", "error": "Something went wrong",
@@ -220,7 +278,8 @@
"createFirst": "Create your first recipe", "createFirst": "Create your first recipe",
"resultSingular": "result", "resultSingular": "result",
"resultPlural": "results", "resultPlural": "results",
"for": "for" "for": "for",
"filterByTag": "Filter by tag…"
}, },
"recipeForm": { "recipeForm": {
"titleLabel": "Title *", "titleLabel": "Title *",
@@ -244,6 +303,9 @@
"ingredient": "Ingredient", "ingredient": "Ingredient",
"note": "Note", "note": "Note",
"addIngredient": "Add ingredient", "addIngredient": "Add ingredient",
"setCover": "Set as cover",
"removePhoto": "Remove",
"expand": "Expand",
"steps": "Steps", "steps": "Steps",
"stepPlaceholder": "Step {n}…", "stepPlaceholder": "Step {n}…",
"timerSeconds": "Timer (s)", "timerSeconds": "Timer (s)",
@@ -277,6 +339,11 @@
"noRecipes": "No recipes found", "noRecipes": "No recipes found",
"addFailed": "Failed to add", "addFailed": "Failed to add",
"addedToPantry": "{count, plural, one {1 item added to pantry} other {{count} items added to pantry}}", "addedToPantry": "{count, plural, one {1 item added to pantry} other {{count} items added to pantry}}",
"moveToPantryFailed": "Failed to move items to pantry",
"aisleOther": "Other",
"listEmptyState": "This list is empty.",
"checkedCount": "{checked}/{total} checked",
"moveToPantry": "Move {count} to pantry",
"listCreated": "List created", "listCreated": "List created",
"days": { "days": {
"mon": "Mon", "mon": "Mon",
@@ -326,7 +393,21 @@
"empty": "No shopping lists yet", "empty": "No shopping lists yet",
"listEmpty": "Empty", "listEmpty": "Empty",
"generated": "Generated", "generated": "Generated",
"items": "{checked}/{total} items" "items": "{checked}/{total} items",
"itemsChecked": "{checked}/{total} items checked",
"fromMealPlan": " · From meal plan",
"addToList": "Add to list",
"dialogTitle": "Add to shopping list",
"dialogDescription": "Add the ingredients of <strong>{title}</strong> to a shopping list.",
"scaledSuffix": "scaled)",
"loadingLists": "Loading your lists…",
"modeExisting": "Add to existing list",
"modeNew": "Create new list",
"listNamePlaceholder": "List name",
"ingredientsWillBeAdded": "{count, plural, one {1 ingredient will be added.} other {{count} ingredients will be added.}}",
"adding": "Adding…",
"addIngredients": "Add ingredients",
"addedCount": "{count} ingredients added to list"
}, },
"collections": { "collections": {
"title": "Collections", "title": "Collections",
@@ -345,7 +426,9 @@
"collectionCreated": "Collection created", "collectionCreated": "Collection created",
"collectionForked": "Collection forked to your library", "collectionForked": "Collection forked to your library",
"inviteSent": "Invitation sent", "inviteSent": "Invitation sent",
"memberRemoved": "Member removed" "memberRemoved": "Member removed",
"replyPlaceholder": "Reply…",
"commentPlaceholder": "Share your thoughts…"
}, },
"cookingMode": { "cookingMode": {
"cooking": "Cooking", "cooking": "Cooking",
@@ -363,6 +446,8 @@
"enableVoice": "Enable voice control", "enableVoice": "Enable voice control",
"stopVoice": "Stop voice", "stopVoice": "Stop voice",
"toggleIngredients": "Toggle ingredients", "toggleIngredients": "Toggle ingredients",
"pageTitle": "Cooking: {title}",
"pageTitleFallback": "Cooking Mode",
"shortcutsTitle": "Shortcuts & commands", "shortcutsTitle": "Shortcuts & commands",
"keyboardSection": "Keyboard", "keyboardSection": "Keyboard",
"voiceSection": "Voice commands", "voiceSection": "Voice commands",
@@ -423,8 +508,16 @@
"redeliveryFailed": "Failed to redeliver", "redeliveryFailed": "Failed to redeliver",
"apiKeyCreateFailed": "Failed to create API key", "apiKeyCreateFailed": "Failed to create API key",
"apiKeyRevokeFailed": "Failed to revoke API key", "apiKeyRevokeFailed": "Failed to revoke API key",
"apiKeyNamePlaceholder": "e.g. My app",
"webhookUrlPlaceholder": "https://example.com/webhook",
"webhookAdding": "Adding…",
"webhookAddButton": "Add webhook",
"modelDefaultPlaceholder": "Default",
"modelNamePlaceholder": "e.g. llama3.2",
"copyFailed": "Failed to copy to clipboard", "copyFailed": "Failed to copy to clipboard",
"byokSaved": "{provider} key saved",
"byokSaveFailed": "Failed to save key", "byokSaveFailed": "Failed to save key",
"byokRemoved": "{provider} key removed",
"byokRemoveFailed": "Failed to remove key", "byokRemoveFailed": "Failed to remove key",
"modelSaved": "Model preferences saved", "modelSaved": "Model preferences saved",
"modelSaveFailed": "Failed to save", "modelSaveFailed": "Failed to save",
+179 -5
View File
@@ -28,6 +28,32 @@
"save": "Enregistrer", "save": "Enregistrer",
"cancel": "Annuler", "cancel": "Annuler",
"delete": "Supprimer", "delete": "Supprimer",
"noIngredientsSteps": "Pas encore d'ingrédients ni d'étapes.",
"generateContent": "Générer avec l'IA",
"editManually": "Modifier manuellement",
"deleted": "Recette supprimée",
"deleteFailed": "Échec de la suppression",
"imported": "Recette importée ! Vérifiez avant de publier.",
"adapted": "Recette adaptée enregistrée comme brouillon",
"adaptFailed": "Échec de l'adaptation de la recette",
"adaptConstraintRequired": "Sélectionnez au moins un ingrédient à exclure ou ajoutez une contrainte",
"adaptConstraintPlaceholder": "ex. Rendre végétalien, réduire les calories, utiliser seulement les produits du garde-manger, sans gluten…",
"variationsDirectionsPlaceholder": "ex. rendre végétalien, utiliser uniquement les produits du garde-manger, réduire le sucre…",
"historyRestoreFailed": "Échec de la restauration de la version",
"pairingMealFailed": "Échec de la suggestion d'accompagnements",
"pairingDrinkFailed": "Échec de la suggestion de boissons",
"pairingGenerateFailed": "Échec de la génération de « {name} »",
"pairingSaveFailed": "Échec de l'enregistrement de « {name} »",
"pairingSuccess": "Recette générée — vérifiez avant de publier",
"pairingBulkSuccess": "{count} recettes générées — retrouvez-les dans votre bibliothèque",
"cookAction": "Cuisiner",
"photoImportFailed": "Échec de l'importation de la recette depuis la photo.",
"shoppingListCreateFailed": "Échec de la création de la liste",
"shoppingListAddFailed": "Échec de l'ajout des ingrédients",
"bulkDeleted": "{count, plural, one {1 recette supprimée} other {{count} recettes supprimées}}",
"bulkVisibility": "{count, plural, one {1 recette définie sur {visibility}} other {{count} recettes définies sur {visibility}}}",
"bulkDeleteFailed": "Échec de la suppression",
"bulkUpdateFailed": "Échec de la mise à jour",
"visibility": { "visibility": {
"private": "Privée", "private": "Privée",
"unlisted": "Non répertoriée", "unlisted": "Non répertoriée",
@@ -52,14 +78,32 @@
"generate": { "generate": {
"title": "Générer une recette avec l'IA", "title": "Générer une recette avec l'IA",
"description": "Décrivez ce que vous voulez cuisiner et l'IA créera une recette complète.", "description": "Décrivez ce que vous voulez cuisiner et l'IA créera une recette complète.",
"descriptionFull": "Décrivez un plat ou prenez une photo — l'IA construit la recette complète.",
"tabDescribe": "Décrire",
"tabPhoto": "Depuis une photo",
"surpriseMe": "Surprends-moi",
"prompt": "Que voulez-vous cuisiner ?", "prompt": "Que voulez-vous cuisiner ?",
"placeholder": "ex. Un risotto crémeux aux champignons et parmesan, 4 portions, niveau facile", "placeholder": "ex. Un risotto crémeux aux champignons et parmesan, 4 portions, niveau facile",
"language": "Langue", "language": "Langue de la recette",
"difficulty": "Difficulté",
"anyDifficulty": "Toutes",
"button": "Générer", "button": "Générer",
"generating": "Génération en cours…", "generating": "Génération en cours…",
"success": "Recette générée ! Vérifiez et modifiez avant de publier.", "success": "Recette générée ! Vérifiez et modifiez avant de publier.",
"error": "Échec de la génération de la recette", "error": "Échec de la génération de la recette",
"saveError": "Échec de l'enregistrement de la recette générée" "saveError": "Échec de l'enregistrement de la recette générée",
"uploadClick": "Cliquez pour importer",
"uploadDrag": "ou glissez une photo du plat",
"uploadFormats": "JPEG, PNG ou WebP · l'IA reconstituera la recette",
"analyzing": "Analyse en cours…",
"analyzePhoto": "Analyse de la photo du plat…",
"recognizeDish": "Reconnaître le plat",
"photoSuccess": "Recette reconnue ! Vérifiez et modifiez avant de publier.",
"photoError": "Échec de l'analyse de la photo",
"contentGenerated": "Ingrédients et étapes générés !",
"contentGenerateFailed": "Échec de la génération",
"contentSaveFailed": "Échec de l'enregistrement du contenu généré",
"generatingContent": "Génération du contenu de la recette…"
}, },
"variations": { "variations": {
"title": "Variations de recette par IA", "title": "Variations de recette par IA",
@@ -96,16 +140,79 @@
"metric": "Métrique", "metric": "Métrique",
"imperial": "Impérial" "imperial": "Impérial"
}, },
"print": {
"footer": "Imprimé depuis Epicure",
"day": "Jour",
"srv": " · {count} pers.",
"days": {
"mon": "Lundi",
"tue": "Mardi",
"wed": "Mercredi",
"thu": "Jeudi",
"fri": "Vendredi",
"sat": "Samedi",
"sun": "Dimanche"
}
},
"publicRecipe": {
"publicRecipeBy": "Recette publique par",
"viewInLibrary": "Voir dans votre bibliothèque",
"signUpFree": "S'inscrire gratuitement",
"logIn": "Se connecter",
"wantToSave": "Envie de sauvegarder cette recette ?",
"wantToSaveDescription": "Créez un compte gratuit pour sauvegarder des recettes, ajuster les portions et construire votre propre bibliothèque.",
"getStartedFree": "Commencer gratuitement"
},
"substitute": {
"fetchError": "Impossible de récupérer les substituts.",
"titleFor": "Substitut pour {ingredient}",
"substitutesFor": "Substituts pour",
"finding": "Recherche de substituts…",
"noneFound": "Aucune substitution trouvée."
},
"recipeChat": {
"sorry": "Désolé, je n'ai pas pu répondre à cela.",
"error": "Une erreur s'est produite. Veuillez réessayer.",
"suggestion1": "Puis-je substituer des ingrédients ?",
"suggestion2": "Comment savoir quand c'est prêt ?",
"suggestion3": "Puis-je préparer cela à l'avance ?",
"suggestion4": "Avec quoi puis-je servir ce plat ?",
"ariaLabel": "Demander à l'IA à propos de cette recette",
"title": "Poser une question sur cette recette",
"intro": "Demandez n'importe quoi sur cette recette — ingrédients, techniques, substitutions, minutage…",
"inputPlaceholder": "Posez une question…"
},
"servingScaler": {
"servings": "Portions",
"reset": "Réinitialiser",
"aiScale": "Ajuster avec l'IA",
"scaling": "Ajustement…",
"aiScaledNote": "Quantités ajustées par l'IA affichées ci-dessous"
},
"explore": {
"searchPlaceholder": "Rechercher des recettes publiques…",
"maxMinutes": "Minutes max",
"aiSearchPlaceholder": "ex. dîners rapides en semaine, cuisine réconfortante italienne…"
},
"common": { "common": {
"loading": "Chargement…", "loading": "Chargement…",
"error": "Une erreur s'est produite", "error": "Une erreur s'est produite",
"save": "Enregistrer", "save": "Enregistrer",
"saved": "Enregistré", "saved": "Enregistré",
"saveFailed": "Échec de l'enregistrement", "saveFailed": "Échec de l'enregistrement",
"deleteFailed": "Échec de la suppression",
"updateFailed": "Échec de la mise à jour",
"copyFailed": "Échec de la copie dans le presse-papiers",
"deleted": "Supprimé",
"cancel": "Annuler", "cancel": "Annuler",
"delete": "Supprimer", "delete": "Supprimer",
"confirm": "Confirmer", "confirm": "Confirmer",
"back": "Retour" "back": "Retour",
"difficulty": "Difficulté",
"anyDifficulty": "Toutes",
"editManually": "Modifier manuellement",
"surpriseMe": "Surprends-moi",
"generatingContent": "Génération du contenu de la recette…"
}, },
"auth": { "auth": {
"signIn": "Se connecter", "signIn": "Se connecter",
@@ -162,7 +269,8 @@
"createFirst": "Créer votre première recette", "createFirst": "Créer votre première recette",
"resultSingular": "résultat", "resultSingular": "résultat",
"resultPlural": "résultats", "resultPlural": "résultats",
"for": "pour" "for": "pour",
"filterByTag": "Filtrer par tag…"
}, },
"recipeForm": { "recipeForm": {
"titleLabel": "Titre *", "titleLabel": "Titre *",
@@ -183,6 +291,9 @@
"ingredient": "Ingrédient", "ingredient": "Ingrédient",
"note": "Note", "note": "Note",
"addIngredient": "Ajouter un ingrédient", "addIngredient": "Ajouter un ingrédient",
"setCover": "Définir comme couverture",
"removePhoto": "Supprimer",
"expand": "Développer",
"steps": "Étapes", "steps": "Étapes",
"stepPlaceholder": "Étape {n}…", "stepPlaceholder": "Étape {n}…",
"timerSeconds": "Minuteur (s)", "timerSeconds": "Minuteur (s)",
@@ -212,7 +323,16 @@
"addTo": "Ajouter à {day} {meal}", "addTo": "Ajouter à {day} {meal}",
"searchRecipes": "Rechercher des recettes…", "searchRecipes": "Rechercher des recettes…",
"servings": "Portions", "servings": "Portions",
"difficulty": "Difficulté",
"noRecipes": "Aucune recette trouvée", "noRecipes": "Aucune recette trouvée",
"addFailed": "Échec de l'ajout",
"addedToPantry": "{count, plural, one {1 article ajouté au garde-manger} other {{count} articles ajoutés au garde-manger}}",
"moveToPantryFailed": "Échec du déplacement des articles vers le garde-manger",
"aisleOther": "Autre",
"listEmptyState": "Cette liste est vide.",
"checkedCount": "{checked}/{total} cochés",
"moveToPantry": "Déplacer {count} vers le garde-manger",
"listCreated": "Liste créée",
"days": { "days": {
"mon": "Lun", "mon": "Lun",
"tue": "Mar", "tue": "Mar",
@@ -261,7 +381,21 @@
"empty": "Aucune liste de courses", "empty": "Aucune liste de courses",
"listEmpty": "Vide", "listEmpty": "Vide",
"generated": "Générée", "generated": "Générée",
"items": "{checked}/{total} articles" "items": "{checked}/{total} articles",
"itemsChecked": "{checked}/{total} articles cochés",
"fromMealPlan": " · Depuis le planning repas",
"addToList": "Ajouter à la liste",
"dialogTitle": "Ajouter à la liste de courses",
"dialogDescription": "Ajouter les ingrédients de <strong>{title}</strong> à une liste de courses.",
"scaledSuffix": "ajustée)",
"loadingLists": "Chargement de vos listes…",
"modeExisting": "Ajouter à une liste existante",
"modeNew": "Créer une nouvelle liste",
"listNamePlaceholder": "Nom de la liste",
"ingredientsWillBeAdded": "{count, plural, one {1 ingrédient sera ajouté.} other {{count} ingrédients seront ajoutés.}}",
"adding": "Ajout…",
"addIngredients": "Ajouter les ingrédients",
"addedCount": "{count} ingrédients ajoutés à la liste"
}, },
"collections": { "collections": {
"title": "Collections", "title": "Collections",
@@ -271,6 +405,19 @@
"recipeCount": "{count} recette", "recipeCount": "{count} recette",
"recipeCountPlural": "{count} recettes" "recipeCountPlural": "{count} recettes"
}, },
"social": {
"followed": "Abonné",
"unfollowed": "Désabonné",
"commentFailed": "Échec de la publication du commentaire",
"deleted": "Supprimé",
"ratingSaved": "Note enregistrée",
"collectionCreated": "Collection créée",
"collectionForked": "Collection dupliquée dans votre bibliothèque",
"inviteSent": "Invitation envoyée",
"memberRemoved": "Membre supprimé",
"replyPlaceholder": "Répondre…",
"commentPlaceholder": "Partagez vos impressions…"
},
"cookingMode": { "cookingMode": {
"cooking": "En cuisine", "cooking": "En cuisine",
"stepOf": "Étape {current} sur {total}", "stepOf": "Étape {current} sur {total}",
@@ -287,6 +434,8 @@
"enableVoice": "Activer les commandes vocales", "enableVoice": "Activer les commandes vocales",
"stopVoice": "Désactiver les commandes vocales", "stopVoice": "Désactiver les commandes vocales",
"toggleIngredients": "Afficher les ingrédients", "toggleIngredients": "Afficher les ingrédients",
"pageTitle": "Cuisiner : {title}",
"pageTitleFallback": "Mode cuisine",
"shortcutsTitle": "Raccourcis et commandes", "shortcutsTitle": "Raccourcis et commandes",
"keyboardSection": "Clavier", "keyboardSection": "Clavier",
"voiceSection": "Commandes vocales", "voiceSection": "Commandes vocales",
@@ -340,6 +489,31 @@
"changePasswordButton": "Changer le mot de passe", "changePasswordButton": "Changer le mot de passe",
"passwordChanged": "Mot de passe modifié avec succès.", "passwordChanged": "Mot de passe modifié avec succès.",
"passwordChangeFailed": "Échec de la modification du mot de passe.", "passwordChangeFailed": "Échec de la modification du mot de passe.",
"webhookCreateFailed": "Échec de la création du webhook",
"webhookDeleteFailed": "Échec de la suppression du webhook",
"webhookUpdateFailed": "Échec de la mise à jour du webhook",
"webhookUrlPlaceholder": "https://exemple.fr/webhook",
"webhookAdding": "Ajout…",
"webhookAddButton": "Ajouter un webhook",
"redeliverySuccess": "Renvoi mis en file d'attente",
"redeliveryFailed": "Échec du renvoi",
"apiKeyCreateFailed": "Échec de la création de la clé API",
"apiKeyRevokeFailed": "Échec de la révocation de la clé API",
"apiKeyNamePlaceholder": "ex. Mon application",
"copyFailed": "Échec de la copie dans le presse-papiers",
"byokSaved": "Clé {provider} enregistrée",
"byokSaveFailed": "Échec de l'enregistrement de la clé",
"byokRemoved": "Clé {provider} supprimée",
"byokRemoveFailed": "Échec de la suppression de la clé",
"modelSaved": "Préférences de modèle enregistrées",
"modelSaveFailed": "Échec de l'enregistrement",
"modelDefaultPlaceholder": "Par défaut",
"modelNamePlaceholder": "ex. llama3.2",
"userUpdated": "Utilisateur mis à jour avec succès",
"userUpdateFailed": "Échec de l'enregistrement",
"adminSettingsSaved": "Paramètres enregistrés",
"adminSettingsFailed": "Échec de l'enregistrement des paramètres",
"nutritionGoalsSaved": "Objectifs nutritionnels enregistrés",
"bio": "Bio", "bio": "Bio",
"publicBio": "Bio publique", "publicBio": "Bio publique",
"publicBioDescription": "Affichée sur votre profil public.", "publicBioDescription": "Affichée sur votre profil public.",