All files / src/components/common/Table Table_rebranded.tsx

79.62% Statements 43/54
58.02% Branches 94/162
84.61% Functions 11/13
83.67% Lines 41/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495                                                                4x   4x                                                                                 3x 3x           3x                                       3x                                                           3x 3x 3x       3x 6x     3x       3x 1x         1x                         3x 1x 1x       3x                               3x                                                                                                                                                                                       18x 18x 18x 18x 18x   18x                                                   18x 18x 18x       18x 18x                                                                                                                                                               4x                             3x         6x 3x     3x                                                                     4x 76x 18x                               4x             3x                        
import {
  Box,
  Table as MuiTable,
  TableRow as MuiTableRow,
  Stack,
  TableCell,
  TableHead,
  styled,
} from "@mui/material";
import TableContainer from "@mui/material/TableContainer";
import { palette } from "@palette";
import React, { useCallback, useEffect, useRef } from "react";
// components
import { Text } from "@common/Text";
import Pagination from "../pagination";
// helpers
import { TableProps } from "./helpers";
// redux
import ErrorCatcher from "@common/Error/ErrorCatcher";
import ExportFilterButtons from "@shared/GiveExportModal/components/ExportFilterButtons";
import { SearchBar } from "@common/SearchBar_V2";
import { useModal } from "@ebay/nice-modal-react";
import { ROWS_PER_PAGE } from "@hooks/common/usePagination";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import { TRANSACTION_INFO_MODAL } from "modals/modal_names";
import { useSelector } from "react-redux";
import { SortComponent } from "./components/SortComponent";
import TableBody from "./components/TableBody";
import { useIterator } from "./hooks";
import { useTableSort } from "./hooks/useTableSort";
import MarkAllCheckBox from "./MarkAllCheckBox";
 
export const currencyColumns = new Set(["Amount", "Total Processed"]);
 
