fix: add theme toggle to desktop header and sync theme across components

Add sun/moon toggle button to the desktop navigation bar so theme
switching is available in web version. Sync theme state across multiple
useTheme() instances via custom DOM event to avoid requiring page reload.
This commit is contained in:
c0mrade
2026-02-04 12:31:32 +03:00
parent c1dc019c8b
commit bf00d37b4a
2 changed files with 70 additions and 1 deletions

View File

@@ -42,8 +42,9 @@ function getCachedEnabledThemes(): EnabledThemes {
return DEFAULT_ENABLED_THEMES;
}
// Custom event for same-tab updates
// Custom events for same-tab updates
const ENABLED_THEMES_CHANGED_EVENT = 'enabledThemesChanged';
const THEME_CHANGED_EVENT = 'themeChanged';
// Update cache (called from admin settings)
export function updateEnabledThemesCache(themes: EnabledThemes) {
@@ -161,8 +162,21 @@ export function useTheme() {
}
localStorage.setItem(THEME_KEY, theme);
// Notify other useTheme() instances in the same tab
window.dispatchEvent(new CustomEvent(THEME_CHANGED_EVENT, { detail: theme }));
}, [theme, enabledThemes]);
// Listen for same-tab theme changes (from other useTheme() instances)
useEffect(() => {
const handleThemeChange = (e: CustomEvent<Theme>) => {
setThemeState(e.detail);
};
window.addEventListener(THEME_CHANGED_EVENT, handleThemeChange as EventListener);
return () =>
window.removeEventListener(THEME_CHANGED_EVENT, handleThemeChange as EventListener);
}, []);
// Listen for system theme changes
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: light)');