2016-11-26 15:39:29 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
import { h, render, Component } from 'preact';
|
2016-12-05 21:55:25 +01:00
|
|
|
import * as numbers from '../lib/numbers.js';
|
2016-11-26 17:40:37 +01:00
|
|
|
const dayInSeconds = 60 * 60 * 24;
|
2016-11-26 15:39:29 +01:00
|
|
|
|
|
|
|
class CountWidget extends Component {
|
|
|
|
constructor(props) {
|
|
|
|
super(props)
|
|
|
|
|
|
|
|
this.state = {
|
2016-11-26 17:40:37 +01:00
|
|
|
count: 0,
|
|
|
|
previousCount: 0
|
2016-11-26 15:39:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
this.fetchData = this.fetchData.bind(this);
|
|
|
|
this.fetchData(props.period);
|
|
|
|
}
|
|
|
|
|
|
|
|
componentWillReceiveProps(newProps) {
|
|
|
|
if(this.props.period != newProps.period) {
|
|
|
|
this.fetchData(newProps.period)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fetchData(period) {
|
2016-11-26 17:40:37 +01:00
|
|
|
const before = Math.round((+new Date() ) / 1000);
|
|
|
|
const after = before - ( period * dayInSeconds );
|
|
|
|
|
|
|
|
fetch(`/api/${this.props.endpoint}/count?before=${before}&after=${after}`, {
|
2016-11-26 15:39:29 +01:00
|
|
|
credentials: 'include'
|
|
|
|
}).then((r) => {
|
|
|
|
if( r.ok ) { return r.json(); }
|
|
|
|
throw new Error();
|
|
|
|
}).then((data) => {
|
|
|
|
this.setState({ count: data })
|
|
|
|
});
|
2016-11-26 17:40:37 +01:00
|
|
|
|
|
|
|
// query previous period
|
|
|
|
const previousBefore = after;
|
|
|
|
const previousAfter = previousBefore - ( period * dayInSeconds );
|
|
|
|
fetch(`/api/${this.props.endpoint}/count?before=${previousBefore}&after=${previousAfter}`, {
|
|
|
|
credentials: 'include'
|
|
|
|
}).then((r) => {
|
|
|
|
if( r.ok ) { return r.json(); }
|
|
|
|
throw new Error();
|
|
|
|
}).then((data) => {
|
|
|
|
this.setState({ previousCount: data })
|
|
|
|
});
|
2016-11-26 15:39:29 +01:00
|
|
|
}
|
|
|
|
|
2016-11-26 17:40:37 +01:00
|
|
|
renderPercentage() {
|
|
|
|
if( ! this.state.previousCount ) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
const percentage = Math.round(( this.state.count / this.state.previousCount * 100 - 100))
|
2016-11-26 15:39:29 +01:00
|
|
|
return (
|
2016-11-26 17:40:37 +01:00
|
|
|
<small class={percentage > 0 ? 'positive' : 'negative'}>{percentage}%</small>
|
|
|
|
)
|
|
|
|
}
|
2016-11-26 15:39:29 +01:00
|
|
|
|
2016-11-26 17:40:37 +01:00
|
|
|
render() {
|
|
|
|
return (
|
2016-11-26 15:39:29 +01:00
|
|
|
<div class="block center-text">
|
2016-11-26 17:40:37 +01:00
|
|
|
<h4 class="">{this.props.title}</h4>
|
2016-12-05 21:55:25 +01:00
|
|
|
<div class="big tiny-margin">{numbers.formatWithComma(this.state.count)} {this.renderPercentage()}</div>
|
2016-11-26 15:39:29 +01:00
|
|
|
<div class="muted">last {this.props.period} days</div>
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default CountWidget
|