Feature 06: PWA shell and offline (#58)
CI / ci (push) Successful in 1m40s

Co-authored-by: dev_agent <dev_agent@cubecraftlabs.com>
This commit was merged in pull request #58.
This commit is contained in:
2026-10-05 15:22:37 -04:00
committed by approver_agent
parent e6fd24db0a
commit 81c5085f9a
44 changed files with 7359 additions and 42 deletions
+18
View File
@@ -0,0 +1,18 @@
.hint {
display: flex;
align-items: center;
gap: var(--space-3);
}
.icon {
color: var(--color-accent);
}
.message {
flex: 1;
margin: 0;
font-family: var(--font-body);
font-size: 15px;
font-weight: 600;
line-height: 1.35;
}
+146
View File
@@ -0,0 +1,146 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DISMISSED_KEY, InstallHint } from './InstallHint.tsx'
const IPHONE_SAFARI =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1'
const IPAD_SAFARI =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15'
const MAC_SAFARI = IPAD_SAFARI
const IPHONE_CHROME =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/138.0.7204.119 Mobile/15E148 Safari/604.1'
const IPHONE_FIREFOX =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/141.0 Mobile/15E148 Safari/605.1.15'
const IPHONE_EDGE =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 EdgiOS/138.3351.83 Mobile/15E148 Safari/605.1.15'
const IPHONE_OPERA =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1 OPT/5.4.0'
const IPHONE_MQQBROWSER =
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 MQQBrowser/11.3.5 Mobile/15E148 Safari/604.1'
const ANDROID_CHROME =
'Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Mobile Safari/537.36'
const DESKTOP_CHROME =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
const copy = 'Tap Share, then Add to Home Screen to get notifications'
type Device = {
userAgent: string
maxTouchPoints?: number
// display-mode: standalone
displayStandalone?: boolean
// navigator.standalone (Safari only; undefined elsewhere)
navigatorStandalone?: boolean
}
// mockDevice pretends to be a browser with the given user agent and
// display mode; jsdom has no matchMedia, navigator.maxTouchPoints or
// navigator.standalone.
function mockDevice({ userAgent, maxTouchPoints = 0, displayStandalone = false, navigatorStandalone }: Device) {
vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(userAgent)
Object.defineProperty(navigator, 'maxTouchPoints', { configurable: true, value: maxTouchPoints })
Object.defineProperty(navigator, 'standalone', { configurable: true, value: navigatorStandalone })
vi.stubGlobal('matchMedia', (query: string) => {
if (query !== '(display-mode: standalone)') throw new Error(`unexpected media query ${query}`)
return { matches: displayStandalone, media: query } as MediaQueryList
})
}
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
Reflect.deleteProperty(navigator, 'maxTouchPoints')
Reflect.deleteProperty(navigator, 'standalone')
localStorage.clear()
})
describe('InstallHint', () => {
it('shows on iPhone Safari in a browser tab', () => {
mockDevice({ userAgent: IPHONE_SAFARI, maxTouchPoints: 5, navigatorStandalone: false })
render(<InstallHint />)
expect(screen.getByRole('note')).toHaveTextContent(copy)
})
it('shows on iPadOS Safari, which reports itself as a Mac with a touch screen', () => {
mockDevice({ userAgent: IPAD_SAFARI, maxTouchPoints: 5, navigatorStandalone: false })
render(<InstallHint />)
expect(screen.getByRole('note')).toHaveTextContent(copy)
})
it('is hidden when navigator.standalone is true', () => {
mockDevice({ userAgent: IPHONE_SAFARI, maxTouchPoints: 5, navigatorStandalone: true })
render(<InstallHint />)
expect(screen.queryByRole('note')).toBeNull()
})
it('is hidden when display-mode is standalone', () => {
mockDevice({ userAgent: IPHONE_SAFARI, maxTouchPoints: 5, displayStandalone: true })
render(<InstallHint />)
expect(screen.queryByRole('note')).toBeNull()
})
it.each([
['Android Chrome', { userAgent: ANDROID_CHROME, maxTouchPoints: 5 }],
['desktop Chrome', { userAgent: DESKTOP_CHROME }],
['desktop Safari on a Mac', { userAgent: MAC_SAFARI }],
['Chrome on iPhone', { userAgent: IPHONE_CHROME, maxTouchPoints: 5 }],
['Firefox on iPhone', { userAgent: IPHONE_FIREFOX, maxTouchPoints: 5 }],
['Edge on iPhone', { userAgent: IPHONE_EDGE, maxTouchPoints: 5 }],
['Opera on iPhone', { userAgent: IPHONE_OPERA, maxTouchPoints: 5 }],
['MQQBrowser on iPhone', { userAgent: IPHONE_MQQBROWSER, maxTouchPoints: 5 }],
])('is hidden on %s', (_name, device: Device) => {
mockDevice(device)
render(<InstallHint />)
expect(screen.queryByRole('note')).toBeNull()
})
it('stays dismissed on this device', () => {
mockDevice({ userAgent: IPHONE_SAFARI, maxTouchPoints: 5, navigatorStandalone: false })
const first = render(<InstallHint />)
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
expect(screen.queryByRole('note')).toBeNull()
expect(localStorage.getItem(DISMISSED_KEY)).toBe('1')
first.unmount()
render(<InstallHint />)
expect(screen.queryByRole('note')).toBeNull()
})
it('stays up and reports the error when the dismissal cannot be saved', () => {
mockDevice({ userAgent: IPHONE_SAFARI, maxTouchPoints: 5, navigatorStandalone: false })
const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new DOMException('quota exceeded', 'QuotaExceededError')
})
render(<InstallHint />)
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
expect(screen.getByRole('note')).toHaveTextContent(copy)
expect(screen.getByRole('alert')).toHaveTextContent(
'Could not remember on this device that this hint was dismissed: QuotaExceededError: quota exceeded',
)
setItem.mockRestore()
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
expect(screen.queryByRole('note')).toBeNull()
expect(screen.queryByRole('alert')).toBeNull()
expect(localStorage.getItem(DISMISSED_KEY)).toBe('1')
})
it('shows and reports the error when storage cannot be read', () => {
mockDevice({ userAgent: IPHONE_SAFARI, maxTouchPoints: 5, navigatorStandalone: false })
const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new DOMException('storage blocked', 'SecurityError')
})
render(<InstallHint />)
expect(screen.getByRole('note')).toHaveTextContent(copy)
expect(screen.getByRole('alert')).toHaveTextContent(
'Could not check whether this hint was dismissed on this device: SecurityError: storage blocked',
)
getItem.mockRestore()
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
expect(screen.getByRole('note')).toHaveTextContent(copy)
expect(screen.queryByRole('alert')).toBeNull()
})
})
+97
View File
@@ -0,0 +1,97 @@
import { useState } from 'react'
import { Share, X } from 'lucide-react'
import { Card } from '../ui/Card.tsx'
import { ErrorBanner } from '../ui/ErrorBanner.tsx'
import { Icon } from '../ui/Icon.tsx'
import { IconButton } from '../ui/IconButton.tsx'
import styles from './InstallHint.module.css'
// DISMISSED_KEY is the localStorage key remembering, on this device, that the
// household dismissed the hint.
export const DISMISSED_KEY = 'mealquest.installHint.dismissed'
// Safari's user agent ends "(KHTML, like Gecko) Version/<v> Mobile/<build>
// Safari/<v>" (iPadOS leaves out Mobile/). Every other iOS browser and in-app
// web view adds its own token (CriOS, FxiOS, EdgiOS, OPiOS, MQQBrowser, GSA,
// ...) or drops Version/ or Safari/, so only this exact tail is Safari.
const SAFARI_TAIL = /\(KHTML, like Gecko\) Version\/[\d.]+ (?:Mobile\/\w+ )?Safari\/[\d.]+$/
// isIosSafari reports whether the page is open in Safari on iPhone, iPod or
// iPad. iPadOS 13+ asks for the desktop site and reports itself as a Mac, so
// a "Macintosh" with a touch screen is an iPad.
export function isIosSafari(nav: Pick<Navigator, 'userAgent' | 'maxTouchPoints'>): boolean {
const ua = nav.userAgent
const ios = /iPhone|iPod|iPad/.test(ua) || (/Macintosh/.test(ua) && nav.maxTouchPoints > 1)
return ios && SAFARI_TAIL.test(ua)
}
// isStandalone reports whether the app is running from the Home Screen.
// Safari sets navigator.standalone; other browsers answer the display-mode
// media query.
export function isStandalone(): boolean {
const legacy = (navigator as Navigator & { standalone?: boolean }).standalone
return legacy === true || window.matchMedia('(display-mode: standalone)').matches
}
// HintState is whether the household dismissed the hint on this device, and
// the storage failure, if any, that stopped us reading or saving that.
type HintState = {
dismissed: boolean
failure: { action: 'read' | 'write'; message: string } | null
}
// Storage can be unavailable (blocked by the browser or privacy settings), in
// which case using it throws. The failure is reported, never treated as a
// remembered dismissal.
function readDismissed(): HintState {
try {
return { dismissed: window.localStorage.getItem(DISMISSED_KEY) === '1', failure: null }
} catch (err) {
return { dismissed: false, failure: { action: 'read', message: String(err) } }
}
}
function writeDismissed(): HintState {
try {
window.localStorage.setItem(DISMISSED_KEY, '1')
return { dismissed: true, failure: null }
} catch (err) {
return { dismissed: false, failure: { action: 'write', message: String(err) } }
}
}
const failureText = {
read: 'Could not check whether this hint was dismissed on this device',
write: 'Could not remember on this device that this hint was dismissed',
}
// InstallHint tells iOS and iPadOS Safari users how to install the app, which
// iOS requires before it delivers Web Push. It shows only in a Safari browser
// tab, never once installed, and stays dismissed on this device. If storage
// fails, the hint stays up with an error saying so. Used by onboarding step 3
// and the Notifications screen.
export function InstallHint() {
const [eligible] = useState(() => isIosSafari(navigator) && !isStandalone())
const [state, setState] = useState<HintState>(() =>
eligible ? readDismissed() : { dismissed: false, failure: null },
)
if (!eligible || state.dismissed) return null
const { failure } = state
return (
<>
<Card tone="muted" role="note" className={styles.hint}>
<Icon icon={Share} className={styles.icon} />
<p className={styles.message}>Tap Share, then Add to Home Screen to get notifications</p>
<IconButton label="Dismiss" onClick={() => setState(writeDismissed())}>
<Icon icon={X} />
</IconButton>
</Card>
{failure && (
<ErrorBanner onRetry={() => setState(failure.action === 'read' ? readDismissed() : writeDismissed())}>
{failureText[failure.action]}: {failure.message}
</ErrorBanner>
)}
</>
)
}
+22
View File
@@ -0,0 +1,22 @@
.pill {
position: fixed;
top: calc(var(--space-3) + env(safe-area-inset-top));
left: 50%;
z-index: 20;
transform: translateX(-50%);
display: inline-flex;
align-items: center;
gap: var(--space-2);
margin: 0;
padding: 6px 14px;
border-radius: var(--radius-pill);
background: var(--color-neutral-800);
color: var(--on-accent);
box-shadow: var(--shadow-md);
font-family: var(--font-body);
font-size: 13px;
font-weight: 700;
line-height: 1.2;
white-space: nowrap;
pointer-events: none;
}
+150
View File
@@ -0,0 +1,150 @@
import { act, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiProvider, createApiClient, createVerifiedSession, type ApiClient } from '../api/index.ts'
import { fakeLocation, jsonResponse, ME, stubFetch } from '../test/fetchStub.ts'
import { cacheFallbackHeader } from '../sw/routes.ts'
import { createNetworkStatus } from './networkStatus.ts'
import { OfflinePill } from './OfflinePill.tsx'
const copy = 'Offline — showing saved data'
let onLine: boolean
beforeEach(() => {
onLine = true
vi.spyOn(navigator, 'onLine', 'get').mockImplementation(() => onLine)
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
function goOffline() {
onLine = false
window.dispatchEvent(new Event('offline'))
}
function goOnline() {
onLine = true
window.dispatchEvent(new Event('online'))
}
function renderPill(): ApiClient {
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
render(
<ApiProvider client={api}>
<OfflinePill />
</ApiProvider>,
)
return api
}
describe('OfflinePill', () => {
it('is hidden while online', () => {
renderPill()
expect(screen.queryByRole('status')).toBeNull()
})
it('shows while the browser is offline when it renders', () => {
onLine = false
renderPill()
expect(screen.getByRole('status')).toHaveTextContent(copy)
})
it('appears on the offline event and disappears on the online event', () => {
renderPill()
act(goOffline)
expect(screen.getByRole('status')).toHaveTextContent(copy)
act(goOnline)
expect(screen.queryByRole('status')).toBeNull()
})
it('appears when a request fails with a network error', async () => {
const api = renderPill()
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new TypeError('Failed to fetch')))
await act(() => expect(api.apiFetch('/api/v1/plan')).rejects.toThrow(TypeError))
expect(screen.getByRole('status')).toHaveTextContent(copy)
act(goOnline)
expect(screen.queryByRole('status')).toBeNull()
})
it('disappears when a later request gets a response', async () => {
const api = renderPill()
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new TypeError('Failed to fetch')))
await act(() => expect(api.apiFetch('/api/v1/plan')).rejects.toThrow(TypeError))
expect(screen.getByRole('status')).toBeInTheDocument()
stubFetch(jsonResponse(200, {}))
await act(() => api.apiFetch('/api/v1/plan'))
expect(screen.queryByRole('status')).toBeNull()
})
it('shows while online when the service worker answers from its cache', async () => {
const api = renderPill()
const cached = jsonResponse(200, { id: '01J9ZR' })
cached.headers.set(cacheFallbackHeader, '1')
stubFetch(cached, jsonResponse(200, { id: '01J9ZR' }))
await act(() => api.apiFetch('/api/v1/recipes/01J9ZR'))
expect(navigator.onLine).toBe(true)
expect(screen.getByRole('status')).toHaveTextContent(copy)
// The server answers again.
await act(() => api.apiFetch('/api/v1/recipes/01J9ZR'))
expect(screen.queryByRole('status')).toBeNull()
})
it('ignores a request body that cannot be serialized', async () => {
const api = renderPill()
const fetchMock = stubFetch(jsonResponse(200, ME))
await act(() => api.loadMe())
const body: Record<string, unknown> = {}
body.self = body
await act(() =>
expect(api.apiFetch('/api/v1/plan', { method: 'PUT', body })).rejects.toThrow(
'PUT /api/v1/plan: request body is not serializable as JSON',
),
)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(screen.queryByRole('status')).toBeNull()
})
it('ignores a GET request with a body, which fetch would refuse to send', async () => {
const api = renderPill()
const fetchMock = stubFetch()
await act(() =>
expect(api.apiFetch('/api/v1/plan', { body: { week: 1 } })).rejects.toThrow(
'GET /api/v1/plan: a GET request cannot carry a body',
),
)
expect(fetchMock).not.toHaveBeenCalled()
expect(screen.queryByRole('status')).toBeNull()
})
it('ignores an aborted request', async () => {
const api = renderPill()
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new DOMException('aborted', 'AbortError')))
await act(() => expect(api.apiFetch('/api/v1/plan')).rejects.toThrow('aborted'))
expect(screen.queryByRole('status')).toBeNull()
})
it('removes its online and offline listeners on unmount', () => {
const add = vi.spyOn(window, 'addEventListener')
const remove = vi.spyOn(window, 'removeEventListener')
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
const { unmount } = render(
<ApiProvider client={api}>
<OfflinePill />
</ApiProvider>,
)
const added = add.mock.calls.filter(([type]) => type === 'online' || type === 'offline')
expect(added.map(([type]) => type).sort()).toEqual(['offline', 'online'])
unmount()
for (const [type, listener] of added) expect(remove).toHaveBeenCalledWith(type, listener)
})
})
+19
View File
@@ -0,0 +1,19 @@
import { useSyncExternalStore } from 'react'
import { WifiOff } from 'lucide-react'
import { useApi } from '../api/index.ts'
import { Icon } from '../ui/Icon.tsx'
import styles from './OfflinePill.module.css'
// OfflinePill tells the household that what they see came from the cache
// while the browser is offline or the server cannot be reached.
export function OfflinePill() {
const { network } = useApi()
const offline = useSyncExternalStore(network.subscribe, network.offline)
if (!offline) return null
return (
<p role="status" className={styles.pill}>
<Icon icon={WifiOff} />
Offline — showing saved data
</p>
)
}
+22
View File
@@ -0,0 +1,22 @@
.toast {
position: fixed;
left: 50%;
bottom: calc(110px + env(safe-area-inset-bottom));
z-index: 20;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: var(--space-3);
width: max-content;
max-width: calc(100vw - 2 * var(--space-4));
padding: var(--space-2) var(--space-2) var(--space-2) var(--space-4);
box-shadow: var(--shadow-lg);
}
.message {
margin: 0;
font-family: var(--font-body);
font-size: 15px;
font-weight: 600;
line-height: 1.35;
}
+165
View File
@@ -0,0 +1,165 @@
import { act, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { SKIP_WAITING, UpdatePrompt, type UpdateContainer } from './UpdatePrompt.tsx'
// FakeWorker is a ServiceWorker whose state the test moves along.
class FakeWorker extends EventTarget {
state: ServiceWorkerState = 'installing'
postMessage = vi.fn()
setState(state: ServiceWorkerState) {
this.state = state
this.dispatchEvent(new Event('statechange'))
}
}
class FakeRegistration extends EventTarget {
installing: FakeWorker | null = null
waiting: FakeWorker | null = null
// install starts a new worker, as the browser does on finding an update.
install(): FakeWorker {
const worker = new FakeWorker()
this.installing = worker
this.dispatchEvent(new Event('updatefound'))
return worker
}
// finishInstall moves the installing worker to waiting.
finishInstall(worker: FakeWorker) {
this.installing = null
this.waiting = worker
worker.setState('installed')
}
}
class FakeContainer extends EventTarget {
controller: object | null = {}
registration = new FakeRegistration()
ready = Promise.resolve(this.registration)
// takeOver makes the waiting worker the controller.
takeOver() {
const worker = this.registration.waiting
this.registration.waiting = null
this.controller = worker
worker?.setState('activated')
this.dispatchEvent(new Event('controllerchange'))
}
}
async function renderPrompt(container: FakeContainer | undefined) {
const reload = vi.fn()
const view = render(<UpdatePrompt container={container as unknown as UpdateContainer} reload={reload} />)
await act(async () => {
await container?.ready
})
return { reload, ...view }
}
const copy = 'New version ready · Reload'
describe('UpdatePrompt', () => {
it('shows nothing without a service worker', async () => {
await renderPrompt(undefined)
expect(screen.queryByRole('status')).toBeNull()
})
it('shows nothing while no worker is waiting', async () => {
const container = new FakeContainer()
await renderPrompt(container)
act(() => {
container.registration.install()
})
expect(screen.queryByRole('status')).toBeNull()
})
it('shows nothing for a waiting worker when the page has no controller', async () => {
const container = new FakeContainer()
container.controller = null
container.registration.waiting = new FakeWorker()
await renderPrompt(container)
expect(screen.queryByRole('status')).toBeNull()
})
it('shows the toast for a worker already waiting when the page loads', async () => {
const container = new FakeContainer()
container.registration.waiting = new FakeWorker()
await renderPrompt(container)
expect(screen.getByRole('status')).toHaveTextContent(copy)
})
it('shows the toast when an update finishes installing', async () => {
const container = new FakeContainer()
await renderPrompt(container)
act(() => container.registration.finishInstall(container.registration.install()))
expect(screen.getByRole('status')).toHaveTextContent(copy)
})
it('sends SKIP_WAITING on Reload and reloads once the new worker controls the page', async () => {
const container = new FakeContainer()
const { reload } = await renderPrompt(container)
const worker = container.registration.install()
act(() => container.registration.finishInstall(worker))
act(() => screen.getByRole('button', { name: 'Reload' }).click())
expect(worker.postMessage).toHaveBeenCalledExactlyOnceWith(SKIP_WAITING)
expect(screen.queryByRole('status')).toBeNull()
expect(reload).not.toHaveBeenCalled()
act(() => container.takeOver())
expect(reload).toHaveBeenCalledOnce()
// A later controller change (another tab's update) does not reload again.
act(() => container.dispatchEvent(new Event('controllerchange')))
expect(reload).toHaveBeenCalledOnce()
expect(screen.queryByRole('status')).toBeNull()
})
it('does not reappear for the worker the household chose to reload into', async () => {
const container = new FakeContainer()
container.registration.waiting = new FakeWorker()
await renderPrompt(container)
act(() => screen.getByRole('button', { name: 'Reload' }).click())
// The worker reports another state change before it takes over.
act(() => container.registration.waiting?.setState('installed'))
expect(screen.queryByRole('status')).toBeNull()
})
it('hides when dismissed until the next update is waiting', async () => {
const container = new FakeContainer()
const { reload } = await renderPrompt(container)
const first = container.registration.install()
act(() => container.registration.finishInstall(first))
act(() => screen.getByRole('button', { name: 'Dismiss' }).click())
expect(screen.queryByRole('status')).toBeNull()
expect(first.postMessage).not.toHaveBeenCalled()
act(() => first.setState('installed'))
expect(screen.queryByRole('status')).toBeNull()
act(() => container.registration.finishInstall(container.registration.install()))
expect(screen.getByRole('status')).toHaveTextContent(copy)
expect(reload).not.toHaveBeenCalled()
})
it('hides when another tab activates the waiting worker', async () => {
const container = new FakeContainer()
container.registration.waiting = new FakeWorker()
const { reload } = await renderPrompt(container)
act(() => container.takeOver())
expect(screen.queryByRole('status')).toBeNull()
expect(reload).not.toHaveBeenCalled()
})
it('removes its listeners on unmount', async () => {
const container = new FakeContainer()
const worker = new FakeWorker()
container.registration.waiting = worker
const { reload, unmount } = await renderPrompt(container)
const removeRegistration = vi.spyOn(container.registration, 'removeEventListener')
const removeWorker = vi.spyOn(worker, 'removeEventListener')
act(() => screen.getByRole('button', { name: 'Reload' }).click())
unmount()
expect(removeRegistration).toHaveBeenCalledWith('updatefound', expect.any(Function))
expect(removeWorker).toHaveBeenCalledWith('statechange', expect.any(Function))
container.takeOver()
expect(reload).not.toHaveBeenCalled()
})
})
+101
View File
@@ -0,0 +1,101 @@
import { useEffect, useRef, useState } from 'react'
import { X } from 'lucide-react'
import { Button } from '../ui/Button.tsx'
import { Card } from '../ui/Card.tsx'
import { Icon } from '../ui/Icon.tsx'
import { IconButton } from '../ui/IconButton.tsx'
import styles from './UpdatePrompt.module.css'
// UpdateContainer is the part of navigator.serviceWorker the prompt uses.
export type UpdateContainer = Pick<ServiceWorkerContainer, 'ready' | 'controller' | 'addEventListener' | 'removeEventListener'>
export type UpdatePromptProps = {
// navigator.serviceWorker, or undefined where the browser has none.
container: UpdateContainer | undefined
// Reloads the page once the new worker controls it.
reload: () => void
}
// SKIP_WAITING is the message src/sw.ts answers by activating the waiting
// worker.
export const SKIP_WAITING = { type: 'SKIP_WAITING' } as const
// UpdatePrompt offers to reload when a new service worker is installed and
// waiting to replace the one controlling the page. Reload asks the waiting
// worker to activate and reloads once it controls the page; dismissing hides
// the prompt until a different worker is waiting.
export function UpdatePrompt({ container, reload }: UpdatePromptProps) {
const [waiting, setWaiting] = useState<ServiceWorker | null>(null)
const [dismissed, setDismissed] = useState<ServiceWorker | null>(null)
const [accepted, setAccepted] = useState<ServiceWorker | null>(null)
const reloadListener = useRef<(() => void) | null>(null)
useEffect(() => {
if (container === undefined) return
const sw = container
let registration: ServiceWorkerRegistration | null = null
let unmounted = false
const watched = new Set<ServiceWorker>()
// A waiting worker only replaces something when the page has a
// controller; without one there is no controllerchange to reload on.
function check() {
if (registration === null) return
setWaiting(sw.controller === null ? null : registration.waiting)
}
function watch(worker: ServiceWorker | null) {
if (worker === null || watched.has(worker)) return
watched.add(worker)
worker.addEventListener('statechange', check)
}
function updateFound() {
watch(registration?.installing ?? null)
}
void sw.ready.then((ready) => {
if (unmounted) return
registration = ready
ready.addEventListener('updatefound', updateFound)
watch(ready.installing)
watch(ready.waiting)
check()
})
return () => {
unmounted = true
registration?.removeEventListener('updatefound', updateFound)
watched.forEach((worker) => worker.removeEventListener('statechange', check))
if (reloadListener.current !== null) {
sw.removeEventListener('controllerchange', reloadListener.current)
reloadListener.current = null
}
}
}, [container])
if (container === undefined || waiting === null || waiting === dismissed || waiting === accepted) return null
function update() {
if (container === undefined || waiting === null || reloadListener.current !== null) return
const listener = () => {
reloadListener.current = null
reload()
}
reloadListener.current = listener
container.addEventListener('controllerchange', listener, { once: true })
setAccepted(waiting)
waiting.postMessage(SKIP_WAITING)
}
return (
<Card role="status" className={styles.toast}>
<p className={styles.message}>
New version ready <span aria-hidden="true">·</span>
</p>
{/* The space keeps the copy "New version ready · Reload" in the text;
a flex container does not render it. */}{' '}
<Button onClick={update}>Reload</Button>
<IconButton label="Dismiss" onClick={() => setDismissed(waiting)}>
<Icon icon={X} />
</IconButton>
</Card>
)
}
+51
View File
@@ -0,0 +1,51 @@
// NetworkWindow is the part of window the network status reads: the browser's
// online flag and its online/offline events.
export type NetworkWindow = Pick<Window, 'navigator' | 'addEventListener' | 'removeEventListener'>
export type NetworkStatus = {
// offline reports whether the browser says it is offline or the last API
// request failed with a network error or was answered from the cache.
offline(): boolean
// subscribe is notified when offline may have changed. It listens for the
// window's online/offline events until the returned function is called.
subscribe(listener: () => void): () => void
// requestFailed records a fetch that rejected with a network error or that
// the service worker answered from its cache.
requestFailed(): void
// requestSucceeded records a fetch the server answered.
requestSucceeded(): void
}
// createNetworkStatus tracks whether MealQuest can reach the server. A failed
// request counts as offline until a later request gets a response or the
// browser reports that it is back online.
export function createNetworkStatus(win: NetworkWindow): NetworkStatus {
let failed = false
const listeners = new Set<() => void>()
function setFailed(value: boolean) {
if (failed === value) return
failed = value
listeners.forEach((listener) => listener())
}
return {
offline: () => !win.navigator.onLine || failed,
subscribe(listener) {
const online = () => {
failed = false
listener()
}
listeners.add(listener)
win.addEventListener('online', online)
win.addEventListener('offline', listener)
return () => {
listeners.delete(listener)
win.removeEventListener('online', online)
win.removeEventListener('offline', listener)
}
},
requestFailed: () => setFailed(true),
requestSucceeded: () => setFailed(false),
}
}