diff --git a/src/globals.css b/src/globals.css index 4161be393a..0022964a77 100644 --- a/src/globals.css +++ b/src/globals.css @@ -253,6 +253,8 @@ --color-code-operator: 219 178, 89; } + /* Also used for prefers-color-scheme: light */ + /* explicitly define it below if we want to change behavior */ body { @apply lightMode; } @@ -261,7 +263,7 @@ @apply darkMode; } - /* new body theme can be applied here + /* new body theme can be applied here */ @media (prefers-color-scheme: dark) { body { @@ -271,9 +273,7 @@ body.light { @apply lightMode; } - - new body theme added above should be applied here as well to cover specificity - } */ + } } #sentry-feedback { diff --git a/src/shared/ThemeContext/ThemeContext.test.tsx b/src/shared/ThemeContext/ThemeContext.test.tsx index b4137d28d5..176b3ff622 100644 --- a/src/shared/ThemeContext/ThemeContext.test.tsx +++ b/src/shared/ThemeContext/ThemeContext.test.tsx @@ -27,6 +27,7 @@ describe('Theme context', () => { function setup() { window.localStorage.__proto__.setItem = vi.fn() window.localStorage.__proto__.getItem = vi.fn() + window.matchMedia = vi.fn().mockResolvedValue({ matches: false }) const user = userEvent.setup() diff --git a/src/shared/ThemeContext/ThemeContext.tsx b/src/shared/ThemeContext/ThemeContext.tsx index 9f69d135dd..eb2d134876 100644 --- a/src/shared/ThemeContext/ThemeContext.tsx +++ b/src/shared/ThemeContext/ThemeContext.tsx @@ -29,8 +29,15 @@ interface ThemeContextProviderProps { export const ThemeContextProvider: FC = ({ children, }) => { - const currentTheme = (localStorage.getItem('theme') as Theme) || Theme.LIGHT - const [theme, setTheme] = useState(currentTheme) + const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches + + let systemTheme = Theme.LIGHT + if (prefersDark) { + systemTheme = Theme.DARK + } + + const currentTheme = localStorage.getItem('theme') as Theme + const [theme, setTheme] = useState(currentTheme ?? systemTheme) const initialRender = useRef(true) if (initialRender.current) { diff --git a/src/vitest.setup.ts b/src/vitest.setup.ts index e20d3ff5b7..761ec2ff06 100644 --- a/src/vitest.setup.ts +++ b/src/vitest.setup.ts @@ -28,6 +28,8 @@ vi.mock('@sentry/react', async () => { } }) +window.matchMedia = vi.fn().mockResolvedValue({ matches: false }) + beforeAll(() => { globalThis.jest = { ...globalThis.jest,