Files
spsays-training/components/notifications/notification-matrix.tsx
T
2026-08-30 11:15:54 +05:30

199 lines
6.3 KiB
TypeScript

"use client";
/**
* NotificationMatrix — the Settings grid controlling which events reach the
* user over which channels (in-app, email, push). Account-wide preferences;
* the device-level PushToggle above it governs whether *this* device can
* receive push at all (two layers, like an OS permission vs. app settings).
*
* Cells write through to PUT /notifications/prefs one at a time and re-render
* from the matrix the server returns, so the UI always shows resolved state.
*/
import { useEffect, useState } from "react";
import { toast } from "sonner";
import {
notifications,
type NotificationPrefs,
type PrefChannel,
type PrefEvent,
} from "@/lib/social";
import { ToggleSwitch } from "@/components/settings/setting-row";
import {
enablePush,
isPushEnabled,
pushPermission,
pushSupported,
} from "@/lib/push";
const EVENTS: {
key: PrefEvent;
label: string;
description: string;
/** Channels this event can actually be delivered on. Omit for all three.
* A cell outside this set renders as "—" rather than a live toggle, so we
* never show a switch that silently does nothing. */
channels?: PrefChannel[];
}[] = [
{
key: "follows",
label: "Follows",
description: "Follow requests and accepted requests.",
},
{
key: "post_interactions",
label: "Post interactions",
description: "Likes and mentions on your posts.",
},
{
key: "sadhna_reminders",
label: "Sādhana reminders",
description: "Daily nudges to chant your rounds and share a verse.",
},
{
key: "messages",
label: "Messages",
description:
"New messages. Email is only ever sent when someone starts a conversation with you.",
// No in-app: chat's in-app delivery is the inbox itself, where a message
// highlights its row rather than entering the notification tray.
channels: ["email", "push"],
},
{
key: "community",
label: "Community",
description:
"Rare announcements — such as new feature, downtime etc.",
// Announcements are in-app/push only; we deliberately don't email them.
channels: ["in_app", "push"],
},
];
const CHANNELS: { key: PrefChannel; label: string }[] = [
{ key: "in_app", label: "In-app" },
{ key: "email", label: "Email" },
{ key: "push", label: "Push" },
];
export function NotificationMatrix() {
const [prefs, setPrefs] = useState<NotificationPrefs | null>(null);
const [failed, setFailed] = useState(false);
// The "event/channel" cell currently being written, so only it disables.
const [busyCell, setBusyCell] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
notifications
.prefs()
.then(({ prefs }) => {
if (!cancelled) setPrefs(prefs);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
};
}, []);
async function toggle(event: PrefEvent, channel: PrefChannel) {
if (!prefs) return;
// Default-on when the key is absent: prefs are stored as opt-outs, and a
// BFF that predates this category simply omits it.
const next = !(prefs[event]?.[channel] ?? true);
setBusyCell(`${event}/${channel}`);
try {
// Turning a push cell ON only helps if this device can receive push —
// offer the permission/subscription right at the gesture, best-effort
// (the account-wide pref still saves if the user declines).
if (
channel === "push" &&
next &&
pushSupported() &&
pushPermission() !== "denied" &&
!(await isPushEnabled())
) {
await enablePush().catch(() => {
/* declined / unavailable — other subscribed devices still get it */
});
}
const { prefs: updated } = await notifications.setPref(
event,
channel,
next,
);
setPrefs(updated);
} catch {
toast.error("Could not update preference");
} finally {
setBusyCell(null);
}
}
if (failed) {
return (
<p className="py-3 text-xs text-muted-foreground">
Couldn&apos;t load your notification preferences. Reload to try again.
</p>
);
}
return (
// Fixed, EQUAL channel columns. With `auto` each one sized to its own
// widest content — "In-app" against the 44px toggle, "Push" against the
// same toggle — so the three columns came out different widths and
// neither the headers nor the switches lined up down the grid.
<div className="grid grid-cols-[1fr_repeat(3,3.25rem)] items-center gap-x-2 gap-y-0 sm:grid-cols-[1fr_repeat(3,4rem)] sm:gap-x-4">
{/* Header row */}
<span aria-hidden />
{CHANNELS.map((c) => (
<span
key={c.key}
className="pb-2 text-center text-xs font-medium text-muted-foreground"
>
{c.label}
</span>
))}
{EVENTS.map((event) => (
<div key={event.key} className="contents">
<div className="min-w-0 border-t border-border py-3">
<span className="text-sm text-foreground">{event.label}</span>
<p className="text-xs text-muted-foreground mt-0.5">
{event.description}
</p>
</div>
{CHANNELS.map((channel) => {
const deliverable =
!event.channels || event.channels.includes(channel.key);
return (
<div
key={channel.key}
className="flex justify-center border-t border-border py-3"
>
{!deliverable ? (
<span
className="text-xs text-muted-foreground"
title={`${event.label} isn't delivered by ${channel.label.toLowerCase()}`}
>
&mdash;
</span>
) : prefs ? (
<ToggleSwitch
checked={prefs[event.key]?.[channel.key] ?? true}
disabled={busyCell === `${event.key}/${channel.key}`}
onToggle={() => toggle(event.key, channel.key)}
label={`${event.label} — ${channel.label}`}
/>
) : (
<span className="text-xs text-muted-foreground">…</span>
)}
</div>
);
})}
</div>
))}
</div>
);
}