index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { useEffect, useMemo, useState } from 'react'
  2. import { useSearchParams } from 'react-router-dom'
  3. import { changeTheme, useVariable } from '@/utils/theme.js'
  4. const allowedThemeKeys = ['light', 'dark']
  5. const useLocalStorageThemeKey = () => {
  6. const [key, setKey] = useState(() => localStorage.getItem('--dt-theme') ?? null)
  7. useEffect(() => {
  8. const cb = (e) => {
  9. const theme = localStorage.getItem('--dt-theme')
  10. setKey(theme ?? null)
  11. }
  12. window.addEventListener('storage', cb)
  13. return () => {
  14. window.removeEventListener('storage', cb)
  15. }
  16. }, [])
  17. return [key]
  18. }
  19. const useThemeKey = () => {
  20. const [lsKey] = useLocalStorageThemeKey()
  21. const [searchParams] = useSearchParams()
  22. const theme = useMemo(() => {
  23. // if (process.env.REACT_APP_THEME_CHANGEABLE == 'false') {
  24. // return process.env.REACT_APP_THEME
  25. // } else {
  26. let key = (
  27. searchParams.get('theme') ??
  28. lsKey ??
  29. // process.env.REACT_APP_THEME ??
  30. 'light'
  31. )
  32. if (allowedThemeKeys.indexOf(key) === -1) {
  33. key = allowedThemeKeys[0]
  34. }
  35. return key
  36. // }
  37. }, [searchParams, lsKey])
  38. return [theme]
  39. }
  40. const useTheme = () => {
  41. const [theme] = useThemeKey()
  42. useEffect(() => {
  43. // console.log(theme);
  44. changeTheme(theme)
  45. // const loTheme = localStorage.getItem('--dt-theme')
  46. // if (typeof loTheme !== 'string' || loTheme === '' || allowedThemeKeys.indexOf(loTheme) !== -1) {
  47. // localStorage.setItem('--dt-theme', theme)
  48. // }
  49. }, [theme])
  50. return [theme]
  51. }
  52. const useColors = colors => {
  53. const [theme] = useThemeKey()
  54. const colorsStr = useMemo(() => {
  55. return JSON.stringify(colors ?? [])
  56. }, [colors])
  57. const pColors = useMemo(() => {
  58. return JSON.parse(colorsStr)
  59. }, [colorsStr])
  60. const [retColors] = useVariable(theme, pColors)
  61. return [retColors]
  62. }
  63. export { useTheme, useColors, useThemeKey }