Add app state, routing and theme switching
This commit is contained in:
1 parent
886a4d8a61
commit
bb032b9512
1 file changed
+55
@@ -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<typeof setTimeout> | undefined;
|
||||||
|
export function toast(text: string) {
|
||||||
|
app.toast = text;
|
||||||
|
clearTimeout(toastTimer);
|
||||||
|
toastTimer = setTimeout(() => (app.toast = ''), 4000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadHousehold() {
|
||||||
|
app.household = await api<Household>('/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<Household>('/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;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user