const Table: React.FC<TableProps> = ({
  columns,
  expandable,
  small = false,
  data,
  maxHeight,
  rowHeight,
  renderExpandedRow,
  iconButton,
  selectable,
  disabled,
  isLoading,
  setSorting,
  tableTitle,
  searchBar,
  queryKey,
  withBackground = true,
  filters,
  tabs,
  initialSortingProperty = "id",
  downloadButton,
  rowRenderKey,
  onOpenSidePanel,
  page,
  numberOfPages,
  BodyRowStyle,
  openedModal = TRANSACTION_INFO_MODAL,
  itemsPerPage,
  isFetching = false,
  handleRowClick,
  emptyState,
  lastItemRef,
  hideTableView = false, //all hideTableView checks can be removed once we implement table views accross all platform
  showExportFilterBtns = true,
  leftSideSearchBar,
  totalRecords,
  defaultSort,
  hideLeftSideFilter = false,
  canBeSelected = true,
  ...props
}) => {
  const { isDesktopView } = useCustomTheme();
  const { handleOpenMenu, orderBy, sortKey, order } = useTableSort({
    small,
    setSorting,
    initialSortingProperty,
    defaultSort,
  });
  const boxStyle = {
    width: "100%",
    display: "flex",
    flexDirection: "column",
    marginBottom: isDesktopView ? 0 : "40px",
    gap: "16px",
    flexGrow: 1,
    borderImageSource:
      "linear-gradient(267.62deg, rgba(214, 217, 243, 0.46) 8.2%, rgba(255, 255, 255, 0.46) 82.68%)",
    "& th": {
      borderBottom: "none",
      padding: small ? "8px 16px" : "10px 16px",
    },
    boxShadow: "none",
    ...(!small && {
      padding: withBackground ? "56px 0" : "0",
      borderRadius: withBackground ? "50px" : "54px",
    }),
  };
 
  const containerStyle = {
    display: "flex",
    flexDirection: "row",
    alignItems: "stretch",
    background: "transparent",
    overflow: "visible",
    ...(small && {
      mb: 2.5,
      padding: "0 4px 4px",
    }),
    ...(maxHeight && {
      maxHeight: maxHeight,
    }),
 
    ...(disabled && {
      position: "relative",
 
      "&::after": {
        content: '""',
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        background: "#f8f8f8",
        zIndex: 1000,
        opacity: 0.5,
      },
    }),
  };
  const modal = useModal(openedModal);
  const reOpening = useRef(false);
  const setReopening = (val: boolean) => {
    reOpening.current = val;
  };
 
  const hideTableFilter = useSelector<any, boolean>(
    (state: any) => state.app.hideTableFilter,
  );
 
  const { onIterator, selectedRowIdx, setSelectedRowIdx } = useIterator({
    dataLen: data.length,
  });
 
  useEffect(() => {
    Iif (isLoading && modal.visible) {
      onOpenSidePanel({});
      return;
    }
 
    Iif (onOpenSidePanel && data[selectedRowIdx]) {
      onOpenSidePanel({
        setReopening,
        rowData: data[selectedRowIdx],
        id: data[selectedRowIdx]?.accID,
        setSelectedRow: onIterator,
        isFirst: data[selectedRowIdx - 1] === undefined && page === 1,
        isLast:
          data[selectedRowIdx + 1] === undefined && page === numberOfPages,
      });
    }
  }, [selectedRowIdx, isLoading]);
 
  useEffect(() => {
    Eif (!modal.visible && !reOpening.current) {
      setSelectedRowIdx(-1);
    }
  }, [modal.visible]);
 
  const onClickRow = useCallback(
    (itemRow: any, idx: number) => {
      if (onOpenSidePanel) {
        onOpenSidePanel({
          setReopening,
          rowData: itemRow,
          setSelectedRow: onIterator,
          isFirst: idx === 0 && page === 1,
          isLast: data[idx + 1] === undefined && page === numberOfPages,
        });
        setSelectedRowIdx(idx);
      }
    },
    [page, data, numberOfPages],
  );
 
  return (
    <Box className="table-container" sx={boxStyle}>
      {tabs && (
        <Box mb="12px" sx={{ width: "100%" }}>
          {tabs}
        </Box>
      )}
      {(tableTitle || searchBar || queryKey || downloadButton) && (
        <Box
          pl={tabs ? "12px" : "0px"}
          flexDirection={{
            xs: "column-reverse",
            sm: "row",
          }}
          display="flex"
          alignItems={{ xs: "flex-start", sm: "center" }}
          gap={{ xs: "16px", sm: 0 }}
          justifyContent="space-between"
        >
          {filters && (
            <Box
              sx={{
                width: hideTableView ? "100%" : undefined,
              }}
            >
              {filters}
            </Box>
          )}
          {!hideLeftSideFilter && (
            <Stack
              direction="row"
              alignItems="center"
              gap="8px"
              justifyContent={
                leftSideSearchBar && isDesktopView
                  ? "space-between"
                  : hideTableView || hideTableFilter
                  ? "flex-end"
                  : "space-between"
              }
              sx={{
                marginLeft:
                  hideTableView || hideTableFilter
                    ? { xs: 0, sm: "auto" }
                    : "undefined",
 
                width:
                  leftSideSearchBar && isDesktopView
                    ? "100%"
                    : hideTableView || hideTableFilter
                    ? { xs: "100%", sm: "undefined" }
                    : "auto",
              }}
            >
              {searchBar
                ? searchBar
                : queryKey && <SearchBar queryKey={queryKey} />}
              <SearchContainer
                containChildren={Boolean(leftSideSearchBar && isDesktopView)}
              >
                {tableTitle && // remove this check when implement export view for all tables
                  ["Merchants", "Merchants list"].includes(tableTitle) &&
                  showExportFilterBtns && (
                    <ExportFilterButtons
                      hideTableView={hideTableView || hideTableFilter}
                      totalRows={
                        props.totalExportRecords
                          ? props.totalExportRecords
                          : totalRecords || 0
                      }
                      totalFilteredRows={totalRecords}
                    />
                  )}
                {downloadButton}
              </SearchContainer>
            </Stack>
          )}
        </Box>
      )}
      <TableContainer sx={containerStyle}>
        <MuiTable
          sx={{
            ...props.sx,
            borderCollapse: "separate",
            borderRadius: "8px",
            tableLayout: "fixed",
          }}
          {...props}
        >
          {!small && (
            <colgroup>
              {columns.map((column, index) => {
                Iif (column?.hideColumn) return null;
                const length = columns.length + 1;
                let columnWidth = 1 / length;
                if (index === 0) columnWidth = 2.2 / length;
                Iif (column.key === "actions") columnWidth = 0.8 / length;
 
                return (
                  <col
                    key={column.key}
                    style={{
                      width:
                        typeof column.columnWidth !== "number"
                          ? column.columnWidth
                          : `${
                              ((column.columnWidth ?? 0) / length ||
                                columnWidth) * 100
                            }%`,
                    }}
                  />
                );
              })}
            </colgroup>
          )}
          <TableHead
            sx={{
              "& th": {
                padding: "8px 8px",
              },
            }}
          >
            <MuiTableRow>
              {columns.map((column, index) => {
                Iif (column?.hideColumn) return null;
                const isCurrencyColumn = currencyColumns.has(column.title);
                const title = isCurrencyColumn
                  ? `${column.title} (USD)`
                  : column.title;
 
                Eif (column.title) {
                  return (
                    <TableCell
                      component="th"
                      key={`head-${column.key}`}
                      className={`tableHeader-${column.key}`}
                      sortDirection={orderBy === column.key ? order : false}
                      sx={column.sx}
                    >
                      <TableHeadContainer
                        onClick={
                          column.sortable ? handleOpenMenu(column) : undefined
                        }
                        isSortable={column.sortable}
                        sx={{
                          justifyContent:
                            column?.headerPosition === "right"
                              ? "flex-end"
                              : column?.headerPosition === "center"
                              ? "center"
                              : "flex-start",
                        }}
                      >
                        {index === 0 && selectable && <MarkAllCheckBox />}
                        <Text noWrap color={palette.neutral.black}>
                          {title}
                        </Text>
                        {column.sortable && (
                          <SortComponent
                            sortedCol={sortKey === column.key}
                            order={order}
                            sortKey={column.key}
                          />
                        )}
                      </TableHeadContainer>
                    </TableCell>
                  );
                }
                return <TableCell component="th" key={`head-${column.key}`} />;
              })}
            </MuiTableRow>
          </TableHead>
 
          <TableBody
            data={data}
            page={page}
            columns={columns}
            isLoading={isLoading}
            isFetching={isFetching}
            queryKey={queryKey}
            renderExpandedRow={renderExpandedRow}
            rowHeight={rowHeight}
            expandable={expandable}
            small={small}
            iconButton={iconButton}
            rowRenderKey={rowRenderKey}
            selectable={selectable}
            BodyRowStyle={BodyRowStyle}
            selectedRowIdx={selectedRowIdx}
            itemsPerPage={itemsPerPage}
            onClickRow={handleRowClick || onClickRow}
            emptyState={emptyState}
            canBeSelected={canBeSelected}
          />
          {data?.length && !isDesktopView && lastItemRef ? (
            <div
              ref={lastItemRef}
              style={{
                width: 1,
                height: "100%",
                paddingBottom: 5,
                visibility: "hidden",
              }}
            ></div>
          ) : null}
        </MuiTable>
      </TableContainer>
    </Box>
  );
};
 
