Grid.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import { FC, MouseEvent, useRef, useEffect, useState } from 'react';
  2. import { makeStyles } from '@material-ui/core/styles';
  3. import Grid from '@material-ui/core/Grid';
  4. import Breadcrumbs from '@material-ui/core/Breadcrumbs';
  5. import TablePagination from '@material-ui/core/TablePagination';
  6. import Typography from '@material-ui/core/Typography';
  7. import CustomToolbar from './ToolBar';
  8. import Table from './Table';
  9. import { AttuGridType } from './Types';
  10. import { useTranslation } from 'react-i18next';
  11. import TablePaginationActions from './TablePaginationActions';
  12. const userStyle = makeStyles(theme => ({
  13. loading: {
  14. height: '100%',
  15. display: 'flex',
  16. alignItems: 'center',
  17. justifyContent: 'center',
  18. padding: theme.spacing(20),
  19. width: '100%',
  20. },
  21. tableTitle: {
  22. '& .last': {
  23. color: 'rgba(0, 0, 0, 0.54)',
  24. },
  25. },
  26. noData: {
  27. pointerEvents: 'none',
  28. color: '#999',
  29. textAlign: 'center',
  30. height: '50vh',
  31. display: 'grid',
  32. justifyContent: 'center',
  33. alignContent: 'center',
  34. fontSize: '32px',
  35. },
  36. pagenation: {
  37. '& .MuiTablePagination-caption': {
  38. position: 'absolute',
  39. left: 0,
  40. bottom: 0,
  41. top: 0,
  42. display: 'flex',
  43. alignItems: 'center',
  44. '& .rows': {
  45. color: 'rgba(0,0,0,0.33)',
  46. marginLeft: theme.spacing(1),
  47. },
  48. },
  49. },
  50. noBottomPadding: {
  51. paddingBottom: '0 !important',
  52. display: 'flex',
  53. flexDirection: 'column',
  54. },
  55. wrapper: {
  56. height: '100%',
  57. },
  58. container: {
  59. flexWrap: 'nowrap',
  60. flexDirection: 'column',
  61. },
  62. }));
  63. /**
  64. *
  65. * @param rowCount required. totoal data count for pagination
  66. * @param rowsPerPage per page for pagination, default is 10
  67. * @param primaryKey required. The unique column for your data. use for checkbox and render key.
  68. * @param onPageChange handle page change
  69. * @param labelDisplayedRows Custom pagination label function, return string;
  70. * @param page current page for pagination
  71. * @param showToolbar control toolbar display. default is false
  72. * @param rows table data you want to render
  73. * @param colDefinitions Define how to render table heder.
  74. * @param isLoading table loading status
  75. * @param title Render breadcrumbs
  76. * @param openCheckBox control checkbox display. default is true
  77. * @param disableSelect disable table row select. default false
  78. * @param noData when table is empty, what tip we need to show.
  79. * @param showHoverStyle control table row hover style display
  80. * @param headEditable if true, user can edit header.
  81. * @param editHeads Only headEditable is true will render editHeads
  82. * @param tableCellMaxWidth Define table cell max width, default is 300
  83. * @param handlesort how to sort table, if it's undefined, then you can not sort table
  84. * @param order 'desc' | 'asc'. sort direction
  85. * @param order order by which table field
  86. * @returns
  87. */
  88. const AttuGrid: FC<AttuGridType> = props => {
  89. const classes = userStyle();
  90. const tableRef = useRef<HTMLDivElement | null>(null);
  91. const [loadingRowCount, setLoadingRowCount] = useState<number>(0);
  92. // i18n
  93. const { t: commonTrans } = useTranslation();
  94. const gridTrans = commonTrans('grid');
  95. const {
  96. rowCount = 20,
  97. rowsPerPage = 10,
  98. tableHeaderHeight = 46,
  99. rowHeight = 43,
  100. pagerHeight = 52,
  101. primaryKey = 'id',
  102. showToolbar = false,
  103. toolbarConfigs = [],
  104. onPageChange = (
  105. e: MouseEvent<HTMLButtonElement> | null,
  106. nextPageNum: number
  107. ) => {
  108. console.log('nextPageNum', nextPageNum);
  109. },
  110. labelDisplayedRows,
  111. page = 0,
  112. rows = [],
  113. colDefinitions = [],
  114. isLoading = false,
  115. title,
  116. openCheckBox = true,
  117. disableSelect = false,
  118. noData = gridTrans.noData,
  119. showHoverStyle = true,
  120. headEditable = false,
  121. editHeads = [],
  122. selected = [],
  123. setSelected = () => {},
  124. setRowsPerPage = () => {},
  125. tableCellMaxWidth,
  126. handleSort,
  127. order,
  128. orderBy,
  129. showPagination = true,
  130. hideOnDisable,
  131. } = props;
  132. const _isSelected = (row: { [x: string]: any }) => {
  133. // console.log("row selected test", row[primaryKey]);
  134. return selected.some((s: any) => s[primaryKey] === row[primaryKey]);
  135. };
  136. const _onSelected = (event: React.MouseEvent, row: { [x: string]: any }) => {
  137. if (disableSelect) {
  138. return;
  139. }
  140. let newSelected: any[] = ([] as any[]).concat(selected);
  141. if (_isSelected(row)) {
  142. newSelected = newSelected.filter(s => s[primaryKey] !== row[primaryKey]);
  143. } else {
  144. newSelected.push(row);
  145. }
  146. setSelected(newSelected);
  147. };
  148. const _onSelectedAll = (event: React.ChangeEvent) => {
  149. if ((event.target as HTMLInputElement).checked) {
  150. const newSelecteds = rows;
  151. setSelected(newSelecteds);
  152. return;
  153. }
  154. setSelected([]);
  155. };
  156. const defaultLabelRows = ({ from = 0, to = 0, count = 0 }) => {
  157. return (
  158. <>
  159. <Typography variant="body2" component="span">
  160. {from} - {to}
  161. </Typography>
  162. <Typography variant="body2" className="rows" component="span">
  163. {gridTrans.of} {count} {gridTrans.rows}
  164. </Typography>
  165. </>
  166. );
  167. };
  168. const calculateRowCountAndPageSize = () => {
  169. if (tableRef.current && rowHeight > 0) {
  170. const containerHeight: number = tableRef.current.offsetHeight;
  171. const hasToolbar = toolbarConfigs.length > 0;
  172. const totleHeight =
  173. containerHeight -
  174. tableHeaderHeight -
  175. (showPagination ? pagerHeight : 0) -
  176. (hasToolbar ? 34 : 0);
  177. const rowCount = Math.floor(totleHeight / rowHeight);
  178. if (setRowsPerPage) {
  179. setRowsPerPage(rowCount);
  180. }
  181. }
  182. };
  183. useEffect(() => {
  184. const timer = setTimeout(() => {
  185. calculateRowCountAndPageSize();
  186. }, 0);
  187. // Add event listener for window resize
  188. window.addEventListener('resize', calculateRowCountAndPageSize);
  189. // Clean up event listener on unmount
  190. return () => {
  191. window.removeEventListener('resize', calculateRowCountAndPageSize);
  192. clearTimeout(timer);
  193. };
  194. }, [tableHeaderHeight, rowHeight, setRowsPerPage]);
  195. return (
  196. <Grid
  197. container
  198. classes={{ root: classes.wrapper, container: classes.container }}
  199. ref={tableRef}
  200. >
  201. {title && (
  202. <Grid item xs={12} className={classes.tableTitle}>
  203. <Breadcrumbs separator="›" aria-label="breadcrumb" role="breadcrumb">
  204. {title.map(
  205. (v: any, i: number) =>
  206. v && (
  207. <Typography
  208. key={v}
  209. className={i === title.length - 1 ? 'last' : ''}
  210. variant="h6"
  211. color="textPrimary"
  212. >
  213. {v}
  214. </Typography>
  215. )
  216. )}
  217. </Breadcrumbs>
  218. </Grid>
  219. )}
  220. {(showToolbar || toolbarConfigs.length > 0) && (
  221. <Grid item>
  222. <CustomToolbar
  223. toolbarConfigs={toolbarConfigs}
  224. selected={selected}
  225. hideOnDisable={hideOnDisable}
  226. ></CustomToolbar>
  227. </Grid>
  228. )}
  229. <Grid item xs={12} className={classes.noBottomPadding}>
  230. <Table
  231. loadingRowCount={loadingRowCount}
  232. openCheckBox={openCheckBox}
  233. primaryKey={primaryKey}
  234. rows={rows}
  235. selected={selected}
  236. colDefinitions={colDefinitions}
  237. onSelectedAll={_onSelectedAll}
  238. onSelected={_onSelected}
  239. isSelected={_isSelected}
  240. disableSelect={disableSelect}
  241. noData={noData}
  242. showHoverStyle={showHoverStyle}
  243. isLoading={isLoading}
  244. headEditable={headEditable}
  245. editHeads={editHeads}
  246. tableCellMaxWidth={tableCellMaxWidth}
  247. handleSort={handleSort}
  248. order={order}
  249. orderBy={orderBy}
  250. ></Table>
  251. {rowCount && showPagination ? (
  252. <TablePagination
  253. component="div"
  254. colSpan={3}
  255. count={rowCount}
  256. page={page}
  257. labelDisplayedRows={labelDisplayedRows || defaultLabelRows}
  258. rowsPerPage={rowsPerPage}
  259. rowsPerPageOptions={[]}
  260. onPageChange={onPageChange}
  261. className={classes.pagenation}
  262. ActionsComponent={TablePaginationActions}
  263. />
  264. ) : null}
  265. </Grid>
  266. </Grid>
  267. );
  268. };
  269. export default AttuGrid;