44 lines
976 B
TypeScript
44 lines
976 B
TypeScript
|
|
import { create } from 'zustand';
|
||
|
|
|
||
|
|
export type Theme = 'dark' | 'light';
|
||
|
|
|
||
|
|
interface UiState {
|
||
|
|
theme: Theme;
|
||
|
|
setTheme: (theme: Theme) => void;
|
||
|
|
toggleTheme: () => void;
|
||
|
|
}
|
||
|
|
|
||
|
|
const STORAGE_KEY = 'glchat.theme';
|
||
|
|
|
||
|
|
function initialTheme(): Theme {
|
||
|
|
if (typeof window === 'undefined') {
|
||
|
|
return 'dark';
|
||
|
|
}
|
||
|
|
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||
|
|
if (stored === 'light' || stored === 'dark') {
|
||
|
|
return stored;
|
||
|
|
}
|
||
|
|
return 'dark';
|
||
|
|
}
|
||
|
|
|
||
|
|
export function applyTheme(theme: Theme): void {
|
||
|
|
if (typeof document === 'undefined') {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
document.documentElement.dataset['theme'] = theme;
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useUiStore = create<UiState>((set, get) => ({
|
||
|
|
theme: initialTheme(),
|
||
|
|
setTheme: (theme) => {
|
||
|
|
if (typeof window !== 'undefined') {
|
||
|
|
window.localStorage.setItem(STORAGE_KEY, theme);
|
||
|
|
}
|
||
|
|
applyTheme(theme);
|
||
|
|
set({ theme });
|
||
|
|
},
|
||
|
|
toggleTheme: () => {
|
||
|
|
get().setTheme(get().theme === 'dark' ? 'light' : 'dark');
|
||
|
|
},
|
||
|
|
}));
|