Skip to content

Commit

Permalink
Sync color mode prior to subscribing in ThemeProvider (#4039)
Browse files Browse the repository at this point in the history
* sync theme once

* sync theme once
  • Loading branch information
mattcosta7 authored Dec 11, 2023
1 parent 6a5d977 commit 21e75dd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/fresh-hotels-begin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

Sync theme in effect
9 changes: 8 additions & 1 deletion src/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 21e75dd

Please sign in to comment.