"use client"; import { useEffect, useState } from "react"; import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { useConfig } from "@/hooks/use-config"; import { getPathPrefix } from "@/lib/browser-navigation"; import { productName } from "@/lib/product-name"; import { useSettingsStore } from "@/stores/settings-store"; import type { ProtocolOpenMode } from "@/stores/settings-store"; import { toast } from "@/stores/toast-store"; import { SettingsSection, SettingItem, Select } from "./settings-section"; type Protocol = "mailto" | "webcal"; function canRegisterProtocolHandler(): boolean { return typeof navigator !== "undefined" && "registerProtocolHandler" in navigator && typeof window !== "undefined" && window.isSecureContext; } function getProtocolHandlerUrl(protocol: Protocol) { return `${window.location.origin}${getPathPrefix()}/protocol/${protocol}?url=%s`; } function registerProtocolHandler(protocol: Protocol) { navigator.registerProtocolHandler( protocol, getProtocolHandlerUrl(protocol), ); } interface ProtocolHandlerSettingsProps { supportsCalendar: boolean; } export function ProtocolHandlerSettings({ supportsCalendar }: ProtocolHandlerSettingsProps) { const t = useTranslations("protocol_handlers"); const appName = productName(useConfig().appName); const protocolOpenMode = useSettingsStore((state) => state.protocolOpenMode); const updateSetting = useSettingsStore((state) => state.updateSetting); const [supported, setSupported] = useState(false); useEffect(() => { setSupported(canRegisterProtocolHandler()); }, []); const handleOpenModeChange = async (value: string) => { const openMode = value as ProtocolOpenMode; if (openMode === "active-session" && typeof window !== "undefined" && "Notification" in window && Notification.permission === "default") { await Notification.requestPermission(); } updateSetting("protocolOpenMode", openMode); }; const handleRegister = (protocol: Protocol) => { try { registerProtocolHandler(protocol); toast.success(protocol === "mailto" ? t("mailto_registered") : t("webcal_registered")); } catch { toast.error(t("registration_failed")); } }; const renderRegistrationControl = (protocol: Protocol) => { return ( handleRegister(protocol)} disabled={!supported}> {protocol === "mailto" ? t("register_mailto") : t("register_webcal")} ); }; return ( {!supported && ( {t("unsupported")} )} {renderRegistrationControl("mailto")} {supportsCalendar && ( {renderRegistrationControl("webcal")} )} {t("browser_note", { appName })} ); }
{t("browser_note", { appName })}