|
1 | | -import { ref, onMounted, onUnmounted } from '@vue/composition-api'; |
2 | | - |
3 | | -export function usePreferredColorScheme() { |
4 | | - const themesObj: Record<string, MediaQueryList> = { |
5 | | - light: window.matchMedia('(prefers-color-scheme: light)'), |
6 | | - dark: window.matchMedia('(prefers-color-scheme: dark)'), |
7 | | - 'no-preference': window.matchMedia('(prefers-color-scheme: no-preference)') |
| 1 | +import { computed, Ref } from '@vue/composition-api'; |
| 2 | +import { useMedia } from './Media'; |
| 3 | + |
| 4 | +export function usePreferredColorScheme(): Ref<'dark' | 'light' | 'no-preference'> { |
| 5 | + const queries = { |
| 6 | + light: '(prefers-color-scheme: light)', |
| 7 | + dark: '(prefers-color-scheme: dark)', |
| 8 | + 'no-preference': '(prefers-color-scheme: no-preference)' |
8 | 9 | }; |
9 | 10 |
|
10 | | - const value = ref(getTheme()); |
| 11 | + const isDark = useMedia(queries.dark); |
| 12 | + const isLight = useMedia(queries.light); |
11 | 13 |
|
12 | | - function getTheme() { |
13 | | - let theme = null; |
14 | | - for (const key in themesObj) { |
15 | | - if (themesObj[key].matches) { |
16 | | - theme = key; |
17 | | - break; |
18 | | - } |
| 14 | + const theme = computed(() => { |
| 15 | + if (isDark.value) { |
| 16 | + return 'dark'; |
19 | 17 | } |
20 | 18 |
|
21 | | - return theme; |
22 | | - } |
23 | | - |
24 | | - function handler() { |
25 | | - value.value = getTheme(); |
26 | | - } |
27 | | - |
28 | | - onMounted(() => { |
29 | | - Object.values(themesObj).forEach(theme => { |
30 | | - theme.addListener(handler); |
31 | | - }); |
32 | | - }); |
| 19 | + if (isLight.value) { |
| 20 | + return 'light'; |
| 21 | + } |
33 | 22 |
|
34 | | - onUnmounted(() => { |
35 | | - Object.values(themesObj).forEach(themeMedia => { |
36 | | - themeMedia.removeListener(handler); |
37 | | - }); |
| 23 | + return 'no-preference'; |
38 | 24 | }); |
39 | 25 |
|
40 | | - return value; |
| 26 | + return theme; |
41 | 27 | } |
0 commit comments