Files
HealthLog/src/lib/timezone-mirror.ts
T
Marc-André Bombeck 9d2fd1db14 fix(tz): one default zone, and the user's own calendar where Berlin was hard-coded
The status assessments folded their recent days, weeks, months and years on
Berlin days whatever the user's zone, the mood and cycle crosstabs keyed
their metric days in Berlin, the resting-pulse proxy defaulted to Berlin
days, the briefing's opener rotated at Berlin midnight, and every
assessment prompt labelled today's date as Berlin's. They now use the
user's zone. Rollup months and years are labelled by their UTC start,
which is how they are cut; read in a zone west of UTC the label named the
month before.

"Europe/Berlin" was written out in some eighty places. DEFAULT_TIMEZONE in
lib/tz/format is now the one definition: the second copy in mood/date-key,
DISPLAY_TIMEZONE, the Berlin-only day key helpers and the per-route copies
are gone. An in-repo lint rule rejects the literal outside lib/tz and
tests; four areas another change owns are listed as pending.
2026-09-26 16:23:14 +02:00

85 lines
3.4 KiB
TypeScript

/**
* Client-side mirror of the per-user display timezone.
*
* The server-authoritative value lives on the user row (`users.timezone`,
* surfaced by `/api/auth/me` and editable via `PUT /api/auth/me/timezone`).
* The mirror follows the `time-format.ts` / `date-format.ts` pattern exactly:
* `fetchMe` writes the resolved value into localStorage so that
*
* 1. `useFormatters()` can read it through `useSyncExternalStore` without
* requiring a QueryClient in the tree, and
* 2. the legacy helpers in `src/lib/format.ts` (plain functions, no React
* context) render the same zone as hook-based call sites.
*
* Fallback chain: valid mirrored profile zone → `DEFAULT_TIMEZONE`
* (Europe/Berlin) inside `makeFormatters`. Deliberately NO browser-timezone
* rung — every server-rendered artifact (doctor-report PDF, exports,
* briefing) resolves profile → Berlin, and a browser rung would let the same
* timestamp render differently on screen vs in the PDF for exactly the
* accounts whose profile zone is stale.
*
* Validity is guarded on BOTH sides: `storeTimezone` refuses to persist a
* non-IANA value (clears the mirror instead, so a poison `/me` payload can
* never wedge a broken zone), and `readStoredTimezone` re-validates so a
* stale mirror written by a pre-validation build reads as absent rather
* than reaching `Intl.DateTimeFormat` (which would throw `RangeError`).
*
* SSR always resolves "" (`window` is undefined) → Berlin fallback; the same
* caveat as the sibling mirrors applies — call sites render their formatted
* strings post-fetch, so there is no hydration-mismatch path today.
*/
import { isValidTimezone } from "./tz/format";
const STORAGE_KEY = "healthlog-timezone";
const CHANGE_EVENT = "healthlog:timezone-change";
/**
* Best-effort read of the mirrored zone. "" on SSR / no mirror / invalid
* stored value — callers treat "" as "fall back to `DEFAULT_TIMEZONE`"
* (which `makeFormatters` does on its own for an empty `userTz`).
*/
export function readStoredTimezone(): string {
if (typeof window === "undefined") return "";
try {
const stored = window.localStorage?.getItem(STORAGE_KEY);
return stored && isValidTimezone(stored) ? stored : "";
} catch {
return "";
}
}
/**
* Persist the mirror and notify same-tab subscribers. Cross-tab updates ride
* the browser's native `storage` event. An invalid or empty value CLEARS the
* mirror (fail toward the deterministic Berlin fallback) rather than storing
* a zone `Intl` would throw on.
*/
export function storeTimezone(value: string): void {
if (typeof window === "undefined") return;
const next = value && isValidTimezone(value) ? value : null;
try {
const previous = window.localStorage?.getItem(STORAGE_KEY) ?? null;
if (previous === next) return;
if (next === null) {
window.localStorage?.removeItem(STORAGE_KEY);
} else {
window.localStorage?.setItem(STORAGE_KEY, next);
}
} catch {
return;
}
window.dispatchEvent(new Event(CHANGE_EVENT));
}
/** `useSyncExternalStore`-shaped subscription for the mirror. */
export function subscribeTimezone(onChange: () => void): () => void {
if (typeof window === "undefined") return () => {};
window.addEventListener(CHANGE_EVENT, onChange);
window.addEventListener("storage", onChange);
return () => {
window.removeEventListener(CHANGE_EVENT, onChange);
window.removeEventListener("storage", onChange);
};
}