@@ -0,0 +1,42 @@
|
||||
function resolveTheme(root) {
|
||||
const preference = root.dataset.theme || 'auto';
|
||||
if (preference === 'light' || preference === 'dark') {
|
||||
return preference;
|
||||
}
|
||||
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
|
||||
}
|
||||
|
||||
function applyThemeState(root) {
|
||||
const resolved = resolveTheme(root);
|
||||
root.dataset.themeResolved = resolved;
|
||||
|
||||
const themeMeta = document.querySelector('meta[name="theme-color"]');
|
||||
if (themeMeta) {
|
||||
const background = getComputedStyle(root).getPropertyValue('--color-bg').trim();
|
||||
if (background) {
|
||||
themeMeta.setAttribute('content', background);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function initTheme() {
|
||||
const root = document.documentElement;
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
|
||||
applyThemeState(root);
|
||||
|
||||
const media = window.matchMedia('(prefers-color-scheme: light)');
|
||||
const handleChange = () => {
|
||||
if ((root.dataset.theme || 'auto') === 'auto') {
|
||||
applyThemeState(root);
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof media.addEventListener === 'function') {
|
||||
media.addEventListener('change', handleChange);
|
||||
} else if (typeof media.addListener === 'function') {
|
||||
media.addListener(handleChange);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user