From 97b17e0284cde8ce1e5c4ebba2f29fbb55d29cb0 Mon Sep 17 00:00:00 2001 From: Danny van Kooten Date: Tue, 4 Dec 2018 11:53:40 +0100 Subject: [PATCH] parse hash fragment for datepicker state (incl. custom dates & group by option) --- assets/src/js/components/DatePicker.js | 83 +++++++++++++++++++------- 1 file changed, 60 insertions(+), 23 deletions(-) diff --git a/assets/src/js/components/DatePicker.js b/assets/src/js/components/DatePicker.js index 44b62c8b..69150bfc 100644 --- a/assets/src/js/components/DatePicker.js +++ b/assets/src/js/components/DatePicker.js @@ -81,17 +81,38 @@ const availablePeriods = { } } +function hashParams() { + var params = {}, + match, + matches = window.location.hash.substring(2).split("&"); + + for(var i=0; i end. user may be busy picking dates. if(start > end) { return; @@ -122,16 +143,20 @@ class DatePicker extends Component { start.setHours(0, 0, 0); end.setHours(23, 59, 59); - let diff = Math.round((end - start) / 1000 / 60 / 60 / 24) - let groupBy = 'day'; - if(diff >= 31) { - groupBy = 'month'; - } else if( diff < 2) { - groupBy = 'hour'; + let diff = this.calculateDiff(start, end) + if(!groupBy) { + groupBy = 'day'; + + if(diff >= 31) { + groupBy = 'month'; + } else if( diff < 2) { + groupBy = 'hour'; + } } + this.setState({ - period: period || '', + period: period, startDate: start, endDate: end, diff: diff, @@ -142,14 +167,24 @@ class DatePicker extends Component { if(!this.timeout) { this.timeout = window.setTimeout(() => { this.props.onChange(this.state); + this.updateURL() this.timeout = null; - - window.localStorage.setItem('period', this.state.period) - window.history.replaceState(this.state, null, `#!${this.state.period}`) }, 5) } } + calculateDiff(start, end) { + return Math.round((end - start) / 1000 / 60 / 60 / 24) + } + + updateURL() { + if(this.state.period !== 'custom') { + window.history.replaceState(this.state, null, `#!p=${this.state.period}&g=${this.state.groupBy}`) + } else { + window.history.replaceState(this.state, null, `#!p=custom&s=${encodeURIComponent(this.state.startDate.toISOString())}&e=${encodeURIComponent(this.state.endDate.toISOString())}&g=${this.state.groupBy}`) + } + } + @bind setPeriod(e) { e.preventDefault(); @@ -159,6 +194,7 @@ class DatePicker extends Component { return; } + window.localStorage.setItem('period', this.state.period) this.updateDatesFromPeriod(newPeriod); } @@ -168,12 +204,12 @@ class DatePicker extends Component { @bind setStartDate(date) { - this.setDateRange(date, this.state.endDate, '') + this.setDateRange(date, this.state.endDate, 'custom') } @bind setEndDate(date) { - this.setDateRange(this.state.startDate, date, '') + this.setDateRange(this.state.startDate, date, 'custom') } @bind @@ -211,6 +247,7 @@ class DatePicker extends Component { groupBy: e.target.getAttribute('data-value') }) this.props.onChange(this.state); + this.updateURL() } render(props, state) { @@ -232,9 +269,9 @@ class DatePicker extends Component {
  • )