'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 = { records: [], limit: 5 } this.tableHeaders = props.headers.map(heading => {heading}) this.fetchRecords = this.fetchRecords.bind(this) this.handleLimitChoice = this.handleLimitChoice.bind(this) } componentDidMount() { this.fetchRecords(this.props.period, this.state.limit) } labelCell(p) { if( this.props.labelCell ) { return this.props.labelCell(p) } return ( {p.Label} ) } componentWillReceiveProps(newProps) { if(this.props.period != newProps.period) { this.fetchRecords(newProps.period, this.state.limit) } } handleLimitChoice(e) { this.setState({ limit: parseInt(e.target.value) }) this.fetchRecords(this.props.period, this.state.limit) } fetchRecords(period, limit) { 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({ records: d })}) .catch((e) => { console.log(e) }) } render() { const tableRows = this.state.records.map((p, i) => ( {i+1} {this.labelCell(p)} {numbers.formatWithComma(p.Count)} {Math.round(p.Percentage)}% )); return (

{this.props.title}

{this.tableHeaders} {tableRows}
) } } export default Table