Files
HealthLog/src/components/providers.tsx
T
Marc-André Bombeck 34a8f081ef feat(app): self-heal the stale-shell post-deploy paper-cut
The v1.4.38.3 `AppError` boundary reloads once when a stale shell
trips `ChunkLoadError`, but the reload only fires AFTER the user
hits a navigation that lazy-loads a missing chunk. Users sitting on
the dashboard or insights overview ride out the staleness until
their next click; some never click and the cached shell silently
drifts further out of date with every deploy.

Three layered fixes so the running app heals itself instead:

- `public/sw.js` now keys both `STATIC_CACHE` and `PAGE_CACHE` to
  the app release tag (`v1.4.38.4`). The `activate` step already
  evicts any cache name outside the current pair, so bumping the
  string at release time guarantees the precached root HTML and the
  precached `/_next/static/*` chunks from the previous deploy are
  dropped on the next SW install.
- `next.config.ts` injects `NEXT_PUBLIC_APP_VERSION` from
  `package.json` into the client bundle so the running shell knows
  which release it was built against.
- New `<VersionPoller>` client component mounts inside `<Providers>`
  and polls `/api/version` every 60 s. If the live version moves
  ahead of the shell-baked version it unregisters every active SW,
  wipes CacheStorage, and `window.location.reload()`s.
  `sessionStorage` gates the reload to once per session so a
  mid-deploy webhook race that briefly returns a stale image cannot
  loop the page.
2026-05-18 05:49:24 +02:00

141 lines
4.1 KiB
TypeScript

"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import { I18nProvider } from "@/lib/i18n/context";
import type { Locale } from "@/lib/i18n/config";
import { Toaster } from "@/components/ui/sonner";
import { AppSettingsProvider } from "@/components/app-settings-provider";
import { VersionPoller } from "@/components/version-poller";
// ── Theme Context ────────────────────────────────────
type Theme = "dark" | "light" | "system";
interface ThemeContextValue {
theme: Theme;
resolvedTheme: "dark" | "light";
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextValue>({
theme: "system",
resolvedTheme: "dark",
setTheme: () => {},
});
export function useTheme() {
return useContext(ThemeContext);
}
function getSystemTheme(): "dark" | "light" {
if (typeof window === "undefined") return "dark";
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function applyTheme(resolved: "dark" | "light") {
document.documentElement.classList.remove("dark", "light");
document.documentElement.classList.add(resolved);
}
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(() => {
if (typeof window === "undefined") return "system";
const saved = localStorage.getItem("healthlog-theme") as Theme | null;
return saved === "light" || saved === "dark" ? saved : "system";
});
const [resolvedTheme, setResolvedTheme] = useState<"dark" | "light">(() => {
if (typeof window === "undefined") return "dark";
const saved = localStorage.getItem("healthlog-theme") as Theme | null;
const t = saved === "light" || saved === "dark" ? saved : "system";
return t === "system" ? getSystemTheme() : t;
});
// Apply theme on mount (inline script handles FOUC, this ensures classes are in sync)
useEffect(() => {
applyTheme(resolvedTheme);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Listen for OS preference changes when in system mode
useEffect(() => {
if (theme !== "system") return;
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const handler = (e: MediaQueryListEvent) => {
const resolved = e.matches ? "dark" : "light";
setResolvedTheme(resolved);
applyTheme(resolved);
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [theme]);
const setTheme = useCallback((next: Theme) => {
setThemeState(next);
if (next === "system") {
localStorage.removeItem("healthlog-theme");
const resolved = getSystemTheme();
setResolvedTheme(resolved);
applyTheme(resolved);
} else {
localStorage.setItem("healthlog-theme", next);
setResolvedTheme(next);
applyTheme(next);
}
}, []);
return (
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// ── Root Providers ───────────────────────────────────
export function Providers({
children,
initialLocale,
}: {
children: ReactNode;
initialLocale?: Locale;
}) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
refetchOnWindowFocus: false,
retry: 1,
},
},
}),
);
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<I18nProvider initialLocale={initialLocale}>
<AppSettingsProvider>
{children}
<Toaster position="bottom-right" richColors />
<VersionPoller />
</AppSettingsProvider>
</I18nProvider>
</ThemeProvider>
</QueryClientProvider>
);
}