|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useMutation, useQueryClient } from "@tanstack/react-query"; |
| 4 | +import { Switch } from "@umamin/ui/components/switch"; |
| 5 | +import { cn } from "@umamin/ui/lib/utils"; |
| 6 | +import { BellIcon } from "lucide-react"; |
| 7 | +import { useEffect, useState } from "react"; |
| 8 | +import { toast } from "sonner"; |
| 9 | +import { |
| 10 | + registerPushSubscriptionAction, |
| 11 | + unregisterPushSubscriptionAction, |
| 12 | +} from "@/app/actions/push"; |
| 13 | +import { useSingleFlightAction } from "@/hooks/use-single-flight-action"; |
| 14 | +import { |
| 15 | + getExistingSubscription, |
| 16 | + isIosWebPushBlocked, |
| 17 | + isPushSupported, |
| 18 | + subscribeToPush, |
| 19 | + unsubscribeFromPush, |
| 20 | +} from "@/lib/push-client"; |
| 21 | +import { queryKeys } from "@/lib/query"; |
| 22 | +import { patchCurrentUser } from "@/lib/query-cache"; |
| 23 | +import type { CurrentUserResponse } from "@/lib/query-types"; |
| 24 | + |
| 25 | +const VAPID_PUBLIC_KEY = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY; |
| 26 | + |
| 27 | +// Effective state is reconciled from LIVE browser facts on mount, not from the |
| 28 | +// stored pushPrefs alone — the device's permission/subscription can diverge |
| 29 | +// from the server bit (cleared browser data, revoked permission, new device). |
| 30 | +type PushState = |
| 31 | + | "loading" |
| 32 | + | "unsupported" |
| 33 | + | "ios-install" |
| 34 | + | "denied" |
| 35 | + | "off" |
| 36 | + | "on"; |
| 37 | + |
| 38 | +const COPY: Record<Exclude<PushState, "loading">, string> = { |
| 39 | + unsupported: "Not available in this browser.", |
| 40 | + "ios-install": |
| 41 | + "Add Umamin to your Home Screen first to enable notifications.", |
| 42 | + denied: |
| 43 | + "Notifications are blocked. Re-enable them in your browser or device settings.", |
| 44 | + off: "Get notified about replies, follows, messages, and group activity.", |
| 45 | + on: "Get notified about replies, follows, messages, and group activity.", |
| 46 | +}; |
| 47 | + |
| 48 | +export function PushNotificationToggle() { |
| 49 | + const queryClient = useQueryClient(); |
| 50 | + const [state, setState] = useState<PushState>("loading"); |
| 51 | + |
| 52 | + const register = useSingleFlightAction(registerPushSubscriptionAction); |
| 53 | + const unregister = useSingleFlightAction(unregisterPushSubscriptionAction); |
| 54 | + |
| 55 | + // Sync the master pushPrefs into the current-user cache (read by /api/me). |
| 56 | + // null = unchanged (a per-device unsubscribe that left other devices on). |
| 57 | + const patchPushPrefs = (pushPrefs: number | null) => { |
| 58 | + if (pushPrefs === null) return; |
| 59 | + queryClient.setQueryData<CurrentUserResponse>( |
| 60 | + queryKeys.currentUser(), |
| 61 | + (current) => |
| 62 | + patchCurrentUser(current, (user) => ({ ...user, pushPrefs })), |
| 63 | + ); |
| 64 | + }; |
| 65 | + |
| 66 | + useEffect(() => { |
| 67 | + let active = true; |
| 68 | + |
| 69 | + (async () => { |
| 70 | + if (!isPushSupported() || !VAPID_PUBLIC_KEY) { |
| 71 | + if (active) setState("unsupported"); |
| 72 | + return; |
| 73 | + } |
| 74 | + if (isIosWebPushBlocked()) { |
| 75 | + if (active) setState("ios-install"); |
| 76 | + return; |
| 77 | + } |
| 78 | + if (Notification.permission === "denied") { |
| 79 | + // Self-heal: a denied device can't show notifications, so prune any |
| 80 | + // lingering subscription server-side instead of fanning out to it. |
| 81 | + const sub = await getExistingSubscription(); |
| 82 | + if (sub) { |
| 83 | + const { endpoint } = sub; |
| 84 | + await sub.unsubscribe().catch(() => {}); |
| 85 | + void unregister({ endpoint }); |
| 86 | + } |
| 87 | + if (active) setState("denied"); |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + const sub = await getExistingSubscription(); |
| 92 | + if (active) setState(sub ? "on" : "off"); |
| 93 | + })(); |
| 94 | + |
| 95 | + return () => { |
| 96 | + active = false; |
| 97 | + }; |
| 98 | + }, [unregister]); |
| 99 | + |
| 100 | + const enable = useMutation({ |
| 101 | + mutationFn: async () => { |
| 102 | + const permission = await Notification.requestPermission(); |
| 103 | + if (permission !== "granted") { |
| 104 | + throw new Error( |
| 105 | + permission === "denied" |
| 106 | + ? "Notifications are blocked. Re-enable them in your browser or device settings." |
| 107 | + : "Notification permission was not granted.", |
| 108 | + ); |
| 109 | + } |
| 110 | + const sub = await subscribeToPush(VAPID_PUBLIC_KEY as string); |
| 111 | + const res = await register(sub); |
| 112 | + if ("error" in res) throw new Error(res.error); |
| 113 | + return res.pushPrefs; |
| 114 | + }, |
| 115 | + onSuccess: (pushPrefs) => { |
| 116 | + patchPushPrefs(pushPrefs); |
| 117 | + setState("on"); |
| 118 | + toast.success("Push notifications enabled."); |
| 119 | + }, |
| 120 | + onError: (err: Error) => { |
| 121 | + if ( |
| 122 | + typeof Notification !== "undefined" && |
| 123 | + Notification.permission === "denied" |
| 124 | + ) { |
| 125 | + setState("denied"); |
| 126 | + } |
| 127 | + toast.error(err.message ?? "Couldn't enable notifications."); |
| 128 | + }, |
| 129 | + }); |
| 130 | + |
| 131 | + const disable = useMutation({ |
| 132 | + mutationFn: async () => { |
| 133 | + const endpoint = await unsubscribeFromPush(); |
| 134 | + if (!endpoint) return null; |
| 135 | + const res = await unregister({ endpoint }); |
| 136 | + if ("error" in res) throw new Error(res.error); |
| 137 | + return res.pushPrefs; |
| 138 | + }, |
| 139 | + onSuccess: (pushPrefs) => { |
| 140 | + patchPushPrefs(pushPrefs); |
| 141 | + setState("off"); |
| 142 | + toast.success("Push notifications disabled."); |
| 143 | + }, |
| 144 | + onError: (err: Error) => { |
| 145 | + toast.error(err.message ?? "Couldn't disable notifications."); |
| 146 | + }, |
| 147 | + }); |
| 148 | + |
| 149 | + const isPending = enable.isPending || disable.isPending; |
| 150 | + const actionable = state === "on" || state === "off"; |
| 151 | + const warn = |
| 152 | + state === "denied" || state === "ios-install" || state === "unsupported"; |
| 153 | + |
| 154 | + return ( |
| 155 | + <div className="flex items-center space-x-4 rounded-md border p-4 mt-4"> |
| 156 | + <BellIcon className="size-6" /> |
| 157 | + <div className="flex-1 space-y-1"> |
| 158 | + <p className="text-sm font-medium leading-none">Push Notifications</p> |
| 159 | + <p |
| 160 | + className={cn( |
| 161 | + "text-sm", |
| 162 | + warn ? "text-yellow-600" : "text-muted-foreground", |
| 163 | + )} |
| 164 | + > |
| 165 | + {state === "loading" ? "Checking notification status…" : COPY[state]} |
| 166 | + </p> |
| 167 | + </div> |
| 168 | + <Switch |
| 169 | + disabled={isPending || !actionable} |
| 170 | + checked={state === "on"} |
| 171 | + onCheckedChange={(checked) => |
| 172 | + checked ? enable.mutate() : disable.mutate() |
| 173 | + } |
| 174 | + /> |
| 175 | + </div> |
| 176 | + ); |
| 177 | +} |
0 commit comments