useAppStore.ts
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { create } from "zustand";
export type Theme = "light" | "dark" | "system";
export type Toast = { id: number; kind: "info" | "ok" | "warn" | "error"; text: string; detail?: string };
interface AppState {
theme: Theme;
setTheme: (t: Theme) => void;
toasts: Toast[];
toast: (kind: Toast["kind"], text: string, detail?: string) => void;
dismiss: (id: number) => void;
sidebarCollapsed: boolean;
toggleSidebar: () => void;
}
const THEME_KEY = "otlgt3.theme";
function readTheme(): Theme {
try {
const v = localStorage.getItem(THEME_KEY);
if (v === "light" || v === "dark" || v === "system") return v;
} catch { /* 隐私模式下 localStorage 会抛异常 */ }
return "system";
}
export function applyTheme(theme: Theme) {
const dark = theme === "dark"
|| (theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", dark);
document.documentElement.style.colorScheme = dark ? "dark" : "light";
}
let toastSeq = 0;
export const useAppStore = create<AppState>((set, get) => ({
theme: readTheme(),
setTheme: (t) => {
try { localStorage.setItem(THEME_KEY, t); } catch { /* ignore */ }
applyTheme(t);
set({ theme: t });
},
toasts: [],
toast: (kind, text, detail) => {
const id = ++toastSeq;
set({ toasts: [...get().toasts, { id, kind, text, detail }] });
setTimeout(() => get().dismiss(id), kind === "error" ? 8000 : 4000);
},
dismiss: (id) => set({ toasts: get().toasts.filter((t) => t.id !== id) }),
sidebarCollapsed: false,
toggleSidebar: () => set({ sidebarCollapsed: !get().sidebarCollapsed }),
}));
export const toast = (kind: Toast["kind"], text: string, detail?: string) =>
useAppStore.getState().toast(kind, text, detail);