/** * prefs.ts — shared, persisted user preferences (Svelte writable store). * ---------------------------------------------------------------------- * Currently stores the unit system (Metric/Imperial) for distance display. * Values are persisted to localStorage so they survive reloads. * * Usage in runes mode: * import { prefs } from '$lib/prefs'; * $prefs.system // read * $prefs.system = 'imperial' // write (auto-persists) */ import { writable } from 'svelte/store'; export type UnitSystem = 'metric' | 'imperial'; export interface Prefs { system: UnitSystem; } const KEY = 'navigator.prefs.v1'; const DEFAULTS: Prefs = { system: 'metric' }; function isValidSystem(v: unknown): v is UnitSystem { return v === 'metric' || v === 'imperial'; } function load(): Prefs { try { const raw = localStorage.getItem(KEY); if (!raw) return { ...DEFAULTS }; const parsed = JSON.parse(raw) as Partial; return { system: isValidSystem(parsed.system) ? parsed.system : DEFAULTS.system }; } catch { return { ...DEFAULTS }; } } function createPrefs() { const store = writable(load()); // Persist on every change. store.subscribe((p) => { try { localStorage.setItem(KEY, JSON.stringify(p)); } catch { /* storage unavailable (private mode, etc.) — ignore */ } }); return store; } export const prefs = createPrefs();