|
1 | 1 | import React, { useEffect, useContext } from "react"; |
2 | 2 | import theme from "@/styles/theme"; |
3 | 3 | import { ThemeProvider } from "styled-components"; |
| 4 | +import useColorScheme from "@/hooks/useColorScheme"; |
4 | 5 |
|
5 | 6 | export const SiteContext = React.createContext({}); |
6 | 7 |
|
7 | 8 | const SiteContextProvider = SiteContext.Provider; |
8 | 9 |
|
9 | 10 | export const useSite = () => useContext(SiteContext); |
10 | 11 |
|
11 | | -function detectColorScheme() { |
12 | | - var theme = 'light'; |
13 | | - |
14 | | - if ( |
15 | | - typeof window.matchMedia !== 'undefined' && |
16 | | - window.matchMedia('(prefers-color-scheme: dark)').matches |
17 | | - ) { |
18 | | - theme = 'dark'; |
19 | | - } |
20 | | - |
21 | | - document.querySelector( |
22 | | - 'input[type=radio][name=colorToggle][value=auto]' |
23 | | - ).checked = true; |
24 | | - |
25 | | - if (window.localStorage.getItem('themeColor') !== 'undefined') { |
26 | | - if (['dark', 'light'].includes(window.localStorage.getItem('themeColor'))) { |
27 | | - theme = window.localStorage.getItem('themeColor'); |
28 | | - var themeToggle = document.querySelector( |
29 | | - 'input[type=radio][name=colorToggle][value=' + theme + ']' |
30 | | - ); |
31 | | - themeToggle.checked = true; |
32 | | - } |
33 | | - } |
34 | | - |
35 | | - setColorScheme(theme, true); |
36 | | -} |
37 | | - |
38 | | -function setColorScheme(theme, auto) { |
39 | | - if (auto !== true) { |
40 | | - window.localStorage.setItem('themeColor', theme); |
41 | | - } |
42 | | - |
43 | | - if (theme === 'auto') { |
44 | | - window.localStorage.removeItem('themeColor'); |
45 | | - detectColorScheme(); |
46 | | - } else { |
47 | | - document.children[0].setAttribute('data-color-scheme', theme); |
48 | | - } |
49 | | - |
50 | | - if (auto !== true) { |
51 | | - document |
52 | | - .querySelectorAll('input[type=radio][name=colorToggle]') |
53 | | - .forEach(function (element) { |
54 | | - if (theme !== element.value) { |
55 | | - element.checked = false; |
56 | | - } |
57 | | - }); |
58 | | - } |
59 | | -} |
60 | | - |
61 | | -function setupActions() { |
62 | | - window |
63 | | - .matchMedia('(prefers-color-scheme: dark)') |
64 | | - .addEventListener('change', function (e) { |
65 | | - detectColorScheme(); |
66 | | - }); |
67 | | -} |
68 | | - |
69 | 12 |
|
70 | 13 |
|
71 | 14 | const Site = ({ children }) => { |
72 | | - useEffect(() => { |
73 | | - detectColorScheme(); |
74 | | - setupActions(); |
75 | | - }, []); |
| 15 | + const { colorScheme, setColorScheme } = useColorScheme(); |
| 16 | + |
| 17 | + console.log({ colorScheme }) |
76 | 18 |
|
77 | 19 | return ( |
78 | | - <SiteContextProvider value={{ setColorScheme }}> |
| 20 | + <SiteContextProvider value={{ colorScheme, setColorScheme }}> |
79 | 21 | <ThemeProvider theme={theme}> |
80 | 22 | {children} |
81 | 23 | </ThemeProvider> |
|
0 commit comments