44 lines
996 B
TypeScript
44 lines
996 B
TypeScript
import { create } from 'zustand';
|
|
|
|
export type Theme = 'dark' | 'light';
|
|
|
|
const STORAGE_KEY = 'fitos-theme';
|
|
|
|
function currentTheme(): Theme {
|
|
try {
|
|
const saved = localStorage.getItem(STORAGE_KEY);
|
|
if (saved === 'light' || saved === 'dark') return saved;
|
|
} catch {
|
|
// ignore
|
|
}
|
|
return 'dark';
|
|
}
|
|
|
|
function apply(theme: Theme) {
|
|
document.documentElement.classList.toggle('light', theme === 'light');
|
|
const meta = document.querySelector('meta[name="theme-color"]');
|
|
if (meta) meta.setAttribute('content', theme === 'light' ? '#f7f4f0' : '#141210');
|
|
}
|
|
|
|
interface ThemeState {
|
|
theme: Theme;
|
|
toggle: () => void;
|
|
}
|
|
|
|
const initial = currentTheme();
|
|
apply(initial);
|
|
|
|
export const useTheme = create<ThemeState>((set, get) => ({
|
|
theme: initial,
|
|
toggle: () => {
|
|
const next: Theme = get().theme === 'dark' ? 'light' : 'dark';
|
|
try {
|
|
localStorage.setItem(STORAGE_KEY, next);
|
|
} catch {
|
|
// ignore
|
|
}
|
|
apply(next);
|
|
set({ theme: next });
|
|
},
|
|
}));
|