Staff with read-all oversight (superuser / system:admin-access) see everyone's notifications in the bell. Add a "Show all users" switch inside the dropdown, rendered only when the caller can view others, that narrows the feed to the caller's own notifications. The choice is remembered per browser (localStorage) and the unread badge follows the selected scope. The inbox route now reports canViewOthers and honors scope=all|mine; non-staff callers are always forced to their own regardless of the param.
319 lines
12 KiB
TypeScript
319 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import Link from "next/link";
|
|
import { BellIcon, CheckIcon } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Switch } from "@/components/ui/switch";
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuLabel,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuTrigger,
|
|
} from "@/components/ui/dropdown-menu";
|
|
import { cn } from "@/lib/utils";
|
|
import { notificationLabel } from "@/lib/notifications";
|
|
import { NOTIFICATION_EVENT } from "@/hooks/useGameTick";
|
|
import {
|
|
markAllNotificationsRead,
|
|
markNotificationsRead,
|
|
} from "@/app/(frontend)/notifications/actions";
|
|
|
|
interface NotificationItem {
|
|
id: number;
|
|
type?: string | null;
|
|
title: string;
|
|
message?: string | null;
|
|
link?: string | null;
|
|
read: boolean;
|
|
createdAt: string;
|
|
/**
|
|
* Whether this notification belongs to the current user. When false the
|
|
* current user (staff with read-all) is viewing someone else's notification;
|
|
* it can be shown and opened but its read-state must never be changed.
|
|
*/
|
|
isMine?: boolean;
|
|
/** Display name of the user this notification is actually meant for. Only set when `!isMine`. */
|
|
ownerName?: string | null;
|
|
}
|
|
|
|
function timeAgo(iso: string): string {
|
|
const diff = Date.now() - new Date(iso).getTime();
|
|
const minutes = Math.floor(diff / 60000);
|
|
if (minutes < 1) return "just now";
|
|
if (minutes < 60) return `${minutes}m ago`;
|
|
const hours = Math.floor(minutes / 60);
|
|
if (hours < 24) return `${hours}h ago`;
|
|
const days = Math.floor(hours / 24);
|
|
return `${days}d ago`;
|
|
}
|
|
|
|
const POLL_MS = 60_000;
|
|
|
|
/**
|
|
* Per-browser memory of whether a staff user wants the bell to show everyone's
|
|
* notifications ("all") or only their own ("mine"). Non-staff are always
|
|
* scoped to their own server-side, so the value is irrelevant to them.
|
|
*/
|
|
const SCOPE_KEY = "ptf:notifications:scope";
|
|
type Scope = "all" | "mine";
|
|
|
|
function readStoredScope(): Scope {
|
|
if (typeof window === "undefined") return "all";
|
|
try {
|
|
return window.localStorage.getItem(SCOPE_KEY) === "mine" ? "mine" : "all";
|
|
} catch {
|
|
return "all";
|
|
}
|
|
}
|
|
|
|
export function NotificationsBell() {
|
|
const router = useRouter();
|
|
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
|
const [open, setOpen] = useState(false);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState(false);
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
const [marking, setMarking] = useState(false);
|
|
const [scope, setScope] = useState<Scope>(readStoredScope);
|
|
const [canViewOthers, setCanViewOthers] = useState(false);
|
|
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
|
|
const unreadCount = notifications.filter((n) => !n.read).length;
|
|
|
|
const fetchNotifications = useCallback(async () => {
|
|
try {
|
|
const res = await fetch(`/api/notifications/inbox?limit=12&sort=-createdAt&scope=${scope}`, {
|
|
cache: "no-store",
|
|
});
|
|
if (!res.ok) throw new Error("Failed to fetch");
|
|
const data = (await res.json()) as {
|
|
notifications?: NotificationItem[];
|
|
canViewOthers?: boolean;
|
|
};
|
|
setNotifications(data.notifications ?? []);
|
|
setCanViewOthers(Boolean(data.canViewOthers));
|
|
setError(false);
|
|
} catch {
|
|
setError(true);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [scope]);
|
|
|
|
useEffect(() => {
|
|
void fetchNotifications();
|
|
intervalRef.current = setInterval(() => void fetchNotifications(), POLL_MS);
|
|
const onNotification = () => void fetchNotifications();
|
|
window.addEventListener(NOTIFICATION_EVENT, onNotification);
|
|
return () => {
|
|
if (intervalRef.current) clearInterval(intervalRef.current);
|
|
window.removeEventListener(NOTIFICATION_EVENT, onNotification);
|
|
};
|
|
}, [fetchNotifications]);
|
|
|
|
// Read-state is personal to the recipient. Never let marking one change
|
|
// another user's read flag — staff are viewing it as an oversight, not as
|
|
// that user, so flipping it would hide the notification from them.
|
|
async function handleMarkOne(item: NotificationItem) {
|
|
if (item.read || marking || item.isMine === false) return;
|
|
setMarking(true);
|
|
setActionError(null);
|
|
try {
|
|
const result = await markNotificationsRead([item.id]);
|
|
if (result.success) {
|
|
setNotifications((prev) =>
|
|
prev.map((n) => (n.id === item.id ? { ...n, read: true } : n)),
|
|
);
|
|
} else {
|
|
setActionError(result.error ?? "Failed to update notifications.");
|
|
}
|
|
} catch (err) {
|
|
setActionError(err instanceof Error ? err.message : "Failed to update notifications.");
|
|
} finally {
|
|
setMarking(false);
|
|
}
|
|
}
|
|
|
|
async function handleItemClick(item: NotificationItem) {
|
|
// Own notifications are marked read on open; others' are only opened, never
|
|
// marked, so the real owner still sees them as unread.
|
|
if (!item.read && item.isMine !== false) await handleMarkOne(item);
|
|
if (item.link) {
|
|
router.push(item.link);
|
|
setOpen(false);
|
|
}
|
|
}
|
|
|
|
async function handleMarkAll() {
|
|
if (unreadCount === 0 || marking) return;
|
|
setMarking(true);
|
|
setActionError(null);
|
|
try {
|
|
const result = await markAllNotificationsRead();
|
|
if (result.success) {
|
|
// Only own rows are guaranteed to have been flipped, so only optimistic-
|
|
// update those. Staff viewing others' rows must not see them flip to read.
|
|
setNotifications((prev) =>
|
|
prev.map((n) => (n.isMine === false ? n : { ...n, read: true })),
|
|
);
|
|
} else {
|
|
setActionError(result.error ?? "Failed to update notifications.");
|
|
}
|
|
} catch (err) {
|
|
setActionError(err instanceof Error ? err.message : "Failed to update notifications.");
|
|
} finally {
|
|
setMarking(false);
|
|
}
|
|
}
|
|
|
|
function handleScopeToggle(next: boolean) {
|
|
const value: Scope = next ? "all" : "mine";
|
|
setScope(value);
|
|
try {
|
|
window.localStorage.setItem(SCOPE_KEY, value);
|
|
} catch {
|
|
// storage unavailable (private mode): the toggle still works this session
|
|
}
|
|
}
|
|
|
|
return (
|
|
<DropdownMenu open={open} onOpenChange={setOpen}>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="ghost" size="icon" className="relative" aria-label="Notifications">
|
|
<BellIcon className="size-5" />
|
|
{unreadCount > 0 && (
|
|
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-semibold text-white">
|
|
{unreadCount > 9 ? "9+" : unreadCount}
|
|
</span>
|
|
)}
|
|
<span aria-live="polite" className="sr-only">
|
|
{unreadCount > 0
|
|
? `${unreadCount} unread notification${unreadCount === 1 ? "" : "s"}`
|
|
: "No unread notifications"}
|
|
</span>
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent align="end" className="w-80 sm:w-96">
|
|
<div className="flex items-center justify-between pr-1">
|
|
<DropdownMenuLabel className="pb-1">Notifications</DropdownMenuLabel>
|
|
{unreadCount > 0 && (
|
|
<button
|
|
onClick={() => void handleMarkAll()}
|
|
disabled={marking}
|
|
aria-label="Mark all of my notifications as read"
|
|
className="text-xs text-muted-foreground hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
|
>
|
|
{marking ? "Marking..." : "Mark all read"}
|
|
</button>
|
|
)}
|
|
</div>
|
|
{canViewOthers && (
|
|
<div className="flex items-center justify-between gap-3 px-3 pb-2 pt-0.5">
|
|
<label htmlFor="notif-scope-all" className="cursor-pointer">
|
|
<span className="block text-xs font-medium">Show all users</span>
|
|
<span className="block text-[10px] text-muted-foreground">
|
|
{scope === "all" ? "You + everyone else" : "Only your notifications"}
|
|
</span>
|
|
</label>
|
|
<Switch
|
|
id="notif-scope-all"
|
|
size="sm"
|
|
checked={scope === "all"}
|
|
onCheckedChange={handleScopeToggle}
|
|
aria-label="Show notifications from all users"
|
|
/>
|
|
</div>
|
|
)}
|
|
<DropdownMenuSeparator />
|
|
<div className="max-h-96 overflow-y-auto">
|
|
{loading ? (
|
|
<p className="px-3 py-6 text-center text-sm text-muted-foreground">Loading...</p>
|
|
) : error ? (
|
|
<p className="px-3 py-6 text-center text-sm text-red-400">
|
|
Could not load notifications.
|
|
</p>
|
|
) : notifications.length === 0 ? (
|
|
<p className="px-3 py-6 text-center text-sm text-muted-foreground">
|
|
No notifications yet.
|
|
</p>
|
|
) : (
|
|
<>
|
|
{actionError && (
|
|
<p role="alert" className="px-3 pb-2 pt-1 text-xs text-red-400">
|
|
{actionError}
|
|
</p>
|
|
)}
|
|
{notifications.map((item) => {
|
|
const isUnread = !item.read;
|
|
const isForeign = item.isMine === false;
|
|
return (
|
|
<DropdownMenuItem
|
|
key={item.id}
|
|
className={cn(
|
|
"flex flex-col items-start gap-1 py-2.5",
|
|
isUnread && "bg-accent/50",
|
|
isForeign && "opacity-80",
|
|
)}
|
|
disabled={marking}
|
|
onClick={() => void handleItemClick(item)}
|
|
>
|
|
<span className="flex w-full items-center justify-between gap-2">
|
|
<span className="min-w-0 truncate text-sm font-medium">
|
|
{!isForeign && isUnread && (
|
|
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
|
|
)}
|
|
{item.title}
|
|
</span>
|
|
{!isForeign && item.read && (
|
|
<button
|
|
type="button"
|
|
title="Mark as read"
|
|
aria-label={`Mark "${item.title}" as read`}
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
void handleMarkOne(item);
|
|
}}
|
|
className="rounded-sm p-0.5 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
|
>
|
|
<CheckIcon className="size-3.5" />
|
|
</button>
|
|
)}
|
|
<span className="flex shrink-0 items-center gap-1.5">
|
|
<span className="text-[10px] text-muted-foreground">
|
|
{timeAgo(item.createdAt)}
|
|
</span>
|
|
</span>
|
|
</span>
|
|
{isForeign && item.ownerName && (
|
|
<span className="text-[10px] font-medium text-amber-400/90">
|
|
meant for {item.ownerName}
|
|
</span>
|
|
)}
|
|
{item.message && (
|
|
<span className="line-clamp-3 w-full text-xs text-muted-foreground">
|
|
{item.message}
|
|
</span>
|
|
)}
|
|
<span className="text-[10px] text-muted-foreground/70">
|
|
{notificationLabel(item.type)}
|
|
</span>
|
|
</DropdownMenuItem>
|
|
);
|
|
})}
|
|
</>
|
|
)}
|
|
</div>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuItem asChild>
|
|
<Link href="/notifications" className="justify-center text-sm font-medium">
|
|
View all
|
|
</Link>
|
|
</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
);
|
|
}
|