2023-11-02 08:06:33 -07:00
|
|
|
import type { AppliedThemeOption, ThemeOption } from '@/Interface';
|
2023-11-07 01:06:08 -08:00
|
|
|
import { useStorage } from '@/composables/useStorage';
|
2023-11-02 08:06:33 -07:00
|
|
|
import { LOCAL_STORAGE_THEME } from '@/constants';
|
|
|
|
|
2023-11-07 01:06:08 -08:00
|
|
|
const themeRef = useStorage(LOCAL_STORAGE_THEME);
|
|
|
|
|
2023-11-02 08:06:33 -07:00
|
|
|
export function addThemeToBody(theme: AppliedThemeOption) {
|
|
|
|
window.document.body.setAttribute('data-theme', theme);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function isValidTheme(theme: string | null): theme is AppliedThemeOption {
|
|
|
|
return !!theme && ['light', 'dark'].includes(theme);
|
|
|
|
}
|
|
|
|
|
|
|
|
// query param allows overriding theme for demo view in preview iframe without flickering
|
|
|
|
export function getThemeOverride() {
|
2023-11-07 01:06:08 -08:00
|
|
|
return getQueryParam('theme') || themeRef.value;
|
2023-11-02 08:06:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
function getQueryParam(paramName: string): string | null {
|
|
|
|
return new URLSearchParams(window.location.search).get(paramName);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function updateTheme(theme: ThemeOption) {
|
|
|
|
if (theme === 'system') {
|
|
|
|
window.document.body.removeAttribute('data-theme');
|
2023-11-07 01:06:08 -08:00
|
|
|
themeRef.value = null;
|
2023-11-02 08:06:33 -07:00
|
|
|
} else {
|
|
|
|
addThemeToBody(theme);
|
2023-11-07 01:06:08 -08:00
|
|
|
themeRef.value = theme;
|
2023-11-02 08:06:33 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getPreferredTheme(): AppliedThemeOption {
|
|
|
|
const isDarkMode =
|
|
|
|
!!window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)')?.matches;
|
|
|
|
|
|
|
|
return isDarkMode ? 'dark' : 'light';
|
|
|
|
}
|