diff --git a/.changeset/fresh-hotels-begin.md b/.changeset/fresh-hotels-begin.md new file mode 100644 index 00000000000..70d2c545718 --- /dev/null +++ b/.changeset/fresh-hotels-begin.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +Sync theme in effect diff --git a/src/ThemeProvider.tsx b/src/ThemeProvider.tsx index eb6df2e7b8a..9b88a2c0cfb 100644 --- a/src/ThemeProvider.tsx +++ b/src/ThemeProvider.tsx @@ -160,13 +160,20 @@ function useSystemColorMode() { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const media = window?.matchMedia?.('(prefers-color-scheme: dark)') + function matchesMediaToColorMode(matches: boolean) { + return matches ? 'night' : 'day' + } + function handleChange(event: MediaQueryListEvent) { const isNight = event.matches - setSystemColorMode(isNight ? 'night' : 'day') + setSystemColorMode(matchesMediaToColorMode(isNight)) } // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (media) { + // just in case the preference changed before the event listener was attached + const isNight = media.matches + setSystemColorMode(matchesMediaToColorMode(isNight)) // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (media.addEventListener !== undefined) { media.addEventListener('change', handleChange)