Table.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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: () => <span title={text}>{text}</span>,
  38. accessor: text,
  39. className: VALUE_REGEX.test(text) ? 'text-right' : '',
  40. show: text !== 'Time',
  41. Cell: row => (
  42. <span className={filterable ? 'link' : ''} title={text + ': ' + row.value}>
  43. {row.value}
  44. </span>
  45. ),
  46. }));
  47. const noDataText = data ? 'The queries returned no data for a table.' : '';
  48. return (
  49. <ReactTable
  50. columns={columns}
  51. data={tableModel.rows}
  52. getTdProps={this.getCellProps}
  53. loading={loading}
  54. minRows={0}
  55. noDataText={noDataText}
  56. resolveData={data => prepareRows(data, columnNames)}
  57. showPagination={Boolean(data)}
  58. />
  59. );
  60. }
  61. }