11import modeOptions from './modeOptions'
22
3- export function activateMode ( mode ) {
3+ function activateMode ( mode ) {
44 const rootElement = document . querySelector ( ':root' )
55 const options = modeOptions [ mode ]
66
@@ -9,23 +9,36 @@ export function activateMode (mode) {
99 }
1010}
1111
12+ // Dark and Light autoswitches
13+ const onDark = ( e ) => e . matches && activateMode ( 'dark' )
14+ const onLight = ( e ) => e . matches && activateMode ( 'light' )
15+
16+ const darkScheme = window . matchMedia ( '(prefers-color-scheme: dark)' )
17+ const lightScheme = window . matchMedia ( '(prefers-color-scheme: light)' )
18+
1219/**
1320 * Sets a color scheme for the website.
14- * If browser supports "prefers-color-scheme" it will respect the setting for light or dark mode
21+ * If browser supports "prefers-color-scheme", 'auto' mode will respect the setting for light or dark mode
1522 * otherwise it will set a dark theme during night time
1623 */
17- export default function setMode ( ) {
18- const isDarkMode = window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches
19- const isLightMode = window . matchMedia ( '(prefers-color-scheme: light)' ) . matches
20- const isNotSpecified = window . matchMedia ( '(prefers-color-scheme: no-preference)' ) . matches
21- const hasNoSupport = ! isDarkMode && ! isLightMode && ! isNotSpecified
24+ export default function setMode ( mode = 'auto' ) {
25+ if ( mode !== 'auto' ) {
26+ darkScheme . removeListener ( onDark )
27+ lightScheme . removeListener ( onLight )
28+ activateMode ( mode )
29+ return
30+ }
2231
23- window . matchMedia ( '(prefers-color-scheme: dark)' ) . addListener ( e => e . matches && activateMode ( 'dark' ) )
24- window . matchMedia ( '(prefers-color-scheme: light)' ) . addListener ( e => e . matches && activateMode ( 'light' ) )
32+ darkScheme . addListener ( onDark )
33+ lightScheme . addListener ( onLight )
34+
35+ const isDarkMode = darkScheme . matches
36+ const isLightMode = lightScheme . matches
2537
2638 if ( isDarkMode ) activateMode ( 'dark' )
2739 if ( isLightMode ) activateMode ( 'light' )
28- if ( isNotSpecified || hasNoSupport ) {
40+
41+ if ( ! isDarkMode && ! isLightMode ) {
2942 console . log ( 'You specified no preference for a color scheme or your browser does not support it. I schedule dark mode during night time.' )
3043 const now = new Date ( )
3144 const hour = now . getHours ( )
0 commit comments