feat(theme): listen for system theme changes [R8S-1190] (#3265)

This commit is contained in:
nickl-portainer
2026-07-24 15:17:47 +12:00
committed by GitHub
parent 841442c19c
commit b4d30a168b
+22 -5
View File
@@ -1,14 +1,31 @@
import { ThemeColor } from '@/portainer/users/types';
let removeAutoThemeListener: (() => void) | null = null;
export function applyTheme(color: ThemeColor) {
removeAutoThemeListener?.();
removeAutoThemeListener = null;
if (color === 'auto' || !color) {
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (isDark) {
document.documentElement.setAttribute('theme', 'dark');
} else {
document.documentElement.removeAttribute('theme');
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
function handleChange() {
applyAutoTheme(mediaQuery);
}
applyAutoTheme(mediaQuery);
mediaQuery.addEventListener('change', handleChange);
removeAutoThemeListener = () =>
mediaQuery.removeEventListener('change', handleChange);
} else {
document.documentElement.setAttribute('theme', color);
}
}
function applyAutoTheme(mediaQuery: MediaQueryList) {
if (mediaQuery.matches) {
document.documentElement.setAttribute('theme', 'dark');
} else {
document.documentElement.removeAttribute('theme');
}
}