// Preferences: what this browser remembers about how its player likes to // play. The kit's own settings are motion and whether a move is confirmed // before it is sent; a game declares more in GameSpec.preferences, and the // panel renders every declaration. Nothing here leaves the browser. import { game } from '$lib/game'; export interface Preference { key: string; label: string; /** A toggle holds a boolean; a choice holds one of its choices' values. */ kind: 'toggle' | 'choice'; choices?: { value: string; label: string }[]; default: boolean | string; note?: string; } /** The settings every game in the kit shares. */ export const KIT_PREFERENCES: Preference[] = [ { key: 'motion', label: 'Motion', kind: 'choice', choices: [{ value: 'full', label: 'pieces move and fade' }, { value: 'reduced', label: 'changes appear at once' }], default: 'full' }, { key: 'confirmMoves', label: 'Confirm a move before it is sent', kind: 'toggle', default: false } ]; /** Every table option is also a preference: the choice a new table starts with. The hall reads and writes the same keys. */ const TABLE_DEFAULTS: Preference[] = (game.options ?? []).map((o) => ({ key: `table.${o.key}`, label: `${o.label}, for a new table`, kind: 'choice', choices: o.choices.map((c) => ({ value: c.value, label: c.label })), default: o.default })); export const PREFERENCES: Preference[] = [...KIT_PREFERENCES, ...TABLE_DEFAULTS, ...(game.preferences ?? [])]; const KEY = 'hnefatafl:prefs'; function defaults(): Record { return Object.fromEntries(PREFERENCES.map((p) => [p.key, p.default])); } function load(): Record { const base = defaults(); try { const saved = JSON.parse(localStorage.getItem(KEY) ?? '{}') as Record; for (const p of PREFERENCES) { const v = saved[p.key]; if (p.kind === 'toggle' && typeof v === 'boolean') base[p.key] = v; if (p.kind === 'choice' && typeof v === 'string' && p.choices?.some((c) => c.value === v)) base[p.key] = v; } } catch { // Without storage the defaults apply for this visit. } return base; } /** The live preferences; read them where they matter, set them through setPref. */ export const prefs = $state>(typeof localStorage === 'undefined' ? defaults() : load()); export function setPref(key: string, value: boolean | string): void { prefs[key] = value; try { localStorage.setItem(KEY, JSON.stringify(prefs)); } catch { // The change still applies for this visit. } } /** The reduced-motion preference, or the system's, whichever asks for calm. */ export function reducedMotion(): boolean { if (prefs.motion === 'reduced') return true; return typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches; }