SPB Git

Repository Public

store.ts 2.5 KB 65 lines typescript

1"use client";2/**3 * Browser-side holder of the anonymous local state (localStorage, key "atlas.v1"). No cookie, no network.4 * Components subscribe with `useAtlas`; every change goes through a pure transition of the learning engine.5 */6import { useSyncExternalStore } from "react";7import { LocalState, STORAGE_KEY, emptyState } from "@/modules/learning-engine/state";89const EMPTY = emptyState(new Date(0));10let cache: LocalState | null = null;11let available: boolean | null = null;12const listeners = new Set<() => void>();1314function read(): LocalState {15  try {16    const raw = window.localStorage.getItem(STORAGE_KEY);17    available = true;18    if (!raw) return EMPTY;19    const parsed = LocalState.safeParse(JSON.parse(raw));20    return parsed.success ? parsed.data : EMPTY;21  } catch { available = false; return EMPTY; }22}2324function emit() { for (const l of listeners) l(); }2526export function getState(): LocalState { return (cache ??= read()); }2728/** Applies a transition and persists it. Returns false when the browser refuses to store (private mode, quota). */29export function update(fn: (s: LocalState) => LocalState): boolean {30  const next = fn(getState());31  cache = next;32  let ok = true;33  try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); available = true; } catch { ok = false; available = false; }34  emit();35  return ok;36}3738/** Erases everything this site stored in the browser. */39export function clearAll(): void {40  try {41    for (const k of Object.keys(window.localStorage)) if (k === STORAGE_KEY || k.startsWith("atlas.")) window.localStorage.removeItem(k);42  } catch { /* nothing stored, nothing to clear */ }43  cache = EMPTY;44  emit();45}4647export const storageAvailable = () => { if (available === null) read(); return available === true; };4849function subscribe(listener: () => void) {50  listeners.add(listener);51  const onStorage = (e: StorageEvent) => { if (e.key === null || e.key === STORAGE_KEY) { cache = read(); listener(); } };52  window.addEventListener("storage", onStorage);53  return () => { listeners.delete(listener); window.removeEventListener("storage", onStorage); };54}5556/** Local state, or the empty state during server rendering and hydration (so markup always matches). */57export function useAtlas(): LocalState {58  return useSyncExternalStore(subscribe, getState, () => EMPTY);59}6061/** True once the component runs in the browser after hydration. */62export function useHydrated(): boolean {63  return useSyncExternalStore(() => () => {}, () => true, () => false);64}65
Files main
Menu

Theme