| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import { useEffect, useMemo, useState } from 'react'
- import { useSearchParams } from 'react-router-dom'
- import { changeTheme, useVariable } from '@/utils/theme.js'
- const allowedThemeKeys = ['light', 'dark']
- const useLocalStorageThemeKey = () => {
- const [key, setKey] = useState(() => localStorage.getItem('--dt-theme') ?? null)
- useEffect(() => {
- const cb = (e) => {
- const theme = localStorage.getItem('--dt-theme')
- setKey(theme ?? null)
- }
- window.addEventListener('storage', cb)
- return () => {
- window.removeEventListener('storage', cb)
- }
- }, [])
- return [key]
- }
- const useThemeKey = () => {
- const [lsKey] = useLocalStorageThemeKey()
- const [searchParams] = useSearchParams()
- const theme = useMemo(() => {
- // if (process.env.REACT_APP_THEME_CHANGEABLE == 'false') {
- // return process.env.REACT_APP_THEME
- // } else {
- let key = (
- searchParams.get('theme') ??
- lsKey ??
- // process.env.REACT_APP_THEME ??
- 'light'
- )
- if (allowedThemeKeys.indexOf(key) === -1) {
- key = allowedThemeKeys[0]
- }
- return key
- // }
- }, [searchParams, lsKey])
- return [theme]
- }
- const useTheme = () => {
- const [theme] = useThemeKey()
- useEffect(() => {
- // console.log(theme);
- changeTheme(theme)
- // const loTheme = localStorage.getItem('--dt-theme')
- // if (typeof loTheme !== 'string' || loTheme === '' || allowedThemeKeys.indexOf(loTheme) !== -1) {
- // localStorage.setItem('--dt-theme', theme)
- // }
- }, [theme])
- return [theme]
- }
- const useColors = colors => {
- const [theme] = useThemeKey()
- const colorsStr = useMemo(() => {
- return JSON.stringify(colors ?? [])
- }, [colors])
- const pColors = useMemo(() => {
- return JSON.parse(colorsStr)
- }, [colorsStr])
- const [retColors] = useVariable(theme, pColors)
- return [retColors]
- }
- export { useTheme, useColors, useThemeKey }
|