wrolpi/app/src/contexts/PwaContext.js
Roland 20d2bb8717
Add PWA: installable app, offline calculators, read-only Inventory
Make the React app an installable PWA whose app shell, calculators
(incl. the One Time Pad), and Inventory work offline. Driving use case:
reference an inventory (e.g. Fasteners) from an iPhone with no connection.

Phase 1 — service worker (Workbox InjectManifest, production build only):
- service-worker.js: precache the shell (calculators work offline),
  NavigationRoute for deep links, NetworkFirst cache of GET /api/inventory
  and /api/inventory/catalog (wrolpi-inventory), NetworkOnly /api/status.
- serviceWorkerRegistration.js + registration in index.js.
- Add workbox-* runtime deps (pinned 6.5.4 to match CRA's bundled plugin).

Phase 2 — offline hardening + read-only Inventory:
- api.js maps offline fetch failures (TypeError / timeout / !navigator.onLine)
  to ApiDownError so the existing nav apiDown indicator lights up.
- toast.js wrapper swallows error toasts while offline; repoint the toast
  import in the 13 files that raise them (App.js container left as-is).
- PwaContext (usePwa() -> {offline, isStandalone}), provider mounted in
  App.js inside StatusProvider. Default offline:false so components render
  without the provider in tests.
- Inventory is read-only offline: InventoryRoute disables the edit buttons
  and shows a banner; InventoryTable hides the new-item row, checkboxes and
  delete, and disables click-to-edit. Values stay visible for reference.

Phase 3 — iOS Add-to-Home-Screen meta tags in public/index.html.

Verified end-to-end against the real API: SW caches the inventory, then with
the origin stopped the cached inventory still renders read-only (reactively
and on cold reload). All 676 Jest tests pass (incl. new InventoryTable
offline tests).

Media "Save for offline" + a Downloads list are intentionally deferred.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 15:21:25 -06:00

58 lines
2.4 KiB
JavaScript

import React, {useContext, useEffect, useMemo, useState} from "react";
import {StatusContext} from "./contexts";
// Cross-cutting PWA state, consumed anywhere via usePwa() instead of prop-drilling.
//
// offline - true when the browser is offline or the API is unreachable. Inventory (and other) reads are
// served from the service-worker cache, but writes can't reach the backend, so editing UI is
// disabled while this is true.
// isStandalone - true when launched as an installed PWA (Add to Home Screen / standalone display mode).
//
// The default value (offline: false) means components rendered outside a PwaProvider — e.g. in unit tests — behave
// as if online, so they need no provider wrapper.
export const PwaContext = React.createContext({
offline: false,
isStandalone: false,
});
const computeOffline = () =>
(typeof navigator !== 'undefined' && navigator.onLine === false) || window.apiDown === true;
const computeStandalone = () =>
(typeof window !== 'undefined') && (
(typeof window.matchMedia === 'function' && window.matchMedia('(display-mode: standalone)').matches) ||
window.navigator.standalone === true
);
export function PwaProvider({children}) {
// Consuming StatusContext makes this provider re-render on every status poll, so window.apiDown (set imperatively
// by useStatus) is picked up without a dedicated interval.
const {status} = useContext(StatusContext);
const [offline, setOffline] = useState(computeOffline);
const [isStandalone] = useState(computeStandalone);
// Instant updates when connectivity flips (the store-aisle case: network drops).
useEffect(() => {
const update = () => setOffline(computeOffline());
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
// Re-sync on each status poll to catch the network-up / API-down case.
useEffect(() => {
setOffline(computeOffline());
}, [status]);
const value = useMemo(() => ({offline, isStandalone}), [offline, isStandalone]);
return <PwaContext.Provider value={value}>{children}</PwaContext.Provider>;
}
export function usePwa() {
return useContext(PwaContext);
}