Browse Source

fix Grid pager

Signed-off-by: ryjiang <jiangruiyi@gmail.com>
ryjiang 1 year ago
parent
commit
32408bbbae

+ 41 - 7
client/src/components/grid/Grid.tsx

@@ -1,5 +1,4 @@
-import { FC, MouseEvent } from 'react';
-import React from 'react';
+import { FC, MouseEvent, useRef, useEffect, useState } from 'react';
 import { makeStyles } from '@material-ui/core/styles';
 import Grid from '@material-ui/core/Grid';
 import Breadcrumbs from '@material-ui/core/Breadcrumbs';
@@ -93,6 +92,8 @@ const userStyle = makeStyles(theme => ({
  */
 const AttuGrid: FC<AttuGridType> = props => {
   const classes = userStyle();
+  const tableRef = useRef<HTMLDivElement | null>(null);
+  const [loadingRowCount, setLoadingRowCount] = useState<number>(0);
 
   // i18n
   const { t: commonTrans } = useTranslation();
@@ -176,10 +177,47 @@ const AttuGrid: FC<AttuGridType> = props => {
       </>
     );
   };
+
+  const calculateRowCountAndPageSize = () => {
+    if (tableRef.current && rowHeight > 0) {
+      const containerHeight: number = tableRef.current.offsetHeight;
+
+      const rowCount = Math.floor(
+        (containerHeight -
+          tableHeaderHeight -
+          (showPagination ? pagerHeight : 0)) /
+          rowHeight
+      );
+
+      // console.log('calc', tableRef.current.offsetHeight);
+      // console.log(rowCount, containerHeight, tableHeaderHeight);
+      setLoadingRowCount(rowCount);
+
+      if (setRowsPerPage) {
+        setRowsPerPage(rowCount);
+      }
+    }
+  };
+
+  useEffect(() => {
+    const timer = setTimeout(() => {
+      calculateRowCountAndPageSize();
+    }, 0);
+    // Add event listener for window resize
+    window.addEventListener('resize', calculateRowCountAndPageSize);
+
+    // Clean up event listener on unmount
+    return () => {
+      window.removeEventListener('resize', calculateRowCountAndPageSize);
+      clearTimeout(timer);
+    };
+  }, [tableHeaderHeight, rowHeight, setRowsPerPage]);
+
   return (
     <Grid
       container
       classes={{ root: classes.wrapper, container: classes.container }}
+      ref={tableRef}
     >
       {title && (
         <Grid item xs={12} className={classes.tableTitle}>
@@ -213,6 +251,7 @@ const AttuGrid: FC<AttuGridType> = props => {
 
       <Grid item xs={12} className={classes.noBottomPadding}>
         <Table
+          loadingRowCount={loadingRowCount}
           openCheckBox={openCheckBox}
           primaryKey={primaryKey}
           rows={rows}
@@ -225,17 +264,12 @@ const AttuGrid: FC<AttuGridType> = props => {
           noData={noData}
           showHoverStyle={showHoverStyle}
           isLoading={isLoading}
-          setPageSize={setRowsPerPage}
           headEditable={headEditable}
           editHeads={editHeads}
           tableCellMaxWidth={tableCellMaxWidth}
           handleSort={handleSort}
           order={order}
           orderBy={orderBy}
-          tableHeaderHeight={tableHeaderHeight}
-          rowHeight={rowHeight}
-          showPagination={showPagination}
-          pagerHeight={pagerHeight}
         ></Table>
         {rowCount && showPagination ? (
           <TablePagination

+ 4 - 44
client/src/components/grid/Table.tsx

@@ -1,4 +1,4 @@
-import { FC, useEffect, useRef, useState } from 'react';
+import { FC, forwardRef } from 'react';
 import { makeStyles } from '@material-ui/core/styles';
 import Table from '@material-ui/core/Table';
 import TableBody from '@material-ui/core/TableBody';
@@ -106,7 +106,7 @@ const useStyles = makeStyles(theme => ({
 }));
 
 const EnhancedTable: FC<TableType> = props => {
-  const {
+  let {
     selected,
     onSelected,
     isSelected,
@@ -123,7 +123,6 @@ const EnhancedTable: FC<TableType> = props => {
     // set true as default
     showHoverStyle = true,
     isLoading,
-    setPageSize,
     headEditable = false,
     // editable heads required param, contains heads components and its value
     editHeads = [],
@@ -132,53 +131,14 @@ const EnhancedTable: FC<TableType> = props => {
     handleSort,
     order,
     orderBy,
-    tableHeaderHeight,
-    rowHeight,
-    showPagination,
-    pagerHeight,
+    loadingRowCount,
   } = props;
   const classes = useStyles({ tableCellMaxWidth });
-  const [loadingRowCount, setLoadingRowCount] = useState<number>(0);
-  const containerRef = useRef<HTMLDivElement | null>(null);
   const { t: commonTrans } = useTranslation();
   const copyTrans = commonTrans('copy');
 
-  const calculateRowCountAndPageSize = () => {
-    if (containerRef.current && rowHeight > 0) {
-      const containerHeight: number = containerRef.current.offsetHeight;
-      const rowCount = Math.ceil(
-        (containerHeight -
-          tableHeaderHeight -
-          (showPagination ? pagerHeight : 0)) /
-          rowHeight
-      );
-      // console.log(rowCount, containerHeight, tableHeaderHeight);
-      setLoadingRowCount(rowCount);
-
-      if (setPageSize) {
-        setPageSize(rowCount);
-      }
-    }
-  };
-
-  useEffect(() => {
-    calculateRowCountAndPageSize();
-    // Add event listener for window resize
-    window.addEventListener('resize', calculateRowCountAndPageSize);
-
-    // Clean up event listener on unmount
-    return () => {
-      window.removeEventListener('resize', calculateRowCountAndPageSize);
-    };
-  }, [tableHeaderHeight, rowHeight, setPageSize]);
-
   return (
-    <TableContainer
-      ref={el => {
-        containerRef.current = el;
-      }}
-      className={classes.root}
-    >
+    <TableContainer className={classes.root}>
       <Box height="100%" className={classes.box}>
         <Table
           stickyHeader

+ 3 - 6
client/src/components/grid/Types.ts

@@ -1,4 +1,4 @@
-import React, { ReactElement } from 'react';
+import React, { ReactElement, Ref } from 'react';
 import { LabelDisplayedRowsArgs } from '@material-ui/core';
 import { IconsType } from '../icons/Types';
 import { SearchType } from '../customInput/Types';
@@ -84,7 +84,6 @@ export type TableType = {
   noData?: string;
   showHoverStyle?: boolean;
   isLoading?: boolean;
-  setPageSize?: (size: number) => void;
   headEditable?: boolean;
   editHeads: EditableHeads[];
   // with unit like '20px'
@@ -92,10 +91,8 @@ export type TableType = {
   handleSort?: (e: any, orderBy: string) => void;
   order?: SortDirection;
   orderBy?: string;
-  tableHeaderHeight: number;
-  rowHeight: number;
-  showPagination: boolean;
-  pagerHeight: number
+  loadingRowCount: number;
+  ref?: Ref<HTMLDivElement>;
 };
 
 export type ColDefinitionsType = {

+ 1 - 1
client/src/hooks/Query.ts

@@ -165,7 +165,7 @@ export const useQuery = (params: {
   // query if expr is changed
   useEffect(() => {
     if (!collection.primaryKey.value || !collection.loaded) {
-      console.info('[skip running query]: no key yet');
+      // console.info('[skip running query]: no key yet');
       return;
     } // reset
     reset();

+ 1 - 1
client/src/i18n/en/search.ts

@@ -15,7 +15,7 @@ const searchTrans = {
   timeTravel: 'Time Travel',
   timeTravelPrefix: 'Data before',
   dynamicFields: 'Dynamic Fields',
-  collectionNotLoaded: 'Collection not loaded',
+  collectionNotLoaded: 'Please load the collection first.',
 };
 
 export default searchTrans;

+ 28 - 37
client/src/pages/query/Query.tsx

@@ -6,7 +6,6 @@ import { rootContext } from '@/context';
 import { DataService } from '@/http';
 import { useQuery, useSearchResult } from '@/hooks';
 import { saveCsvAs } from '@/utils';
-import EmptyCard from '@/components/cards/EmptyCard';
 import icons from '@/components/icons/Icons';
 import CustomButton from '@/components/customButton/CustomButton';
 import AttuGrid from '@/components/grid/Grid';
@@ -38,7 +37,6 @@ const Query = () => {
   const { setDialog, handleCloseDialog, openSnackBar } =
     useContext(rootContext);
   // icons
-  const VectorSearchIcon = icons.vectorSearch;
   const ResetIcon = icons.refresh;
   // translations
   const { t: dialogTrans } = useTranslation('dialog');
@@ -364,41 +362,34 @@ const Query = () => {
           </CustomButton>
         </div>
       </div>
-      {tableLoading || queryResultMemo?.length ? (
-        <AttuGrid
-          toolbarConfigs={[]}
-          colDefinitions={collection.fields.map((i: any) => ({
-            id: i.name,
-            align: 'left',
-            disablePadding: false,
-            needCopy: true,
-            label:
-              i.name === DYNAMIC_FIELD ? searchTrans('dynamicFields') : i.name,
-          }))}
-          primaryKey={collection.primaryKey.value}
-          openCheckBox={true}
-          isLoading={!!tableLoading}
-          rows={queryResultMemo}
-          rowCount={total}
-          selected={selectedData}
-          setSelected={onSelectChange}
-          page={currentPage}
-          onPageChange={handlePageChange}
-          setRowsPerPage={setPageSize}
-          rowsPerPage={pageSize}
-          labelDisplayedRows={getLabelDisplayedRows(
-            `(${queryResult.latency || ''} ms)`
-          )}
-        />
-      ) : (
-        <EmptyCard
-          wrapperClass={`page-empty-card ${classes.emptyCard}`}
-          icon={<VectorSearchIcon />}
-          text={searchTrans(
-            `${collection.loaded ? 'empty' : 'collectionNotLoaded'}`
-          )}
-        />
-      )}
+      <AttuGrid
+        toolbarConfigs={[]}
+        colDefinitions={collection.fields.map((i: any) => ({
+          id: i.name,
+          align: 'left',
+          disablePadding: false,
+          needCopy: true,
+          label:
+            i.name === DYNAMIC_FIELD ? searchTrans('dynamicFields') : i.name,
+        }))}
+        primaryKey={collection.primaryKey.value}
+        openCheckBox={true}
+        isLoading={!!tableLoading}
+        rows={queryResultMemo}
+        rowCount={total}
+        selected={selectedData}
+        setSelected={onSelectChange}
+        page={currentPage}
+        onPageChange={handlePageChange}
+        setRowsPerPage={setPageSize}
+        rowsPerPage={pageSize}
+        labelDisplayedRows={getLabelDisplayedRows(
+          `(${queryResult.latency || ''} ms)`
+        )}
+        noData={searchTrans(
+          `${collection.loaded ? 'empty' : 'collectionNotLoaded'}`
+        )}
+      />
     </div>
   );
 };