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";
|
const VAPID_PUBLIC_KEY = "BDLNGyVp7hDzRujZBncNQ0qyz4zVFAhAWX1nsCMRC2tagmer46Sy6exZOymsGVk-TDb1bhkkXXth9Jkzdv4SdJg";
|
||||||
|
|
||||||
|
|
@ -16,7 +16,7 @@ const apiHeaders = {
|
||||||
const normalizePhone = (phone) => {
|
const normalizePhone = (phone) => {
|
||||||
if (!phone) return "";
|
if (!phone) return "";
|
||||||
const clean = String(phone).replace(/\D/g, "");
|
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("8")) return "7" + clean.slice(1);
|
||||||
if (!clean.startsWith("7")) return "7" + clean;
|
if (!clean.startsWith("7")) return "7" + clean;
|
||||||
return clean;
|
return clean;
|
||||||
|
|
@ -42,12 +42,10 @@ const urlBase64ToUint8Array = (base64String) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
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 [dismissed, setDismissed] = useState(false);
|
||||||
const [phoneInput, setPhoneInput] = useState("");
|
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 propPhone = normalizePhone(phone);
|
||||||
const storedPhone = propPhone || readStoredPhone();
|
const storedPhone = propPhone || readStoredPhone();
|
||||||
|
|
||||||
|
|
@ -56,7 +54,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
try {
|
try {
|
||||||
window.localStorage.setItem(PHONE_STORAGE_KEY, propPhone);
|
window.localStorage.setItem(PHONE_STORAGE_KEY, propPhone);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// localStorage unavailable (private mode) — ignore
|
|
||||||
void e;
|
void e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -64,33 +61,12 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
|
|
||||||
const phoneNorm = storedPhone || normalizePhone(phoneInput);
|
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 isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
|
||||||
const isStandalone = window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
|
const isStandalone = window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
|
||||||
const isIOSNotInstalled = isIOS && !isStandalone;
|
const isIOSNotInstalled = isIOS && !isStandalone;
|
||||||
|
|
||||||
// Check if push is supported
|
const subscribe = useCallback(async (overridePhone) => {
|
||||||
useEffect(() => {
|
const resolvedPhone = overridePhone || normalizePhone(phoneInput) || storedPhone;
|
||||||
// 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;
|
|
||||||
if (!resolvedPhone) {
|
if (!resolvedPhone) {
|
||||||
setStatus("need_phone");
|
setStatus("need_phone");
|
||||||
return;
|
return;
|
||||||
|
|
@ -99,7 +75,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
try {
|
try {
|
||||||
window.localStorage.setItem(PHONE_STORAGE_KEY, resolvedPhone);
|
window.localStorage.setItem(PHONE_STORAGE_KEY, resolvedPhone);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// localStorage unavailable — ignore
|
|
||||||
void e;
|
void e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -114,7 +89,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
|
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// Send to backend
|
|
||||||
const sub = subscription.toJSON();
|
const sub = subscription.toJSON();
|
||||||
const resp = await fetch(getEndpoint("push-subscribe"), {
|
const resp = await fetch(getEndpoint("push-subscribe"), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|
@ -142,7 +116,57 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
setStatus("idle");
|
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 () => {
|
const unsubscribe = async () => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -150,7 +174,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
const sub = await reg.pushManager.getSubscription();
|
const sub = await reg.pushManager.getSubscription();
|
||||||
if (sub) {
|
if (sub) {
|
||||||
await sub.unsubscribe();
|
await sub.unsubscribe();
|
||||||
// Notify backend
|
|
||||||
await fetch(getEndpoint("push-unsubscribe"), {
|
await fetch(getEndpoint("push-unsubscribe"), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: apiHeaders,
|
headers: apiHeaders,
|
||||||
|
|
@ -167,9 +190,39 @@ 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 (status === "unsupported") return null;
|
||||||
if (dismissed && status !== "subscribed" && status !== "denied") return null;
|
// 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">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm">🔔</span>
|
||||||
|
<p className="text-sm font-medium text-[var(--color-accent)]">
|
||||||
|
Уведомления включены
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={unsubscribe}
|
||||||
|
className="text-xs text-[var(--color-text-muted)] transition hover:text-[var(--color-text)] underline"
|
||||||
|
>
|
||||||
|
Отключить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</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
|
// iOS not installed — show instruction to add to Home Screen
|
||||||
if (status === "ios_not_installed") {
|
if (status === "ios_not_installed") {
|
||||||
|
|
@ -188,7 +241,7 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
<li>1. Нажмите <span className="font-medium">«Поделиться»</span> (квадрат со стрелкой ↑) внизу Safari</li>
|
<li>1. Нажмите <span className="font-medium">«Поделиться»</span> (квадрат со стрелкой ↑) внизу Safari</li>
|
||||||
<li>2. Выберите <span className="font-medium">«На экран Домой»</span> → «Добавить»</li>
|
<li>2. Выберите <span className="font-medium">«На экран Домой»</span> → «Добавить»</li>
|
||||||
<li>3. Откройте приложение с иконки <span className="font-medium">«СуперСам»</span> на главном экране</li>
|
<li>3. Откройте приложение с иконки <span className="font-medium">«СуперСам»</span> на главном экране</li>
|
||||||
<li>4. Нажмите <span className="font-medium">«Разрешить»</span> в этом баннере</li>
|
<li>4. Разрешите уведомления при первом открытии</li>
|
||||||
</ol>
|
</ol>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -205,29 +258,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subscribed state — show small confirmation + unsubscribe option
|
|
||||||
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">
|
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm">🔔</span>
|
|
||||||
<p className="text-sm font-medium text-[var(--color-accent)]">
|
|
||||||
Уведомления включены
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={unsubscribe}
|
|
||||||
className="text-xs text-[var(--color-text-muted)] transition hover:text-[var(--color-text)] underline"
|
|
||||||
>
|
|
||||||
Отключить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Denied — user blocked notifications
|
// Denied — user blocked notifications
|
||||||
if (status === "denied") {
|
if (status === "denied") {
|
||||||
return (
|
return (
|
||||||
|
|
@ -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)
|
// Need a phone number to subscribe (opened the installed app without a token)
|
||||||
if (status === "need_phone" || (!phoneNorm && !isIOSNotInstalled)) {
|
if (status === "need_phone" || (!phoneNorm && !isIOSNotInstalled)) {
|
||||||
return (
|
return (
|
||||||
|
|
@ -275,7 +296,7 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="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"
|
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 (
|
return (
|
||||||
<div className="rounded-xl border border-[rgba(18,128,92,0.2)] bg-[var(--color-accent-soft)] px-4 py-3">
|
<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">
|
<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">
|
<div className="flex items-center gap-2 flex-shrink-0">
|
||||||
<button
|
<button
|
||||||
type="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"
|
className="rounded-xl bg-[var(--color-accent)] px-4 py-2 text-sm font-semibold text-white transition hover:opacity-90"
|
||||||
>
|
>
|
||||||
Разрешить
|
Разрешить
|
||||||
|
|
@ -323,4 +344,4 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default PushSubscriptionBanner;
|
export default PushSubscriptionBanner;
|
||||||
Loading…
Reference in New Issue