feat(push): auto-subscribe in standalone mode — no button needed, iOS system prompt only
This commit is contained in:
parent
47a06bb285
commit
1cbcff6a16
|
|
@ -1,4 +1,4 @@
|
|||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
|
||||
const VAPID_PUBLIC_KEY = "BDLNGyVp7hDzRujZBncNQ0qyz4zVFAhAWX1nsCMRC2tagmer46Sy6exZOymsGVk-TDb1bhkkXXth9Jkzdv4SdJg";
|
||||
|
||||
|
|
@ -16,7 +16,7 @@ const apiHeaders = {
|
|||
const normalizePhone = (phone) => {
|
||||
if (!phone) return "";
|
||||
const clean = String(phone).replace(/\D/g, "");
|
||||
if (clean.length < 10) return ""; // too short to be a real number
|
||||
if (clean.length < 10) return "";
|
||||
if (clean.startsWith("8")) return "7" + clean.slice(1);
|
||||
if (!clean.startsWith("7")) return "7" + clean;
|
||||
return clean;
|
||||
|
|
@ -42,12 +42,10 @@ const urlBase64ToUint8Array = (base64String) => {
|
|||
};
|
||||
|
||||
export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||
const [status, setStatus] = useState("idle"); // idle | prompting | subscribed | denied | unsupported
|
||||
const [status, setStatus] = useState("idle");
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const [phoneInput, setPhoneInput] = useState("");
|
||||
|
||||
// Persist a known phone so the installed app (which opens without a token)
|
||||
// can still subscribe. Prefer prop, fall back to stored value.
|
||||
const propPhone = normalizePhone(phone);
|
||||
const storedPhone = propPhone || readStoredPhone();
|
||||
|
||||
|
|
@ -56,7 +54,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
try {
|
||||
window.localStorage.setItem(PHONE_STORAGE_KEY, propPhone);
|
||||
} catch (e) {
|
||||
// localStorage unavailable (private mode) — ignore
|
||||
void e;
|
||||
}
|
||||
}
|
||||
|
|
@ -64,33 +61,12 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
|
||||
const phoneNorm = storedPhone || normalizePhone(phoneInput);
|
||||
|
||||
// Detect iOS Safari (not in standalone mode = not added to Home Screen)
|
||||
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
|
||||
const isStandalone = window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
|
||||
const isIOSNotInstalled = isIOS && !isStandalone;
|
||||
|
||||
// Check if push is supported
|
||||
useEffect(() => {
|
||||
// iOS Safari in browser mode (not standalone) doesn't support Push API
|
||||
if (isIOSNotInstalled) {
|
||||
setStatus("ios_not_installed");
|
||||
return;
|
||||
}
|
||||
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
|
||||
setStatus("unsupported");
|
||||
return;
|
||||
}
|
||||
// Check existing subscription
|
||||
navigator.serviceWorker.ready.then(async (reg) => {
|
||||
const existing = await reg.pushManager.getSubscription();
|
||||
if (existing) {
|
||||
setStatus("subscribed");
|
||||
}
|
||||
}).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const subscribe = async () => {
|
||||
const resolvedPhone = normalizePhone(phoneInput) || storedPhone;
|
||||
const subscribe = useCallback(async (overridePhone) => {
|
||||
const resolvedPhone = overridePhone || normalizePhone(phoneInput) || storedPhone;
|
||||
if (!resolvedPhone) {
|
||||
setStatus("need_phone");
|
||||
return;
|
||||
|
|
@ -99,7 +75,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
try {
|
||||
window.localStorage.setItem(PHONE_STORAGE_KEY, resolvedPhone);
|
||||
} catch (e) {
|
||||
// localStorage unavailable — ignore
|
||||
void e;
|
||||
}
|
||||
}
|
||||
|
|
@ -114,7 +89,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
|
||||
});
|
||||
}
|
||||
// Send to backend
|
||||
const sub = subscription.toJSON();
|
||||
const resp = await fetch(getEndpoint("push-subscribe"), {
|
||||
method: "POST",
|
||||
|
|
@ -142,15 +116,64 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
setStatus("idle");
|
||||
}
|
||||
}
|
||||
}, [phoneInput, storedPhone, orderGroupId]);
|
||||
|
||||
// Init: check support → check existing subscription → auto-subscribe if possible
|
||||
useEffect(() => {
|
||||
if (isIOSNotInstalled) {
|
||||
setStatus("ios_not_installed");
|
||||
return;
|
||||
}
|
||||
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
|
||||
setStatus("unsupported");
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const init = async () => {
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
if (cancelled) return;
|
||||
|
||||
const existing = await reg.pushManager.getSubscription();
|
||||
if (cancelled) return;
|
||||
|
||||
if (existing) {
|
||||
setStatus("subscribed");
|
||||
return;
|
||||
}
|
||||
|
||||
// No existing subscription — decide whether to auto-subscribe
|
||||
const permission = Notification.permission;
|
||||
|
||||
if (permission === "denied") {
|
||||
setStatus("denied");
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-subscribe when:
|
||||
// - permission already granted (user allowed before), OR
|
||||
// - standalone mode (installed PWA — iOS shows system prompt on subscribe)
|
||||
// AND we have a phone to associate
|
||||
const canAutoSubscribe =
|
||||
(permission === "granted" || isStandalone) && storedPhone;
|
||||
|
||||
if (canAutoSubscribe) {
|
||||
await subscribe(storedPhone);
|
||||
}
|
||||
// else: stay idle, show banner with button / phone input
|
||||
};
|
||||
|
||||
init().catch(() => undefined);
|
||||
return () => { cancelled = true; };
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const unsubscribe = async () => {
|
||||
try {
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
const sub = await reg.pushManager.getSubscription();
|
||||
if (sub) {
|
||||
await sub.unsubscribe();
|
||||
// Notify backend
|
||||
await fetch(getEndpoint("push-unsubscribe"), {
|
||||
method: "POST",
|
||||
headers: apiHeaders,
|
||||
|
|
@ -167,45 +190,10 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
}
|
||||
};
|
||||
|
||||
// Don't render if unsupported, dismissed, or no phone
|
||||
// Don't render if unsupported
|
||||
if (status === "unsupported") return null;
|
||||
if (dismissed && status !== "subscribed" && status !== "denied") return null;
|
||||
|
||||
// iOS not installed — show instruction to add to Home Screen
|
||||
if (status === "ios_not_installed") {
|
||||
return (
|
||||
<div className="rounded-xl border border-[rgba(18,128,92,0.2)] bg-[var(--color-accent-soft)] px-4 py-3">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span className="text-base flex-shrink-0 mt-0.5">🔔</span>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-semibold text-[var(--color-text)]">
|
||||
Включить уведомления о доставке
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mt-1 leading-5">
|
||||
На iPhone уведомления работают только если приложение добавлено на главный экран.
|
||||
</p>
|
||||
<ol className="text-xs text-[var(--color-text-muted)] mt-2 space-y-1 leading-5">
|
||||
<li>1. Нажмите <span className="font-medium">«Поделиться»</span> (квадрат со стрелкой ↑) внизу Safari</li>
|
||||
<li>2. Выберите <span className="font-medium">«На экран Домой»</span> → «Добавить»</li>
|
||||
<li>3. Откройте приложение с иконки <span className="font-medium">«СуперСам»</span> на главном экране</li>
|
||||
<li>4. Нажмите <span className="font-medium">«Разрешить»</span> в этом баннере</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end mt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDismissed(true)}
|
||||
className="text-xs text-[var(--color-text-muted)] transition hover:text-[var(--color-text)]"
|
||||
>
|
||||
Позже
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Subscribed state — show small confirmation + unsubscribe option
|
||||
// Auto-subscribed or prompting — no UI needed
|
||||
if (status === "subscribed" || status === "prompting") {
|
||||
if (status === "subscribed") {
|
||||
return (
|
||||
<div className="rounded-xl border border-[rgba(18,128,92,0.25)] bg-[var(--color-accent-soft)] px-4 py-3">
|
||||
|
|
@ -227,6 +215,48 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
// prompting — show minimal loading
|
||||
return (
|
||||
<div className="rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] px-4 py-3">
|
||||
<p className="text-sm text-[var(--color-text-muted)]">Ожидание разрешения…</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (dismissed) return null;
|
||||
|
||||
// iOS not installed — show instruction to add to Home Screen
|
||||
if (status === "ios_not_installed") {
|
||||
return (
|
||||
<div className="rounded-xl border border-[rgba(18,128,92,0.2)] bg-[var(--color-accent-soft)] px-4 py-3">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span className="text-base flex-shrink-0 mt-0.5">🔔</span>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-semibold text-[var(--color-text)]">
|
||||
Включить уведомления о доставке
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-text-muted)] mt-1 leading-5">
|
||||
На iPhone уведомления работают только если приложение добавлено на главный экран.
|
||||
</p>
|
||||
<ol className="text-xs text-[var(--color-text-muted)] mt-2 space-y-1 leading-5">
|
||||
<li>1. Нажмите <span className="font-medium">«Поделиться»</span> (квадрат со стрелкой ↑) внизу Safari</li>
|
||||
<li>2. Выберите <span className="font-medium">«На экран Домой»</span> → «Добавить»</li>
|
||||
<li>3. Откройте приложение с иконки <span className="font-medium">«СуперСам»</span> на главном экране</li>
|
||||
<li>4. Разрешите уведомления при первом открытии</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end mt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDismissed(true)}
|
||||
className="text-xs text-[var(--color-text-muted)] transition hover:text-[var(--color-text)]"
|
||||
>
|
||||
Позже
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Denied — user blocked notifications
|
||||
if (status === "denied") {
|
||||
|
|
@ -242,15 +272,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
);
|
||||
}
|
||||
|
||||
// Prompting — show loading
|
||||
if (status === "prompting") {
|
||||
return (
|
||||
<div className="rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] px-4 py-3">
|
||||
<p className="text-sm text-[var(--color-text-muted)]">Ожидание разрешения…</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Need a phone number to subscribe (opened the installed app without a token)
|
||||
if (status === "need_phone" || (!phoneNorm && !isIOSNotInstalled)) {
|
||||
return (
|
||||
|
|
@ -275,7 +296,7 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={subscribe}
|
||||
onClick={() => subscribe()}
|
||||
className="flex-shrink-0 rounded-xl bg-[var(--color-accent)] px-4 py-2 text-sm font-semibold text-white transition hover:opacity-90"
|
||||
>
|
||||
Разрешить
|
||||
|
|
@ -287,7 +308,7 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
);
|
||||
}
|
||||
|
||||
// Idle — show subscription banner
|
||||
// Idle — show subscription banner with button (non-standalone, permission=default)
|
||||
return (
|
||||
<div className="rounded-xl border border-[rgba(18,128,92,0.2)] bg-[var(--color-accent-soft)] px-4 py-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
|
|
@ -305,7 +326,7 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
|||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={subscribe}
|
||||
onClick={() => subscribe()}
|
||||
className="rounded-xl bg-[var(--color-accent)] px-4 py-2 text-sm font-semibold text-white transition hover:opacity-90"
|
||||
>
|
||||
Разрешить
|
||||
|
|
|
|||
Loading…
Reference in New Issue