From 21e75dd858810df05c2002ed60d3e6c6ee320a47 Mon Sep 17 00:00:00 2001 From: Matthew Costabile Date: Mon, 11 Dec 2023 14:20:47 -0500 Subject: [PATCH] Sync color mode prior to subscribing in ThemeProvider (#4039) * sync theme once * sync theme once --- .changeset/fresh-hotels-begin.md | 5 +++++ src/ThemeProvider.tsx | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) 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 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)