export const Table_V2 = ({
  data,
  handlePageChange,
  withPagination,
  hasPaginationWhenEmpty = true,
  page = 1,
  totalRecords,
  noTrailing,
  currentRowsPerPage = ROWS_PER_PAGE,
  downloadButton,
  alwaysShowDownloadBtn,
  emptyBox,
  defaultSort,
  ...rest
}: TableProps) => {
  const numberOfPages = Math.ceil(
    Number(totalRecords ?? 0) / currentRowsPerPage,
  );
 
  const sumPageAmount =
    data?.reduce((acc, v) => acc + (v.totalAmount ?? v.charged), 0) ?? 0;
  const downloadBtn = alwaysShowDownloadBtn
    ? downloadButton
    : data.length > 0 && downloadButton;
  return (
    <>
      <ErrorCatcher errorID="Table">
        <Table
          {...rest}
          defaultSort={defaultSort}
          page={page}
          data={data}
          totalRecords={totalRecords || data?.length}
          numberOfPages={numberOfPages}
          downloadButton={downloadBtn}
          itemsPerPage={currentRowsPerPage}
        />
        {withPagination && hasPaginationWhenEmpty && (
          <Box paddingY="25px" paddingX={0} width="85%" margin="0 auto">
            <Pagination
              page={page}
              onChange={handlePageChange}
              totalRecords={totalRecords || data?.length}
              currentRowsPerPage={data.length}
              noTrailing={noTrailing}
              numberOfPages={numberOfPages}
              sumPageAmount={sumPageAmount}
              emptyBox={emptyBox}
            />
          </Box>
        )}
      </ErrorCatcher>
    </>
  );
};
 
interface TableHeadContainerProps {
  isSortable?: boolean;
}
const TableHeadContainer = styled(Box, {
  shouldForwardProp: (prop) => prop !== "isSortable",
})<TableHeadContainerProps>(({ isSortable }) => ({
  display: "inline-flex",
  alignItems: "center",
  gap: "8px",
  verticalAlign: "middle",
  userSelect: "none",
  padding: "4px 8px",
  width: "100%",
  ...(isSortable && {
    "&:hover": {
      cursor: "pointer",
      borderRadius: "32px",
    },
  }),
}));
 
const SearchContainer = ({
  children,
  containChildren,
}: {
  children: React.ReactNode;
  containChildren: boolean;
}) =>
  containChildren ? (
    <Stack
      direction="row"
      alignItems="center"
      gap="8px"
      justifyContent="flex-end"
    >
      {children}
    </Stack>
  ) : (
    <>{children}</>
  );