| 1 | // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt |
| 2 | |
| 3 | import { useSnapState } from './state' |
| 4 | import { useEffect } from 'react' |
| 5 | import { useMediaQuery } from 'usehooks-ts' |
| 6 | import { getHFS } from '@hfs/shared' |
| 7 | |
| 8 | export default function useTheme() { |
| 9 | const { theme } = useSnapState() |
| 10 | const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)') // don't use useDarkMode() as it persists in localstorage and there's no way to just read system setting |
| 11 | useEffect(()=>{ |
| 12 | const e = document.body |
| 13 | if (!e) return |
| 14 | const name = getHFS().forceTheme || theme || (isDarkMode ? 'dark' : 'light') |
| 15 | const pre = 'theme-' |
| 16 | const ct = pre + name |
| 17 | const list = e.classList |
| 18 | for (const c of Array.from(list)) |
| 19 | if (c.startsWith(pre) && c !== ct) |
| 20 | list.remove(c) |
| 21 | if (name) |
| 22 | list.add(ct) |
| 23 | }, [theme, isDarkMode]) |
| 24 | } |