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

88 lines
2.3 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-09-14 20:22:57 +02:00
import posed, { PoseGroup } from 'react-pose'
2018-09-14 20:58:49 +02:00
import { fadeIn } from '../atoms/Transitions'
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
2018-09-14 20:58:49 +02:00
const Animation = posed.aside(fadeIn)
2018-09-14 20:22:57 +02:00
2018-09-06 14:28:01 +02:00
const ThemeToggle = ({ dark }) => (
<span id="toggle" className={styles.checkboxContainer} aria-live="assertive">
2018-09-06 14:28:01 +02:00
<Day className={dark ? null : 'active'} />
<span className={styles.checkboxFake} />
2018-09-06 14:28:01 +02:00
<Night className={dark ? 'active' : null} />
</span>
)
2018-05-23 00:03:46 +02:00
2018-09-06 14:28:01 +02:00
ThemeToggle.propTypes = {
dark: PropTypes.bool
}
2018-05-10 16:06:17 +02:00
2018-09-06 14:28:01 +02:00
export default class ThemeSwitch extends PureComponent {
state = { dark: null }
2018-06-24 20:53:15 +02:00
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>
2018-09-14 20:22:57 +02:00
<PoseGroup animateOnMount={true}>
<Animation 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"
checked={this.isDark()}
/>
<ThemeToggle dark={this.isDark()} />
</label>
</Animation>
</PoseGroup>
2018-05-12 01:42:29 +02:00
</Fragment>
2018-05-10 16:06:17 +02:00
)
}
}