You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ashen-earth/app/Appearance.tsx

43 lines
1.0 KiB
TypeScript

'use client'
import { useState, useEffect, MouseEvent } from 'react'
type AppearanceMode = undefined | 'light' | 'dark'
export default function Appearance() {
const [appearance, setAppearance] = useState<AppearanceMode>(undefined)
useEffect(() => {
if (appearance !== undefined) {
document.body.parentElement?.classList.remove('light')
document.body.parentElement?.classList.remove('dark')
document.body.parentElement?.classList.add(appearance)
}
}, [appearance])
function toggleDarkMode(ev: MouseEvent<HTMLAnchorElement>) {
ev.preventDefault()
const current = appearance ?? getDefaultTheme()
switch (current) {
case 'light':
setAppearance('dark')
return
case 'dark':
setAppearance('light')
return
}
}
return (
<a id="darkLightToggle" href="#" onClick={toggleDarkMode}>appearance</a>
)
}
function getDefaultTheme(): 'light' | 'dark' {
const { matches: lightTheme } = window.matchMedia('(prefers-color-scheme: light)')
return lightTheme ? 'light' : 'dark'
}