diff --git a/src/components/client/PushSubscriptionBanner.jsx b/src/components/client/PushSubscriptionBanner.jsx index 05ed79e..bf6f609 100644 --- a/src/components/client/PushSubscriptionBanner.jsx +++ b/src/components/client/PushSubscriptionBanner.jsx @@ -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,7 +116,57 @@ 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 { @@ -150,7 +174,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => { const sub = await reg.pushManager.getSubscription(); if (sub) { await sub.unsubscribe(); - // Notify backend await fetch(getEndpoint("push-unsubscribe"), { method: "POST", 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 (dismissed && status !== "subscribed" && status !== "denied") return null; + // Auto-subscribed or prompting — no UI needed + if (status === "subscribed" || status === "prompting") { + if (status === "subscribed") { + return ( +
+
+
+ 🔔 +

+ Уведомления включены +

+
+ +
+
+ ); + } + // prompting — show minimal loading + return ( +
+

Ожидание разрешения…

+
+ ); + } + if (dismissed) return null; // iOS not installed — show instruction to add to Home Screen if (status === "ios_not_installed") { @@ -188,7 +241,7 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
  • 1. Нажмите «Поделиться» (квадрат со стрелкой ↑) внизу Safari
  • 2. Выберите «На экран Домой» → «Добавить»
  • 3. Откройте приложение с иконки «СуперСам» на главном экране
  • -
  • 4. Нажмите «Разрешить» в этом баннере
  • +
  • 4. Разрешите уведомления при первом открытии
  • @@ -205,29 +258,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => { ); } - // Subscribed state — show small confirmation + unsubscribe option - if (status === "subscribed") { - return ( -
    -
    -
    - 🔔 -

    - Уведомления включены -

    -
    - -
    -
    - ); - } - // Denied — user blocked notifications if (status === "denied") { return ( @@ -242,15 +272,6 @@ export const PushSubscriptionBanner = ({ phone, orderGroupId }) => { ); } - // Prompting — show loading - if (status === "prompting") { - return ( -
    -

    Ожидание разрешения…

    -
    - ); - } - // 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 }) => { />