- announcements collection: info/success/warning/error variants, banner/modal/dialog/toast display types, up to 3 action buttons, dismissible flag, activeFrom/activeUntil windows, audience targeting (all/users/roles) and path include/exclude matching copied from the Shims pattern - pure client-safe evaluation lib (enabled, time window, audience via roleDoc IDs, path match) plus per-browser localStorage dismissals - AnnouncementHost mounted in the (frontend) layout: banners render inline, toasts via sonner custom markup, modals and confirmation dialogs queue one at a time - permissions announcements:create/read/update/delete + admin:announcements:manage - description is Lexical richText rendered via RichText/lexical-content on all surfaces; role targeting uses the dynamic Roles collection - hand-written migrations with snapshot sidecars (collection, roleDocs targeting, description richtext conversion) + integration tests (12 passing)
312 lines
11 KiB
TypeScript
312 lines
11 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { usePathname, useRouter } from "next/navigation";
|
|
import { toast } from "sonner";
|
|
import { AlertTriangle, CheckCircle2, Info, X, XCircle } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogContent,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
} from "@/components/ui/alert-dialog";
|
|
import { RichText } from "@payloadcms/richtext-lexical/react";
|
|
import { cn } from "@/lib/utils";
|
|
import {
|
|
isAnnouncementActive,
|
|
type AnnouncementButtonStyle,
|
|
type AnnouncementEntry,
|
|
type AnnouncementVariant,
|
|
} from "@/lib/announcements/evaluate";
|
|
import {
|
|
readAnnouncementDismissals,
|
|
storeAnnouncementDismissal,
|
|
type AnnouncementDismissals,
|
|
} from "@/lib/announcements/dismissals";
|
|
|
|
interface AnnouncementHostProps {
|
|
announcements: AnnouncementEntry[];
|
|
userId: number | null;
|
|
userRoleDocIds: number[];
|
|
}
|
|
|
|
const VARIANT_CLASSES: Record<AnnouncementVariant, string> = {
|
|
info: "border-blue-500/40 bg-blue-500/10 text-blue-100",
|
|
success: "border-emerald-500/40 bg-emerald-500/10 text-emerald-100",
|
|
warning: "border-amber-500/40 bg-amber-500/10 text-amber-100",
|
|
error: "border-red-500/40 bg-red-500/10 text-red-100",
|
|
};
|
|
|
|
const OVERLAY_CLASSES: Record<AnnouncementVariant, string> = {
|
|
info: "border-blue-500/40 bg-blue-950/50 text-blue-100",
|
|
success: "border-emerald-500/40 bg-emerald-950/50 text-emerald-100",
|
|
warning: "border-amber-500/40 bg-amber-950/50 text-amber-100",
|
|
error: "border-red-500/40 bg-red-950/50 text-red-100",
|
|
};
|
|
|
|
const VARIANT_ICONS: Record<AnnouncementVariant, typeof Info> = {
|
|
info: Info,
|
|
success: CheckCircle2,
|
|
warning: AlertTriangle,
|
|
error: XCircle,
|
|
};
|
|
|
|
const BUTTON_VARIANTS: Record<AnnouncementButtonStyle, "default" | "outline" | "destructive"> = {
|
|
default: "default",
|
|
outline: "outline",
|
|
destructive: "destructive",
|
|
};
|
|
|
|
type LexicalData = Parameters<typeof RichText>[0]["data"];
|
|
|
|
function AnnouncementRichText({ description }: { description: unknown }) {
|
|
if (typeof description === "string") {
|
|
return <p className="mt-2 font-normal text-sm opacity-90">{description}</p>;
|
|
}
|
|
if (!description || typeof description !== "object") return null;
|
|
return (
|
|
<div className="lexical-content mt-2">
|
|
<RichText data={description as LexicalData} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function AnnouncementHost({ announcements, userId, userRoleDocIds }: AnnouncementHostProps) {
|
|
const pathname = usePathname();
|
|
const router = useRouter();
|
|
const [mounted, setMounted] = useState(false);
|
|
const [dismissed, setDismissed] = useState<AnnouncementDismissals>({});
|
|
const [closedOverlayIds, setClosedOverlayIds] = useState<Set<number>>(new Set());
|
|
const [overlayOpen, setOverlayOpen] = useState(true);
|
|
const firedToastIdsRef = useRef<Set<number>>(new Set());
|
|
|
|
useEffect(() => {
|
|
setDismissed(readAnnouncementDismissals(Date.now()));
|
|
setMounted(true);
|
|
}, []);
|
|
|
|
const active = useMemo(() => {
|
|
if (!mounted) return [];
|
|
const now = Date.now();
|
|
return announcements.filter(
|
|
(announcement) =>
|
|
isAnnouncementActive(announcement, userId, userRoleDocIds, pathname, now) &&
|
|
!dismissed[String(announcement.id)],
|
|
);
|
|
}, [mounted, announcements, userId, userRoleDocIds, pathname, dismissed]);
|
|
|
|
const { banners, overlays, toasts } = useMemo(
|
|
() => ({
|
|
banners: active.filter((a) => a.displayType === "banner"),
|
|
overlays: active.filter((a) => a.displayType === "modal" || a.displayType === "dialog"),
|
|
toasts: active.filter((a) => a.displayType === "toast"),
|
|
}),
|
|
[active],
|
|
);
|
|
|
|
const currentOverlay = overlays.find((a) => !closedOverlayIds.has(a.id)) ?? null;
|
|
|
|
useEffect(() => {
|
|
setOverlayOpen(true);
|
|
}, [currentOverlay?.id]);
|
|
|
|
const dismiss = useCallback((announcement: AnnouncementEntry) => {
|
|
if (!announcement.dismissible) return;
|
|
storeAnnouncementDismissal(announcement.id, announcement.activeUntil, Date.now());
|
|
setDismissed((prev) => ({ ...prev, [String(announcement.id)]: Date.now() }));
|
|
}, []);
|
|
|
|
const dismissAndCloseOverlay = useCallback(
|
|
(announcement: AnnouncementEntry) => {
|
|
setClosedOverlayIds((prev) => new Set(prev).add(announcement.id));
|
|
setOverlayOpen(false);
|
|
dismiss(announcement);
|
|
},
|
|
[dismiss],
|
|
);
|
|
|
|
useEffect(() => {
|
|
for (const announcement of toasts) {
|
|
if (firedToastIdsRef.current.has(announcement.id)) continue;
|
|
firedToastIdsRef.current.add(announcement.id);
|
|
const Icon = VARIANT_ICONS[announcement.variant] ?? Info;
|
|
// toast.custom bypasses the shared Toaster's toastOptions, which force
|
|
// bg-background/text-foreground and flatten sonner's variant colors.
|
|
toast.custom(
|
|
(t) => (
|
|
<div
|
|
className={cn(
|
|
"flex items-start gap-3 rounded-lg border px-4 py-3 text-sm shadow-lg",
|
|
OVERLAY_CLASSES[announcement.variant],
|
|
)}
|
|
>
|
|
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
|
<div className="min-w-0 flex-1">
|
|
<span className="text-base font-bold">{announcement.title}</span>
|
|
{announcement.subtitle && (
|
|
<p className="text-xs opacity-80">{announcement.subtitle}</p>
|
|
)}
|
|
<AnnouncementRichText description={announcement.description} />
|
|
</div>
|
|
{announcement.dismissible && (
|
|
<button
|
|
type="button"
|
|
onClick={() => toast.dismiss(t)}
|
|
aria-label="Dismiss announcement"
|
|
className="rounded p-1 opacity-70 transition-opacity hover:opacity-100"
|
|
>
|
|
<X className="size-4" aria-hidden="true" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
),
|
|
{ duration: announcement.dismissible ? 10_000 : 15_000 },
|
|
);
|
|
}
|
|
}, [toasts]);
|
|
|
|
function handleButtonClick(announcement: AnnouncementEntry, href?: string | null) {
|
|
dismissAndCloseOverlay(announcement);
|
|
if (href) router.push(href);
|
|
}
|
|
|
|
function renderButtons(announcement: AnnouncementEntry, size: "sm" | "default") {
|
|
const buttons = announcement.buttons ?? [];
|
|
const rendered = buttons.map((button, index) => (
|
|
<Button
|
|
key={`${index}-${button.label}`}
|
|
variant={BUTTON_VARIANTS[button.style] ?? "default"}
|
|
size={size}
|
|
onClick={() => handleButtonClick(announcement, button.href)}
|
|
>
|
|
{button.label}
|
|
</Button>
|
|
));
|
|
if (rendered.length === 0) {
|
|
rendered.push(
|
|
<Button key="ok" size={size} onClick={() => dismissAndCloseOverlay(announcement)}>
|
|
OK
|
|
</Button>,
|
|
);
|
|
}
|
|
return rendered;
|
|
}
|
|
|
|
function renderBody(announcement: AnnouncementEntry, Header: typeof DialogHeader, Title: typeof DialogTitle) {
|
|
const Icon = VARIANT_ICONS[announcement.variant] ?? Info;
|
|
return (
|
|
<>
|
|
<Header>
|
|
<div className="flex items-start gap-2.5">
|
|
<Icon className="mt-0.5 size-5 shrink-0" aria-hidden="true" />
|
|
<div className="min-w-0">
|
|
<Title className="text-left text-xl font-bold">{announcement.title}</Title>
|
|
{announcement.subtitle && (
|
|
<p className="text-xs text-muted-foreground">{announcement.subtitle}</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</Header>
|
|
<AnnouncementRichText description={announcement.description} />
|
|
</>
|
|
);
|
|
}
|
|
|
|
if (!mounted) return null;
|
|
|
|
return (
|
|
<>
|
|
{banners.map((announcement) => {
|
|
const Icon = VARIANT_ICONS[announcement.variant] ?? Info;
|
|
const buttons = announcement.buttons ?? [];
|
|
return (
|
|
<div
|
|
key={announcement.id}
|
|
role={announcement.variant === "error" ? "alert" : "status"}
|
|
className={cn(
|
|
"flex items-start gap-3 border-b px-4 py-2.5 text-sm",
|
|
VARIANT_CLASSES[announcement.variant],
|
|
)}
|
|
>
|
|
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
|
<div className="min-w-0 flex-1">
|
|
<span className="text-base font-bold">{announcement.title}</span>
|
|
{announcement.subtitle && (
|
|
<p className="text-xs opacity-80">{announcement.subtitle}</p>
|
|
)}
|
|
<AnnouncementRichText description={announcement.description} />
|
|
{buttons.length > 0 && (
|
|
<div className="mt-2 flex flex-wrap gap-2">
|
|
{buttons.map((button, index) => (
|
|
<Button
|
|
key={`${index}-${button.label}`}
|
|
variant={BUTTON_VARIANTS[button.style] ?? "default"}
|
|
size="sm"
|
|
onClick={() => handleButtonClick(announcement, button.href)}
|
|
>
|
|
{button.label}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
{announcement.dismissible && (
|
|
<button
|
|
type="button"
|
|
onClick={() => dismiss(announcement)}
|
|
aria-label="Dismiss announcement"
|
|
className="rounded p-1 opacity-70 transition-opacity hover:opacity-100"
|
|
>
|
|
<X className="size-4" aria-hidden="true" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
|
|
{currentOverlay && currentOverlay.displayType === "modal" && (
|
|
<Dialog
|
|
open={overlayOpen}
|
|
onOpenChange={(open) => {
|
|
if (!open && currentOverlay) dismissAndCloseOverlay(currentOverlay);
|
|
}}
|
|
>
|
|
<DialogContent
|
|
className={cn("border", OVERLAY_CLASSES[currentOverlay.variant])}
|
|
aria-describedby={undefined}
|
|
onOpenAutoFocus={(event) => event.preventDefault()}
|
|
>
|
|
{renderBody(currentOverlay, DialogHeader, DialogTitle)}
|
|
<DialogFooter>{renderButtons(currentOverlay, "default")}</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)}
|
|
|
|
{currentOverlay && currentOverlay.displayType === "dialog" && (
|
|
<AlertDialog
|
|
open={overlayOpen}
|
|
onOpenChange={(open) => {
|
|
if (!open && currentOverlay) dismissAndCloseOverlay(currentOverlay);
|
|
}}
|
|
>
|
|
<AlertDialogContent
|
|
className={cn("border", OVERLAY_CLASSES[currentOverlay.variant])}
|
|
aria-describedby={undefined}
|
|
>
|
|
{renderBody(currentOverlay, AlertDialogHeader, AlertDialogTitle)}
|
|
<AlertDialogFooter>{renderButtons(currentOverlay, "default")}</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
)}
|
|
</>
|
|
);
|
|
}
|