fathom/assets/js/components/CountWidget.js

114 lines
2.7 KiB
JavaScript
Raw Normal View History

'use strict';
2018-05-03 08:54:22 +00:00
import { h, Component } from 'preact';
import * as numbers from '../lib/numbers.js';
import Client from '../lib/client.js';
2018-05-01 14:06:17 +00:00
import { bind } from 'decko';
function getSundayOfCurrentWeek(d){
var day = d.getDay();
return new Date(d.getFullYear(), d.getMonth(), d.getDate() + (day == 0?0:7)-day );
}
const dayInSeconds = 60 * 60 * 24;
class CountWidget extends Component {
constructor(props) {
super(props)
this.state = {
2018-05-15 20:26:24 +00:00
value: 0.00,
loading: false,
before: props.before,
after: props.after,
}
}
componentWillReceiveProps(newProps, prevState) {
if(newProps.before == prevState.before && newProps.after == prevState.after) {
return;
}
2018-05-01 14:06:17 +00:00
this.setState({
before: newProps.before,
after: newProps.after,
});
this.fetchData();
}
2018-05-15 20:26:24 +00:00
@bind
countUp(toValue) {
const duration = 1000;
const easeOutQuint = function (t) { return 1+(--t)*t*t*t*t };
const setState = this.setState.bind(this);
const startValue = this.state.value;
const diff = toValue - startValue;
let startTime;
const tick = function(t) {
if(!startTime) { startTime = t; }
let progress = ( t - startTime ) / duration;
let newValue = Math.round(startValue + (easeOutQuint(progress) * diff));
setState({
value: newValue,
})
if(progress < 1) {
window.requestAnimationFrame(tick);
}
}
window.requestAnimationFrame(tick);
}
@bind
fetchData() {
2016-12-10 17:19:44 +00:00
this.setState({ loading: true })
let before = this.state.before;
let after = this.state.after;
Client.request(`${this.props.endpoint}?before=${before}&after=${after}`)
2018-05-01 14:06:17 +00:00
.then((d) => {
// request finished; check if timestamp range is still the one user wants to see
if( this.state.before != before || this.state.after != after ) {
return;
}
2018-05-01 14:06:17 +00:00
this.setState({
2018-05-15 20:26:24 +00:00
loading: false,
2018-05-01 14:06:17 +00:00
})
2018-05-15 20:26:24 +00:00
this.countUp(d);
2018-05-01 14:06:17 +00:00
})
}
2018-05-01 14:06:17 +00:00
render(props, state) {
2018-05-15 20:26:24 +00:00
let formattedValue = "-";
if(state.value > 0) {
switch(props.format) {
case "percentage":
formattedValue = numbers.formatPercentage(state.value)
break;
default:
case "number":
formattedValue = numbers.formatWithComma(state.value)
break;
case "duration":
formattedValue = numbers.formatDuration(state.value)
break;
}
}
return (
<div class={"totals-detail " + ( state.loading ? "loading" : '')}>
2018-05-01 14:06:17 +00:00
<div class="total-heading">{props.title}</div>
2018-05-15 20:26:24 +00:00
<div class="total-numbers">{formattedValue}</div>
</div>
)
}
}
export default CountWidget