From 69842003c97c25639d9909b3f0068cf38b0eb582 Mon Sep 17 00:00:00 2001 From: Anton Tranelis Date: Sun, 12 Oct 2025 12:31:08 +0200 Subject: [PATCH] fix auto theme --- .../Components/AppShell/hooks/useTheme.tsx | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/lib/src/Components/AppShell/hooks/useTheme.tsx b/lib/src/Components/AppShell/hooks/useTheme.tsx index 367d8fd3..be24a6f5 100644 --- a/lib/src/Components/AppShell/hooks/useTheme.tsx +++ b/lib/src/Components/AppShell/hooks/useTheme.tsx @@ -1,12 +1,38 @@ import { useEffect } from 'react' +/** + * Apply a theme based on the saved preference, a provided default theme, or the user's system preference. + * Falls back to the system dark/light preference when no theme is provided. + */ export const useTheme = (defaultTheme = 'default') => { useEffect(() => { - const savedTheme = localStorage.getItem('theme') - const initialTheme = savedTheme ? (JSON.parse(savedTheme) as string) : defaultTheme - if (initialTheme !== 'default') { - document.documentElement.setAttribute('data-theme', defaultTheme) - localStorage.setItem('theme', JSON.stringify(initialTheme)) + const savedThemeRaw = localStorage.getItem('theme') + const savedTheme = savedThemeRaw ? (JSON.parse(savedThemeRaw) as string) : undefined + + const prefersDark = + typeof window !== 'undefined' && typeof window.matchMedia === 'function' + ? window.matchMedia('(prefers-color-scheme: dark)').matches + : false + + const fallbackTheme = + defaultTheme && defaultTheme !== 'default' + ? defaultTheme + : prefersDark + ? 'dark' + : 'light' + + const themeToApply = savedTheme ?? fallbackTheme + + if (themeToApply === 'default') { + document.documentElement.removeAttribute('data-theme') + localStorage.removeItem('theme') + return + } + + document.documentElement.setAttribute('data-theme', themeToApply) + + if (!savedTheme || savedTheme !== themeToApply) { + localStorage.setItem('theme', JSON.stringify(themeToApply)) } }, [defaultTheme]) }