fathom/assets/js/components/Table.js

99 lines
2.4 KiB
JavaScript
Raw Normal View History

'use strict';
import { h, render, Component } from 'preact';
import * as numbers from '../lib/numbers.js';
import Client from '../lib/client.js';
const dayInSeconds = 60 * 60 * 24;
class Table extends Component {
constructor(props) {
super(props)
this.state = {
2016-12-07 21:00:55 +00:00
records: [],
2016-12-10 17:19:44 +00:00
limit: 5,
loading: true
}
2016-12-07 21:00:55 +00:00
this.tableHeaders = props.headers.map(heading => <th>{heading}</th>)
this.fetchRecords = this.fetchRecords.bind(this)
this.handleLimitChoice = this.handleLimitChoice.bind(this)
}
componentDidMount() {
2016-12-08 11:43:13 +00:00
this.fetchRecords(this.props.period, this.state.limit)
}
2016-11-26 15:17:52 +00:00
labelCell(p) {
if( this.props.labelCell ) {
2016-12-07 21:00:55 +00:00
return this.props.labelCell(p)
2016-11-26 15:17:52 +00:00
}
return (
2016-12-10 15:07:03 +00:00
<td>{p.Label.substring(0, 15)}</td>
2016-11-26 15:17:52 +00:00
)
}
componentWillReceiveProps(newProps) {
if(this.props.period != newProps.period) {
2016-12-07 21:00:55 +00:00
this.fetchRecords(newProps.period, this.state.limit)
}
}
2016-12-07 21:00:55 +00:00
handleLimitChoice(e) {
this.setState({ limit: parseInt(e.target.value) })
this.fetchRecords(this.props.period, this.state.limit)
}
fetchRecords(period, limit) {
2016-12-10 17:19:44 +00:00
this.setState({ loading: true });
const before = Math.round((+new Date() ) / 1000);
const after = before - ( period * dayInSeconds );
Client.request(`${this.props.endpoint}?before=${before}&after=${after}&limit=${limit}`)
.then((d) => {
this.setState({ loading: false, records: d }
)}).catch((e) => { console.log(e) })
}
render() {
const tableRows = this.state.records.map((p, i) => (
<tr>
2016-11-24 15:47:33 +00:00
<td class="muted">{i+1}</td>
2016-11-26 15:17:52 +00:00
{this.labelCell(p)}
<td>{numbers.formatWithComma(p.Value)}</td>
<td>{Math.round(p.PercentageValue)}%</td>
</tr>
));
2016-12-10 17:19:44 +00:00
const loadingOverlay = this.state.loading ? <div class="loading-overlay"><div></div></div> : '';
return (
2016-11-24 15:47:33 +00:00
<div class="block">
2016-12-10 17:19:44 +00:00
{loadingOverlay}
2016-12-07 21:00:55 +00:00
<div class="clearfix">
<h3 class="pull-left">{this.props.title}</h3>
<div class="pull-right">
<select onchange={this.handleLimitChoice}>
<option>5</option>
<option>20</option>
<option>100</option>
</select>
</div>
</div>
<table>
<thead>
<tr>{this.tableHeaders}</tr>
</thead>
<tbody>
{tableRows}
</tbody>
</table>
</div>
)
}
}
export default Table