200 lines
6.9 KiB
TypeScript
200 lines
6.9 KiB
TypeScript
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
type ReactNode,
|
|
} from 'react'
|
|
import { registerSW } from 'virtual:pwa-register'
|
|
import { router } from '../../router'
|
|
import { useAuth } from '../../context/AuthProvider'
|
|
import { useToast } from '../../components/ui'
|
|
import { InstallPrompt } from './InstallPrompt'
|
|
|
|
/** `beforeinstallprompt` todavía no está en lib.dom (Chromium >= 108). */
|
|
type BeforeInstallPromptEvent = Event & {
|
|
prompt: () => Promise<void>
|
|
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
|
|
}
|
|
|
|
type PwaContextValue = {
|
|
/** El navegador ofreció instalar y el usuario todavía no lo decidió. */
|
|
canPrompt: boolean
|
|
/** Safari en iOS: no hay `prompt()`, hay que instruir al usuario. */
|
|
canShowIosHint: boolean
|
|
promptInstall: () => Promise<void>
|
|
dismiss: () => void
|
|
}
|
|
|
|
const PwaContext = createContext<PwaContextValue | null>(null)
|
|
|
|
/**
|
|
* El descarte es definitivo: una vez que el usuario dice "ahora no" no se vuelve
|
|
* a preguntar. Comparte clave con la pista de iOS porque el motivo es el mismo.
|
|
*/
|
|
const DISMISSED_KEY = 'pwa-install-dismissed'
|
|
|
|
/**
|
|
* Cuánto hay que quedarse en la misma ruta antes de ofrecer instalar. El evento
|
|
* `beforeinstallprompt` llega a los segundos, así que sin este margen el banner
|
|
* cae en medio de la primera tarea de la visita.
|
|
*/
|
|
const DWELL_MS = 20_000
|
|
|
|
/** iOS Safari no dispara `beforeinstallprompt`: se chequea el modo standalone. */
|
|
function isStandalone() {
|
|
return (
|
|
window.matchMedia('(display-mode: standalone)').matches ||
|
|
(navigator as Navigator & { standalone?: boolean }).standalone === true
|
|
)
|
|
}
|
|
|
|
/**
|
|
* iOS real, Safari real. Excluye Chrome/Firefox/Edge/Opera en iOS: usan WebKit
|
|
* pero también los instala desde Safari, así que la instrucción de compartir
|
|
* no aplica. El iPad de iPadOS 13+ se reporta como MacIntel con touch points.
|
|
*/
|
|
function detectIos() {
|
|
if (isStandalone()) return false
|
|
|
|
const ua = navigator.userAgent
|
|
const isIosDevice =
|
|
/iPad|iPhone|iPod/.test(ua) ||
|
|
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
|
|
if (!isIosDevice) return false
|
|
|
|
return !/CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo|YaBrowser/.test(ua)
|
|
}
|
|
|
|
/**
|
|
* El registro se hace desde el provider y no con `injectRegister: 'auto'` para
|
|
* poder avisar cuando el shell quedó cacheado. El flag es de módulo porque
|
|
* StrictMode monta dos veces en dev y `onOfflineReady` dispararía dos toasts.
|
|
* No se limpia en el unmount: StrictMode lo resetea en el mismo ciclo de montaje
|
|
* y volvería a registrar. Con HMR el módulo se re-evalua y arranca en false.
|
|
*/
|
|
let registered = false
|
|
|
|
export function PwaProvider({ children }: { children: ReactNode }) {
|
|
const { user } = useAuth()
|
|
const { success, info } = useToast()
|
|
const [installEvent, setInstallEvent] = useState<BeforeInstallPromptEvent | null>(null)
|
|
const [dismissed, setDismissed] = useState(() => localStorage.getItem(DISMISSED_KEY) === '1')
|
|
const [isInstalled, setIsInstalled] = useState(isStandalone)
|
|
const [isIos] = useState(detectIos)
|
|
const [pathname, setPathname] = useState(() => router.state.location.pathname)
|
|
const [settled, setSettled] = useState(false)
|
|
|
|
useEffect(() => {
|
|
if (registered) return
|
|
registered = true
|
|
registerSW({
|
|
immediate: true,
|
|
onOfflineReady() {
|
|
success('La app quedó lista para abrirse sin conexión', 'Ya podés usar Gruperly offline.')
|
|
},
|
|
onRegisterError(error) {
|
|
console.error('No se pudo registrar el service worker', error)
|
|
},
|
|
})
|
|
}, [success])
|
|
|
|
useEffect(() => {
|
|
const onBeforeInstallPrompt = (event: Event) => {
|
|
// Sin preventDefault el navegador muestra su propio mini-infobar.
|
|
event.preventDefault()
|
|
setInstallEvent(event as BeforeInstallPromptEvent)
|
|
}
|
|
const onInstalled = () => {
|
|
setIsInstalled(true)
|
|
setInstallEvent(null)
|
|
}
|
|
|
|
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
|
window.addEventListener('appinstalled', onInstalled)
|
|
return () => {
|
|
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
|
window.removeEventListener('appinstalled', onInstalled)
|
|
}
|
|
}, [])
|
|
|
|
// `PwaProvider` monta fuera del `RouterProvider`, así que no puede usar
|
|
// `useRouterState`: se suscribe al singleton. Conviene tener la ruta acá y no
|
|
// en el componente que muestra el banner, porque `AppLayoutGuard` desmonta
|
|
// `RootLayout` cada vez que su query de onboarding vuelve a `pending` y un
|
|
// timer de dwell en el hijo se perdería en cada navegación.
|
|
useEffect(
|
|
() => router.subscribe('onResolved', ({ toLocation }) => setPathname(toLocation.pathname)),
|
|
[],
|
|
)
|
|
|
|
// Durante el alta inicial no se ofrece instalar: la persona todavía no
|
|
// conoce la app. El timer ni siquiera corre, así que al salir arranca de cero
|
|
// en la primera pantalla real.
|
|
const inOnboarding = pathname.startsWith('/onboarding')
|
|
|
|
useEffect(() => {
|
|
// Navegar antes de que se cumpla el tiempo reinicia la cuenta: tampoco
|
|
// estamos pidiendo instalar a alguien que está peleando con la app. Una
|
|
// vez cumplido queda armed y no se oculta más al navegar.
|
|
if (settled || inOnboarding) return
|
|
const timer = setTimeout(() => setSettled(true), DWELL_MS)
|
|
return () => clearTimeout(timer)
|
|
}, [pathname, settled, inOnboarding])
|
|
|
|
const promptInstall = useCallback(async () => {
|
|
if (!installEvent) return
|
|
await installEvent.prompt()
|
|
const { outcome } = await installEvent.userChoice
|
|
setInstallEvent(null)
|
|
if (outcome === 'accepted') {
|
|
localStorage.setItem(DISMISSED_KEY, '1')
|
|
setDismissed(true)
|
|
success('App instalada', 'Ahora tenés Gruperly en tu pantalla de inicio.')
|
|
}
|
|
}, [installEvent, success])
|
|
|
|
const dismiss = useCallback(() => {
|
|
setDismissed(true)
|
|
localStorage.setItem(DISMISSED_KEY, '1')
|
|
info('Podés instalarla más adelante desde el menú del navegador.')
|
|
}, [info])
|
|
|
|
/**
|
|
* Sin sesión no hay nada que instalar todavía: la primera vez que alguien
|
|
* conoce la app es instalándola, no pidiéndole que la instale.
|
|
*
|
|
* OJO: `_authenticated` NO es un guard de sesión. `AppLayoutGuard` renderiza
|
|
* `RootLayout` aunque no haya usuario, así que el gate se chequea acá y no
|
|
* se puede inferir de dónde se monte el prompt.
|
|
*/
|
|
const eligible = !!user && settled && !dismissed && !isInstalled && !inOnboarding
|
|
|
|
const value = useMemo<PwaContextValue>(
|
|
() => ({
|
|
canPrompt: eligible && installEvent !== null,
|
|
canShowIosHint: eligible && isIos,
|
|
promptInstall,
|
|
dismiss,
|
|
}),
|
|
[eligible, installEvent, isIos, promptInstall, dismiss],
|
|
)
|
|
|
|
return (
|
|
<PwaContext.Provider value={value}>
|
|
{children}
|
|
<InstallPrompt />
|
|
</PwaContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function usePwa() {
|
|
const context = useContext(PwaContext)
|
|
if (!context) {
|
|
throw new Error('usePwa debe usarse dentro de <PwaProvider>')
|
|
}
|
|
return context
|
|
}
|