navigator/src/lib/prefs.ts
2026-08-10 14:22:31 +00:00

55 lines
1.4 KiB
TypeScript

/**
* 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<Prefs>;
return {
system: isValidSystem(parsed.system) ? parsed.system : DEFAULTS.system
};
} catch {
return { ...DEFAULTS };
}
}
function createPrefs() {
const store = writable<Prefs>(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();