2016-11-24 13:55:59 +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:19:15 +01:00
|
|
|
const dayInSeconds = 60 * 60 * 24;
|
2016-11-24 13:55:59 +01:00
|
|
|
|
|
|
|
class Table extends Component {
|
|
|
|
|
|
|
|
constructor(props) {
|
|
|
|
super(props)
|
|
|
|
|
|
|
|
this.state = {
|
|
|
|
records: []
|
|
|
|
}
|
|
|
|
|
|
|
|
this.tableHeaders = props.headers.map(heading => <th>{heading}</th>);
|
|
|
|
this.fetchRecords = this.fetchRecords.bind(this);
|
|
|
|
this.fetchRecords(props.period);
|
|
|
|
}
|
|
|
|
|
2016-11-26 16:17:52 +01:00
|
|
|
labelCell(p) {
|
|
|
|
if( this.props.labelCell ) {
|
|
|
|
return this.props.labelCell(p);
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<td>{p.Label}</td>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2016-11-24 13:55:59 +01:00
|
|
|
componentWillReceiveProps(newProps) {
|
|
|
|
if(this.props.period != newProps.period) {
|
|
|
|
this.fetchRecords(newProps.period)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fetchRecords(period) {
|
2016-11-26 17:19:15 +01:00
|
|
|
const before = Math.round((+new Date() ) / 1000);
|
|
|
|
const after = before - ( period * dayInSeconds );
|
|
|
|
|
|
|
|
return fetch(`/api/${this.props.endpoint}?before=${before}&after=${after}`, {
|
2016-11-24 13:55:59 +01:00
|
|
|
credentials: 'include'
|
|
|
|
}).then((r) => {
|
|
|
|
if( r.ok ) {
|
|
|
|
return r.json();
|
|
|
|
}
|
|
|
|
|
2016-11-25 16:30:38 +01:00
|
|
|
// TODO: Make this pretty.
|
|
|
|
if( r.status == 401 ) {
|
|
|
|
this.props.onAuthError();
|
|
|
|
}
|
|
|
|
|
2016-11-24 13:55:59 +01:00
|
|
|
// TODO: do something with error
|
2016-11-25 16:30:38 +01:00
|
|
|
throw new Error();
|
2016-11-24 13:55:59 +01:00
|
|
|
}).then((data) => {
|
|
|
|
this.setState({ records: data })
|
2016-11-25 16:30:38 +01:00
|
|
|
}).catch((e) => {
|
|
|
|
|
2016-11-24 13:55:59 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
2016-11-25 16:30:38 +01:00
|
|
|
const tableRows = this.state.records.map((p, i) => (
|
2016-11-24 13:55:59 +01:00
|
|
|
<tr>
|
2016-11-24 16:47:33 +01:00
|
|
|
<td class="muted">{i+1}</td>
|
2016-11-26 16:17:52 +01:00
|
|
|
{this.labelCell(p)}
|
2016-12-05 21:55:25 +01:00
|
|
|
<td>{numbers.formatWithComma(p.Count)}</td>
|
2016-11-24 13:55:59 +01:00
|
|
|
<td>{Math.round(p.Percentage)}%</td>
|
|
|
|
</tr>
|
|
|
|
));
|
|
|
|
|
|
|
|
return (
|
2016-11-24 16:47:33 +01:00
|
|
|
<div class="block">
|
2016-11-24 13:55:59 +01:00
|
|
|
<h3>{this.props.title}</h3>
|
|
|
|
<table>
|
|
|
|
<thead>
|
|
|
|
<tr>{this.tableHeaders}</tr>
|
|
|
|
</thead>
|
|
|
|
<tbody>
|
|
|
|
{tableRows}
|
|
|
|
</tbody>
|
|
|
|
</table>
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Table
|