assetflow/static/js/handleColorMode.js

31 lines
1002 B
JavaScript
Raw Permalink Normal View History

2023-05-20 22:04:46 +02:00
// Listen for changes in the prefers-color-scheme media query and update the "data-bs-theme" attribute on the <html> element.
// TODO: Probably migrate theme mode storage to api.
function updateColorMode() {
const currentTheme = localStorage.getItem('bs.theme') ?? 'auto';
const isDark = currentTheme === 'dark';
const isLight = currentTheme === 'light';
const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;
if (currentTheme === 'auto') {
if (prefersLight) {
document.documentElement.setAttribute('data-bs-theme', 'light');
} else {
document.documentElement.setAttribute('data-bs-theme', 'dark');
}
} else if (isDark) {
document.documentElement.setAttribute('data-bs-theme', 'dark');
} else if (isLight) {
document.documentElement.setAttribute('data-bs-theme', 'light');
}
}
(function () {
const mql = window.matchMedia('(prefers-color-scheme: dark)');
mql.addEventListener('change', () => {
updateColorMode();
});
updateColorMode();
})();