notifications
Deploy / deploy (push) Successful in 2m32s

This commit is contained in:
twotalesanimation
2026-06-19 13:25:19 +02:00
parent 1a77a82566
commit 835081c1b9
3 changed files with 242 additions and 55 deletions
+42
View File
@@ -0,0 +1,42 @@
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
// Mark a single notification as read
export async function PATCH(
_req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
await db.notification.updateMany({
where: { id, userId: session.user.id },
data: { isRead: true },
});
return NextResponse.json({ success: true });
}
// Dismiss (delete) a single notification
export async function DELETE(
_req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
await db.notification.deleteMany({
where: { id, userId: session.user.id },
});
return NextResponse.json({ success: true });
}
+15
View File
@@ -21,6 +21,7 @@ export async function GET() {
return NextResponse.json({ notifications, unreadCount }); return NextResponse.json({ notifications, unreadCount });
} }
// Mark all as read
export async function PATCH() { export async function PATCH() {
const session = await auth(); const session = await auth();
if (!session?.user) { if (!session?.user) {
@@ -34,3 +35,17 @@ export async function PATCH() {
return NextResponse.json({ success: true }); return NextResponse.json({ success: true });
} }
// Clear all notifications
export async function DELETE() {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
await db.notification.deleteMany({
where: { userId: session.user.id },
});
return NextResponse.json({ success: true });
}
+185 -55
View File
@@ -1,13 +1,23 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect, useCallback } from "react";
import { Bell, Check, CheckCheck } from "lucide-react"; import {
Bell,
CheckCheck,
Film,
MessageSquare,
CheckCircle2,
XCircle,
AlertCircle,
UserPlus,
Clock,
CornerDownRight,
X,
Trash2,
} from "lucide-react";
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -26,55 +36,119 @@ interface Notification {
createdAt: string; createdAt: string;
} }
const TYPE_CONFIG: Record<
string,
{ icon: React.ElementType; color: string; bg: string }
> = {
VERSION_UPLOADED: { icon: Film, color: "text-blue-400", bg: "bg-blue-500/10" },
FEEDBACK_ADDED: { icon: MessageSquare, color: "text-amber-400", bg: "bg-amber-500/10" },
SHOT_APPROVED: { icon: CheckCircle2, color: "text-emerald-400", bg: "bg-emerald-500/10" },
SHOT_REJECTED: { icon: XCircle, color: "text-red-400", bg: "bg-red-500/10" },
REVISION_REQUESTED: { icon: AlertCircle, color: "text-orange-400", bg: "bg-orange-500/10" },
COMMENT_REPLY: { icon: CornerDownRight, color: "text-zinc-400", bg: "bg-zinc-500/10" },
MENTION: { icon: MessageSquare, color: "text-sky-400", bg: "bg-sky-500/10" },
TASK_ASSIGNED: { icon: UserPlus, color: "text-sky-400", bg: "bg-sky-500/10" },
TASK_READY_FOR_REVIEW: { icon: Clock, color: "text-purple-400", bg: "bg-purple-500/10" },
TASK_APPROVED: { icon: CheckCircle2, color: "text-emerald-400", bg: "bg-emerald-500/10" },
TASK_CHANGES_REQUESTED: { icon: AlertCircle, color: "text-orange-400", bg: "bg-orange-500/10" },
TASK_OVERDUE: { icon: AlertCircle, color: "text-red-400", bg: "bg-red-500/10" },
};
function getNotificationHref(n: Notification): string | null {
const data = n.data as Record<string, string> | null;
if (data?.versionId) return `/review/${data.versionId}`;
if (data?.taskId) return `/tasks?highlight=${data.taskId}`;
return null;
}
export function NotificationBell() { export function NotificationBell() {
const [notifications, setNotifications] = useState<Notification[]>([]); const [notifications, setNotifications] = useState<Notification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const unreadCount = notifications.filter((n) => !n.isRead).length; const [open, setOpen] = useState(false);
const fetchNotifications = async () => { const fetchNotifications = useCallback(async () => {
setIsLoading(true); setIsLoading(true);
try { try {
const res = await fetch("/api/notifications"); const res = await fetch("/api/notifications");
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setNotifications(data.notifications ?? []); setNotifications(data.notifications ?? []);
setUnreadCount(data.unreadCount ?? 0);
} }
} catch { } catch {
// silent // silent
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; }, []);
// Initial load + poll every 30s (skip while panel is open to avoid flicker)
useEffect(() => {
fetchNotifications();
const interval = setInterval(() => {
if (!open) fetchNotifications();
}, 30_000);
return () => clearInterval(interval);
}, [fetchNotifications, open]);
// Refresh full list whenever the panel opens
useEffect(() => {
if (open) fetchNotifications();
}, [open, fetchNotifications]);
const markAllRead = async () => { const markAllRead = async () => {
try { try {
await fetch("/api/notifications", { method: "PATCH" }); await fetch("/api/notifications", { method: "PATCH" });
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true }))); setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
setUnreadCount(0);
} catch { } catch {
// silent // silent
} }
}; };
const getNotificationHref = (n: Notification): string | null => { const markOneRead = useCallback(
const data = n.data as Record<string, string> | null; async (id: string) => {
if (data?.versionId) return `/review/${data.versionId}`; const n = notifications.find((n) => n.id === id);
return null; if (!n || n.isRead) return;
try {
await fetch(`/api/notifications/${id}`, { method: "PATCH" });
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
);
setUnreadCount((prev) => Math.max(0, prev - 1));
} catch {
// silent
}
},
[notifications]
);
const dismiss = async (e: React.MouseEvent, id: string) => {
e.preventDefault();
e.stopPropagation();
const wasUnread = notifications.find((n) => n.id === id)?.isRead === false;
try {
await fetch(`/api/notifications/${id}`, { method: "DELETE" });
setNotifications((prev) => prev.filter((n) => n.id !== id));
if (wasUnread) setUnreadCount((prev) => Math.max(0, prev - 1));
} catch {
// silent
}
}; };
const getNotificationIcon = (type: string): string => { const clearAll = async () => {
const icons: Record<string, string> = { try {
VERSION_UPLOADED: "🎬", await fetch("/api/notifications", { method: "DELETE" });
FEEDBACK_ADDED: "💬", setNotifications([]);
SHOT_APPROVED: "✅", setUnreadCount(0);
SHOT_REJECTED: "❌", } catch {
COMMENT_REPLY: "↩️", // silent
REVISION_REQUESTED: "⚠️", }
};
return icons[type] ?? "🔔";
}; };
return ( return (
<DropdownMenu onOpenChange={(open) => open && fetchNotifications()}> <DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" className="relative"> <Button variant="ghost" size="icon-sm" className="relative">
<Bell className="h-4 w-4" /> <Bell className="h-4 w-4" />
@@ -85,16 +159,23 @@ export function NotificationBell() {
)} )}
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 p-0">
<DropdownMenuContent align="end" className="w-96 p-0">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-border"> <div className="flex items-center justify-between px-4 py-3 border-b border-border">
<DropdownMenuLabel className="p-0 text-sm font-semibold"> <div className="flex items-center gap-2">
Notifications <span className="text-sm font-semibold">Notifications</span>
</DropdownMenuLabel> {unreadCount > 0 && (
<span className="inline-flex items-center justify-center h-5 min-w-5 px-1.5 rounded-full bg-primary text-[10px] font-bold text-primary-foreground">
{unreadCount}
</span>
)}
</div>
{unreadCount > 0 && ( {unreadCount > 0 && (
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
className="h-auto py-0 text-xs text-muted-foreground hover:text-foreground" className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
onClick={markAllRead} onClick={markAllRead}
> >
<CheckCheck className="h-3 w-3 mr-1" /> <CheckCheck className="h-3 w-3 mr-1" />
@@ -103,62 +184,111 @@ export function NotificationBell() {
)} )}
</div> </div>
<ScrollArea className="max-h-80"> {/* Notification list */}
{isLoading ? ( <ScrollArea className="max-h-[480px]">
<div className="flex items-center justify-center py-8"> {isLoading && notifications.length === 0 ? (
<div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" /> <div className="flex items-center justify-center py-10">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div> </div>
) : notifications.length === 0 ? ( ) : notifications.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-muted-foreground"> <div className="flex flex-col items-center justify-center py-12 text-muted-foreground gap-2">
<Bell className="h-8 w-8 mb-2 opacity-30" /> <Bell className="h-8 w-8 opacity-20" />
<p className="text-sm">No notifications</p> <p className="text-sm">You&rsquo;re all caught up</p>
</div> </div>
) : ( ) : (
<div> <div>
{notifications.map((n) => { {notifications.map((n) => {
const href = getNotificationHref(n); const href = getNotificationHref(n);
const cfg = TYPE_CONFIG[n.type] ?? {
icon: Bell,
color: "text-zinc-400",
bg: "bg-zinc-500/10",
};
const Icon = cfg.icon;
const content = ( const inner = (
<> <div
<span className="text-base mt-0.5 shrink-0"> className={cn(
{getNotificationIcon(n.type)} "flex gap-3 px-4 py-3 border-b border-border/50 last:border-0 group/row relative transition-colors",
</span> !n.isRead ? "bg-primary/5" : "",
<div className="flex-1 min-w-0"> (href || !n.isRead) && "hover:bg-secondary/40"
<p className={cn("text-xs leading-relaxed", !n.isRead && "font-medium")}> )}
>
{/* Type icon */}
<div className={cn("mt-0.5 shrink-0 rounded-full p-1.5", cfg.bg)}>
<Icon className={cn("h-3.5 w-3.5", cfg.color)} />
</div>
{/* Message + time */}
<div className="flex-1 min-w-0 pr-5">
<p
className={cn(
"text-xs leading-relaxed text-foreground",
!n.isRead && "font-medium"
)}
>
{n.message} {n.message}
</p> </p>
<p className="text-xs text-muted-foreground mt-0.5"> <p className="text-[11px] text-muted-foreground mt-0.5">
{formatRelativeDate(new Date(n.createdAt))} {formatRelativeDate(new Date(n.createdAt))}
</p> </p>
</div> </div>
{!n.isRead && (
<div className="h-2 w-2 rounded-full bg-primary shrink-0 mt-1.5" />
)}
</>
);
const className = cn( {/* Unread dot */}
"flex gap-3 px-4 py-3 hover:bg-secondary/50 transition-colors cursor-pointer border-b border-border/50 last:border-0", {!n.isRead && (
!n.isRead && "bg-primary/5" <div className="absolute right-7 top-4 h-1.5 w-1.5 rounded-full bg-primary shrink-0" />
)}
{/* Dismiss button */}
<button
onClick={(e) => dismiss(e, n.id)}
className="absolute right-2 top-2.5 opacity-0 group-hover/row:opacity-100 p-0.5 rounded text-muted-foreground hover:text-foreground transition-all"
title="Dismiss"
>
<X className="h-3 w-3" />
</button>
</div>
); );
if (href) { if (href) {
return ( return (
<Link key={n.id} href={href} className={className}> <Link
{content} key={n.id}
href={href}
className="block"
onClick={() => markOneRead(n.id)}
>
{inner}
</Link> </Link>
); );
} }
return ( return (
<div key={n.id} className={className}> <div
{content} key={n.id}
onClick={() => markOneRead(n.id)}
className="cursor-default"
>
{inner}
</div> </div>
); );
})} })}
</div> </div>
)} )}
</ScrollArea> </ScrollArea>
{/* Footer */}
{notifications.length > 0 && (
<div className="flex items-center justify-center px-4 py-2 border-t border-border">
<button
onClick={clearAll}
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<Trash2 className="h-3 w-3" />
Clear all
</button>
</div>
)}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
); );