Files
spsays-training/app/(app)/notifications/page.tsx
T
2026-10-09 06:40:28 +05:30

377 lines
11 KiB
TypeScript

"use client";
/**
* /notifications — the signed-in user's notifications, split into two tabs:
*
* • "Notifications" — the activity feed (likes, comments, mentions, accepted
* follows, admin messages). Marked read on open so the header bell clears.
* • "Friend Requests" — pending incoming follow requests, accepted/rejected
* inline. Sourced from the live `follows` table (not the notifications
* feed), so handled requests disappear and never go stale.
*
* Anonymous visitors are bounced through the auth gate (then home if they
* dismiss it), mirroring /u/me.
*/
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Bell, Check, UserPlus, X } from "lucide-react";
import { toast } from "sonner";
import { useAuth } from "@/components/auth/auth-provider";
import { useAuthGate } from "@/components/auth/auth-gate";
import { useNotifications } from "@/components/notifications/notifications-provider";
import {
notifications,
relationships,
SocialError,
type AppNotification,
type UserSummary,
} from "@/lib/social";
import { RichText } from "@/lib/rich-text";
import { UserAvatar } from "@/components/ui/user-avatar";
import { Button } from "@/components/ui/button";
import { timeAgo } from "@/lib/time";
import { cn } from "@/lib/utils";
type Tab = "all" | "requests";
export default function NotificationsPage() {
const { user, loading } = useAuth();
const { requireAuth } = useAuthGate();
const { lastEventAt, clearUnread } = useNotifications();
const router = useRouter();
const [tab, setTab] = useState<Tab>("all");
const [items, setItems] = useState<AppNotification[]>([]);
const [requests, setRequests] = useState<UserSummary[]>([]);
const [state, setState] = useState<"loading" | "ready" | "error">("loading");
// Auth gate — same pattern as /u/me.
useEffect(() => {
if (loading || user) return;
let cancelled = false;
(async () => {
const ok = await requireAuth();
if (!ok && !cancelled) router.replace("/");
})();
return () => {
cancelled = true;
};
}, [loading, user, requireAuth, router]);
// Load the feed + pending requests, and mark the feed read, once we have a
// user — and again whenever a realtime notification arrives while the page
// is open (lastEventAt bumps). Marking read here clears the header badge.
useEffect(() => {
if (!user) return;
let cancelled = false;
Promise.all([notifications.list(), relationships.incomingRequests()])
.then(([rows, reqs]) => {
if (!cancelled) {
setItems(rows ?? []);
setRequests(reqs?.users ?? []);
setState("ready");
}
})
.catch(() => {
if (!cancelled) setState("error");
});
notifications
.markAllRead()
.then(() => clearUnread())
.catch(() => {
/* non-critical */
});
return () => {
cancelled = true;
};
}, [user, lastEventAt, clearUnread]);
if (loading || !user) {
return (
<main className="flex-1 flex items-center justify-center px-4 py-12">
<p className="text-sm text-muted-foreground">
{loading ? "Loading…" : "Sign in to view your notifications."}
</p>
</main>
);
}
// Follow requests live in their own tab — keep them out of the activity feed.
const feedItems = items.filter((n) => n.kind !== "follow_request");
const resolveRequest = (handle: string) =>
setRequests((prev) => prev.filter((r) => r.handle !== handle));
return (
<main className="flex-1 max-w-2xl w-full mx-auto px-4 sm:px-6 py-6 space-y-6">
<h1 className="font-[family-name:var(--font-title)] text-3xl font-semibold text-foreground">
Notifications
</h1>
{/* Tabs */}
<div className="flex gap-1 rounded-lg bg-muted p-1">
<TabButton active={tab === "all"} onClick={() => setTab("all")}>
Notifications
</TabButton>
<TabButton
active={tab === "requests"}
onClick={() => setTab("requests")}
badge={requests.length}
>
Friend Requests
</TabButton>
</div>
{state === "error" ? (
<p className="text-sm text-destructive">
Could not load notifications. Please try again.
</p>
) : state === "loading" ? (
<p className="text-sm text-muted-foreground">Loading…</p>
) : tab === "all" ? (
feedItems.length === 0 ? (
<Empty
icon={<Bell className="size-8" />}
text="No notifications yet."
/>
) : (
<ul className="divide-y divide-border rounded-2xl border border-border overflow-hidden">
{feedItems.map((n) => (
<NotificationRow key={n.id} n={n} selfHandle={user.handle} />
))}
</ul>
)
) : requests.length === 0 ? (
<Empty
icon={<UserPlus className="size-8" />}
text="No pending friend requests."
/>
) : (
<ul className="divide-y divide-border rounded-2xl border border-border overflow-hidden">
{requests.map((u) => (
<RequestRow key={u.handle} u={u} onResolve={resolveRequest} />
))}
</ul>
)}
</main>
);
}
function TabButton({
active,
onClick,
badge,
children,
}: {
active: boolean;
onClick: () => void;
badge?: number;
children: React.ReactNode;
}) {
return (
<button
type="button"
onClick={onClick}
className={cn(
"flex-1 inline-flex items-center justify-center gap-2 h-9 rounded-md text-sm font-medium transition-colors",
active
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}
>
{children}
{badge && badge > 0 ? (
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 rounded-full bg-primary text-primary-foreground dark:text-white text-xs font-semibold">
{badge}
</span>
) : null}
</button>
);
}
function RequestRow({
u,
onResolve,
}: {
u: UserSummary;
onResolve: (handle: string) => void;
}) {
const [busy, setBusy] = useState(false);
const display = u.name || `@${u.handle}`;
async function act(kind: "accept" | "reject") {
if (busy) return;
setBusy(true);
try {
await relationships[kind](u.handle);
if (kind === "accept") {
toast(`${display} now follows you`, { duration: 2500 });
}
onResolve(u.handle);
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not update request",
{ duration: 3000 },
);
setBusy(false);
}
}
return (
<li className="flex items-center gap-3 px-4 py-3">
<Link href={`/u/${u.handle}`} className="shrink-0">
<UserAvatar src={u.avatar_url} name={display} />
</Link>
<div className="min-w-0 flex-1">
<Link
href={`/u/${u.handle}`}
className="block text-sm font-semibold text-foreground truncate hover:underline"
>
{display}
</Link>
<p className="text-xs text-muted-foreground truncate">
@{u.handle} · requested to follow you
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button size="sm" onClick={() => act("accept")} disabled={busy}>
<Check className="size-4" />
Accept
</Button>
<Button
size="sm"
variant="outline"
onClick={() => act("reject")}
disabled={busy}
aria-label="Reject request"
>
<X className="size-4" />
</Button>
</div>
</li>
);
}
function NotificationRow({
n,
selfHandle,
}: {
n: AppNotification;
selfHandle: string;
}) {
// admin_message rows have no actor — they're a direct message from the team.
const isAdmin = n.kind === "admin_message";
const display = isAdmin
? "Prabhupāda Says"
: n.actor_name || (n.actor_handle ? `@${n.actor_handle}` : "Someone");
const message = messageFor(n);
const unread = !n.read_at;
const body = (
<div
className={cnRow(unread)}
>
<UserAvatar src={isAdmin ? null : n.actor_avatar_url} name={display} />
<div className="min-w-0 flex-1">
{isAdmin ? (
// A div, not a <p>: the formatted body nests elements, and RichText
// handles line breaks itself (so no whitespace-pre-line either).
<div className="text-sm text-foreground leading-snug">
<span className="font-semibold">{display}</span>
{n.body ? (
<span className="block mt-0.5">
<RichText text={n.body} />
</span>
) : null}
</div>
) : (
<p className="text-sm text-foreground leading-snug">
<span className="font-semibold">{display}</span> {message}
</p>
)}
<p className="text-xs text-muted-foreground mt-0.5">
{timeAgo(n.created_at)}
</p>
</div>
{unread ? (
<span className="mt-1.5 size-2 shrink-0 rounded-full bg-primary" />
) : null}
</div>
);
// A like links to your own post; a mention links to the actor's post you
// were tagged in; everything else links to the actor's profile.
const href =
n.kind === "post_like" && n.post_id
? `/u/${selfHandle}/posts#post-${n.post_id}`
: n.kind === "post_mention" && n.post_id && n.actor_handle
? `/u/${n.actor_handle}/posts#post-${n.post_id}`
: (n.kind === "post_comment" ||
n.kind === "comment_reply" ||
n.kind === "comment_mention") &&
n.post_id &&
n.post_author_handle
? `/u/${n.post_author_handle}/posts#post-${n.post_id}`
: n.actor_handle
? `/u/${n.actor_handle}`
: null;
return href ? (
<li>
<Link href={href} className="block">
{body}
</Link>
</li>
) : (
<li>{body}</li>
);
}
function cnRow(unread: boolean) {
return [
"flex items-start gap-3 px-4 py-3 transition-colors hover:bg-muted/50",
unread ? "bg-primary/5" : "",
].join(" ");
}
/** Human-readable tail for each notification kind. Add cases as new
* notification kinds are introduced on the backend. */
function messageFor(n: AppNotification): string {
switch (n.kind) {
case "follow_request":
return "requested to follow you.";
case "follow_accepted":
return "accepted your follow request.";
case "post_like": {
const others = (n.actor_count ?? 1) - 1;
if (others <= 0) return "liked your post.";
return `and ${others} ${others === 1 ? "other" : "others"} liked your post.`;
}
case "post_mention":
return "mentioned you in a post.";
case "post_comment":
return "commented on your post.";
case "comment_reply":
return "replied to your comment.";
case "comment_mention":
return "mentioned you in a comment.";
case "disciple_joined":
return "— a direct disciple of Śrīla Prabhupāda — has joined Prabhupāda Says.";
case "admin_message":
return n.body ?? "sent you a message.";
default:
return "sent you a notification.";
}
}
function Empty({ icon, text }: { icon: React.ReactNode; text: string }) {
return (
<div className="flex flex-col items-center text-center gap-3 py-16 text-muted-foreground">
{icon}
<p className="text-sm">{text}</p>
</div>
);
}