1
0
mirror of https://github.com/kremalicious/portfolio.git synced 2024-06-28 00:27:40 +02:00
portfolio/src/components/molecules/ThemeSwitch.jsx

87 lines
2.1 KiB
React
Raw Normal View History

2018-05-12 01:42:29 +02:00
import React, { PureComponent, Fragment } from 'react'
2018-05-23 00:03:46 +02:00
import PropTypes from 'prop-types'
2018-05-12 01:42:29 +02:00
import Helmet from 'react-helmet'
2018-06-20 23:26:40 +02:00
import Day from '../svg/Day'
import Night from '../svg/Night'
2018-06-11 19:48:38 +02:00
import styles from './ThemeSwitch.module.scss'
2018-05-10 16:06:17 +02:00
const ThemeToggle = props => (
<span id="toggle" className={styles.checkboxContainer} aria-live="assertive">
<Day className={props.dark ? null : 'active'} />
<span className={styles.checkboxFake} />
<Night className={props.dark ? 'active' : null} />
</span>
)
2018-05-23 00:03:46 +02:00
class ThemeSwitch extends PureComponent {
2018-05-10 16:06:17 +02:00
constructor(props) {
super(props)
2018-06-24 20:53:15 +02:00
this.state = { dark: null }
}
isDark = () => this.state.dark === true
darkLocalStorageMode = darkLocalStorage => {
if (darkLocalStorage === 'true') {
this.setState({ dark: true })
} else {
2018-06-24 20:53:15 +02:00
this.setState({ dark: false })
}
}
darkMode = now => {
if (!this.isDark() && (now >= 19 || now <= 7)) {
this.setState({ dark: true })
} else {
this.setState({ dark: null })
}
2018-05-10 16:06:17 +02:00
}
2018-05-12 01:42:29 +02:00
componentDidMount() {
2018-05-10 17:58:45 +02:00
const now = new Date().getHours()
const darkLocalStorage = localStorage.getItem('dark')
2018-06-24 20:53:15 +02:00
if (darkLocalStorage) {
this.darkLocalStorageMode(darkLocalStorage)
} else {
this.darkMode(now)
2018-05-10 17:58:45 +02:00
}
}
2018-05-10 17:58:45 +02:00
2018-06-24 20:53:15 +02:00
handleChange = event => {
this.setState({ dark: event.target.checked })
localStorage.setItem('dark', event.target.checked)
2018-05-10 16:06:17 +02:00
}
render() {
return (
2018-05-12 01:42:29 +02:00
<Fragment>
<Helmet>
2018-06-24 21:44:13 +02:00
<body className={this.isDark() ? 'dark' : null} />
2018-05-12 01:42:29 +02:00
</Helmet>
<aside className={styles.themeSwitch}>
<label className={styles.checkbox}>
<span className={styles.label}>Toggle Night Mode</span>
<input
onChange={this.handleChange}
type="checkbox"
name="toggle"
value="toggle"
aria-describedby="toggle"
2018-06-24 21:44:13 +02:00
checked={this.isDark()}
/>
2018-06-24 21:44:13 +02:00
<ThemeToggle dark={this.isDark()} />
</label>
</aside>
2018-05-12 01:42:29 +02:00
</Fragment>
2018-05-10 16:06:17 +02:00
)
}
}
2018-05-23 00:03:46 +02:00
ThemeToggle.propTypes = {
dark: PropTypes.bool
}
2018-05-10 16:06:17 +02:00
export default ThemeSwitch