blog-robertops-v2/src/utils/setting-utils.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-08-03 16:40:20 +08:00
import {
AUTO_MODE,
DARK_MODE,
DEFAULT_THEME,
LIGHT_MODE,
} from '@constants/constants.ts'
import type { LIGHT_DARK_MODE } from '@/types/config'
2024-02-18 18:13:43 +08:00
export function getDefaultHue(): number {
const fallback = '250'
const configCarrier = document.getElementById('config-carrier')
return parseInt(configCarrier?.dataset.hue || fallback)
}
export function getHue(): number {
const stored = localStorage.getItem('hue')
return stored ? parseInt(stored) : getDefaultHue()
}
export function setHue(hue: number): void {
localStorage.setItem('hue', String(hue))
2024-07-21 15:47:49 +08:00
const r = document.querySelector(':root') as HTMLElement
2024-02-18 18:13:43 +08:00
if (!r) {
return
}
2024-07-21 15:47:49 +08:00
r.style.setProperty('--hue', String(hue))
2024-02-18 18:13:43 +08:00
}
export function applyThemeToDocument(theme: LIGHT_DARK_MODE) {
switch (theme) {
case LIGHT_MODE:
document.documentElement.classList.remove('dark')
break
case DARK_MODE:
document.documentElement.classList.add('dark')
break
case AUTO_MODE:
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
break
}
}
export function setTheme(theme: LIGHT_DARK_MODE): void {
localStorage.setItem('theme', theme)
applyThemeToDocument(theme)
}
export function getStoredTheme(): LIGHT_DARK_MODE {
2024-08-03 16:40:20 +08:00
return (localStorage.getItem('theme') as LIGHT_DARK_MODE) || DEFAULT_THEME
}