diff --git a/frontend/src/lib/state.svelte.ts b/frontend/src/lib/state.svelte.ts new file mode 100644 index 0000000..11e9593 --- /dev/null +++ b/frontend/src/lib/state.svelte.ts @@ -0,0 +1,55 @@ +import { api, type Household } from './api'; + +export const app = $state({ + household: null as Household | null, + toast: '', + route: location.hash || '#/', +}); + +let toastTimer: ReturnType | undefined; +export function toast(text: string) { + app.toast = text; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => (app.toast = ''), 4000); +} + +export async function loadHousehold() { + app.household = await api('/state'); + // The time zone defaults to this device's until someone sets it. + const here = Intl.DateTimeFormat().resolvedOptions().timeZone; + if (app.household.timezone === 'UTC' && here && here !== 'UTC') { + app.household = await api('/user', { method: 'PUT', json: { timezone: here } }); + } +} + +export function setHousehold(h: Household) { + app.household = h; +} + +export function go(hash: string) { + location.hash = hash; +} + +window.addEventListener('hashchange', () => { + app.route = location.hash || '#/'; + window.scrollTo(0, 0); +}); + +// Theme: 'system' follows the phone; 'light' or 'dark' is saved on this device. +export type Theme = 'system' | 'light' | 'dark'; +export function getTheme(): Theme { + try { + const t = localStorage.getItem('theme'); + return t === 'light' || t === 'dark' ? t : 'system'; + } catch { + return 'system'; + } +} +export function setTheme(t: Theme) { + try { + if (t === 'system') localStorage.removeItem('theme'); + else localStorage.setItem('theme', t); + } catch {} + if (t === 'system') delete document.documentElement.dataset.theme; + else document.documentElement.dataset.theme = t; +}