|
| 1 | +import React from 'react'; |
| 2 | + |
1 | 3 | export function hashCode(str: string) {
|
2 | 4 | let hash = 0;
|
3 | 5 | for (let i = 0; i < str.length; i++) {
|
@@ -34,3 +36,71 @@ export function isValidURL(url: string): boolean {
|
34 | 36 | }
|
35 | 37 | }
|
36 | 38 | }
|
| 39 | + |
| 40 | +export const colorSchemes = { |
| 41 | + light: '(prefers-color-scheme: light)', |
| 42 | + dark: '(prefers-color-scheme: dark)' |
| 43 | +}; |
| 44 | + |
| 45 | +/** |
| 46 | + * quick method to check system theme |
| 47 | + * @param theme auto, light, dark |
| 48 | + * @returns dark or light |
| 49 | + */ |
| 50 | +export function getTheme(theme: string) { |
| 51 | + if (theme !== 'auto') { |
| 52 | + return theme; |
| 53 | + } |
| 54 | + |
| 55 | + const dark = window.matchMedia(colorSchemes.dark); |
| 56 | + |
| 57 | + return dark.matches ? 'dark' : 'light'; |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * create a listener for system theme |
| 62 | + * @param cb callback for theme change |
| 63 | + * @returns destroy listener |
| 64 | + */ |
| 65 | +export const useSystemTheme = (cb: (theme: string) => void) => { |
| 66 | + const dark = window.matchMedia(colorSchemes.dark); |
| 67 | + const light = window.matchMedia(colorSchemes.light); |
| 68 | + |
| 69 | + const listener = () => { |
| 70 | + cb(dark.matches ? 'dark' : 'light'); |
| 71 | + }; |
| 72 | + |
| 73 | + dark.addEventListener('change', listener); |
| 74 | + light.addEventListener('change', listener); |
| 75 | + |
| 76 | + return () => { |
| 77 | + dark.removeEventListener('change', listener); |
| 78 | + light.removeEventListener('change', listener); |
| 79 | + }; |
| 80 | +}; |
| 81 | + |
| 82 | +export const useTheme = (props: {theme: string}) => { |
| 83 | + const [theme, setTheme] = React.useState(getTheme(props.theme)); |
| 84 | + |
| 85 | + React.useEffect(() => { |
| 86 | + let destroyListener: (() => void) | undefined; |
| 87 | + |
| 88 | + // change theme by system, only register listener when theme is auto |
| 89 | + if (props.theme === 'auto') { |
| 90 | + destroyListener = useSystemTheme(systemTheme => { |
| 91 | + setTheme(systemTheme); |
| 92 | + }); |
| 93 | + } |
| 94 | + |
| 95 | + // change theme manually |
| 96 | + if (props.theme !== theme) { |
| 97 | + setTheme(getTheme(props.theme)); |
| 98 | + } |
| 99 | + |
| 100 | + return () => { |
| 101 | + destroyListener?.(); |
| 102 | + }; |
| 103 | + }, [props.theme]); |
| 104 | + |
| 105 | + return [theme]; |
| 106 | +}; |
0 commit comments