fathom/assets/js/components/Graph.js

86 lines
1.9 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;
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() {
this.chart = new Chart(this.ctx, {
2016-11-23 18:40:35 +00:00
type: 'line',
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(0, 0, 255, .2)'
},
{
label: '# of Pageviews',
data: this.state.pageviewData.map((d) => d.Count),
backgroundColor: 'rgba(0, 0, 125, .2)'
}
]
2016-11-23 18:40:35 +00:00
},
options: {
scale: {
ticks: {
beginAtZero: true
}
}
}
});
}
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) => r.json())
.then((data) => {
this.setState({ visitorData: data})
this.refreshChart();
});
// 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'
2016-11-23 19:30:09 +00:00
}).then((r) => r.json())
2016-11-23 18:40:35 +00:00
.then((data) => {
2016-11-23 19:30:09 +00:00
this.setState({ pageviewData: data})
this.refreshChart();
2016-11-23 18:40:35 +00:00
});
}
render() {
return (
<div class="block">
<canvas width="600" height="220" ref={(el) => { this.ctx = el; }} />
</div>
)
}
}
export default Graph