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:
@@ -6,7 +6,7 @@ export function BottomNav() {
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 backdrop-blur lg:hidden">
|
||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
|
||||
<div className="mx-auto grid max-w-md grid-cols-4">
|
||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||
const isActive = location.pathname === to
|
||||
|
||||
@@ -11,7 +11,11 @@ export function RootLayout({ children }: { children: ReactNode }) {
|
||||
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
||||
<Sidebar />
|
||||
|
||||
<main className="min-w-0 flex-1 px-4 pb-24 pt-4 lg:px-0 lg:pb-8 lg:pt-8">{children}</main>
|
||||
{/* pb-24 deja lugar para la BottomNav; en iOS standalone hay que sumar
|
||||
el inset del home indicator o el contenido queda debajo. */}
|
||||
<main className="min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] pt-4 lg:px-0 lg:pb-8 lg:pt-8">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<BottomNav />
|
||||
|
||||
@@ -18,6 +18,10 @@ type ThemeContextValue = {
|
||||
|
||||
const STORAGE_KEY = 'theme'
|
||||
|
||||
/** Colores de la barra de estado en modo standalone. Debe matchear index.css. */
|
||||
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
|
||||
const THEME_COLOR_META_ID = 'theme-color'
|
||||
|
||||
function readStoredTheme(): Theme {
|
||||
const value = localStorage.getItem(STORAGE_KEY)
|
||||
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
||||
@@ -41,9 +45,16 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
document.documentElement.classList.toggle('dark', resolveDark(theme))
|
||||
setIsDark(document.documentElement.classList.contains('dark'))
|
||||
const dark = resolveDark(theme)
|
||||
document.documentElement.classList.toggle('dark', dark)
|
||||
setIsDark(dark)
|
||||
localStorage.setItem(STORAGE_KEY, theme)
|
||||
|
||||
// En standalone la barra de estado se pinta con theme-color; sin esto
|
||||
// queda congelada en el valor que puso el script inline de index.html.
|
||||
document
|
||||
.getElementById(THEME_COLOR_META_ID)
|
||||
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)
|
||||
}
|
||||
update()
|
||||
|
||||
|
||||
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'
|
||||
@@ -1,5 +1,27 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* Inter variable auto-hospedada. Declaramos solo latin y latin-ext a mano en
|
||||
lugar de importar el wght.css de @fontsource: ese trae los 7 subsets y el
|
||||
service worker precachea todo lo emitido, casi 1 MB que nunca se descarga.
|
||||
El archivo .woff2 sí viene del paquete, con hash y cache immutable. */
|
||||
@font-face {
|
||||
font-family: "Inter Variable";
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-weight: 100 900;
|
||||
src: url("@fontsource-variable/inter/files/inter-latin-wght-normal.woff2") format("woff2-variations");
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Inter Variable";
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-weight: 100 900;
|
||||
src: url("@fontsource-variable/inter/files/inter-latin-ext-wght-normal.woff2") format("woff2-variations");
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme inline {
|
||||
@@ -45,7 +67,8 @@
|
||||
--radius-xl: 0.75rem;
|
||||
|
||||
/* Tipografía (igual que la landing) */
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||
/* @fontsource-variable/inter registra la familia como "Inter Variable" */
|
||||
--font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif;
|
||||
|
||||
/* Animaciones */
|
||||
--animate-fade-in: fade-in 0.2s ease-out;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { router } from './router'
|
||||
import { AuthProvider } from './context/AuthProvider'
|
||||
import { ThemeProvider } from './context/ThemeProvider'
|
||||
import { ToastProvider } from './components/ui'
|
||||
import { PwaProvider } from './features/pwa'
|
||||
import './index.css'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -20,7 +21,9 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<RouterProvider router={router} />
|
||||
<PwaProvider>
|
||||
<RouterProvider router={router} />
|
||||
</PwaProvider>
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
|
||||
3
apps/web/src/vite-env.d.ts
vendored
3
apps/web/src/vite-env.d.ts
vendored
@@ -1 +1,2 @@
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
|
||||
Reference in New Issue
Block a user