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
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
import { Check, Package, Loader2 } from "lucide-react";
import { toast } from "sonner";
@@ -23,6 +24,8 @@ export function ShoppingListView({
listId: string;
initialItems: Item[];
}) {
const t = useTranslations("mealPlan");
const tShopping = useTranslations("shoppingLists");
const [items, setItems] = useState<Item[]>(initialItems);
const [movingToPantry, setMovingToPantry] = useState(false);
@@ -43,8 +46,8 @@ export function ShoppingListView({
})),
}),
});
if (!res.ok) { toast.error("Failed to move items to pantry"); return; }
toast.success(`${checkedItems.length} item${checkedItems.length !== 1 ? "s" : ""} added to pantry`);
if (!res.ok) { toast.error(t("moveToPantryFailed")); return; }
toast.success(t("addedToPantry", { count: checkedItems.length }));
} finally {
setMovingToPantry(false);
}
@@ -61,7 +64,7 @@ export function ShoppingListView({
}
const grouped = items.reduce<Record<string, Item[]>>((acc, item) => {
const key = item.aisle ?? "Other";
const key = item.aisle ?? t("aisleOther");
(acc[key] ??= []).push(item);
return acc;
}, {});
@@ -69,17 +72,17 @@ export function ShoppingListView({
const checkedCount = items.filter((i) => i.checked).length;
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 (
<div className="space-y-6">
<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 && (
<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" />}
Move {checkedCount} to pantry
{t("moveToPantry", { count: checkedCount })}
</Button>
)}
</div>
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Wand2, Loader2, X } from "lucide-react";
import { toast } from "sonner";
@@ -26,6 +27,7 @@ export function AdaptRecipeButton({
recipeId: string;
ingredients: Ingredient[];
}) {
const t = useTranslations("recipe");
const router = useRouter();
const [open, setOpen] = useState(false);
const [excluded, setExcluded] = useState<Set<string>>(new Set());
@@ -50,7 +52,7 @@ export function AdaptRecipeButton({
async function handleAdapt() {
if (excluded.size === 0 && !extraConstraints.trim()) {
toast.error("Select at least one ingredient to exclude or add a constraint");
toast.error(t("adaptConstraintRequired"));
return;
}
@@ -68,7 +70,7 @@ export function AdaptRecipeButton({
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to adapt recipe");
toast.error(err.error ?? t("adaptFailed"));
return;
}
@@ -154,7 +156,7 @@ export function AdaptRecipeButton({
id="extra-constraints"
value={extraConstraints}
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}
disabled={adapting}
/>
@@ -1,6 +1,7 @@
"use client";
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { ShoppingCart, Loader2, Plus, Check } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -45,6 +46,10 @@ export function AddToShoppingListButton({
baseServings: number;
ingredients: Ingredient[];
}) {
const t = useTranslations("recipe");
const tShopping = useTranslations("shoppingLists");
const tCommon = useTranslations("common");
const tForm = useTranslations("recipeForm");
const [open, setOpen] = useState(false);
const [lists, setLists] = useState<ShoppingList[]>([]);
const [loadingLists, setLoadingLists] = useState(false);
@@ -91,7 +96,7 @@ export function AddToShoppingListButton({
headers: { "Content-Type": "application/json" },
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 };
listId = created.id;
}
@@ -102,9 +107,9 @@ export function AddToShoppingListButton({
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);
} finally {
setAdding(false);
@@ -120,7 +125,7 @@ export function AddToShoppingListButton({
<ShoppingCart className="h-4 w-4" />
</Button>
} />
<TooltipContent>Add to list</TooltipContent>
<TooltipContent>{tShopping("addToList")}</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -129,17 +134,20 @@ export function AddToShoppingListButton({
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<ShoppingCart className="h-5 w-5 text-primary" />
Add to shopping list
{tShopping("dialogTitle")}
</DialogTitle>
<DialogDescription>
Add the ingredients of <strong>{recipeTitle}</strong> to a shopping list.
{tShopping.rich("dialogDescription", {
title: recipeTitle,
strong: (chunks) => <strong>{chunks}</strong>,
})}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{/* Servings scaler */}
<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">
<Button
type="button" variant="ghost" size="icon" className="h-7 w-7"
@@ -153,7 +161,7 @@ export function AddToShoppingListButton({
>+</Button>
</div>
{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>
@@ -162,7 +170,7 @@ export function AddToShoppingListButton({
{/* List picker */}
{loadingLists ? (
<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 className="space-y-3">
@@ -170,7 +178,7 @@ export function AddToShoppingListButton({
<RadioGroup value={mode} onValueChange={(v: string) => setMode(v as "existing" | "new")}>
<div className="flex items-center gap-2">
<RadioGroupItem value="existing" id="mode-existing" />
<Label htmlFor="mode-existing">Add to existing list</Label>
<Label htmlFor="mode-existing">{tShopping("modeExisting")}</Label>
</div>
{mode === "existing" && (
<div className="ml-6 space-y-1.5">
@@ -192,7 +200,7 @@ export function AddToShoppingListButton({
)}
<div className="flex items-center gap-2">
<RadioGroupItem value="new" id="mode-new" />
<Label htmlFor="mode-new">Create new list</Label>
<Label htmlFor="mode-new">{tShopping("modeNew")}</Label>
</div>
</RadioGroup>
)}
@@ -202,7 +210,7 @@ export function AddToShoppingListButton({
<Input
value={newListName}
onChange={(e) => setNewListName(e.target.value)}
placeholder="List name"
placeholder={tShopping("listNamePlaceholder")}
/>
</div>
)}
@@ -211,13 +219,13 @@ export function AddToShoppingListButton({
<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">
<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)}>
{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>
</div>
</div>
@@ -1,6 +1,7 @@
"use client";
import { useState, useRef } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Sparkles, Loader2, Camera, Type, Upload, X, Shuffle } from "lucide-react";
import { toast } from "sonner";
@@ -69,6 +70,7 @@ export function AiGenerateDialog({
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const t = useTranslations("ai.generate");
const router = useRouter();
const [tab, setTab] = useState<Tab>("describe");
@@ -122,7 +124,7 @@ export function AiGenerateDialog({
});
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to generate recipe");
toast.error(err.error ?? t("error"));
return;
}
const generated = await res.json() as GeneratedRecipe;
@@ -131,9 +133,9 @@ export function AiGenerateDialog({
headers: { "Content-Type": "application/json" },
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 };
toast.success("Recipe generated! Review and edit before publishing.");
toast.success(t("success"));
handleClose();
router.push(`/recipes/${saved.id}/edit`);
} finally {
@@ -151,13 +153,13 @@ export function AiGenerateDialog({
body: JSON.stringify({ imageBase64: photoBase64, mimeType: photoMime }),
});
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 */ }
toast.error(msg);
return;
}
const { id } = await res.json() as { id: string };
toast.success("Recipe recognized! Review and edit before publishing.");
toast.success(t("photoSuccess"));
handleClose();
router.push(`/recipes/${id}/edit`);
} finally {
@@ -226,7 +228,7 @@ export function AiGenerateDialog({
id="ai-prompt"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="e.g. A creamy mushroom risotto with parmesan, serves 4, easy difficulty"
placeholder={t("placeholder")}
rows={4}
disabled={busy}
/>
@@ -249,7 +251,7 @@ export function AiGenerateDialog({
<Label>Difficulty</Label>
<Select value={difficulty} onValueChange={(v) => setDifficulty(v as typeof difficulty)} disabled={busy}>
<SelectTrigger>
<SelectValue placeholder="Any" />
<SelectValue placeholder={t("anyDifficulty")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="">Any</SelectItem>
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -19,6 +20,7 @@ import { toast } from "sonner";
import { cn } from "@/lib/utils";
export function DeleteRecipeButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("recipe");
const [open, setOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const router = useRouter();
@@ -31,10 +33,10 @@ export function DeleteRecipeButton({ recipeId }: { recipeId: string }) {
const data = await res.json() as { error?: string };
throw new Error(data.error ?? "Delete failed");
}
toast.success("Recipe deleted");
toast.success(t("deleted"));
router.push("/recipes");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Delete failed");
toast.error(err instanceof Error ? err.message : t("deleteFailed"));
setDeleting(false);
}
}
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Sparkles, Loader2 } from "lucide-react";
import { toast } from "sonner";
@@ -21,6 +22,7 @@ export function GenerateContentButton({
title: string;
description?: string | null;
}) {
const t = useTranslations("ai.generate");
const router = useRouter();
const [busy, setBusy] = useState(false);
@@ -38,8 +40,7 @@ export function GenerateContentButton({
});
if (!genRes.ok) {
const err = await genRes.json() as { error?: string };
toast.error(err.error ?? "Generation failed");
toast.error(t("contentGenerateFailed"));
return;
}
@@ -65,11 +66,11 @@ export function GenerateContentButton({
});
if (!saveRes.ok) {
toast.error("Failed to save generated content");
toast.error(t("contentSaveFailed"));
return;
}
toast.success("Ingredients and steps generated!");
toast.success(t("contentGenerated"));
router.refresh();
} finally {
setBusy(false);
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { UtensilsCrossed, Sparkles, Loader2, ChefHat, Salad, Wine, Cake, Sandwich, Soup, Check } from "lucide-react";
@@ -54,6 +55,7 @@ const DIFFICULTY_VARIANT = {
} as const;
export function MealPairingButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("recipe");
const router = useRouter();
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
@@ -71,7 +73,7 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
headers: { "Content-Type": "application/json" },
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[] };
setPairings(data.pairings);
} finally {
@@ -101,7 +103,7 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
headers: { "Content-Type": "application/json" },
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 {
title: string; description?: string; baseServings?: number; prepMins?: number;
cookMins?: number; difficulty?: string; dietaryTags?: Record<string, boolean>;
@@ -113,11 +115,11 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
headers: { "Content-Type": "application/json" },
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 };
savedIds.push(saved.id);
} 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);
if (savedIds.length === 1) {
toast.success("Recipe generated — review before publishing");
toast.success(t("pairingSuccess"));
router.push(`/recipes/${savedIds[0]}/edit`);
} 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");
}
}
@@ -1,6 +1,7 @@
"use client";
import { useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Camera, Loader2 } from "lucide-react";
import { toast } from "sonner";
@@ -8,6 +9,7 @@ import { Button } from "@/components/ui/button";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
export function PhotoImportButton() {
const t = useTranslations("recipe");
const router = useRouter();
const fileRef = useRef<HTMLInputElement>(null);
const [loading, setLoading] = useState(false);
@@ -52,7 +54,7 @@ export function PhotoImportButton() {
const { id } = await res.json() as { id: string };
router.push(`/recipes/${id}/edit`);
} 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 {
setLoading(false);
// Reset input so the same file can be re-selected
@@ -1,6 +1,7 @@
"use client";
import { useState, useRef } from "react";
import { useTranslations } from "next-intl";
import { Upload, X, Star } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getPublicUrl } from "@/lib/storage";
@@ -20,6 +21,7 @@ export function PhotoUploader({
photos: PhotoEntry[];
onChange: (photos: PhotoEntry[]) => void;
}) {
const t = useTranslations("recipeForm");
const [uploading, setUploading] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
@@ -72,7 +74,7 @@ export function PhotoUploader({
type="button"
onClick={() => setCover(photo.key)}
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"}`} />
</button>
@@ -80,7 +82,7 @@ export function PhotoUploader({
type="button"
onClick={() => remove(photo.key)}
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" />
</button>
@@ -1,6 +1,7 @@
"use client";
import { useState, useRef, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
@@ -19,6 +20,7 @@ type Props = {
};
export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
const t = useTranslations("recipeChat");
const [open, setOpen] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
@@ -49,12 +51,12 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
const data = await res.json() as { answer?: string; error?: string };
setMessages((prev) => [
...prev,
{ role: "assistant", content: data.answer ?? "Sorry, I couldn't answer that." },
{ role: "assistant", content: data.answer ?? t("sorry") },
]);
} catch {
setMessages((prev) => [
...prev,
{ role: "assistant", content: "Something went wrong. Please try again." },
{ role: "assistant", content: t("error") },
]);
} finally {
setLoading(false);
@@ -62,10 +64,10 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
};
const suggestions = [
"Can I substitute any ingredients?",
"How do I know when it's done?",
"Can I make this ahead of time?",
"What can I serve with this?",
t("suggestion1"),
t("suggestion2"),
t("suggestion3"),
t("suggestion4"),
];
return (
@@ -75,7 +77,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
size="icon"
className="fixed bottom-6 right-6 h-12 w-12 rounded-full shadow-lg z-40"
onClick={() => setOpen(true)}
aria-label="Ask AI about this recipe"
aria-label={t("ariaLabel")}
>
<MessageCircle className="h-5 w-5" />
</Button>
@@ -85,7 +87,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
<SheetTitle className="text-base flex items-center gap-2">
<Bot className="h-4 w-4 text-primary" />
Ask about this recipe
{t("title")}
</SheetTitle>
<p className="text-xs text-muted-foreground text-left">{recipeTitle}</p>
</SheetHeader>
@@ -94,7 +96,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
{messages.length === 0 && (
<div className="space-y-3">
<p className="text-sm text-muted-foreground text-center py-4">
Ask anything about this recipe ingredients, techniques, substitutions, timing
{t("intro")}
</p>
<div className="space-y-2">
{suggestions.map((s) => (
@@ -163,7 +165,7 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
<Input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Ask a question…"
placeholder={t("inputPlaceholder")}
disabled={loading}
className="flex-1"
autoComplete="off"
+6 -4
View File
@@ -1,6 +1,7 @@
"use client";
import { useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks } from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";
import {
@@ -173,6 +174,7 @@ function SelectableRecipeCard({
}
export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] }) {
const t = useTranslations("recipe");
const [recipes, setRecipes] = useState(initialRecipes);
const [selectMode, setSelectMode] = useState(false);
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");
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();
} catch {
toast.error("Delete failed");
toast.error(t("bulkDeleteFailed"));
} finally {
setBusy(false);
}
@@ -229,10 +231,10 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
setRecipes((prev) =>
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();
} catch {
toast.error("Update failed");
toast.error(t("bulkUpdateFailed"));
} finally {
setBusy(false);
}
@@ -22,13 +22,14 @@ import { UrlImportDialog } from "./url-import-dialog";
function TagFilterInput({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const [local, setLocal] = useState(value);
const t = useTranslations("recipes");
return (
<input
value={local}
onChange={(e) => setLocal(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") 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"
/>
);
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { Minus, Plus, Sparkles, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { scaleQuantity, hasQuantity } from "@/lib/fractions";
@@ -35,6 +36,7 @@ export function ServingScaler({
recipeId?: string;
onAiScale?: (ingredients: ScaledIngredient[] | null) => void;
}) {
const t = useTranslations("servingScaler");
const [servings, setServings] = useState(baseServings);
const [aiScaledIngredients, setAiScaledIngredients] = useState<ScaledIngredient[] | null>(null);
const [aiScaling, setAiScaling] = useState(false);
@@ -67,7 +69,7 @@ export function ServingScaler({
return (
<div className="space-y-4">
<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">
<Button
variant="outline"
@@ -94,7 +96,7 @@ export function ServingScaler({
className="text-xs text-muted-foreground hover:text-foreground underline"
onClick={() => setServings(baseServings)}
>
reset
{t("reset")}
</button>
)}
{recipeId && servings !== baseServings && (
@@ -106,7 +108,7 @@ export function ServingScaler({
disabled={aiScaling}
>
<Sparkles className="h-3 w-3" />
{aiScaling ? "Scaling" : "AI Scale"}
{aiScaling ? t("scaling") : t("aiScale")}
</Button>
)}
</div>
@@ -114,7 +116,7 @@ export function ServingScaler({
{aiScaledIngredients && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Sparkles className="h-3 w-3 shrink-0" />
<span>AI-scaled quantities shown below</span>
<span>{t("aiScaledNote")}</span>
<button
className="ml-auto hover:text-foreground"
onClick={dismissAiScale}
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { Shuffle, Loader2 } from "lucide-react";
import {
Popover,
@@ -29,6 +30,7 @@ export function SubstituteIngredientPopover({
ingredient: string;
recipeTitle: string;
}) {
const t = useTranslations("substitute");
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [substitutions, setSubstitutions] = useState<Substitution[]>([]);
@@ -47,14 +49,14 @@ export function SubstituteIngredientPopover({
});
if (!res.ok) {
const body = await res.json().catch(() => null) as { error?: string } | null;
setError(body?.error ?? "Couldn't fetch substitutes.");
setError(body?.error ?? t("fetchError"));
return;
}
const data = await res.json() as { substitutions: Substitution[] };
setSubstitutions(data.substitutions);
setFetched(true);
} catch {
setError("Couldn't fetch substitutes.");
setError(t("fetchError"));
} finally {
setLoading(false);
}
@@ -69,18 +71,18 @@ export function SubstituteIngredientPopover({
<Popover open={open} onOpenChange={handleOpen}>
<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"
title={`Substitute for ${ingredient}`}
title={t("titleFor", { ingredient })}
>
<Shuffle className="h-3 w-3" />
</PopoverTrigger>
<PopoverContent className="w-80 p-3 space-y-3" align="start">
<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>
{loading && (
<div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Finding substitutes
{t("finding")}
</div>
)}
{!loading && substitutions.length > 0 && (
@@ -103,7 +105,7 @@ export function SubstituteIngredientPopover({
<p className="text-sm text-destructive py-1">{error}</p>
)}
{!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>
</Popover>
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Languages, Loader2 } from "lucide-react";
import { toast } from "sonner";
@@ -32,6 +33,7 @@ const LANGUAGES = [
];
export function TranslateButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("ai.translate");
const router = useRouter();
const [open, setOpen] = useState(false);
const [targetLanguage, setTargetLanguage] = useState("French");
@@ -48,12 +50,12 @@ export function TranslateButton({ recipeId }: { recipeId: string }) {
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to translate recipe");
toast.error(err.error ?? t("error"));
return;
}
const { id } = await res.json() as { id: string };
toast.success("Translation saved as new draft recipe");
toast.success(t("success"));
setOpen(false);
router.push(`/recipes/${id}/edit`);
} finally {
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { Sparkles, Loader2, ChevronRight, Replace } from "lucide-react";
@@ -61,6 +62,7 @@ export function VariationsDialog({
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const t = useTranslations("recipe");
const router = useRouter();
const [generating, setGenerating] = useState(false);
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>
<Textarea
id="directions"
placeholder="e.g. make it vegan, use only pantry staples, reduce sugar…"
placeholder={t("variationsDirectionsPlaceholder")}
value={directions}
onChange={(e) => setDirections(e.target.value)}
disabled={generating}
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { History, RotateCcw, ChevronDown } from "lucide-react";
import { toast } from "sonner";
@@ -39,6 +40,8 @@ function formatDate(dateStr: string): string {
}
export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
const t = useTranslations("recipe");
const tForm = useTranslations("recipeForm");
const router = useRouter();
const [open, setOpen] = useState(false);
const [versions, setVersions] = useState<VersionSummary[]>([]);
@@ -91,7 +94,7 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
setOpen(false);
router.refresh();
} else {
toast.error("Failed to restore version");
toast.error(t("historyRestoreFailed"));
}
} finally {
setRestoringId(null);
@@ -143,7 +146,7 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
title="Expand"
title={tForm("expand")}
onClick={() => void handleExpand(v)}
>
<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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
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";
const DIFFICULTY_COLORS: Record<string, string> = {
@@ -100,6 +101,8 @@ type Props = {
export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
const router = useRouter();
const searchParams = useSearchParams();
const t = useTranslations("explore");
const tCommon = useTranslations("common");
const [inputValue, setInputValue] = useState(initialQuery);
const [query, setQuery] = useState(initialQuery);
@@ -243,7 +246,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
ref={inputRef}
value={inputValue}
onChange={(e) => handleInputChange(e.target.value)}
placeholder="Search public recipes…"
placeholder={t("searchPlaceholder")}
className="pl-10 h-12 text-base"
autoFocus={!!initialQuery}
/>
@@ -253,7 +256,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
<div className="flex flex-wrap items-center gap-3">
<Select value={difficulty} onValueChange={handleDifficultyChange}>
<SelectTrigger className="w-40">
<SelectValue placeholder="Difficulty" />
<SelectValue placeholder={tCommon("difficulty")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="any">Any difficulty</SelectItem>
@@ -265,7 +268,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
<Input
type="number"
min={1}
placeholder="Max minutes"
placeholder={t("maxMinutes")}
value={maxMins}
onChange={(e) => handleMaxMinsChange(e.target.value)}
className="w-36"
@@ -342,7 +345,7 @@ export function ExplorePageContent({ trending, recent, initialQuery }: Props) {
<Input
value={ideasPrompt}
onChange={(e) => setIdeasPrompt(e.target.value)}
placeholder="e.g. quick weeknight dinners, Italian comfort food…"
placeholder={t("aiSearchPlaceholder")}
className="bg-background"
/>
<Button type="submit" disabled={ideasLoading} variant="secondary" className="shrink-0">
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -30,6 +31,7 @@ function formatDate(iso: string) {
}
export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
const t = useTranslations("settingsForm");
const [keys, setKeys] = useState<ApiKey[]>(initialKeys);
const [name, setName] = useState("");
const [creating, setCreating] = useState(false);
@@ -48,7 +50,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
});
if (!res.ok) {
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;
setNewKey(data.key);
@@ -58,7 +60,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
]);
setName("");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create API key");
toast.error(err instanceof Error ? err.message : t("apiKeyCreateFailed"));
} finally {
setCreating(false);
}
@@ -69,11 +71,11 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
const res = await fetch(`/api/v1/api-keys/${id}`, { method: "DELETE" });
if (!res.ok) {
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));
} 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);
setTimeout(() => setCopied(false), 2000);
} 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">
<Input
id="key-name"
placeholder="e.g. My app"
placeholder={t("apiKeyNamePlaceholder")}
value={name}
onChange={(e) => setName(e.target.value)}
maxLength={100}
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Key, Trash2, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -17,6 +18,7 @@ const PROVIDERS: { id: Provider; label: string; placeholder: string }[] = [
];
export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
const t = useTranslations("settingsForm");
const [configuredKeys, setConfiguredKeys] = useState<Set<string>>(new Set(initialKeys));
const [inputs, setInputs] = useState<Partial<Record<Provider, string>>>({});
const [saving, setSaving] = useState<Provider | null>(null);
@@ -35,9 +37,9 @@ export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
if (res.ok) {
setConfiguredKeys((prev) => new Set([...prev, provider]));
setInputs((prev) => ({ ...prev, [provider]: "" }));
toast.success(`${provider} key saved`);
toast.success(t("byokSaved", { provider }));
} else {
toast.error("Failed to save key");
toast.error(t("byokSaveFailed"));
}
} finally {
setSaving(null);
@@ -50,9 +52,9 @@ export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
const res = await fetch(`/api/v1/ai-keys/${provider}`, { method: "DELETE" });
if (res.ok) {
setConfiguredKeys((prev) => { const s = new Set(prev); s.delete(provider); return s; });
toast.success(`${provider} key removed`);
toast.success(t("byokRemoved", { provider }));
} else {
toast.error("Failed to remove key");
toast.error(t("byokRemoveFailed"));
}
} finally {
setRemoving(null);
@@ -14,6 +14,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
type Provider = "openai" | "anthropic" | "openrouter" | "ollama" | "";
@@ -59,6 +60,7 @@ type Prefs = {
};
export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null }) {
const t = useTranslations("settingsForm");
const [prefs, setPrefs] = useState<Prefs>(initialPrefs ?? {});
const [saving, setSaving] = useState(false);
@@ -75,9 +77,9 @@ export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null })
body: JSON.stringify(prefs),
});
if (!res.ok) throw new Error("Save failed");
toast.success("Model preferences saved");
toast.success(t("modelSaved"));
} catch {
toast.error("Failed to save");
toast.error(t("modelSaveFailed"));
} finally {
setSaving(false);
}
@@ -132,7 +134,7 @@ export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null })
onValueChange={(v) => setField(modelKey, v === "default" ? null : v)}
>
<SelectTrigger className="h-8 text-sm">
<SelectValue placeholder="Default" />
<SelectValue placeholder={t("modelDefaultPlaceholder")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">
@@ -149,7 +151,7 @@ export function ModelPrefsForm({ initialPrefs }: { initialPrefs: Prefs | null })
) : (
<Input
className="h-8 text-sm"
placeholder={provider ? "e.g. llama3.2" : "—"}
placeholder={provider ? t("modelNamePlaceholder") : "—"}
value={model}
onChange={(e) => setField(modelKey, e.target.value)}
disabled={!provider}
@@ -2,6 +2,7 @@
import { useState } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { ChevronDown, ChevronUp, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -65,6 +66,7 @@ function formatDateTime(iso: string) {
}
export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
const t = useTranslations("settingsForm");
const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
const [url, setUrl] = useState("");
const [selectedEvents, setSelectedEvents] = useState<WebhookEventType[]>([]);
@@ -94,7 +96,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
});
if (!res.ok) {
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;
setNewSecret({ id: data.id, secret: data.secret });
@@ -105,7 +107,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
setUrl("");
setSelectedEvents([]);
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create webhook");
toast.error(err instanceof Error ? err.message : t("webhookCreateFailed"));
} finally {
setCreating(false);
}
@@ -116,12 +118,12 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
const res = await fetch(`/api/v1/webhooks/${id}`, { method: "DELETE" });
if (!res.ok && res.status !== 204) {
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));
if (newSecret?.id === id) setNewSecret(null);
} 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) {
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) =>
prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w))
);
} 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);
setTimeout(() => setCopied(false), 2000);
} 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 }),
});
if (res.ok) {
toast.success("Redelivery queued");
toast.success(t("redeliverySuccess"));
} else {
toast.error("Failed to redeliver");
toast.error(t("redeliveryFailed"));
}
} finally {
setRedelivering(null);
@@ -210,7 +212,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
<Input
id="webhook-url"
type="url"
placeholder="https://example.com/webhook"
placeholder={t("webhookUrlPlaceholder")}
value={url}
onChange={(e) => setUrl(e.target.value)}
maxLength={2048}
@@ -242,7 +244,7 @@ export function WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[
</div>
<Button type="submit" disabled={creating || !url.trim()}>
{creating ? "Adding" : "Add webhook"}
{creating ? t("webhookAdding") : t("webhookAddButton")}
</Button>
</form>
@@ -3,6 +3,7 @@
import { useState, useEffect, useCallback } from "react";
import { MessageCircle, Reply, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
@@ -97,6 +98,7 @@ function CommentItem({
}) {
const [showReply, setShowReply] = useState(false);
const isOwn = comment.userId === currentUserId;
const t = useTranslations("social");
async function deleteComment() {
const res = await fetch(`/api/v1/comments/${comment.id}`, { method: "DELETE" });
@@ -141,7 +143,7 @@ function CommentItem({
recipeId={recipeId}
parentId={comment.id}
onSubmit={() => { setShowReply(false); onRefresh(); }}
placeholder="Reply…"
placeholder={t("replyPlaceholder")}
onCancel={() => setShowReply(false)}
/>
)}
@@ -191,6 +193,7 @@ export function CommentsSection({
}) {
const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true);
const t = useTranslations("social");
const load = useCallback(async () => {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments`);
@@ -212,7 +215,7 @@ export function CommentsSection({
</div>
{currentUserId && (
<CommentForm recipeId={recipeId} onSubmit={load} placeholder="Share your thoughts…" />
<CommentForm recipeId={recipeId} onSubmit={load} placeholder={t("commentPlaceholder")} />
)}
{loading ? (