feat: implement remaining TODO.md feature ideas + fix mobile headers

Implements the six previously-unscoped feature ideas plus a mobile
layout fix reported via screenshot:

- Mobile: Recipes/Collections/Pantry/Meal Plan/Shopping Lists headers
  now stack and wrap instead of clipping buttons on narrow viewports.
- Recipe diff/compare view: word/list diff against any past version,
  next to Restore in version history.
- Shared meal plans & shopping lists: new shoppingListMembers/
  mealPlanMembers tables (viewer/editor roles, mirrors
  collectionMembers), share dialogs, membership-checked routes.
- PDF cookbook export: /print/collection/[id] renders a whole
  collection with page breaks, using the existing print-CSS pattern
  instead of adding a PDF rendering dependency.
- Grocery delivery handoff: shopping lists can copy-as-text (works
  today) or send to Instacart once INSTACART_API_KEY is configured
  (stub adapter — real API needs a partner agreement).
- Personalized "For You" feed tab: ranks public recipes by tag/
  dietary overlap with the user's favorited/highly-rated history.
- PWA: added manifest.json + icons on top of the existing service
  worker so the app is installable; cook-mode pages were already
  cached for offline use.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-02 12:13:00 +02:00
parent d2faf98ac1
commit e5d1080fb9
56 changed files with 6096 additions and 74 deletions
@@ -22,7 +22,7 @@ export function CollectionsPageContent({ collections }: Props) {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>
<p className="text-muted-foreground mt-1">{t("subtitle")}</p>
+42 -3
View File
@@ -2,7 +2,7 @@
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { Clock, Users, ChefHat, Flame, Heart } from "lucide-react";
import { Clock, Users, ChefHat, Flame, Heart, Sparkles } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { useLocale } from "@/lib/i18n/provider";
@@ -99,10 +99,36 @@ function TrendingTab() {
);
}
function ForYouTab() {
const { locale } = useLocale();
const t = useTranslations("feed");
const [recipes, setRecipes] = useState<FeedRecipe[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("/api/v1/feed/for-you")
.then((r) => r.json() as Promise<{ data: FeedRecipe[] }>)
.then(({ data }) => setRecipes(data))
.catch(() => {})
.finally(() => setLoading(false));
}, []);
if (loading) return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
if (recipes.length === 0) return <p className="text-sm text-muted-foreground">{t("forYouEmpty")}</p>;
return (
<div className="space-y-4">
{recipes.map((recipe) => (
<RecipeCard key={recipe.id} recipe={recipe} locale={locale} />
))}
</div>
);
}
export function FeedPageContent({ followedCount, feedRecipes }: Props) {
const t = useTranslations("feed");
const { locale } = useLocale();
const [tab, setTab] = useState<"following" | "trending">("following");
const [tab, setTab] = useState<"following" | "trending" | "forYou">("following");
return (
<div className="space-y-6 max-w-2xl">
@@ -131,6 +157,17 @@ export function FeedPageContent({ followedCount, feedRecipes }: Props) {
<Flame className="h-3.5 w-3.5" />
{t("trending")}
</button>
<button
onClick={() => setTab("forYou")}
className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${
tab === "forYou"
? "border-primary text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground"
}`}
>
<Sparkles className="h-3.5 w-3.5" />
{t("forYou")}
</button>
</div>
{tab === "following" ? (
@@ -147,8 +184,10 @@ export function FeedPageContent({ followedCount, feedRecipes }: Props) {
))}
</div>
)
) : (
) : tab === "trending" ? (
<TrendingTab />
) : (
<ForYouTab />
)}
</div>
);
@@ -0,0 +1,191 @@
"use client";
import { useState } from "react";
import { UserPlus, X } from "lucide-react";
import { toast } from "sonner";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
type Role = "viewer" | "editor";
interface Member {
id: string;
userId: string;
role: Role;
createdAt: string;
user: {
name: string;
username: string | null;
avatarUrl: string | null;
};
}
interface Props {
weekStart: string;
}
export function ShareMealPlanButton({ weekStart }: Props) {
const [open, setOpen] = useState(false);
const [email, setEmail] = useState("");
const [role, setRole] = useState<Role>("viewer");
const [members, setMembers] = useState<Member[]>([]);
const [loading, setLoading] = useState(false);
const [inviting, setInviting] = useState(false);
async function fetchMembers() {
setLoading(true);
try {
const res = await fetch(`/api/v1/meal-plans/${weekStart}/members`);
if (!res.ok) throw new Error("Failed to load members");
const data = await res.json() as Member[];
setMembers(data);
} catch {
toast.error("Could not load members");
} finally {
setLoading(false);
}
}
function handleOpenChange(next: boolean) {
setOpen(next);
if (next) {
void fetchMembers();
} else {
setEmail("");
setRole("viewer");
}
}
async function handleInvite() {
if (!email.trim()) {
toast.error("Enter an email address");
return;
}
setInviting(true);
try {
const res = await fetch(`/api/v1/meal-plans/${weekStart}/members`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email.trim(), role }),
});
if (res.status === 409) { toast.error("Already a member"); return; }
if (res.status === 404) { toast.error("User not found"); return; }
if (!res.ok) { toast.error("Could not invite user"); return; }
toast.success("Invitation sent");
setEmail("");
await fetchMembers();
} catch {
toast.error("Could not invite user");
} finally {
setInviting(false);
}
}
async function handleRemove(memberId: string) {
try {
const res = await fetch(
`/api/v1/meal-plans/${weekStart}/members?memberId=${memberId}`,
{ method: "DELETE" },
);
if (!res.ok) { toast.error("Could not remove member"); return; }
setMembers((prev) => prev.filter((m) => m.id !== memberId));
toast.success("Member removed");
} catch {
toast.error("Could not remove member");
}
}
return (
<>
<Button variant="outline" size="sm" onClick={() => handleOpenChange(true)}>
<UserPlus className="h-4 w-4" />
Share
</Button>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Share this week&apos;s plan</DialogTitle>
<DialogDescription>
Invite household members to view or edit this week&apos;s meal plan.
</DialogDescription>
</DialogHeader>
<div className="flex gap-2 mt-2">
<Input
type="email"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") void handleInvite(); }}
className="flex-1"
/>
<Select value={role} onValueChange={(v) => setRole(v as Role)}>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="viewer">Viewer</SelectItem>
<SelectItem value="editor">Editor</SelectItem>
</SelectContent>
</Select>
<Button onClick={() => void handleInvite()} disabled={inviting}>
Invite
</Button>
</div>
<div className="mt-4 space-y-2">
{loading && (
<p className="text-sm text-muted-foreground">Loading members</p>
)}
{!loading && members.length === 0 && (
<p className="text-sm text-muted-foreground">No members yet.</p>
)}
{members.map((m) => (
<div
key={m.id}
className="flex items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm"
>
<div className="flex-1 min-w-0">
<span className="font-medium truncate">{m.user.name}</span>
{m.user.username && (
<span className="text-muted-foreground ml-1">
@{m.user.username}
</span>
)}
</div>
<Badge variant={m.role === "editor" ? "default" : "secondary"}>
{m.role}
</Badge>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={() => void handleRemove(m.id)}
aria-label="Remove member"
>
<X className="h-3.5 w-3.5" />
</Button>
</div>
))}
</div>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,128 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
type Day = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
type MealType = "breakfast" | "lunch" | "dinner" | "snack";
const DAYS: Day[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
const MEAL_TYPES: MealType[] = ["breakfast", "lunch", "dinner", "snack"];
type Entry = {
id: string;
day: Day;
mealType: MealType;
servings: number;
recipe: { id: string; title: string } | null;
};
type UserRecipe = { id: string; title: string };
export function SharedMealPlanView({
mealPlanId,
initialEntries,
userRecipes,
canEdit,
}: {
mealPlanId: string;
initialEntries: Entry[];
userRecipes: UserRecipe[];
canEdit: boolean;
}) {
const [entries, setEntries] = useState<Entry[]>(initialEntries);
const [addingCell, setAddingCell] = useState<string | null>(null);
function cellKey(day: Day, mealType: MealType) {
return `${day}-${mealType}`;
}
async function addEntry(day: Day, mealType: MealType, recipeId: string) {
const res = await fetch(`/api/v1/meal-plans/shared/${mealPlanId}/entries`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ day, mealType, recipeId, servings: 2 }),
});
if (!res.ok) { toast.error("Could not add recipe"); return; }
const { id } = await res.json() as { id: string };
const recipe = userRecipes.find((r) => r.id === recipeId) ?? null;
setEntries((prev) => [
...prev.filter((e) => !(e.day === day && e.mealType === mealType)),
{ id, day, mealType, servings: 2, recipe },
]);
setAddingCell(null);
}
async function removeEntry(entry: Entry) {
const res = await fetch(`/api/v1/meal-plans/shared/${mealPlanId}/entries?entryId=${entry.id}`, {
method: "DELETE",
});
if (!res.ok) { toast.error("Could not remove entry"); return; }
setEntries((prev) => prev.filter((e) => e.id !== entry.id));
}
return (
<div className="overflow-x-auto">
<table className="w-full border-collapse text-sm min-w-[640px]">
<thead>
<tr>
<th className="text-left p-2 text-muted-foreground font-medium"></th>
{DAYS.map((day) => (
<th key={day} className="text-left p-2 text-muted-foreground font-medium capitalize">{day}</th>
))}
</tr>
</thead>
<tbody>
{MEAL_TYPES.map((mealType) => (
<tr key={mealType} className="border-t">
<td className="p-2 text-muted-foreground font-medium capitalize align-top">{mealType}</td>
{DAYS.map((day) => {
const entry = entries.find((e) => e.day === day && e.mealType === mealType);
const key = cellKey(day, mealType);
return (
<td key={key} className="p-2 align-top min-w-[120px]">
{entry ? (
<div className="flex items-start justify-between gap-1 rounded-lg border p-2">
<span className="text-xs">{entry.recipe?.title ?? "—"}</span>
{canEdit && (
<Button variant="ghost" size="icon" className="h-5 w-5 shrink-0" onClick={() => void removeEntry(entry)}>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
) : canEdit ? (
addingCell === key ? (
<Select onValueChange={(v) => void addEntry(day, mealType, v as string)}>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="Pick recipe" />
</SelectTrigger>
<SelectContent>
{userRecipes.map((r) => (
<SelectItem key={r.id} value={r.id}>{r.title}</SelectItem>
))}
</SelectContent>
</Select>
) : (
<button
className="w-full h-8 rounded-lg border border-dashed text-xs text-muted-foreground hover:bg-muted/30"
onClick={() => setAddingCell(key)}
>
+ Add
</button>
)
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
}
@@ -20,9 +20,11 @@ type Item = {
export function ShoppingListView({
listId,
initialItems,
readOnly = false,
}: {
listId: string;
initialItems: Item[];
readOnly?: boolean;
}) {
const t = useTranslations("mealPlan");
const tShopping = useTranslations("shoppingLists");
@@ -54,6 +56,7 @@ export function ShoppingListView({
}
async function toggleItem(item: Item) {
if (readOnly) return;
const next = !item.checked;
setItems((prev) => prev.map((i) => i.id === item.id ? { ...i, checked: next } : i));
await fetch(`/api/v1/shopping-lists/${listId}/items/${item.id}`, {
@@ -97,7 +100,8 @@ export function ShoppingListView({
<button
key={item.id}
onClick={() => toggleItem(item)}
className="w-full flex items-center gap-3 px-4 py-3 hover:bg-muted/30 text-left transition-colors"
disabled={readOnly}
className="w-full flex items-center gap-3 px-4 py-3 hover:bg-muted/30 text-left transition-colors disabled:cursor-default disabled:hover:bg-transparent"
>
<div className={cn(
"h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",
@@ -8,12 +8,12 @@ import { cn } from "@/lib/utils";
export function PantryPageHeader() {
const t = useTranslations("pantry");
return (
<div className="flex items-start justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>
<p className="text-muted-foreground mt-1">{t("subtitle")}</p>
</div>
<div className="flex items-center gap-2">
<div className="flex flex-wrap items-center gap-2">
<Link href="/recipes/can-cook" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
<ChefHat className="h-4 w-4" />
{t("canCook")}
@@ -2,7 +2,7 @@
import Link from "next/link";
import { useTranslations } from "next-intl";
import { Package } from "lucide-react";
import { Package, Clock } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { buttonVariants } from "@/components/ui/button";
@@ -19,6 +19,7 @@ type ScoredItem = {
total: number;
pct: number;
missing: string[];
usesExpiring: string[];
};
type Props = {
@@ -40,7 +41,15 @@ function RecipeRow({ s }: { s: ScoredItem }) {
<div className="h-14 w-14 rounded-lg bg-muted shrink-0" />
)}
<div className="flex-1 min-w-0 space-y-1">
<p className="font-medium truncate">{s.recipe.title}</p>
<div className="flex items-center gap-2">
<p className="font-medium truncate">{s.recipe.title}</p>
{s.usesExpiring.length > 0 && (
<Badge variant="outline" className="shrink-0 text-orange-500 border-orange-500 gap-1">
<Clock className="h-3 w-3" />
{t("useItUp")}
</Badge>
)}
</div>
<div className="flex items-center gap-2">
<Progress value={s.pct} className="h-1.5 flex-1 max-w-[120px]" />
<span className="text-xs text-muted-foreground">
@@ -111,7 +111,7 @@ export function RecipesHeader({
return (
<>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>
<p className="text-muted-foreground mt-1">
@@ -120,7 +120,7 @@ export function RecipesHeader({
: t(count !== 1 ? "resultPlural" : "resultSingular", { count })}
</p>
</div>
<div className="flex items-center gap-2">
<div className="flex flex-wrap items-center gap-2">
<Button variant="ghost" size="sm" onClick={() => setUrlOpen(true)}>
<Link2 className="h-4 w-4" />
{t("importUrl")}
@@ -0,0 +1,103 @@
"use client";
import { diffWords } from "diff";
export type DiffSnapshot = {
title: string;
description?: string | null;
ingredients: Array<{ rawName: string; quantity?: string | number | null; unit?: string | null; note?: string | null }>;
steps: Array<{ instruction: string; timerSeconds?: number | null }>;
};
function ingredientLine(i: DiffSnapshot["ingredients"][number]): string {
return [i.quantity, i.unit, i.rawName, i.note && `(${i.note})`].filter(Boolean).join(" ");
}
function stepLine(s: DiffSnapshot["steps"][number]): string {
return s.instruction;
}
function TextDiff({ before, after }: { before: string; after: string }) {
const parts = diffWords(before, after);
return (
<p className="text-sm leading-relaxed">
{parts.map((part, i) => (
<span
key={i}
className={
part.added
? "bg-green-500/20 text-green-700 dark:text-green-400"
: part.removed
? "bg-red-500/20 text-red-700 dark:text-red-400 line-through"
: undefined
}
>
{part.value}
</span>
))}
</p>
);
}
function ListDiff({ before, after }: { before: string[]; after: string[] }) {
const max = Math.max(before.length, after.length);
const rows = [];
for (let i = 0; i < max; i++) {
const b = before[i];
const a = after[i];
if (b === undefined) {
rows.push(
<div key={i} className="bg-green-500/10 rounded px-2 py-1 text-sm text-green-700 dark:text-green-400">
+ {a}
</div>
);
} else if (a === undefined) {
rows.push(
<div key={i} className="bg-red-500/10 rounded px-2 py-1 text-sm text-red-700 dark:text-red-400 line-through">
{b}
</div>
);
} else if (b === a) {
rows.push(
<div key={i} className="px-2 py-1 text-sm text-muted-foreground">
{b}
</div>
);
} else {
rows.push(
<div key={i} className="rounded px-2 py-1">
<TextDiff before={b} after={a} />
</div>
);
}
}
return <div className="space-y-1">{rows}</div>;
}
export function VersionDiffView({ before, after }: { before: DiffSnapshot; after: DiffSnapshot }) {
return (
<div className="space-y-6">
<section className="space-y-2">
<h3 className="text-sm font-semibold text-muted-foreground">Title</h3>
<TextDiff before={before.title} after={after.title} />
</section>
{(before.description || after.description) && (
<section className="space-y-2">
<h3 className="text-sm font-semibold text-muted-foreground">Description</h3>
<TextDiff before={before.description ?? ""} after={after.description ?? ""} />
</section>
)}
<section className="space-y-2">
<h3 className="text-sm font-semibold text-muted-foreground">Ingredients</h3>
<ListDiff before={before.ingredients.map(ingredientLine)} after={after.ingredients.map(ingredientLine)} />
</section>
<section className="space-y-2">
<h3 className="text-sm font-semibold text-muted-foreground">Steps</h3>
<ListDiff before={before.steps.map(stepLine)} after={after.steps.map(stepLine)} />
</section>
</div>
);
}
@@ -3,7 +3,7 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { History, RotateCcw, ChevronDown } from "lucide-react";
import { History, RotateCcw, ChevronDown, GitCompare } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
@@ -12,7 +12,14 @@ import {
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { VersionDiffView, type DiffSnapshot } from "@/components/recipe/version-diff-view";
type VersionSummary = {
id: string;
@@ -21,9 +28,13 @@ type VersionSummary = {
createdAt: string;
};
type SnapshotData = {
ingredients: unknown[];
steps: unknown[];
type SnapshotData = DiffSnapshot & {
description?: string | null;
baseServings?: number;
difficulty?: string | null;
prepMins?: number | null;
cookMins?: number | null;
dietaryTags?: Record<string, boolean>;
};
type VersionDetail = {
@@ -39,7 +50,13 @@ function formatDate(dateStr: string): string {
return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}
export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
export function VersionHistoryButton({
recipeId,
currentSnapshot,
}: {
recipeId: string;
currentSnapshot: DiffSnapshot;
}) {
const t = useTranslations("recipe");
const tForm = useTranslations("recipeForm");
const router = useRouter();
@@ -49,6 +66,7 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
const [expandedId, setExpandedId] = useState<string | null>(null);
const [expandedData, setExpandedData] = useState<Record<string, VersionDetail>>({});
const [restoringId, setRestoringId] = useState<string | null>(null);
const [comparingId, setComparingId] = useState<string | null>(null);
async function handleOpen(isOpen: boolean) {
setOpen(isOpen);
@@ -66,19 +84,27 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
}
}
async function ensureDetail(versionId: string): Promise<VersionDetail | null> {
if (expandedData[versionId]) return expandedData[versionId]!;
const res = await fetch(`/api/v1/recipes/${recipeId}/versions/${versionId}`);
if (!res.ok) return null;
const data = await res.json() as VersionDetail;
setExpandedData((prev) => ({ ...prev, [versionId]: data }));
return data;
}
async function handleExpand(version: VersionSummary) {
if (expandedId === version.id) {
setExpandedId(null);
return;
}
setExpandedId(version.id);
if (!expandedData[version.id]) {
const res = await fetch(`/api/v1/recipes/${recipeId}/versions/${version.id}`);
if (res.ok) {
const data = await res.json() as VersionDetail;
setExpandedData((prev) => ({ ...prev, [version.id]: data }));
}
}
await ensureDetail(version.id);
}
async function handleCompare(version: VersionSummary) {
await ensureDetail(version.id);
setComparingId(version.id);
}
async function handleRestore(version: VersionSummary) {
@@ -151,6 +177,15 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
>
<ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`} />
</Button>
<Button
variant="outline"
size="sm"
className="shrink-0"
onClick={() => void handleCompare(v)}
>
<GitCompare className="h-3 w-3" />
Compare
</Button>
<Button
variant="outline"
size="sm"
@@ -169,8 +204,8 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
<p>Loading...</p>
) : (
<p>
{(detail.snapshotData.ingredients as unknown[]).length} ingredient{(detail.snapshotData.ingredients as unknown[]).length !== 1 ? "s" : ""},{" "}
{(detail.snapshotData.steps as unknown[]).length} step{(detail.snapshotData.steps as unknown[]).length !== 1 ? "s" : ""}
{detail.snapshotData.ingredients.length} ingredient{detail.snapshotData.ingredients.length !== 1 ? "s" : ""},{" "}
{detail.snapshotData.steps.length} step{detail.snapshotData.steps.length !== 1 ? "s" : ""}
</p>
)}
</div>
@@ -181,6 +216,19 @@ export function VersionHistoryButton({ recipeId }: { recipeId: string }) {
</div>
</SheetContent>
</Sheet>
<Dialog open={comparingId !== null} onOpenChange={(isOpen) => !isOpen && setComparingId(null)}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{comparingId ? `Compare v${expandedData[comparingId]?.version} with current` : "Compare"}
</DialogTitle>
</DialogHeader>
{comparingId && expandedData[comparingId] && (
<VersionDiffView before={expandedData[comparingId]!.snapshotData} after={currentSnapshot} />
)}
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,83 @@
"use client";
import { useState } from "react";
import { ShoppingBag, Copy, ExternalLink } from "lucide-react";
import { toast } from "sonner";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import type { GroceryExportPayload } from "@/lib/grocery-export";
import { groceryExportToText } from "@/lib/grocery-export";
interface Props {
listId: string;
/** Set when NEXT_PUBLIC_GROCERY_PROVIDER=instacart — otherwise only "copy as text" is offered. */
instacartEnabled: boolean;
}
export function GroceryExportButton({ listId, instacartEnabled }: Props) {
const [loading, setLoading] = useState(false);
async function fetchPayload(): Promise<GroceryExportPayload | null> {
const res = await fetch(`/api/v1/shopping-lists/${listId}/export`);
if (!res.ok) {
toast.error("Could not build export");
return null;
}
return res.json() as Promise<GroceryExportPayload>;
}
async function handleCopy() {
setLoading(true);
try {
const payload = await fetchPayload();
if (!payload) return;
await navigator.clipboard.writeText(groceryExportToText(payload));
toast.success("List copied to clipboard");
} finally {
setLoading(false);
}
}
async function handleInstacart() {
setLoading(true);
try {
const res = await fetch(`/api/v1/shopping-lists/${listId}/export/instacart`, { method: "POST" });
if (!res.ok) {
toast.error("Instacart isn't configured yet");
return;
}
const { url } = await res.json() as { url: string };
window.open(url, "_blank");
} finally {
setLoading(false);
}
}
return (
<DropdownMenu>
<DropdownMenuTrigger render={
<Button variant="outline" size="sm" disabled={loading}>
<ShoppingBag className="h-4 w-4" />
Send to grocery delivery
</Button>
} />
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => void handleCopy()}>
<Copy className="h-4 w-4" />
Copy list as text
</DropdownMenuItem>
{instacartEnabled && (
<DropdownMenuItem onClick={() => void handleInstacart()}>
<ExternalLink className="h-4 w-4" />
Send to Instacart
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,191 @@
"use client";
import { useState } from "react";
import { UserPlus, X } from "lucide-react";
import { toast } from "sonner";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
type Role = "viewer" | "editor";
interface Member {
id: string;
userId: string;
role: Role;
createdAt: string;
user: {
name: string;
username: string | null;
avatarUrl: string | null;
};
}
interface Props {
listId: string;
}
export function ShareShoppingListButton({ listId }: Props) {
const [open, setOpen] = useState(false);
const [email, setEmail] = useState("");
const [role, setRole] = useState<Role>("viewer");
const [members, setMembers] = useState<Member[]>([]);
const [loading, setLoading] = useState(false);
const [inviting, setInviting] = useState(false);
async function fetchMembers() {
setLoading(true);
try {
const res = await fetch(`/api/v1/shopping-lists/${listId}/members`);
if (!res.ok) throw new Error("Failed to load members");
const data = await res.json() as Member[];
setMembers(data);
} catch {
toast.error("Could not load members");
} finally {
setLoading(false);
}
}
function handleOpenChange(next: boolean) {
setOpen(next);
if (next) {
void fetchMembers();
} else {
setEmail("");
setRole("viewer");
}
}
async function handleInvite() {
if (!email.trim()) {
toast.error("Enter an email address");
return;
}
setInviting(true);
try {
const res = await fetch(`/api/v1/shopping-lists/${listId}/members`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email.trim(), role }),
});
if (res.status === 409) { toast.error("Already a member"); return; }
if (res.status === 404) { toast.error("User not found"); return; }
if (!res.ok) { toast.error("Could not invite user"); return; }
toast.success("Invitation sent");
setEmail("");
await fetchMembers();
} catch {
toast.error("Could not invite user");
} finally {
setInviting(false);
}
}
async function handleRemove(memberId: string) {
try {
const res = await fetch(
`/api/v1/shopping-lists/${listId}/members?memberId=${memberId}`,
{ method: "DELETE" },
);
if (!res.ok) { toast.error("Could not remove member"); return; }
setMembers((prev) => prev.filter((m) => m.id !== memberId));
toast.success("Member removed");
} catch {
toast.error("Could not remove member");
}
}
return (
<>
<Button variant="outline" size="sm" onClick={() => handleOpenChange(true)}>
<UserPlus className="h-4 w-4" />
Share
</Button>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Share shopping list</DialogTitle>
<DialogDescription>
Invite household members to view or edit this list.
</DialogDescription>
</DialogHeader>
<div className="flex gap-2 mt-2">
<Input
type="email"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") void handleInvite(); }}
className="flex-1"
/>
<Select value={role} onValueChange={(v) => setRole(v as Role)}>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="viewer">Viewer</SelectItem>
<SelectItem value="editor">Editor</SelectItem>
</SelectContent>
</Select>
<Button onClick={() => void handleInvite()} disabled={inviting}>
Invite
</Button>
</div>
<div className="mt-4 space-y-2">
{loading && (
<p className="text-sm text-muted-foreground">Loading members</p>
)}
{!loading && members.length === 0 && (
<p className="text-sm text-muted-foreground">No members yet.</p>
)}
{members.map((m) => (
<div
key={m.id}
className="flex items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm"
>
<div className="flex-1 min-w-0">
<span className="font-medium truncate">{m.user.name}</span>
{m.user.username && (
<span className="text-muted-foreground ml-1">
@{m.user.username}
</span>
)}
</div>
<Badge variant={m.role === "editor" ? "default" : "secondary"}>
{m.role}
</Badge>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={() => void handleRemove(m.id)}
aria-label="Remove member"
>
<X className="h-3.5 w-3.5" />
</Button>
</div>
))}
</div>
</DialogContent>
</Dialog>
</>
);
}
@@ -12,16 +12,24 @@ type ShoppingListItem = {
checkedItems: number;
};
type Props = {
lists: ShoppingListItem[];
type SharedListItem = {
id: string;
name: string;
ownerName: string;
role: "viewer" | "editor";
};
export function ShoppingListsPageContent({ lists }: Props) {
type Props = {
lists: ShoppingListItem[];
sharedLists?: SharedListItem[];
};
export function ShoppingListsPageContent({ lists, sharedLists = [] }: Props) {
const t = useTranslations("shoppingLists");
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>
<p className="text-muted-foreground mt-1">{t("subtitle")}</p>
@@ -58,6 +66,26 @@ export function ShoppingListsPageContent({ lists }: Props) {
))}
</div>
)}
{sharedLists.length > 0 && (
<div className="space-y-3 max-w-lg">
<h2 className="text-sm font-semibold text-muted-foreground">Shared with you</h2>
{sharedLists.map((list) => (
<Link
key={list.id}
href={`/shopping-lists/${list.id}`}
className="flex items-center justify-between rounded-xl border p-4 hover:shadow-sm transition-shadow"
>
<div className="space-y-1">
<h3 className="font-semibold">{list.name}</h3>
<p className="text-sm text-muted-foreground">
{list.ownerName} · {list.role}
</p>
</div>
</Link>
))}
</div>
)}
</div>
);
}