"use client"; import { useEffect, useState } from "react"; import { Bell, BellOff, Send } from "lucide-react"; import { Button } from "@/components/ui/button"; import { useT } from "@/components/I18n"; 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 t = useT(); const [state, setState] = useState("loading"); const [endpoint, setEndpoint] = useState(null); const [msg, setMsg] = useState(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(t("Не удалось включить: {message}", { message: (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 ? t("Отправлено — уведомление должно появиться через пару секунд.") : t("Не дошло: {error}", { error: t.text(r.error) })); setBusy(false); } return (
{state === "on" ? ( <> {t("Push в этом браузере включены.")} ) : state === "off" ? ( ) : state === "denied" ? ( {t("Уведомления для этого сайта запрещены в браузере — разрешите их в настройках сайта (значок слева от адреса) и обновите страницу.")} ) : state === "unsupported" ? ( {t("Этот браузер не умеет Web Push. В Safari на iPhone — сначала «На экран Домой».")} ) : ( {t("Проверяю…")} )}
{msg &&

{msg}

}
); }