fathom/assets/js/components/Graph.js

101 lines
2.5 KiB
JavaScript
Raw Normal View History

2016-11-23 18:40:35 +00:00
'use strict';
import { h, render, Component } from 'preact';
import Chart from 'chart.js'
2016-11-23 19:30:09 +00:00
Chart.defaults.global.tooltips.xPadding = 10;
Chart.defaults.global.tooltips.yPadding = 10;
Chart.defaults.global.layout = { padding: 10 }
2016-11-23 19:30:09 +00:00
2016-11-23 18:40:35 +00:00
class Graph extends Component {
constructor(props) {
super(props)
this.state = {
2016-11-23 19:30:09 +00:00
visitorData: [],
pageviewData: []
2016-11-23 18:40:35 +00:00
}
this.fetchData = this.fetchData.bind(this);
2016-11-23 20:29:54 +00:00
this.fetchData(props.period);
}
componentWillReceiveProps(newProps) {
if(this.props.period != newProps.period) {
this.fetchData(newProps.period)
}
2016-11-23 18:40:35 +00:00
}
2016-11-23 19:30:09 +00:00
refreshChart() {
if( ! this.canvas ) { return; }
// clear canvas
var newCanvas = document.createElement('canvas');
this.canvas.parentNode.style.minHeight = this.canvas.parentNode.clientHeight + "px";
this.canvas.parentNode.replaceChild(newCanvas, this.canvas);
this.canvas = newCanvas;
if( this.chart ) { this.chart.clear(); }
this.chart = new Chart(this.canvas, {
type: 'line',
2016-11-23 18:40:35 +00:00
data: {
2016-11-23 19:30:09 +00:00
labels: this.state.visitorData.map((d) => d.Label),
datasets: [
{
2016-11-23 18:40:35 +00:00
label: '# of Visitors',
2016-11-23 19:30:09 +00:00
data: this.state.visitorData.map((d) => d.Count),
backgroundColor: 'rgba(255, 155, 0, .6)',
pointStyle: 'rect',
pointBorderWidth: 0.1,
2016-11-23 19:30:09 +00:00
},
{
label: '# of Pageviews',
data: this.state.pageviewData.map((d) => d.Count),
backgroundColor: 'rgba(0, 155, 255, .4)',
pointStyle: 'rect',
pointBorderWidth: 0.1,
2016-11-23 19:30:09 +00:00
}
],
}
2016-11-23 18:40:35 +00:00
});
}
2016-11-23 20:29:54 +00:00
fetchData(period) {
2016-11-23 19:30:09 +00:00
// fetch visitor data
2016-11-23 20:29:54 +00:00
fetch('/api/visits/count/day?period=' + period, {
2016-11-23 19:30:09 +00:00
credentials: 'include'
}).then((r) => {
if( r.ok ) {
return r.json();
}
throw new Error();
}).then((data) => {
this.setState({ visitorData: data })
window.requestAnimationFrame(this.refreshChart.bind(this));
2016-11-23 19:30:09 +00:00
});
// fetch pageview data
2016-11-23 20:29:54 +00:00
fetch('/api/pageviews/count/day?period=' + period, {
2016-11-23 18:40:35 +00:00
credentials: 'include'
}).then((r) => {
if( r.ok ) {
return r.json();
}
throw new Error();
}).then((data) => {
this.setState({ pageviewData: data })
window.requestAnimationFrame(this.refreshChart.bind(this));
2016-11-23 18:40:35 +00:00
});
}
render() {
return (
<div class="block">
<canvas height="100" ref={(el) => { this.canvas = el; }} />
2016-11-23 18:40:35 +00:00
</div>
)
}
}
export default Graph