-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
35 lines (32 loc) · 1.24 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
module.exports = ({ onChange = () => {} }) => {
const themes = Object.freeze({
DARK: 'dark',
LIGHT: 'light',
NO_PREF: 'no-preference',
NO_SUPP: 'no-support'
});
const darkQuery = window.matchMedia(`(prefers-color-scheme: ${themes.DARK})`);
const lightQuery = window.matchMedia(`(prefers-color-scheme: ${themes.LIGHT})`);
const noPrefQuery = window.matchMedia(`(prefers-color-scheme: ${themes.NO_PREF})`);
const isSupported = darkQuery.matches || lightQuery.matches || noPrefQuery.matches;
const queryListener = (q, theme) => q.matches && onChange(theme, themes);
const darkQueryListener = q => queryListener(q, themes.DARK);
const lightQueryListener = q => queryListener(q, themes.LIGHT);
if (isSupported) {
if (darkQuery.matches) onChange(themes.DARK, themes);
if (lightQuery.matches) onChange(themes.LIGHT, themes);
if (noPrefQuery.matches) onChange(themes.NO_PREF, themes);
darkQuery.addListener(darkQueryListener);
lightQuery.addListener(lightQueryListener);
} else {
onChange(themes.NO_SUPP, themes);
}
return {
removeListeners: () => {
if (isSupported) {
darkQuery.removeListener(darkQueryListener);
lightQuery.removeListener(lightQueryListener);
}
}
};
};