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:
50
apps/web/src/features/pwa/InstallBanner.tsx
Normal file
50
apps/web/src/features/pwa/InstallBanner.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Download, X } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
type InstallBannerProps = {
|
||||
visible: boolean
|
||||
onInstall: () => void
|
||||
onDismiss: () => void
|
||||
}
|
||||
|
||||
export function InstallBanner({ visible, onInstall, onDismiss }: InstallBannerProps) {
|
||||
if (!visible) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'fixed inset-x-0 z-30 px-4 lg:left-auto lg:right-6 lg:w-96 lg:px-0',
|
||||
// Encima de BottomNav en móvil; abajo a la derecha en desktop.
|
||||
'bottom-[calc(4.5rem+env(safe-area-inset-bottom))] lg:bottom-6',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-3 rounded-xl border border-border bg-surface p-4 shadow-lg">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-semibold text-primary">Instalá Gruperly</p>
|
||||
<p className="mt-0.5 text-xs leading-relaxed text-foreground/70">
|
||||
Abrila directo desde tu pantalla de inicio, sin barra de navegador.
|
||||
</p>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<Button variant="primary" size="sm" onClick={onInstall}>
|
||||
<Download className="size-4" strokeWidth={2} />
|
||||
Instalar app
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={onDismiss}>
|
||||
Ahora no
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDismiss}
|
||||
aria-label="Cerrar aviso de instalación"
|
||||
className="shrink-0 rounded-lg p-1 text-foreground/40 transition-colors hover:bg-primary-soft hover:text-foreground"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
126
apps/web/src/features/pwa/PwaProvider.tsx
Normal file
126
apps/web/src/features/pwa/PwaProvider.tsx
Normal 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
|
||||
}
|
||||
2
apps/web/src/features/pwa/index.ts
Normal file
2
apps/web/src/features/pwa/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { PwaProvider, usePwa } from './PwaProvider'
|
||||
export { InstallBanner } from './InstallBanner'
|
||||
Reference in New Issue
Block a user