Table.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import React, { PureComponent } from 'react';
  2. import TableModel from 'app/core/table_model';
  3. const EMPTY_TABLE = new TableModel();
  4. interface TableProps {
  5. className?: string;
  6. data: TableModel;
  7. loading: boolean;
  8. onClickCell?: (columnKey: string, rowValue: string) => void;
  9. }
  10. interface SFCCellProps {
  11. columnIndex: number;
  12. onClickCell?: (columnKey: string, rowValue: string, columnIndex: number, rowIndex: number, table: TableModel) => void;
  13. rowIndex: number;
  14. table: TableModel;
  15. value: string;
  16. }
  17. function Cell(props: SFCCellProps) {
  18. const { columnIndex, rowIndex, table, value, onClickCell } = props;
  19. const column = table.columns[columnIndex];
  20. if (column && column.filterable && onClickCell) {
  21. const onClick = event => {
  22. event.preventDefault();
  23. onClickCell(column.text, value, columnIndex, rowIndex, table);
  24. };
  25. return (
  26. <td>
  27. <a className="link" onClick={onClick}>
  28. {value}
  29. </a>
  30. </td>
  31. );
  32. }
  33. return <td>{value}</td>;
  34. }
  35. export default class Table extends PureComponent<TableProps, {}> {
  36. render() {
  37. const { className = '', data, loading, onClickCell } = this.props;
  38. const tableModel = data || EMPTY_TABLE;
  39. if (!loading && data && data.rows.length === 0) {
  40. return (
  41. <table className={`${className} filter-table`}>
  42. <thead>
  43. <tr>
  44. <th>Table</th>
  45. </tr>
  46. </thead>
  47. <tbody>
  48. <tr>
  49. <td className="muted">The queries returned no data for a table.</td>
  50. </tr>
  51. </tbody>
  52. </table>
  53. );
  54. }
  55. return (
  56. <table className={`${className} filter-table`}>
  57. <thead>
  58. <tr>{tableModel.columns.map(col => <th key={col.text}>{col.text}</th>)}</tr>
  59. </thead>
  60. <tbody>
  61. {tableModel.rows.map((row, i) => (
  62. <tr key={i}>
  63. {row.map((value, j) => (
  64. <Cell
  65. key={j}
  66. columnIndex={j}
  67. rowIndex={i}
  68. value={String(value)}
  69. table={data}
  70. onClickCell={onClickCell}
  71. />
  72. ))}
  73. </tr>
  74. ))}
  75. </tbody>
  76. </table>
  77. );
  78. }
  79. }