1
0
Fork 0
blog/src/components/molecules/ThemeSwitch.tsx

72 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-03-13 04:11:44 +01:00
import React, { ReactElement, useEffect, useState } from 'react'
2020-04-11 23:37:19 +02:00
import { Helmet } from 'react-helmet'
import * as styles from './ThemeSwitch.module.css'
2019-11-15 22:10:53 +01:00
import Icon from '../atoms/Icon'
2021-03-13 04:11:44 +01:00
import useDarkMode from '../../hooks/useDarkMode'
2019-10-03 19:18:01 +02:00
const ThemeToggleInput = ({
isDark,
toggleDark
}: {
isDark: boolean
2021-03-13 04:11:44 +01:00
toggleDark: () => void
2019-10-03 19:18:01 +02:00
}) => (
<input
2021-03-13 04:11:44 +01:00
onChange={() => toggleDark()}
2019-10-03 19:18:01 +02:00
type="checkbox"
name="toggle"
value="toggle"
aria-describedby="toggle"
checked={isDark}
/>
)
2021-03-13 04:11:44 +01:00
const HeadMarkup = ({
bodyClass,
themeColor
}: {
bodyClass: string
themeColor: string
}) => (
2019-11-24 14:29:25 +01:00
<Helmet>
2021-03-13 04:11:44 +01:00
<body className={bodyClass} />
2019-11-24 14:29:25 +01:00
<meta name="theme-color" content={themeColor} />
<meta
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"
/>
</Helmet>
)
2020-05-22 14:38:19 +02:00
export default function ThemeSwitch(): ReactElement {
2021-03-13 04:11:44 +01:00
const { value, toggle } = useDarkMode()
const [themeColor, setThemeColor] = useState<string>()
const [bodyClass, setBodyClass] = useState<string>()
2021-03-13 04:11:44 +01:00
useEffect(() => {
setBodyClass(value ? 'dark' : null)
setThemeColor(value ? '#1d2224' : '#e7eef4')
}, [value])
2019-11-09 19:20:39 +01:00
2019-10-03 19:18:01 +02:00
return (
2019-11-09 19:20:39 +01:00
<>
2021-03-13 04:11:44 +01:00
<HeadMarkup themeColor={themeColor} bodyClass={bodyClass} />
<aside className={styles.themeSwitch} title="Toggle Dark Mode">
2019-11-09 19:20:39 +01:00
<label
htmlFor="toggle"
className={styles.checkbox}
2021-03-13 04:11:44 +01:00
onClick={toggle}
onKeyPress={toggle}
2019-12-09 22:49:41 +01:00
role="presentation"
2019-11-09 19:20:39 +01:00
>
<span className={styles.label}>Toggle Dark Mode</span>
2021-03-13 04:11:44 +01:00
<ThemeToggleInput isDark={value} toggleDark={toggle} />
2020-04-04 10:34:19 +02:00
<div aria-live="assertive">
2021-03-13 04:11:44 +01:00
{value ? <Icon name="Sun" /> : <Icon name="Moon" />}
2020-04-04 10:34:19 +02:00
</div>
2019-11-09 19:20:39 +01:00
</label>
</aside>
</>
2019-10-03 19:18:01 +02:00
)
}