sonda/web/src/pwa/useInstall.ts
tgiachi 2217a12042 feat(web): the app can be installed and opens offline (PWA)
- A web app manifest with the name, the colours, the display mode and the icons (also a maskable one), so a browser offers to install it; Settings has an Install button where the browser lets the page ask.
- A service worker keeps the files of the app (the page, its scripts and styles, the manifest and the icons) so it opens at once, and shows its own page when the server cannot be reached. It never touches /api/: nothing from the API is kept, answered from a cache, or asked for by the worker. Files that failed, and anything that is not a file of the app, are not kept; the scripts it keeps are capped.
- A new version waits until the page says it may take over: a line says a new version is ready and its button reloads the page after the new worker took over.
- The server gives the manifest its type (application/manifest+json); the worker and the manifest are asked again every time, and the policy of the page needs no change.
2026-11-13 12:22:00 +01:00

40 lines
1.5 KiB
TypeScript

import { useCallback, useEffect, useState } from 'react'
/** What the browser gives to ask a person to install the app: only some browsers have it. */
interface InstallPrompt extends Event {
prompt: () => Promise<void>
userChoice: Promise<{ outcome: string }>
}
/**
* Lets a page offer to install the app when the browser allows it. The bar of the browser is kept back, so the page asks
* when it wants: in Settings. It is offered once, only when the app is not already running as an app, and not after it
* was installed.
*/
export function useInstall(): { available: boolean; install: () => Promise<void> } {
const [prompt, setPrompt] = useState<InstallPrompt | null>(null)
useEffect(() => {
const standalone = typeof window.matchMedia === 'function' && window.matchMedia('(display-mode: standalone)').matches
const onPrompt = (e: Event) => {
e.preventDefault()
if (!standalone) setPrompt(e as InstallPrompt)
}
const onInstalled = () => setPrompt(null)
window.addEventListener('beforeinstallprompt', onPrompt)
window.addEventListener('appinstalled', onInstalled)
return () => {
window.removeEventListener('beforeinstallprompt', onPrompt)
window.removeEventListener('appinstalled', onInstalled)
}
}, [])
const install = useCallback(async () => {
if (!prompt) return
await prompt.prompt()
await prompt.userChoice
setPrompt(null) // a prompt can be used once
}, [prompt])
return { available: prompt !== null, install }
}