From 9bfa1b17a10f1042e20f4befc90e4a31bf6683ed Mon Sep 17 00:00:00 2001 From: Matthew Costabile Date: Sat, 9 Dec 2023 13:51:22 +0000 Subject: [PATCH 1/2] sync theme once --- src/ThemeProvider.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ThemeProvider.tsx b/src/ThemeProvider.tsx index eb6df2e7b8a..0f4f335eeb4 100644 --- a/src/ThemeProvider.tsx +++ b/src/ThemeProvider.tsx @@ -167,6 +167,8 @@ function useSystemColorMode() { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (media) { + // just in case the preference changed before the event listener was attached + setSystemColorMode(media.matches ? 'night' : 'day') // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (media.addEventListener !== undefined) { media.addEventListener('change', handleChange) From 4b33f0f7a759504bb3f34df15ca2a8af1be27403 Mon Sep 17 00:00:00 2001 From: Matthew Costabile Date: Sat, 9 Dec 2023 14:02:08 +0000 Subject: [PATCH 2/2] sync theme once --- .changeset/fresh-hotels-begin.md | 5 +++++ src/ThemeProvider.tsx | 9 +++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 .changeset/fresh-hotels-begin.md 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 0f4f335eeb4..9b88a2c0cfb 100644 --- a/src/ThemeProvider.tsx +++ b/src/ThemeProvider.tsx @@ -160,15 +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 - setSystemColorMode(media.matches ? 'night' : 'day') + const isNight = media.matches + setSystemColorMode(matchesMediaToColorMode(isNight)) // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (media.addEventListener !== undefined) { media.addEventListener('change', handleChange)