import React from 'react' ; import { Table , TableBody , TableCell , TableContainer , TableHead , TableRow , TablePagination , } from '@material-ui/core' ; import styled from 'styled-components' ; import { QueryData } from '../../../types' ; import { greyPrimary , DarkPaperFull } from '../../../style-variables' ; const StyledCell = styled ( TableCell ) `
  border-bottom: 1px solid ${ greyPrimary };
` ; interface Column { name : string ; align : 'left' | 'right' ; } const isNumber = ( val ) => { if ( typeof val === 'number' ) return true ; const numberRgx = /^-?[0-9.]+$/ ; if ( numberRgx . test ( val as string ) ) return true ; return false ; } ; const buildColumns = ( row ) : Column [ ] => Object . entries ( row ) . map ( ( [ column , value ] ) => ( { name : column , align : isNumber ( value ) ? 'right' : 'left' , } ) ) ; interface QueryResultsProps { results : QueryData [ 'returnedRows' ] ; } const QueryResults = ( { results } ) => { if ( ! results || ! results . length ) return null ; const [ page , setPage ] = React . useState ( 0 ) ; const rowsPerPage = 10 ; if ( page * rowsPerPage > results . length ) setPage ( 0 ) ; const columns = buildColumns ( results [ 0 ] ) ; const handleChangePage = ( event , newPage ) => { setPage ( newPage ) ; } ; return ( < DarkPaperFull > < TableContainer > < Table > < TableHead > < TableRow > { columns . map ( ( column ) => ( < TableCell key = { column . name } align = { column . align } > < strong > { column . name } < /strong> < /TableCell>))} < /TableRow> < /TableHead> < TableBody > { results . slice ( page * rowsPerPage , page * rowsPerPage + rowsPerPage ) . map ( ( row ) => ( < TableRow hover role = "checkbox" tabIndex = { - 1 } key = { Object . values ( row ) . join ( ) } > { columns . map ( ( column ) => ( < StyledCell align = { column . align } key = { `${ column . name }_${ row [ column . name ] }` } > { ( row [ column . name ] as any ) ?. toString ( ) } < /StyledCell>))} < /TableRow>))} < /TableBody> < /Table> < /TableContainer> < TablePagination rowsPerPageOptions = { [ 10 ] } component = "div" count = { results . length } rowsPerPage = { rowsPerPage } page = { page } onChangePage = { handleChangePage } / > < /DarkPaperFull>); } ; export default QueryResults ;