MCPcopy
hub / github.com/primer/react / useSystemColorMode

Function useSystemColorMode

packages/react/src/ThemeProvider.tsx:158–197  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

156}
157
158function useSystemColorMode() {
159 const [systemColorMode, setSystemColorMode] = React.useState(getSystemColorMode)
160
161 React.useEffect(() => {
162 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
163 const media = window?.matchMedia?.('(prefers-color-scheme: dark)')
164
165 function matchesMediaToColorMode(matches: boolean) {
166 return matches ? 'night' : 'day'
167 }
168
169 function handleChange(event: MediaQueryListEvent) {
170 const isNight = event.matches
171 setSystemColorMode(matchesMediaToColorMode(isNight))
172 }
173
174 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
175 if (media) {
176 // just in case the preference changed before the event listener was attached
177 const isNight = media.matches
178 setSystemColorMode(matchesMediaToColorMode(isNight))
179 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
180 if (media.addEventListener !== undefined) {
181 media.addEventListener('change', handleChange)
182 return function cleanup() {
183 media.removeEventListener('change', handleChange)
184 }
185 }
186 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
187 else if (media.addListener !== undefined) {
188 media.addListener(handleChange)
189 return function cleanup() {
190 media.removeListener(handleChange)
191 }
192 }
193 }
194 }, [])
195
196 return systemColorMode
197}
198
199function getSystemColorMode(): ColorMode {
200 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition

Callers 1

ThemeProviderFunction · 0.85

Calls 1

matchesMediaToColorModeFunction · 0.85

Tested by

no test coverage detected