feat(pwa): implement PWA installation banner and context provider

- Add `generate-icons.ts` script to generate PWA icons from SVG.
- Create `InstallBanner` component for prompting users to install the app.
- Implement `PwaProvider` to manage PWA installation state and events.
- Export `PwaProvider` and `InstallBanner` from the PWA feature index.
This commit is contained in:
Jose Selesan
2026-09-28 20:55:48 -03:00
parent 05da085e36
commit 2fd1826014
23 changed files with 1032 additions and 24 deletions

View File

@@ -0,0 +1,126 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react'
import { registerSW } from 'virtual:pwa-register'
import { useToast } from '../../components/ui'
import { InstallBanner } from './InstallBanner'
/** `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 la app y el usuario todavía no lo decidió. */
canInstall: boolean
isInstalled: boolean
promptInstall: () => Promise<void>
}
const PwaContext = createContext<PwaContextValue | null>(null)
const DISMISSED_KEY = 'pwa-install-dismissed'
/** 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
)
}
/**
* 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 { success, info } = useToast()
const [installEvent, setInstallEvent] = useState<BeforeInstallPromptEvent | null>(null)
const [dismissed, setDismissed] = useState(() => localStorage.getItem(DISMISSED_KEY) === '1')
const [isInstalled, setIsInstalled] = useState(isStandalone)
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)
}
}, [])
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 value = useMemo<PwaContextValue>(
() => ({ canInstall: installEvent !== null && !dismissed, isInstalled, promptInstall }),
[installEvent, dismissed, isInstalled, promptInstall],
)
return (
<PwaContext.Provider value={value}>
{children}
<InstallBanner
visible={value.canInstall}
onInstall={promptInstall}
onDismiss={() => {
setDismissed(true)
localStorage.setItem(DISMISSED_KEY, '1')
info('Podés instalarla más adelante desde el menú del navegador.')
}}
/>
</PwaContext.Provider>
)
}
export function usePwa() {
const context = useContext(PwaContext)
if (!context) {
throw new Error('usePwa debe usarse dentro de <PwaProvider>')
}
return context
}