index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import React from 'react';
  2. import {Location} from 'history';
  3. import EmptyStateWarning from 'app/components/emptyStateWarning';
  4. import LoadingIndicator from 'app/components/loadingIndicator';
  5. import {IconWarning} from 'app/icons';
  6. import {t} from 'app/locale';
  7. import {
  8. Body,
  9. Grid,
  10. GridBody,
  11. GridBodyCell,
  12. GridBodyCellStatus,
  13. GridHead,
  14. GridHeadCell,
  15. GridHeadCellStatic,
  16. GridResizer,
  17. GridRow,
  18. Header,
  19. HeaderButtonContainer,
  20. HeaderTitle,
  21. } from './styles';
  22. import {
  23. GridColumn,
  24. GridColumnHeader,
  25. GridColumnOrder,
  26. GridColumnSortBy,
  27. ObjectKey,
  28. } from './types';
  29. import {COL_WIDTH_MINIMUM, COL_WIDTH_UNDEFINED, ColResizeMetadata} from './utils';
  30. type GridEditableProps<DataRow, ColumnKey> = {
  31. location: Location;
  32. isLoading?: boolean;
  33. error?: React.ReactNode | null;
  34. /**
  35. * GridEditable (mostly) do not maintain any internal state and relies on the
  36. * parent component to tell it how/what to render and will mutate the view
  37. * based on this 3 main props.
  38. *
  39. * - `columnOrder` determines the columns to show, from left to right
  40. * - `columnSortBy` is not used at the moment, however it might be better to
  41. * move sorting into Grid for performance
  42. */
  43. title?: string;
  44. /**
  45. * Inject a set of buttons into the top of the grid table.
  46. * The controlling component is responsible for handling any actions
  47. * in these buttons and updating props to the GridEditable instance.
  48. */
  49. headerButtons?: () => React.ReactNode;
  50. columnOrder: GridColumnOrder<ColumnKey>[];
  51. columnSortBy: GridColumnSortBy<ColumnKey>[];
  52. data: DataRow[];
  53. /**
  54. * GridEditable allows the parent component to determine how to display the
  55. * data within it. Note that this is optional.
  56. */
  57. grid: {
  58. renderHeadCell?: (
  59. column: GridColumnOrder<ColumnKey>,
  60. columnIndex: number
  61. ) => React.ReactNode;
  62. renderBodyCell?: (
  63. column: GridColumnOrder<ColumnKey>,
  64. dataRow: DataRow,
  65. rowIndex: number,
  66. columnIndex: number
  67. ) => React.ReactNode;
  68. onResizeColumn?: (
  69. columnIndex: number,
  70. nextColumn: GridColumnOrder<ColumnKey>
  71. ) => void;
  72. renderPrependColumns?: (
  73. isHeader: boolean,
  74. dataRow?: DataRow,
  75. rowIndex?: number
  76. ) => React.ReactNode[];
  77. prependColumnWidths?: string[];
  78. };
  79. };
  80. type GridEditableState = {
  81. numColumn: number;
  82. };
  83. class GridEditable<
  84. DataRow extends {[key: string]: any},
  85. ColumnKey extends ObjectKey
  86. > extends React.Component<GridEditableProps<DataRow, ColumnKey>, GridEditableState> {
  87. // Static methods do not allow the use of generics bounded to the parent class
  88. // For more info: https://github.com/microsoft/TypeScript/issues/14600
  89. static getDerivedStateFromProps(
  90. props: Readonly<GridEditableProps<Object, keyof Object>>,
  91. prevState: GridEditableState
  92. ): GridEditableState {
  93. return {
  94. ...prevState,
  95. numColumn: props.columnOrder.length,
  96. };
  97. }
  98. state = {
  99. numColumn: 0,
  100. };
  101. componentDidMount() {
  102. window.addEventListener('resize', this.redrawGridColumn);
  103. this.setGridTemplateColumns(this.props.columnOrder);
  104. }
  105. componentDidUpdate() {
  106. // Redraw columns whenever new props are received
  107. this.setGridTemplateColumns(this.props.columnOrder);
  108. }
  109. componentWillUnmount() {
  110. this.clearWindowLifecycleEvents();
  111. window.removeEventListener('resize', this.redrawGridColumn);
  112. }
  113. private refGrid = React.createRef<HTMLTableElement>();
  114. private resizeMetadata?: ColResizeMetadata;
  115. private resizeWindowLifecycleEvents: {
  116. [eventName: string]: any[];
  117. } = {
  118. mousemove: [],
  119. mouseup: [],
  120. };
  121. clearWindowLifecycleEvents() {
  122. Object.keys(this.resizeWindowLifecycleEvents).forEach(e => {
  123. this.resizeWindowLifecycleEvents[e].forEach(c => window.removeEventListener(e, c));
  124. this.resizeWindowLifecycleEvents[e] = [];
  125. });
  126. }
  127. onResetColumnSize = (e: React.MouseEvent, i: number) => {
  128. e.stopPropagation();
  129. const nextColumnOrder = [...this.props.columnOrder];
  130. nextColumnOrder[i] = {
  131. ...nextColumnOrder[i],
  132. width: COL_WIDTH_UNDEFINED,
  133. };
  134. this.setGridTemplateColumns(nextColumnOrder);
  135. const onResizeColumn = this.props.grid.onResizeColumn;
  136. if (onResizeColumn) {
  137. onResizeColumn(i, {
  138. ...nextColumnOrder[i],
  139. width: COL_WIDTH_UNDEFINED,
  140. });
  141. }
  142. };
  143. onResizeMouseDown = (e: React.MouseEvent, i: number = -1) => {
  144. e.stopPropagation();
  145. // Block right-click and other funky stuff
  146. if (i === -1 || e.type === 'contextmenu') {
  147. return;
  148. }
  149. // <GridResizer> is nested 1 level down from <GridHeadCell>
  150. const cell = e.currentTarget!.parentElement;
  151. if (!cell) {
  152. return;
  153. }
  154. // HACK: Do not put into state to prevent re-rendering of component
  155. this.resizeMetadata = {
  156. columnIndex: i,
  157. columnWidth: cell.offsetWidth,
  158. cursorX: e.clientX,
  159. };
  160. window.addEventListener('mousemove', this.onResizeMouseMove);
  161. this.resizeWindowLifecycleEvents.mousemove.push(this.onResizeMouseMove);
  162. window.addEventListener('mouseup', this.onResizeMouseUp);
  163. this.resizeWindowLifecycleEvents.mouseup.push(this.onResizeMouseUp);
  164. };
  165. onResizeMouseUp = (e: MouseEvent) => {
  166. const metadata = this.resizeMetadata;
  167. const onResizeColumn = this.props.grid.onResizeColumn;
  168. if (!metadata || !onResizeColumn) {
  169. return;
  170. }
  171. const {columnOrder} = this.props;
  172. const widthChange = e.clientX - metadata.cursorX;
  173. onResizeColumn(metadata.columnIndex, {
  174. ...columnOrder[metadata.columnIndex],
  175. width: metadata.columnWidth + widthChange,
  176. });
  177. this.resizeMetadata = undefined;
  178. this.clearWindowLifecycleEvents();
  179. };
  180. onResizeMouseMove = (e: MouseEvent) => {
  181. const {resizeMetadata} = this;
  182. if (!resizeMetadata) {
  183. return;
  184. }
  185. window.requestAnimationFrame(() => this.resizeGridColumn(e, resizeMetadata));
  186. };
  187. resizeGridColumn(e: MouseEvent, metadata: ColResizeMetadata) {
  188. const grid = this.refGrid.current;
  189. if (!grid) {
  190. return;
  191. }
  192. const widthChange = e.clientX - metadata.cursorX;
  193. const nextColumnOrder = [...this.props.columnOrder];
  194. nextColumnOrder[metadata.columnIndex] = {
  195. ...nextColumnOrder[metadata.columnIndex],
  196. width: Math.max(metadata.columnWidth + widthChange, 0),
  197. };
  198. this.setGridTemplateColumns(nextColumnOrder);
  199. }
  200. /**
  201. * Recalculate the dimensions of Grid and Columns and redraws them
  202. */
  203. redrawGridColumn = () => {
  204. this.setGridTemplateColumns(this.props.columnOrder);
  205. };
  206. /**
  207. * Set the CSS for Grid Column
  208. */
  209. setGridTemplateColumns(columnOrder: GridColumnOrder[]) {
  210. const grid = this.refGrid.current;
  211. if (!grid) {
  212. return;
  213. }
  214. const prependColumns = this.props.grid.prependColumnWidths || [];
  215. const prepend = prependColumns.join(' ');
  216. const widths = columnOrder.map((item, index) => {
  217. if (item.width === COL_WIDTH_UNDEFINED) {
  218. return `minmax(${COL_WIDTH_MINIMUM}px, auto)`;
  219. } else if (typeof item.width === 'number' && item.width > COL_WIDTH_MINIMUM) {
  220. if (index === columnOrder.length - 1) {
  221. return `minmax(${item.width}px, auto)`;
  222. }
  223. return `${item.width}px`;
  224. }
  225. if (index === columnOrder.length - 1) {
  226. return `minmax(${COL_WIDTH_MINIMUM}px, auto)`;
  227. }
  228. return `${COL_WIDTH_MINIMUM}px`;
  229. });
  230. // The last column has no resizer and should always be a flexible column
  231. // to prevent underflows.
  232. grid.style.gridTemplateColumns = `${prepend} ${widths.join(' ')}`;
  233. }
  234. renderGridHead() {
  235. const {error, isLoading, columnOrder, grid, data} = this.props;
  236. // Ensure that the last column cannot be removed
  237. const numColumn = columnOrder.length;
  238. const prependColumns = grid.renderPrependColumns
  239. ? grid.renderPrependColumns(true)
  240. : [];
  241. return (
  242. <GridRow>
  243. {prependColumns &&
  244. prependColumns.map((item, i) => (
  245. <GridHeadCellStatic key={`prepend-${i}`}>{item}</GridHeadCellStatic>
  246. ))}
  247. {
  248. /* Note that this.onResizeMouseDown assumes GridResizer is nested
  249. 1 levels under GridHeadCell */
  250. columnOrder.map((column, i) => (
  251. <GridHeadCell key={`${i}.${column.key}`} isFirst={i === 0}>
  252. {grid.renderHeadCell ? grid.renderHeadCell(column, i) : column.name}
  253. {i !== numColumn - 1 && (
  254. <GridResizer
  255. dataRows={!error && !isLoading && data ? data.length : 0}
  256. onMouseDown={e => this.onResizeMouseDown(e, i)}
  257. onDoubleClick={e => this.onResetColumnSize(e, i)}
  258. onContextMenu={this.onResizeMouseDown}
  259. />
  260. )}
  261. </GridHeadCell>
  262. ))
  263. }
  264. </GridRow>
  265. );
  266. }
  267. renderGridBody() {
  268. const {data, error, isLoading} = this.props;
  269. if (error) {
  270. return this.renderError();
  271. }
  272. if (isLoading) {
  273. return this.renderLoading();
  274. }
  275. if (!data || data.length === 0) {
  276. return this.renderEmptyData();
  277. }
  278. return data.map(this.renderGridBodyRow);
  279. }
  280. renderGridBodyRow = (dataRow: DataRow, row: number) => {
  281. const {columnOrder, grid} = this.props;
  282. const prependColumns = grid.renderPrependColumns
  283. ? grid.renderPrependColumns(false, dataRow, row)
  284. : [];
  285. return (
  286. <GridRow key={row}>
  287. {prependColumns &&
  288. prependColumns.map((item, i) => (
  289. <GridBodyCell key={`prepend-${i}`}>{item}</GridBodyCell>
  290. ))}
  291. {columnOrder.map((col, i) => (
  292. <GridBodyCell key={`${col.key}${i}`}>
  293. {grid.renderBodyCell
  294. ? grid.renderBodyCell(col, dataRow, row, i)
  295. : dataRow[col.key]}
  296. </GridBodyCell>
  297. ))}
  298. </GridRow>
  299. );
  300. };
  301. renderError() {
  302. return (
  303. <GridRow>
  304. <GridBodyCellStatus>
  305. <IconWarning color="gray300" size="lg" />
  306. </GridBodyCellStatus>
  307. </GridRow>
  308. );
  309. }
  310. renderLoading() {
  311. return (
  312. <GridRow>
  313. <GridBodyCellStatus>
  314. <LoadingIndicator />
  315. </GridBodyCellStatus>
  316. </GridRow>
  317. );
  318. }
  319. renderEmptyData() {
  320. return (
  321. <GridRow>
  322. <GridBodyCellStatus>
  323. <EmptyStateWarning>
  324. <p>{t('No results found for your query')}</p>
  325. </EmptyStateWarning>
  326. </GridBodyCellStatus>
  327. </GridRow>
  328. );
  329. }
  330. render() {
  331. const {title, headerButtons} = this.props;
  332. const showHeader = title || headerButtons;
  333. return (
  334. <React.Fragment>
  335. {showHeader && (
  336. <Header>
  337. {title && <HeaderTitle>{title}</HeaderTitle>}
  338. {headerButtons && (
  339. <HeaderButtonContainer>{headerButtons()}</HeaderButtonContainer>
  340. )}
  341. </Header>
  342. )}
  343. <Body>
  344. <Grid data-test-id="grid-editable" ref={this.refGrid}>
  345. <GridHead>{this.renderGridHead()}</GridHead>
  346. <GridBody>{this.renderGridBody()}</GridBody>
  347. </Grid>
  348. </Body>
  349. </React.Fragment>
  350. );
  351. }
  352. }
  353. export default GridEditable;
  354. export {
  355. COL_WIDTH_MINIMUM,
  356. COL_WIDTH_UNDEFINED,
  357. GridColumn,
  358. GridColumnHeader,
  359. GridColumnOrder,
  360. GridColumnSortBy,
  361. };