import React from 'react'; import { withRouter } from 'react-router-dom' import { Link } from 'react-router-dom' import {shiftDays, shiftMonths, formatDay, formatMonthYYYY, formatISO, isToday} from './date' class DatePicker extends React.Component { constructor(props) { super(props) this.handleKeyup = this.handleKeyup.bind(this) } componentDidMount() { document.addEventListener("keyup", this.handleKeyup); } componentWillUnmount() { document.removeEventListener("keyup", this.handleKeyup); } handleKeyup(e) { const {query, history} = this.props if (e.key === 'ArrowLeft') { if (query.period === 'day') { const prevDate = formatISO(shiftDays(query.date, -1)) history.push('?period=day&date=' + prevDate) } else if (query.period === 'month') { const prevMonth = formatISO(shiftMonths(query.date, -1)) history.push('?period=month&date=' + prevMonth) } } else if (e.key === 'ArrowRight') { if (query.period === 'day') { const nextDate = formatISO(shiftDays(query.date, 1)) history.push('?period=day&date=' + nextDate) } else if (query.period === 'month') { const nextMonth = formatISO(shiftMonths(query.date, 1)) history.push('?period=month&date=' + nextMonth) } } } timeFrameText() { const {query, site} = this.props if (query.period === 'day') { if (isToday(site, query.date)) { return 'Today' } else { return formatDay(query.date) } } else if (query.period === '7d') { return 'Last 7 days' } else if (query.period === '30d') { return 'Last 30 days' } else if (query.period === 'month') { return formatMonthYYYY(query.date) } else if (query.period === '3mo') { return 'Last 3 months' } else if (query.period === '6mo') { return 'Last 6 months' } } renderArrow(period, prevDate, nextDate) { return (
) } renderArrows() { const {query} = this.props if (query.period === 'month') { const prevDate = formatISO(shiftMonths(query.date, -1)) const nextDate = formatISO(shiftMonths(query.date, 1)) return this.renderArrow('month', prevDate, nextDate) } else if (query.period === 'day') { const prevDate = formatISO(shiftDays(query.date, -1)) const nextDate = formatISO(shiftDays(query.date, 1)) return this.renderArrow('day', prevDate, nextDate) } } renderDropDown() { return (
{this.timeFrameText()}
Today Last 7 days Last 30 days Last 3 months Last 6 months
) } render() { return (
{ this.renderArrows() } { this.renderDropDown() }
) } } export default withRouter(DatePicker)