"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DataTable = void 0;
var _styled = _interopRequireDefault(require("@emotion/styled"));
var _materialReactTable = require("material-react-table");
var _react = require("react");
var _Box = require("../Box.cjs");
var _Button = require("../Buttons/Button.cjs");
var _MenuButton = require("../Buttons/MenuButton.cjs");
var _Callout = require("../Callout.cjs");
var _EmptyState = require("../EmptyState.cjs");
var _i18n = require("../i18n.generated/i18n.cjs");
var _index = require("../icons.generated/index.cjs");
var _DataFilters = require("../labs/DataFilters.cjs");
var _OdysseyDesignTokensContext = require("../OdysseyDesignTokensContext.cjs");
var _Pagination = require("../Pagination/Pagination.cjs");
var _usePagination = require("../Pagination/usePagination.cjs");
var _constants = require("./constants.cjs");
var _DataTableRowActions = require("./DataTableRowActions.cjs");
var _DataTableSettings = require("./DataTableSettings.cjs");
var _useRowReordering = require("./useRowReordering.cjs");
var _useScrollIndication = require("./useScrollIndication.cjs");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/*!
 * Copyright (c) 2023-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */const ScrollableTableContainer = (0, _styled.default)("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens" && prop !== "isScrollableStart" && prop !== "isScrollableEnd"
})(({
  odysseyDesignTokens,
  isScrollableStart,
  isScrollableEnd
}) => ({
  marginBlockEnd: odysseyDesignTokens.Spacing4,
  position: "relative",
  borderInlineStartColor: isScrollableStart ? odysseyDesignTokens.HueNeutral200 : "transparent",
  borderInlineStartStyle: "solid",
  borderInlineStartWidth: odysseyDesignTokens.BorderWidthMain,
  "::before": {
    background: "linear-gradient(-90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.33) 50%, rgba(0, 0, 0, 1) 100%)",
    content: '""',
    opacity: isScrollableStart ? "0.075" : "0",
    pointerEvents: "none",
    position: "absolute",
    top: 0,
    left: 0,
    bottom: 0,
    width: odysseyDesignTokens.Spacing6,
    zIndex: 100,
    transition: `opacity ${odysseyDesignTokens.TransitionDurationMain} ${odysseyDesignTokens.TransitionTimingMain}`
  },
  borderInlineEndColor: isScrollableEnd ? odysseyDesignTokens.HueNeutral200 : "transparent",
  borderInlineEndStyle: "solid",
  borderInlineEndWidth: odysseyDesignTokens.BorderWidthMain,
  "::after": {
    background: "linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.33) 50%, rgba(0, 0, 0, 1) 100%)",
    content: '""',
    opacity: isScrollableEnd ? "0.075" : "0",
    pointerEvents: "none",
    position: "absolute",
    top: 0,
    right: 0,
    bottom: 0,
    width: odysseyDesignTokens.Spacing6,
    transition: `opacity ${odysseyDesignTokens.TransitionDurationMain} ${odysseyDesignTokens.TransitionTimingMain}`
  }
}));
const defaultGetRowId = row => row.id;
const DataTable = ({
  additionalActionButton,
  additionalActionMenuItems,
  bulkActionMenuItems,
  columns,
  currentPage = 1,
  emptyPlaceholder,
  errorMessage: errorMessageProp,
  filters: filtersProp,
  getData,
  getRowId = defaultGetRowId,
  hasChangeableDensity,
  hasColumnResizing,
  hasColumnVisibility,
  hasFilters,
  hasPagination,
  hasRowReordering,
  hasRowSelection,
  hasSearch,
  hasSearchSubmitButton,
  hasSorting,
  initialDensity = _constants.densityValues[0],
  initialSearchValue = "",
  isPaginationMoreDisabled,
  noResultsPlaceholder,
  onChangeRowSelection,
  onReorderRows,
  paginationType = "paged",
  renderDetailPanel,
  resultsPerPage = 20,
  maxResultsPerPage,
  maxPages,
  rowActionButtons,
  rowActionMenuItems,
  searchDelayTime,
  selectedRows,
  totalRows
}) => {
  const {
    t
  } = (0, _i18n.useTranslation)();
  const [data, setData] = (0, _react.useState)([]);
  const [pagination, setPagination] = (0, _react.useState)({
    pageIndex: currentPage,
    pageSize: resultsPerPage
  });
  const [draggingRow, setDraggingRow] = (0, _react.useState)();
  const [isTableContainerScrolledToStart, setIsTableContainerScrolledToStart] = (0, _react.useState)(true);
  const [isTableContainerScrolledToEnd, setIsTableContainerScrolledToEnd] = (0, _react.useState)(true);
  const [tableInnerContainerWidth, setTableInnerContainerWidth] = (0, _react.useState)("100%");
  const tableOuterContainerRef = (0, _react.useRef)(null);
  const tableInnerContainerRef = (0, _react.useRef)(null);
  const tableContentRef = (0, _react.useRef)(null);
  const [columnSorting, setColumnSorting] = (0, _react.useState)([]);
  const [columnVisibility, setColumnVisibility] = (0, _react.useState)();
  const [rowDensity, setRowDensity] = (0, _react.useState)(initialDensity);
  const [search, setSearch] = (0, _react.useState)(initialSearchValue);
  const [filters, setFilters] = (0, _react.useState)();
  const [initialFilters, setInitialFilters] = (0, _react.useState)();
  const [isLoading, setIsLoading] = (0, _react.useState)(true);
  const [isEmpty, setIsEmpty] = (0, _react.useState)();
  const [errorMessage, setErrorMessage] = (0, _react.useState)(errorMessageProp);
  const [rowSelection, setRowSelection] = (0, _react.useState)(selectedRows ?? {});
  (0, _useScrollIndication.useScrollIndication)({
    tableOuterContainer: tableOuterContainerRef.current,
    tableInnerContainer: tableInnerContainerRef.current,
    setIsTableContainerScrolledToStart: setIsTableContainerScrolledToStart,
    setIsTableContainerScrolledToEnd: setIsTableContainerScrolledToEnd,
    setTableInnerContainerWidth: setTableInnerContainerWidth
  });
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  const {
    dragHandleStyles,
    dragHandleText,
    draggableTableBodyRowClassName,
    handleDragHandleKeyDown,
    handleDragHandleOnDragCapture,
    handleDragHandleOnDragEnd,
    resetDraggingAndHoveredRow,
    updateRowOrder
  } = (0, _useRowReordering.useRowReordering)({
    totalRows,
    onReorderRows,
    data,
    setData,
    draggingRow,
    setDraggingRow,
    resultsPerPage: pagination.pageSize,
    page: pagination.pageIndex
  });
  const rowDensityClassName = (0, _react.useMemo)(() => {
    return rowDensity === "spacious" ? "MuiTableBody-spacious" : rowDensity === "compact" ? "MuiTableBody-compact" : "MuiTableBody-default";
  }, [rowDensity]);
  const renderRowActions = (0, _react.useCallback)(({
    row
  }) => {
    const currentIndex = row.index + (pagination.pageIndex - 1) * pagination.pageSize;
    return (0, _jsxRuntime.jsx)(_DataTableRowActions.DataTableRowActions, {
      row: row,
      rowActionButtons: rowActionButtons,
      rowActionMenuItems: rowActionMenuItems,
      rowIndex: currentIndex,
      totalRows: totalRows,
      updateRowOrder: hasRowReordering && onReorderRows ? updateRowOrder : undefined
    });
  }, [pagination, rowActionButtons, rowActionMenuItems, hasRowReordering, onReorderRows, totalRows, updateRowOrder]);
  const convertFilterSelectOptions = (0, _react.useCallback)(options => options?.map(option => typeof option === "string" ? {
    label: option,
    value: option
  } : {
    label: option.label ?? option.value,
    value: option.value ?? option.label
  }), []);
  const convertColumnToFilter = (0, _react.useCallback)(column => column.enableColumnFilter !== false && column.accessorKey ? {
    id: column.accessorKey,
    label: column.header,
    variant: column.filterVariant,
    options: convertFilterSelectOptions(column.filterSelectOptions)
  } : null, [convertFilterSelectOptions]);
  const dataTableFilters = (0, _react.useMemo)(() => {
    const providedFilters = filtersProp || columns;
    return providedFilters.reduce((accumulator, item) => {
      if (typeof item === "string") {
        const foundColumn = columns.find(column => column.accessorKey === item);
        if (foundColumn) {
          const filter = convertColumnToFilter(foundColumn);
          if (filter) {
            return accumulator.concat(filter);
          }
        }
      } else if ("accessorKey" in item) {
        const filter = convertColumnToFilter(item);
        if (filter) {
          return accumulator.concat(filter);
        }
      } else if ("label" in item) {
        return accumulator.concat(item);
      }
      return accumulator;
    }, []);
  }, [columns, filtersProp, convertColumnToFilter]);
  const defaultCell = (0, _react.useCallback)(({
    cell
  }) => {
    const value = cell.getValue();
    const hasTextWrapping = cell.column.columnDef.hasTextWrapping || cell.column.columnDef.enableWrapping;
    return hasTextWrapping ? value : (0, _jsxRuntime.jsx)(_Box.Box, {
      sx: {
        whiteSpace: "nowrap",
        textOverflow: "ellipsis",
        overflow: "hidden"
      },
      children: value
    });
  }, []);
  const emptyState = (0, _react.useCallback)(() => {
    const noResultsInnerContent = noResultsPlaceholder || (0, _jsxRuntime.jsx)(_EmptyState.EmptyState, {
      description: t("table.noresults.text"),
      heading: t("table.noresults.heading")
    });
    const emptyStateInnerContent = emptyPlaceholder && isEmpty ? emptyPlaceholder : noResultsInnerContent;
    return (0, _jsxRuntime.jsx)(_Box.Box, {
      sx: {
        width: tableInnerContainerWidth
      },
      children: emptyStateInnerContent
    });
  }, [emptyPlaceholder, isEmpty, noResultsPlaceholder, t, tableInnerContainerWidth]);
  const columnIds = (0, _react.useMemo)(() => {
    return columns.map(column => column.accessorKey);
  }, [columns]);
  const columnOrder = (0, _react.useMemo)(() => ["mrt-row-drag", "mrt-row-select", "mrt-row-expand", ...columnIds, "mrt-row-actions"], [columnIds]);
  const shouldDisplayRowActions = (0, _react.useMemo)(() => hasRowReordering === true && onReorderRows || rowActionButtons || rowActionMenuItems ? true : false, [hasRowReordering, onReorderRows, rowActionButtons, rowActionMenuItems]);
  const muiTableBodyProps = (0, _react.useCallback)(() => ({
    className: rowDensityClassName
  }), [rowDensityClassName]);
  const muiTableBodyCellProps = (0, _react.useCallback)(({
    column
  }) => ({
    className: column.getIsResizing() ? "isResizing" : "",
    sx: {
      overflowWrap: "anywhere"
    }
  }), []);
  const muiDetailPanelProps = (0, _react.useCallback)(({
    row
  }) => ({
    sx: {
      paddingBlock: row.getIsExpanded() ? `${odysseyDesignTokens.Spacing3} !important` : undefined
    }
  }), [odysseyDesignTokens.Spacing3]);
  const muiTableBodyRowProps = (0, _react.useCallback)(({
    table,
    row,
    isDetailPanel
  }) => ({
    className: draggableTableBodyRowClassName({
      currentRowId: row.id,
      draggingRowId: draggingRow?.id,
      hoveredRowId: table.getState().hoveredRow?.id
    }),
    sx: {
      ...(isDetailPanel && {
        paddingBlock: "0 !important",
        border: 0,
        ["&:hover"]: {
          backgroundColor: `transparent !important`
        }
      })
    }
  }), [draggableTableBodyRowClassName, draggingRow?.id]);
  const muiRowDragHandleProps = (0, _react.useCallback)(({
    table,
    row
  }) => ({
    onKeyDown: event => handleDragHandleKeyDown({
      table,
      row,
      event
    }),
    onBlur: () => resetDraggingAndHoveredRow(table),
    onDragEnd: () => handleDragHandleOnDragEnd(table),
    onDragCapture: () => handleDragHandleOnDragCapture(table),
    sx: dragHandleStyles,
    ...dragHandleText
  }), [dragHandleStyles, dragHandleText, handleDragHandleKeyDown, resetDraggingAndHoveredRow, handleDragHandleOnDragEnd, handleDragHandleOnDragCapture]);
  const muiTableHeadCellProps = (0, _react.useCallback)(({
    column: currentColumn
  }) => ({
    className: columnSorting.find(sortedColumn => sortedColumn.id === currentColumn.id) ? "isSorted" : "isUnsorted"
  }), [columnSorting]);
  const hasColumnWithGrow = (0, _react.useMemo)(() => columns.some(column => column.grow === true), [columns]);
  const dataTable = (0, _materialReactTable.useMaterialReactTable)({
    columns: columns,
    data: data,
    getRowId,
    state: {
      sorting: columnSorting,
      globalFilter: search,
      columnVisibility,
      isLoading,
      rowSelection,
      columnOrder
    },
    icons: {
      ArrowDownwardIcon: _index.ArrowDownIcon,
      DragHandleIcon: _index.DragIndicatorIcon,
      SyncAltIcon: _index.ArrowUnsortedIcon,
      ExpandMoreIcon: _index.ChevronDownIcon
    },
    enableColumnActions: false,
    enableColumnResizing: hasColumnResizing,
    enableDensityToggle: false,
    enableFilters: false,
    enableFullScreenToggle: false,
    enableGlobalFilter: false,
    enableHiding: false,
    enablePagination: false,
    layoutMode: "grid-no-grow",
    manualFiltering: true,
    manualSorting: true,
    muiTablePaperProps: {
      elevation: 0,
      sx: {
        overflow: "visible"
      }
    },
    selectAllMode: "all",
    displayColumnDefOptions: {
      "mrt-row-actions": {
        header: "",
        grow: true,
        muiTableBodyCellProps: {
          align: "right",
          sx: {
            overflow: "visible",
            width: "unset"
          },
          className: "ods-actions-cell"
        },
        muiTableHeadCellProps: {
          align: "right",
          sx: {
            width: "unset"
          },
          className: "ods-actions-cell",
          children: (0, _jsxRuntime.jsxs)(_Box.Box, {
            sx: {
              display: "flex",
              visibility: "hidden"
            },
            children: [rowActionButtons && rowActionButtons({
              id: null
            }), (hasRowReordering && onReorderRows || rowActionMenuItems) && (0, _jsxRuntime.jsx)(_Box.Box, {
              children: (0, _jsxRuntime.jsx)(_Button.Button, {
                ariaLabel: t("table.moreactions.arialabel"),
                endIcon: (0, _jsxRuntime.jsx)(_index.MoreIcon, {}),
                isDisabled: true,
                size: "small",
                variant: "floating"
              })
            })]
          })
        }
      },
      "mrt-row-drag": {
        header: "",
        muiTableBodyCellProps: {
          sx: {
            minWidth: 0,
            width: "auto"
          },
          className: "ods-drag-handle"
        },
        muiTableHeadCellProps: {
          sx: {
            minWidth: 0,
            width: "auto"
          },
          children: (0, _jsxRuntime.jsx)(_Box.Box, {
            sx: {
              marginInline: "-0.1rem"
            },
            children: (0, _jsxRuntime.jsx)(_index.DragIndicatorIcon, {
              sx: {
                marginInline: 1,
                opacity: 0
              }
            })
          })
        }
      },
      "mrt-row-select": {
        muiTableHeadCellProps: {
          padding: "checkbox"
        },
        muiTableBodyCellProps: {
          padding: "checkbox"
        }
      },
      "mrt-row-expand": {
        header: ""
      }
    },
    muiTableBodyProps,
    defaultColumn: {
      Cell: defaultCell
    },
    muiTableBodyCellProps,
    enableRowOrdering: hasRowReordering && Boolean(onReorderRows),
    enableRowDragging: hasRowReordering && Boolean(onReorderRows),
    muiDetailPanelProps,
    muiTableBodyRowProps,
    muiRowDragHandleProps,
    enableRowActions: shouldDisplayRowActions,
    positionActionsColumn: "last",
    renderRowActions: ({
      row
    }) => renderRowActions({
      row
    }),
    enableRowSelection: hasRowSelection,
    onRowSelectionChange: setRowSelection,
    enableSorting: hasSorting,
    onSortingChange: setColumnSorting,
    muiTableHeadCellProps,
    enableRowVirtualization: paginationType !== "loadMore" && pagination.pageSize > 50,
    rowVirtualizerInstanceRef: (0, _react.useRef)(null),
    rowVirtualizerOptions: {
      overscan: 4
    },
    renderEmptyRowsFallback: emptyState,
    muiTableProps: {
      ref: tableContentRef,
      className: !shouldDisplayRowActions && hasColumnResizing ? hasColumnWithGrow ? "ods-hide-spacer-column" : "ods-hide-spacer-column ods-column-grow" : ""
    },
    muiTableContainerProps: {
      ref: tableInnerContainerRef
    },
    enableExpandAll: false,
    renderDetailPanel: renderDetailPanel
  });
  const bulkActionMenuButton = (0, _react.useMemo)(() => (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
    children: (0, _jsxRuntime.jsx)(_MenuButton.MenuButton, {
      ariaLabel: "More actions",
      buttonVariant: "secondary",
      endIcon: (0, _jsxRuntime.jsx)(_index.MoreIcon, {}),
      isDisabled: Object.keys(rowSelection).length === 0,
      children: bulkActionMenuItems?.(rowSelection)
    })
  }), [bulkActionMenuItems, rowSelection]);
  (0, _react.useEffect)(() => {
    (async () => {
      setIsLoading(true);
      setErrorMessage(errorMessageProp);
      try {
        const incomingData = await getData?.({
          page: pagination.pageIndex,
          resultsPerPage: pagination.pageSize,
          search,
          filters,
          sort: columnSorting
        });
        setData(incomingData);
      } catch (error) {
        setErrorMessage(typeof error === "string" ? error : t("table.error"));
      } finally {
        setIsLoading(false);
      }
    })();
  }, [columnSorting, errorMessageProp, filters, getData, pagination, search, t]);
  (0, _react.useEffect)(() => {
    if (!initialFilters && filters) {
      setInitialFilters(filters);
    }
    setIsEmpty(pagination.pageIndex === currentPage && pagination.pageSize === resultsPerPage && search === "" && filters === initialFilters && data.length === 0);
  }, [filters, pagination, search, data, currentPage, initialFilters, resultsPerPage]);
  (0, _react.useEffect)(() => {
    setPagination(prev => ({
      pageIndex: 1,
      pageSize: prev.pageSize
    }));
  }, [filters, search]);
  (0, _react.useEffect)(() => {
    onChangeRowSelection?.(rowSelection);
  }, [rowSelection, onChangeRowSelection]);
  const {
    lastRow
  } = (0, _usePagination.usePagination)({
    currentRowsCount: data.length,
    pageIndex: pagination.pageIndex,
    pageSize: pagination.pageSize,
    totalRows
  });
  return (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [(hasSearch || hasFilters || hasChangeableDensity || hasColumnVisibility || bulkActionMenuItems || additionalActionButton || additionalActionMenuItems) && (0, _jsxRuntime.jsx)(_Box.Box, {
      sx: {
        marginBottom: 5
      },
      children: (0, _jsxRuntime.jsx)(_DataFilters.DataFilters, {
        additionalActions: (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [(0, _jsxRuntime.jsx)(_DataTableSettings.DataTableSettings, {
            columns: columns,
            columnVisibility: columnVisibility,
            hasChangeableDensity: hasChangeableDensity,
            hasColumnVisibility: hasColumnVisibility,
            rowDensity: rowDensity,
            setColumnVisibility: setColumnVisibility,
            setRowDensity: setRowDensity
          }), bulkActionMenuItems && bulkActionMenuButton, additionalActionButton, additionalActionMenuItems && (0, _jsxRuntime.jsx)(_MenuButton.MenuButton, {
            ariaLabel: t("table.moreactions.arialabel"),
            buttonVariant: "secondary",
            endIcon: (0, _jsxRuntime.jsx)(_index.MoreIcon, {}),
            menuAlignment: "right",
            children: additionalActionMenuItems
          })]
        }),
        defaultSearchTerm: initialSearchValue,
        filters: hasFilters ? dataTableFilters : undefined,
        hasSearchSubmitButton: hasSearchSubmitButton,
        isDisabled: isEmpty,
        onChangeFilters: hasFilters ? setFilters : undefined,
        onChangeSearch: hasSearch ? setSearch : undefined,
        searchDelayTime: searchDelayTime
      })
    }), errorMessage && (0, _jsxRuntime.jsx)(_Box.Box, {
      sx: {
        marginBlockEnd: 2
      },
      children: (0, _jsxRuntime.jsx)(_Callout.Callout, {
        severity: "error",
        text: errorMessage
      })
    }), (0, _jsxRuntime.jsx)(ScrollableTableContainer, {
      isScrollableEnd: !isTableContainerScrolledToEnd,
      isScrollableStart: !isTableContainerScrolledToStart,
      odysseyDesignTokens: odysseyDesignTokens,
      ref: tableOuterContainerRef,
      children: (0, _jsxRuntime.jsx)(_materialReactTable.MRT_TableContainer, {
        table: dataTable
      })
    }), hasPagination && (0, _jsxRuntime.jsx)(_Pagination.Pagination, {
      currentPageLabel: t("pagination.page"),
      currentRowsCount: data.length,
      isDisabled: isEmpty,
      isMoreDisabled: isPaginationMoreDisabled,
      lastRow: lastRow,
      loadMoreLabel: t("pagination.loadmore"),
      maxPageIndex: maxPages,
      maxPageSize: maxResultsPerPage,
      nextLabel: t("pagination.next"),
      onPaginationChange: setPagination,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      previousLabel: t("pagination.previous"),
      rowsPerPageLabel: t("pagination.rowsperpage"),
      totalRows: totalRows,
      variant: paginationType
    })]
  });
};
const MemoizedDataTable = exports.DataTable = (0, _react.memo)(DataTable);
MemoizedDataTable.displayName = "DataTable";
//# sourceMappingURL=DataTable.cjs.map