feat: copy/export as Markdown wherever print exists

Added a shared ExportMarkdownButton (copy to clipboard / download .md)
next to every existing print button: recipe, shopping list,
collection, meal plan, pantry. Each surface gets a small serializer in
lib/markdown/ built from data already in scope at that page — no new
queries except pantry, where items now thread through as a prop to
PantryPageHeader instead of being fetched only for PantryManager.

Also fixes an unrelated bug hit while verifying the collection export:
RecipeCard called the client-only useTranslations() hook without
"use client", so it rendered fine everywhere it happened to run inside
an already-client tree but 500'd — "Couldn't find next-intl config
file" — when Next tried to run it as a Server Component, which only
happens on the collection detail page (its only caller). Collections
with recipes in them were completely broken.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-08 22:15:48 +02:00
parent 68cbd5b4e4
commit 1677e40668
15 changed files with 296 additions and 13 deletions
+16 -4
View File
@@ -10,6 +10,8 @@ import { ForkCollectionButton } from "@/components/collections/fork-collection-b
import { ShareCollectionButton } from "@/components/collections/share-collection-button";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { collectionToMarkdown } from "@/lib/markdown/collection";
import { getMessages } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> };
@@ -46,10 +48,20 @@ export default async function CollectionPage({ params }: Params) {
</div>
<div className="flex flex-wrap items-center gap-2">
{col.recipes.length > 0 && (
<Link href={`/print/collection/${id}`} target="_blank" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
<Printer className="h-4 w-4" />
{m.collections.exportPdf}
</Link>
<>
<Link href={`/print/collection/${id}`} target="_blank" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
<Printer className="h-4 w-4" />
{m.collections.exportPdf}
</Link>
<ExportMarkdownButton
markdown={collectionToMarkdown({
name: col.name,
description: col.description,
recipes: col.recipes.flatMap((r) => (r.recipe ? [r.recipe] : [])),
})}
filename={col.name}
/>
</>
)}
{isOwner && <ShareCollectionButton collectionId={id} />}
{!isOwner && col.isPublic && (
+6
View File
@@ -9,6 +9,8 @@ import { MealPlanner } from "@/components/meal-plan/meal-planner";
import { ShareMealPlanButton } from "@/components/meal-plan/share-meal-plan-button";
import { WeeklyNutritionBar } from "@/components/nutrition/weekly-nutrition-bar";
import { cn } from "@/lib/utils";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { mealPlanToMarkdown } from "@/lib/markdown/meal-plan";
import { getMessages, formatMessage } from "@/lib/i18n/server";
export const metadata: Metadata = { title: "Meal Plan" };
@@ -98,6 +100,10 @@ export default async function MealPlanPage({
<Printer className="h-4 w-4" />
{msgs.common.print}
</Link>
<ExportMarkdownButton
markdown={mealPlanToMarkdown({ label, entries })}
filename={`meal-plan-${weekStart}`}
/>
<Link href={`/meal-plan?week=${prevWeek}`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
<ChevronLeft className="h-4 w-4" />
</Link>
+10 -8
View File
@@ -16,16 +16,18 @@ export default async function PantryPage() {
orderBy: asc(pantryItems.rawName),
});
const mappedItems = items.map((i) => ({
id: i.id,
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
expiresAt: i.expiresAt?.toISOString() ?? null,
}));
return (
<div className="space-y-6">
<PantryPageHeader />
<PantryManager initialItems={items.map((i) => ({
id: i.id,
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
expiresAt: i.expiresAt?.toISOString() ?? null,
}))} />
<PantryPageHeader items={mappedItems} />
<PantryManager initialItems={mappedItems} />
</div>
);
}
+16
View File
@@ -31,6 +31,8 @@ import { getPublicUrl } from "@/lib/storage";
import { cn } from "@/lib/utils";
import { RecipeChatPanel } from "@/components/recipe/recipe-chat-panel";
import { KeepScreenAwake } from "@/components/recipe/keep-screen-awake";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { recipeToMarkdown } from "@/lib/markdown/recipe";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> };
@@ -172,6 +174,20 @@ export default async function RecipePage({ params }: Params) {
/>
<ShareRecipeButton recipeId={id} visibility={recipe.visibility} />
<PrintButton recipeId={id} />
<ExportMarkdownButton
markdown={recipeToMarkdown({
title: recipe.title,
description: recipe.description,
baseServings: recipe.baseServings,
prepMins: recipe.prepMins,
cookMins: recipe.cookMins,
difficulty: recipe.difficulty,
sourceUrl: recipe.sourceUrl,
ingredients: recipe.ingredients,
steps: recipe.steps,
})}
filename={recipe.title}
/>
{isOwner && (
<>
<VersionHistoryButton
@@ -11,6 +11,8 @@ import { GroceryExportButton } from "@/components/shopping-lists/grocery-export-
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { shoppingListToMarkdown } from "@/lib/markdown/shopping-list";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> };
@@ -52,6 +54,10 @@ export default async function ShoppingListPage({ params }: Params) {
<Printer className="h-4 w-4" />
{m.common.print}
</Link>
<ExportMarkdownButton
markdown={shoppingListToMarkdown({ name: list.name, items: list.items })}
filename={list.name}
/>
</div>
</div>
<ShoppingListView
@@ -4,8 +4,12 @@ import Link from "next/link";
import { ChefHat, Printer } from "lucide-react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { pantryToMarkdown } from "@/lib/markdown/pantry";
export function PantryPageHeader() {
type PantryItem = { rawName: string; quantity: string | null; unit: string | null; expiresAt: string | null };
export function PantryPageHeader({ items }: { items: PantryItem[] }) {
const t = useTranslations("pantry");
const tCommon = useTranslations("common");
return (
@@ -23,6 +27,7 @@ export function PantryPageHeader() {
<Printer className="h-4 w-4" />
{tCommon("print")}
</a>
<ExportMarkdownButton markdown={pantryToMarkdown({ items })} filename="pantry" />
</div>
</div>
);
@@ -1,3 +1,5 @@
"use client";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { Clock, Users, Lock, Globe, Link2 } from "lucide-react";
@@ -0,0 +1,63 @@
"use client";
import { Copy, Download, FileDown } from "lucide-react";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
export function ExportMarkdownButton({
markdown,
filename,
}: {
markdown: string;
filename: string;
}) {
const t = useTranslations("common");
async function handleCopy() {
try {
await navigator.clipboard.writeText(markdown);
toast.success(t("copiedToClipboard"));
} catch {
toast.error(t("copyFailed"));
}
}
function handleDownload() {
const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename.endsWith(".md") ? filename : `${filename}.md`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
return (
<DropdownMenu>
<DropdownMenuTrigger render={
<Button variant="ghost" size="icon" title={t("exportMarkdown")}>
<FileDown className="h-4 w-4" />
</Button>
} />
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => { void handleCopy(); }}>
<Copy className="h-4 w-4" />
{t("copyMarkdown")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDownload}>
<Download className="h-4 w-4" />
{t("downloadMarkdown")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
+32
View File
@@ -0,0 +1,32 @@
type CollectionMarkdownInput = {
name: string;
description: string | null;
recipes: Array<{
title: string;
description: string | null;
baseServings: number;
prepMins: number | null;
cookMins: number | null;
difficulty: "easy" | "medium" | "hard" | null;
}>;
};
export function collectionToMarkdown(collection: CollectionMarkdownInput): string {
const lines: string[] = [`# ${collection.name}`, ""];
if (collection.description) {
lines.push(collection.description, "");
}
for (const recipe of collection.recipes) {
lines.push(`## ${recipe.title}`, "");
if (recipe.description) lines.push(recipe.description, "");
const meta: string[] = [`Servings: ${recipe.baseServings}`];
if (recipe.prepMins) meta.push(`Prep: ${recipe.prepMins} min`);
if (recipe.cookMins) meta.push(`Cook: ${recipe.cookMins} min`);
if (recipe.difficulty) meta.push(`Difficulty: ${recipe.difficulty}`);
lines.push(meta.join(" · "), "");
}
return lines.join("\n").trim() + "\n";
}
+33
View File
@@ -0,0 +1,33 @@
type MealPlanMarkdownInput = {
label: string;
entries: Array<{
day: string;
mealType: string;
servings: number;
note: string | null;
recipe: { title: string } | null;
}>;
};
export function mealPlanToMarkdown(plan: MealPlanMarkdownInput): string {
const lines: string[] = [`# Meal Plan — ${plan.label}`, ""];
const byDay = new Map<string, typeof plan.entries>();
for (const entry of plan.entries) {
const group = byDay.get(entry.day) ?? [];
group.push(entry);
byDay.set(entry.day, group);
}
for (const [day, entries] of byDay) {
lines.push(`## ${day}`, "");
for (const entry of entries) {
const title = entry.recipe?.title ?? "(no recipe)";
const note = entry.note ? `${entry.note}` : "";
lines.push(`- **${entry.mealType}**: ${title} (${entry.servings} servings)${note}`);
}
lines.push("");
}
return lines.join("\n").trim() + "\n";
}
+15
View File
@@ -0,0 +1,15 @@
type PantryMarkdownInput = {
items: Array<{ rawName: string; quantity: string | null; unit: string | null; expiresAt: string | null }>;
};
export function pantryToMarkdown(pantry: PantryMarkdownInput): string {
const lines: string[] = ["# Pantry", ""];
for (const item of pantry.items) {
const qty = [item.quantity, item.unit].filter(Boolean).join(" ");
const expiry = item.expiresAt ? ` (expires ${new Date(item.expiresAt).toLocaleDateString()})` : "";
lines.push(`- ${qty ? `${qty} ` : ""}${item.rawName}${expiry}`);
}
return lines.join("\n").trim() + "\n";
}
+54
View File
@@ -0,0 +1,54 @@
type RecipeMarkdownInput = {
title: string;
description: string | null;
baseServings: number;
prepMins: number | null;
cookMins: number | null;
difficulty: "easy" | "medium" | "hard" | null;
sourceUrl: string | null;
ingredients: Array<{ rawName: string; quantity: string | null; unit: string | null; note: string | null }>;
steps: Array<{ instruction: string; timerSeconds: number | null }>;
};
function formatQuantity(quantity: string | null, unit: string | null): string {
return [quantity, unit].filter(Boolean).join(" ");
}
export function recipeToMarkdown(recipe: RecipeMarkdownInput): string {
const lines: string[] = [`# ${recipe.title}`, ""];
if (recipe.description) {
lines.push(recipe.description, "");
}
const meta: string[] = [`Servings: ${recipe.baseServings}`];
if (recipe.prepMins) meta.push(`Prep: ${recipe.prepMins} min`);
if (recipe.cookMins) meta.push(`Cook: ${recipe.cookMins} min`);
if (recipe.difficulty) meta.push(`Difficulty: ${recipe.difficulty}`);
lines.push(meta.join(" · "), "");
if (recipe.ingredients.length > 0) {
lines.push("## Ingredients", "");
for (const ing of recipe.ingredients) {
const qty = formatQuantity(ing.quantity, ing.unit);
const note = ing.note ? ` (${ing.note})` : "";
lines.push(`- ${qty ? `${qty} ` : ""}${ing.rawName}${note}`);
}
lines.push("");
}
if (recipe.steps.length > 0) {
lines.push("## Instructions", "");
recipe.steps.forEach((step, i) => {
const timer = step.timerSeconds ? ` (${Math.round(step.timerSeconds / 60)} min)` : "";
lines.push(`${i + 1}. ${step.instruction}${timer}`);
});
lines.push("");
}
if (recipe.sourceUrl) {
lines.push(`Source: ${recipe.sourceUrl}`);
}
return lines.join("\n").trim() + "\n";
}
+27
View File
@@ -0,0 +1,27 @@
type ShoppingListMarkdownInput = {
name: string;
items: Array<{ rawName: string; quantity: string | null; unit: string | null; aisle: string | null; checked: boolean }>;
};
export function shoppingListToMarkdown(list: ShoppingListMarkdownInput): string {
const lines: string[] = [`# ${list.name}`, ""];
const byAisle = new Map<string, typeof list.items>();
for (const item of list.items) {
const aisle = item.aisle ?? "Other";
const group = byAisle.get(aisle) ?? [];
group.push(item);
byAisle.set(aisle, group);
}
for (const [aisle, items] of byAisle) {
lines.push(`## ${aisle}`, "");
for (const item of items) {
const qty = [item.quantity, item.unit].filter(Boolean).join(" ");
lines.push(`- [${item.checked ? "x" : " "}] ${qty ? `${qty} ` : ""}${item.rawName}`);
}
lines.push("");
}
return lines.join("\n").trim() + "\n";
}
+5
View File
@@ -301,6 +301,11 @@
"save": "Save",
"saved": "Saved",
"saveFailed": "Failed to save",
"exportMarkdown": "Export as Markdown",
"copyMarkdown": "Copy as Markdown",
"downloadMarkdown": "Download as Markdown",
"copiedToClipboard": "Copied to clipboard",
"copyFailed": "Failed to copy",
"print": "Print",
"share": "Share",
"deleteFailed": "Delete failed",
+5
View File
@@ -301,6 +301,11 @@
"save": "Enregistrer",
"saved": "Enregistré",
"saveFailed": "Échec de l'enregistrement",
"exportMarkdown": "Exporter en Markdown",
"copyMarkdown": "Copier en Markdown",
"downloadMarkdown": "Télécharger en Markdown",
"copiedToClipboard": "Copié dans le presse-papiers",
"copyFailed": "Échec de la copie",
"print": "Imprimer",
"share": "Partager",
"deleteFailed": "Échec de la suppression",