feat: notifications inbox page

The bell only ever showed the last 30; add a full paginated /notifications
page, per-notification mark-read, and a shared notificationHref helper so
the bell and the page route identically instead of duplicating the logic.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-10 07:57:17 +02:00
parent 45b886e398
commit 913410dbf3
9 changed files with 265 additions and 12 deletions
@@ -0,0 +1,14 @@
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
export default function NotificationsLoading() {
return (
<div className="space-y-6 max-w-2xl">
<PageHeaderSkeleton actions={1} />
<div className="space-y-3">
{Array.from({ length: 6 }).map((_, i) => (
<ListRowSkeleton key={i} />
))}
</div>
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { NotificationsPageContent } from "@/components/notifications/notifications-page-content";
export const metadata: Metadata = {};
export default async function NotificationsPage() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
return <NotificationsPageContent />;
}
@@ -0,0 +1,17 @@
import { NextResponse } from "next/server";
import { db, notifications, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
export async function POST(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
await db
.update(notifications)
.set({ read: true })
.where(and(eq(notifications.id, id), eq(notifications.userId, session!.user.id)));
return NextResponse.json({ ok: true });
}
+22 -5
View File
@@ -1,12 +1,18 @@
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { db, notifications, users, eq, and, desc, count } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
export async function GET() {
export async function GET(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const [rows, unread] = await Promise.all([
const { searchParams } = req.nextUrl;
const limitRaw = parseInt(searchParams.get("limit") ?? "20");
const limit = Math.min(Number.isNaN(limitRaw) ? 20 : Math.max(1, limitRaw), 100);
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
const [rows, unread, totalRow] = await Promise.all([
db
.select({
id: notifications.id,
@@ -24,12 +30,23 @@ export async function GET() {
.innerJoin(users, eq(notifications.actorId, users.id))
.where(eq(notifications.userId, session!.user.id))
.orderBy(desc(notifications.createdAt))
.limit(30),
.limit(limit)
.offset(offset),
db
.select({ total: count() })
.from(notifications)
.where(and(eq(notifications.userId, session!.user.id), eq(notifications.read, false))),
db
.select({ total: count() })
.from(notifications)
.where(eq(notifications.userId, session!.user.id)),
]);
return NextResponse.json({ notifications: rows, unreadCount: unread[0]?.total ?? 0 });
return NextResponse.json({
notifications: rows,
unreadCount: unread[0]?.total ?? 0,
total: totalRow[0]?.total ?? 0,
limit,
offset,
});
}
@@ -0,0 +1,164 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { notificationHref, type NotificationType } from "@/lib/notification-links";
const PAGE_SIZE = 20;
type Notification = {
id: string;
type: NotificationType;
recipeId: string | null;
commentId: string | null;
read: boolean;
createdAt: string;
actorId: string;
actorName: string;
actorUsername: string | null;
actorAvatarUrl: string | null;
};
type NotificationsResponse = {
notifications: Notification[];
unreadCount: number;
total: number;
limit: number;
offset: number;
};
function timeAgo(dateStr: string, t: ReturnType<typeof useTranslations>) {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return t("justNow");
if (mins < 60) return t("minutesAgo", { mins });
const hours = Math.floor(mins / 60);
if (hours < 24) return t("hoursAgo", { hours });
return t("daysAgo", { days: Math.floor(hours / 24) });
}
export function NotificationsPageContent() {
const t = useTranslations("notifications");
const tSocial = useTranslations("social");
const [items, setItems] = useState<Notification[]>([]);
const [total, setTotal] = useState(0);
const [unreadCount, setUnreadCount] = useState(0);
const [offset, setOffset] = useState(0);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState(false);
const fetchPage = useCallback(async (off: number, append: boolean) => {
if (append) setLoadingMore(true);
else setLoading(true);
setError(false);
try {
const res = await fetch(`/api/v1/notifications?limit=${PAGE_SIZE}&offset=${off}`);
if (!res.ok) throw new Error("Request failed");
const json = (await res.json()) as NotificationsResponse;
setItems((prev) => (append ? [...prev, ...json.notifications] : json.notifications));
setTotal(json.total);
setUnreadCount(json.unreadCount);
setOffset(off + json.notifications.length);
} catch {
setError(true);
} finally {
setLoading(false);
setLoadingMore(false);
}
}, []);
useEffect(() => {
void fetchPage(0, false);
}, [fetchPage]);
async function markRead(id: string) {
setItems((prev) => prev.map((n) => (n.id === id ? { ...n, read: true } : n)));
setUnreadCount((prev) => {
const n = items.find((x) => x.id === id);
return n && !n.read ? Math.max(0, prev - 1) : prev;
});
await fetch(`/api/v1/notifications/${id}/read`, { method: "POST" });
}
async function markAllRead() {
setUnreadCount(0);
setItems((prev) => prev.map((n) => ({ ...n, read: true })));
await fetch("/api/v1/notifications/read", { method: "POST" });
}
const hasMore = items.length < total;
return (
<div className="space-y-6 max-w-2xl">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>
{unreadCount > 0 && (
<Button variant="outline" size="sm" onClick={() => void markAllRead()}>
{t("markAllRead")}
</Button>
)}
</div>
{loading ? (
<p className="text-sm text-muted-foreground">{t("loading")}</p>
) : error && items.length === 0 ? (
<div className="flex flex-col items-start gap-2">
<p className="text-sm text-destructive">{t("loadFailed")}</p>
<Button variant="outline" size="sm" onClick={() => void fetchPage(0, false)}>
{t("retry")}
</Button>
</div>
) : items.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">{t("empty")}</p>
) : (
<div className="divide-y rounded-xl border">
{items.map((n) => (
<Link
key={n.id}
href={notificationHref(n)}
onClick={() => { if (!n.read) void markRead(n.id); }}
className={cn(
"flex items-start gap-3 p-4 hover:bg-accent transition-colors",
!n.read && "bg-accent/40"
)}
>
<Avatar className="h-9 w-9 shrink-0">
<AvatarImage src={n.actorAvatarUrl ?? ""} alt={n.actorName} />
<AvatarFallback className="text-xs">{n.actorName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-1">
<p className={cn("text-sm", !n.read && "font-medium")}>
{t(n.type, { name: n.actorName })}
</p>
<p className="text-xs text-muted-foreground">{timeAgo(n.createdAt, tSocial)}</p>
</div>
{!n.read && <span className="mt-1.5 h-2 w-2 rounded-full bg-primary shrink-0" aria-label={t("unread")} />}
</Link>
))}
</div>
)}
{error && items.length > 0 && (
<p className="text-sm text-destructive">{t("loadFailed")}</p>
)}
{(hasMore || (error && items.length > 0)) && (
<div className="flex justify-center pt-2">
<Button
variant="outline"
size="sm"
onClick={() => void fetchPage(offset, true)}
disabled={loadingMore}
>
{loadingMore ? t("loading") : error ? t("retry") : t("loadMore")}
</Button>
</div>
)}
</div>
);
}
@@ -13,10 +13,11 @@ import {
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { notificationHref, type NotificationType } from "@/lib/notification-links";
type Notification = {
id: string;
type: "follow" | "comment" | "reply" | "reaction" | "rating" | "mention";
type: NotificationType;
recipeId: string | null;
commentId: string | null;
read: boolean;
@@ -26,12 +27,6 @@ type Notification = {
actorUsername: string | null;
};
function notificationHref(n: Notification): string {
if (n.type === "follow") return n.actorUsername ? `/u/${n.actorUsername}` : "#";
if (n.recipeId) return `/recipes/${n.recipeId}`;
return "#";
}
export function NotificationBell() {
const t = useTranslations("notifications");
const [notifications, setNotifications] = useState<Notification[]>([]);
@@ -104,6 +99,12 @@ export function NotificationBell() {
</DropdownMenuItem>
))}
</div>
<DropdownMenuItem
render={<Link href="/notifications" />}
className="justify-center text-sm text-muted-foreground hover:text-foreground"
>
{t("viewAll")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
+15
View File
@@ -0,0 +1,15 @@
export type NotificationType = "follow" | "comment" | "reply" | "reaction" | "rating" | "mention";
export type NotificationLinkable = {
type: NotificationType;
recipeId: string | null;
actorUsername: string | null;
};
/** Where clicking a notification should navigate to. Shared by the bell dropdown
* and the full notifications page so the two never drift apart. */
export function notificationHref(n: NotificationLinkable): string {
if (n.type === "follow") return n.actorUsername ? `/u/${n.actorUsername}` : "#";
if (n.recipeId) return `/recipes/${n.recipeId}`;
return "#";
}
+6
View File
@@ -24,6 +24,12 @@
"title": "Notifications",
"empty": "No notifications yet.",
"markAllRead": "Mark all as read",
"viewAll": "View all",
"loading": "Loading…",
"loadMore": "Load more",
"loadFailed": "Failed to load notifications. Check your connection and try again.",
"retry": "Retry",
"unread": "Unread",
"follow": "{name} followed you",
"comment": "{name} commented on your recipe",
"reply": "{name} replied to your comment",
+6
View File
@@ -24,6 +24,12 @@
"title": "Notifications",
"empty": "Aucune notification pour l'instant.",
"markAllRead": "Tout marquer comme lu",
"viewAll": "Tout voir",
"loading": "Chargement…",
"loadMore": "Charger plus",
"loadFailed": "Échec du chargement des notifications. Vérifiez votre connexion et réessayez.",
"retry": "Réessayer",
"unread": "Non lu",
"follow": "{name} vous suit désormais",
"comment": "{name} a commenté votre recette",
"reply": "{name} a répondu à votre commentaire",