aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/components/PushNotificationSettings.tsx
blob: af3206ab101778d075a6569acfd02b815d20e589 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import { BellOff, BellRing, Loader } from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { writeFavorites } from "~/utils/idb";

/** Convert a base64url string (as returned by the VAPID endpoint) to a Uint8Array. */
function urlBase64ToUint8Array(base64String: string): Uint8Array {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
  const rawData = atob(base64);
  return Uint8Array.from([...rawData].map((c) => c.charCodeAt(0)));
}

/** Sync all three favourites lists from localStorage to IndexedDB. */
async function syncFavouritesToIdb() {
  const keys = [
    "favouriteStops",
    "favouriteRoutes",
    "favouriteAgencies",
  ] as const;
  await Promise.all(
    keys.map((key) => {
      const raw = localStorage.getItem(key);
      const ids: string[] = raw ? JSON.parse(raw) : [];
      return writeFavorites(key, ids);
    })
  );
}

type Status =
  | "loading" // checking current state
  | "unsupported" // browser does not support Push API
  | "denied" // permission was explicitly blocked
  | "subscribed" // user is actively subscribed
  | "unsubscribed"; // user is not subscribed (or permission not yet granted)

export function PushNotificationSettings() {
  const { t } = useTranslation();
  const [status, setStatus] = useState<Status>("loading");
  const [working, setWorking] = useState(false);

  useEffect(() => {
    checkStatus().then(setStatus);
  }, []);

  async function checkStatus(): Promise<Status> {
    if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
      return "unsupported";
    }
    if (Notification.permission === "denied") return "denied";

    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      return sub ? "subscribed" : "unsubscribed";
    } catch {
      return "unsubscribed";
    }
  }

  async function subscribe() {
    setWorking(true);
    try {
      const permission = await Notification.requestPermission();
      if (permission !== "granted") {
        setStatus("denied");
        return;
      }

      // Fetch the VAPID public key
      const res = await fetch("/api/push/vapid-public-key");
      if (!res.ok) {
        console.error("Push notifications not configured on this server.");
        return;
      }
      const { publicKey } = await res.json();

      const reg = await navigator.serviceWorker.ready;
      const subscription = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicKey),
      });

      // Mirror favourites to IDB before registering so the SW has them from day 1
      await syncFavouritesToIdb();

      const json = subscription.toJSON();
      await fetch("/api/push/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          endpoint: json.endpoint,
          p256Dh: json.keys?.p256dh,
          auth: json.keys?.auth,
        }),
      });

      setStatus("subscribed");
    } finally {
      setWorking(false);
    }
  }

  async function unsubscribe() {
    setWorking(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      if (sub) {
        const endpoint = sub.endpoint;
        await sub.unsubscribe();
        await fetch("/api/push/unsubscribe", {
          method: "DELETE",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ endpoint }),
        });
      }
      setStatus("unsubscribed");
    } finally {
      setWorking(false);
    }
  }

  return (
    <section className="mb-8">
      <h2 className="text-xl font-semibold mb-2 text-text">
        {t("settings.push_title", "Notificaciones")}
      </h2>
      <p className="text-sm text-muted mb-4">
        {t(
          "settings.push_description",
          "Recibe notificaciones cuando haya alertas de servicio relevantes para tus paradas, líneas o operadores favoritos."
        )}
      </p>

      {status === "loading" && (
        <div className="flex items-center gap-2 text-muted text-sm">
          <Loader className="w-4 h-4 animate-spin" />
          {t("common.loading", "Cargando...")}
        </div>
      )}

      {status === "unsupported" && (
        <p className="text-sm text-muted p-4 rounded-lg border border-border bg-surface">
          {t(
            "settings.push_unsupported",
            "Tu navegador no soporta notificaciones push. Prueba con Chrome, Edge o Firefox."
          )}
        </p>
      )}

      {status === "denied" && (
        <p className="text-sm text-muted p-4 rounded-lg border border-amber-300 bg-amber-50 dark:bg-amber-950 dark:border-amber-700">
          {t(
            "settings.push_permission_denied",
            "Has bloqueado los permisos de notificación en este navegador. Para activarlos, ve a la configuración del sitio y permite las notificaciones."
          )}
        </p>
      )}

      {(status === "subscribed" || status === "unsubscribed") && (
        <label className="flex items-center justify-between p-4 rounded-lg border border-border bg-surface cursor-pointer hover:bg-surface/50 transition-colors">
          <span className="flex items-center gap-2 text-text font-medium">
            {status === "subscribed" ? (
              <BellRing className="w-5 h-5 text-primary" />
            ) : (
              <BellOff className="w-5 h-5 text-muted" />
            )}
            {status === "subscribed"
              ? t("settings.push_subscribed", "Notificaciones activadas")
              : t(
                  "settings.push_subscribe",
                  "Activar notificaciones de alertas"
                )}
          </span>
          <button
            onClick={status === "subscribed" ? unsubscribe : subscribe}
            disabled={working}
            aria-pressed={status === "subscribed"}
            className={`
              relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200
              focus:outline-none focus:ring-2 focus:ring-primary/50
              disabled:opacity-50
              ${status === "subscribed" ? "bg-primary" : "bg-border"}
            `}
          >
            <span
              className={`
                inline-block h-4 w-4 rounded-full bg-white shadow transition-transform duration-200
                ${status === "subscribed" ? "translate-x-6" : "translate-x-1"}
              `}
            />
          </button>
        </label>
      )}
    </section>
  );
}