diff --git a/apps/web/src/lib/register-sw.ts b/apps/web/src/lib/register-sw.ts new file mode 100644 index 0000000..d704ca1 --- /dev/null +++ b/apps/web/src/lib/register-sw.ts @@ -0,0 +1,78 @@ +import { registerSW } from 'virtual:pwa-register' + +/** How often an open app asks the server for a new service worker. */ +const UPDATE_INTERVAL_MS = 30 * 60 * 1000 + +function isEditing() { + const element = document.activeElement + if (!(element instanceof HTMLElement)) return false + return ( + element.isContentEditable || + element instanceof HTMLInputElement || + element instanceof HTMLTextAreaElement || + element instanceof HTMLSelectElement + ) +} + +/** + * Reloads into the new release as soon as it is safe: right away, unless the + * user is typing (an item name, a list name...), in which case it waits until + * the app goes to the background so nothing they wrote is lost. + */ +function reloadWhenIdle() { + if (document.visibilityState === 'hidden' || !isEditing()) { + window.location.reload() + return + } + + document.addEventListener( + 'visibilitychange', + () => { + if (document.visibilityState === 'hidden') window.location.reload() + }, + { once: true }, + ) +} + +/** + * Registers the service worker and keeps the installed PWA up to date. + * + * With `registerType: 'autoUpdate'` the new worker skips waiting and claims the + * page as soon as it is installed, but the browser only looks for one on a + * navigation. An installed PWA is rarely navigated (it stays open in the + * background for days), so this also checks periodically, whenever the app + * comes back to the foreground and when the connection returns. + */ +export function registerServiceWorker() { + if (!('serviceWorker' in navigator)) return + + registerSW({ + immediate: true, + onNeedReload: reloadWhenIdle, + onRegisteredSW(swUrl, registration) { + if (!registration) return + + const checkForUpdate = async () => { + if (registration.installing || !navigator.onLine) return + + // Skip the check when the server is unreachable instead of letting + // `update()` reject (it would log an unhandled error offline). + try { + const response = await fetch(swUrl, { + cache: 'no-store', + headers: { 'cache-control': 'no-cache' }, + }) + if (response.ok) await registration.update() + } catch { + // Offline or server down: try again on the next trigger. + } + } + + setInterval(checkForUpdate, UPDATE_INTERVAL_MS) + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') void checkForUpdate() + }) + window.addEventListener('online', () => void checkForUpdate()) + }, + }) +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index bdfc86d..97e9240 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -4,10 +4,13 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import { createQueryClient } from '@/lib/query-client' +import { registerServiceWorker } from '@/lib/register-sw' import { routeTree } from './routeTree.gen' import './index.css' +registerServiceWorker() + const queryClient = createQueryClient() const router = createRouter({ diff --git a/apps/web/tsconfig.app.json b/apps/web/tsconfig.app.json index 6f5f76f..fea5440 100644 --- a/apps/web/tsconfig.app.json +++ b/apps/web/tsconfig.app.json @@ -4,7 +4,7 @@ "target": "es2023", "lib": ["ES2023", "DOM", "DOM.Iterable"], "module": "esnext", - "types": ["vite/client"], + "types": ["vite/client", "vite-plugin-pwa/vanillajs"], "allowArbitraryExtensions": true, "skipLibCheck": true, diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 549332b..64fdf4c 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -15,10 +15,11 @@ export default defineConfig({ react(), tailwindcss(), VitePWA({ - // `autoUpdate` pre-caches the app shell and swaps in new releases on the - // next navigation. Registration is injected into `index.html` at build - // time, so no `virtual:pwa-register` import is needed in the app. + // `autoUpdate`: a new service worker activates as soon as it is installed + // and the page reloads into the new release. Registration (and the + // periodic update checks) live in `src/lib/register-sw.ts`. registerType: 'autoUpdate', + injectRegister: false, includeAssets: ['favicon.svg', 'apple-touch-icon.png'], manifest: { name: 'Superlist — Listas de compras compartidas', @@ -48,6 +49,11 @@ export default defineConfig({ // SPA fallback so deep links work offline, but never swallow API calls. navigateFallback: 'index.html', navigateFallbackDenylist: [/^\/api\//], + // Drop caches left behind by previous releases once the new one activates. + cleanupOutdatedCaches: true, + // Take control of every open tab as soon as the new worker activates. + clientsClaim: true, + skipWaiting: true, }, devOptions: { // The service worker is only built for `vite build`; verify with `preview`.