| 45 | /* Table */ |
| 46 | |
| 47 | export default class Table<T extends ScalarDict> extends React.Component< |
| 48 | Pick<TableProps<T>, "data"> & Partial<TableProps<T>> |
| 49 | > { |
| 50 | /* Config */ |
| 51 | |
| 52 | /** |
| 53 | * Merges provided configuration with defaults. |
| 54 | */ |
| 55 | getConfig(): TableProps<T> { |
| 56 | return { |
| 57 | data: this.props.data, |
| 58 | columns: this.props.columns || this.getDataKeys(), |
| 59 | padding: this.props.padding || 1, |
| 60 | header: this.props.header || Header, |
| 61 | cell: this.props.cell || Cell, |
| 62 | skeleton: this.props.skeleton || Skeleton, |
| 63 | }; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Gets all keyes used in data by traversing through the data. |
| 68 | */ |
| 69 | getDataKeys(): (keyof T)[] { |
| 70 | const keys = new Set<keyof T>(); |
| 71 | |
| 72 | // Collect all the keys. |
| 73 | for (const data of this.props.data) { |
| 74 | for (const key in data) { |
| 75 | keys.add(key); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | return Array.from(keys); |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Calculates the width of each column by finding |
| 84 | * the longest value in a cell of a particular column. |
| 85 | * |
| 86 | * Returns a list of column names and their widths. |
| 87 | */ |
| 88 | getColumns(): Column<T>[] { |
| 89 | const { columns, padding } = this.getConfig(); |
| 90 | |
| 91 | const widths: Column<T>[] = columns.map((key) => { |
| 92 | const header = String(key).length; |
| 93 | /* Get the width of each cell in the column */ |
| 94 | const data = this.props.data.map((data) => { |
| 95 | const value = data[key]; |
| 96 | |
| 97 | if (value == undefined || value == null) return 0; |
| 98 | return String(value).length; |
| 99 | }); |
| 100 | |
| 101 | const width = Math.max(...data, header) + padding * 2; |
| 102 | |
| 103 | /* Construct a cell */ |
| 104 | return { |