Table.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import _ from 'lodash';
  2. import React, { PureComponent } from 'react';
  3. import ReactTable from 'react-table';
  4. import TableModel from 'app/core/table_model';
  5. const EMPTY_TABLE = new TableModel();
  6. // Identify columns that contain values
  7. const VALUE_REGEX = /^[Vv]alue #\d+/;
  8. interface TableProps {
  9. data: TableModel;
  10. loading: boolean;
  11. onClickCell?: (columnKey: string, rowValue: string) => void;
  12. }
  13. function prepareRows(rows, columnNames) {
  14. return rows.map(cells => _.zipObject(columnNames, cells));
  15. }
  16. export default class Table extends PureComponent<TableProps> {
  17. getCellProps = (state, rowInfo, column) => {
  18. return {
  19. onClick: (e: React.SyntheticEvent) => {
  20. // Only handle click on link, not the cell
  21. if (e.target) {
  22. const link = e.target as HTMLElement;
  23. if (link.className === 'link') {
  24. const columnKey = column.Header;
  25. const rowValue = rowInfo.row[columnKey];
  26. this.props.onClickCell(columnKey, rowValue);
  27. }
  28. }
  29. },
  30. };
  31. };
  32. render() {
  33. const { data, loading } = this.props;
  34. const tableModel = data || EMPTY_TABLE;
  35. const columnNames = tableModel.columns.map(({ text }) => text);
  36. const columns = tableModel.columns.map(({ filterable, text }) => ({
  37. Header: text,
  38. accessor: text,
  39. className: VALUE_REGEX.test(text) ? 'text-right' : '',
  40. show: text !== 'Time',
  41. Cell: row => <span className={filterable ? 'link' : ''}>{row.value}</span>,
  42. }));
  43. const noDataText = data ? 'The queries returned no data for a table.' : '';
  44. return (
  45. <ReactTable
  46. columns={columns}
  47. data={tableModel.rows}
  48. getTdProps={this.getCellProps}
  49. loading={loading}
  50. minRows={0}
  51. noDataText={noDataText}
  52. resolveData={data => prepareRows(data, columnNames)}
  53. showPagination={Boolean(data)}
  54. />
  55. );
  56. }
  57. }