import { FormattedMessage } from "react-intl"; import { useEffect, useState } from "react"; import Icon from "@/Icons/Icon"; import useLogin from "@/Hooks/useLogin"; import { subscribeToNotifications } from "@/Notifications"; import useEventPublisher from "@/Hooks/useEventPublisher"; import messages from "./messages"; interface StatusIndicatorProps { status: boolean; enabledMessage: React.ComponentProps; disabledMessage: React.ComponentProps; } const StatusIndicator = ({ status, enabledMessage, disabledMessage }: StatusIndicatorProps) => { return status ? (
) : (
); }; const PreferencesPage = () => { const login = useLogin(); const { publisher } = useEventPublisher(); const [serviceWorkerReady, setServiceWorkerReady] = useState(false); const hasNotificationsApi = "Notification" in window; const [notificationsAllowed, setNotificationsAllowed] = useState( hasNotificationsApi && Notification.permission === "granted", ); const [subscribedToPush, setSubscribedToPush] = useState(false); const allGood = !login.readonly && hasNotificationsApi && notificationsAllowed && serviceWorkerReady; useEffect(() => { if ("serviceWorker" in navigator) { navigator.serviceWorker.ready.then(registration => { if (registration.active) { setServiceWorkerReady(true); } }); } }, []); const trySubscribePush = async () => { try { if (allGood && publisher && !subscribedToPush) { await subscribeToNotifications(publisher); setSubscribedToPush(true); } } catch (e) { console.error(e); } }; useEffect(() => { trySubscribePush(); }, [allGood, publisher]); const requestNotificationPermission = () => { Notification.requestPermission().then(permission => { const allowed = permission === "granted"; setNotificationsAllowed(allowed); if (!allowed) { alert("Please allow notifications in your browser settings and try again."); } }); }; if (!login.publicKey) { return null; } return (

{hasNotificationsApi && !notificationsAllowed && ( )}
{allGood && !subscribedToPush && ( )}
); }; export default PreferencesPage;