94 lines
2.4 KiB
TypeScript
94 lines
2.4 KiB
TypeScript
/**
|
|
* shared/composables/useTheme.ts
|
|
* 主题 preference 与 dark/light 切换(全局单例)。
|
|
*/
|
|
import { computed, ref } from 'vue';
|
|
|
|
export type ThemePreference = 'light' | 'dark' | 'system';
|
|
export type AppliedTheme = 'light' | 'dark';
|
|
|
|
const THEME_KEY = 'hxops_theme_preference';
|
|
const validThemePrefs: ThemePreference[] = ['light', 'dark', 'system'];
|
|
|
|
const themePreference = ref<ThemePreference>('system');
|
|
const systemPrefersDark = ref(false);
|
|
|
|
let initialized = false;
|
|
let mediaListenerCleanup: (() => void) | null = null;
|
|
|
|
const appliedTheme = computed<AppliedTheme>(() => {
|
|
if (themePreference.value === 'system') {
|
|
return systemPrefersDark.value ? 'dark' : 'light';
|
|
}
|
|
return themePreference.value;
|
|
});
|
|
|
|
const applyTheme = () => {
|
|
const root = document.documentElement;
|
|
const isDark = appliedTheme.value === 'dark';
|
|
root.classList.toggle('dark', isDark);
|
|
root.setAttribute('data-theme', appliedTheme.value);
|
|
};
|
|
|
|
const parseTheme = (value: string | null | undefined): ThemePreference | null => {
|
|
if (!value) return null;
|
|
return validThemePrefs.includes(value as ThemePreference) ? (value as ThemePreference) : null;
|
|
};
|
|
|
|
const setThemePreference = (value: ThemePreference, persist = true) => {
|
|
themePreference.value = value;
|
|
if (persist) {
|
|
localStorage.setItem(THEME_KEY, value);
|
|
}
|
|
applyTheme();
|
|
};
|
|
|
|
const toggleLightDark = () => {
|
|
setThemePreference(appliedTheme.value === 'dark' ? 'light' : 'dark');
|
|
};
|
|
|
|
const initTheme = () => {
|
|
if (initialized) {
|
|
applyTheme();
|
|
return;
|
|
}
|
|
|
|
initialized = true;
|
|
|
|
const media = window.matchMedia('(prefers-color-scheme: dark)');
|
|
systemPrefersDark.value = media.matches;
|
|
|
|
const onMediaChange = (event: MediaQueryListEvent) => {
|
|
systemPrefersDark.value = event.matches;
|
|
if (themePreference.value === 'system') {
|
|
applyTheme();
|
|
}
|
|
};
|
|
|
|
media.addEventListener('change', onMediaChange);
|
|
mediaListenerCleanup = () => media.removeEventListener('change', onMediaChange);
|
|
|
|
const stored = parseTheme(localStorage.getItem(THEME_KEY));
|
|
if (stored) {
|
|
themePreference.value = stored;
|
|
}
|
|
applyTheme();
|
|
};
|
|
|
|
const cleanupTheme = () => {
|
|
mediaListenerCleanup?.();
|
|
mediaListenerCleanup = null;
|
|
initialized = false;
|
|
};
|
|
|
|
export function useTheme() {
|
|
return {
|
|
themePreference,
|
|
appliedTheme,
|
|
initTheme,
|
|
cleanupTheme,
|
|
setThemePreference,
|
|
toggleLightDark,
|
|
};
|
|
}
|