111 lines
4.8 KiB
TypeScript
111 lines
4.8 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useState } from "react";
|
||
import { Bell, BellOff, Send } from "lucide-react";
|
||
import { Button } from "@/components/ui/button";
|
||
import { deletePushSubscriptionAction, savePushSubscriptionAction, testPushAction } from "@/app/(app)/actions";
|
||
|
||
type State = "loading" | "unsupported" | "denied" | "off" | "on";
|
||
|
||
const toBytes = (b64u: string) => {
|
||
const s = atob(b64u.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (b64u.length % 4)) % 4));
|
||
return Uint8Array.from(s, (c) => c.charCodeAt(0));
|
||
};
|
||
|
||
async function registration() {
|
||
await navigator.serviceWorker.register("/sw.js", { scope: "/" });
|
||
return navigator.serviceWorker.ready;
|
||
}
|
||
|
||
/** «Push в этом браузере» (PEP-55): permission, Web Push subscription, test, unsubscribe. */
|
||
export function PushNotifications({ vapidKey, known }: { vapidKey: string; known: string[] }) {
|
||
const [state, setState] = useState<State>("loading");
|
||
const [endpoint, setEndpoint] = useState<string | null>(null);
|
||
const [msg, setMsg] = useState<string | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
|
||
useEffect(() => {
|
||
(async () => {
|
||
if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) return setState("unsupported");
|
||
if (Notification.permission === "denied") return setState("denied");
|
||
const reg = await navigator.serviceWorker.getRegistration("/");
|
||
const sub = await reg?.pushManager.getSubscription();
|
||
if (!sub) return setState("off");
|
||
setEndpoint(sub.endpoint);
|
||
// Subscribed in the browser but unknown to Peppa (e.g. removed after a 410): tell it again.
|
||
if (!known.includes(sub.endpoint)) await savePushSubscriptionAction(sub.toJSON() as never, navigator.userAgent);
|
||
setState("on");
|
||
})().catch((e) => (setMsg(String(e?.message ?? e)), setState("off")));
|
||
}, [known]);
|
||
|
||
async function enable() {
|
||
setBusy(true);
|
||
setMsg(null);
|
||
try {
|
||
if ((await Notification.requestPermission()) !== "granted") return setState("denied");
|
||
const reg = await registration();
|
||
const sub = (await reg.pushManager.getSubscription()) ?? (await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: toBytes(vapidKey) }));
|
||
await savePushSubscriptionAction(sub.toJSON() as never, navigator.userAgent);
|
||
setEndpoint(sub.endpoint);
|
||
setState("on");
|
||
} catch (e) {
|
||
setMsg(`Не удалось включить: ${(e as Error).message}`);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
async function disable() {
|
||
setBusy(true);
|
||
try {
|
||
const reg = await navigator.serviceWorker.getRegistration("/");
|
||
const sub = await reg?.pushManager.getSubscription();
|
||
if (sub) {
|
||
await deletePushSubscriptionAction(sub.endpoint);
|
||
await sub.unsubscribe();
|
||
}
|
||
setEndpoint(null);
|
||
setState("off");
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
async function test() {
|
||
if (!endpoint) return;
|
||
setBusy(true);
|
||
const r = await testPushAction(endpoint).catch((e) => ({ ok: false, error: String(e) }));
|
||
setMsg(r.ok ? "Отправлено — уведомление должно появиться через пару секунд." : `Не дошло: ${r.error}`);
|
||
setBusy(false);
|
||
}
|
||
|
||
return (
|
||
<div className="flex flex-col gap-2">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
{state === "on" ? (
|
||
<>
|
||
<span className="text-sm">Push в этом браузере включены.</span>
|
||
<Button size="sm" type="button" onClick={test} disabled={busy}>
|
||
<Send /> Проверить
|
||
</Button>
|
||
<Button size="sm" type="button" variant="destructive" onClick={disable} disabled={busy}>
|
||
<BellOff /> Отключить
|
||
</Button>
|
||
</>
|
||
) : state === "off" ? (
|
||
<Button size="sm" type="button" variant="default" onClick={enable} disabled={busy}>
|
||
<Bell /> Включить push в этом браузере
|
||
</Button>
|
||
) : state === "denied" ? (
|
||
<span className="text-sm text-muted-foreground">Уведомления для этого сайта запрещены в браузере — разрешите их в настройках сайта (значок слева от адреса) и обновите страницу.</span>
|
||
) : state === "unsupported" ? (
|
||
<span className="text-sm text-muted-foreground">Этот браузер не умеет Web Push. В Safari на iPhone — сначала «На экран Домой».</span>
|
||
) : (
|
||
<span className="text-sm text-muted-foreground">Проверяю…</span>
|
||
)}
|
||
</div>
|
||
{msg && <p className="m-0 text-sm text-muted-foreground">{msg}</p>}
|
||
</div>
|
||
);
|
||
}
|