var _excluded = ["bulkActions", "headerChildren", "data", "dataColumns", "dataGa", "enableColumnPinning", "columnPinning", "onColumnPinningChange", "enableColumnVisibility", "columnVisibility", "onColumnVisibilityChange", "columnSizing", "onColumnSizingChange", "enablePagination", "enableResizing", "enableSelection", "enableSubRowSelection", "rowSelection", "onRowSelectionChange", "singleRowSelection", "expanded", "onExpandedChange", "autoResetExpanded", "enableSorting", "sortBy", "onSortingChange", "globalFilter", "onSearch", "globalFilterFn", "enableCustomSearch", "grouping", "onGroupByChange", "groupByColumns", "onRowSelected", "paginationOptions", "onPaginationChange", "rowActions", "testPrefix", "meta", "title", "virtualizeOptions", "tableRef", "className", "width", "getRowCanExpand", "getRowId", "ref"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
import React, { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react";
import { getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, getExpandedRowModel, getGroupedRowModel, useReactTable } from "@tanstack/react-table";
import isEqual from "lodash/isEqual";
import identity from "lodash/identity";
import Flex from "../templates/flex";
import Layer from "../templates/layer";
import { Text } from "../typography";
import { Icon } from "../icon";
import { comparison, includesString, select } from "./helpers/filterFns";
import useColumns from "./useColumns";
import TableProvider, { useTableDispatch } from "./provider";
import Pagination from "./components/pagination";
import { throttle } from "throttle-debounce";
import Header from "./header";
import HeaderActions from "./header/actions";
import Body from "./body";
import usePinning from "./usePinning";
import useVisibility from "./useVisibility";
import useSizing from "./useSizing";
import useExpanding from "./useExpanding";
import usePaginating from "./usePaginating";
import useSearching from "./useSearching";
import useSelecting from "./useSelecting";
import useSorting from "./useSorting";
import useGrouping from "./useGrouping";
var noop = function noop() {};
var emptyObj = {};
var filterFns = {
  comparison: comparison,
  select: select
};
var tableDefaultProps = {
  coloredSortedColumn: true,
  enableColumnPinning: false,
  enableColumnVisibility: false,
  enableResizing: false,
  globalFilterFn: includesString,
  onColumnVisibilityChange: noop,
  onSortingChange: noop,
  onExpandedChange: noop,
  paginationOptions: {
    pageIndex: 0,
    pageSize: 100
  },
  expanded: emptyObj,
  rowSelection: emptyObj,
  rowActions: emptyObj,
  meta: emptyObj,
  globalFilter: "",
  testPrefix: "",
  virtualizeOptions: {}
};
var Table = /*#__PURE__*/memo(function (props) {
  var _tableDefaultProps$pr = _objectSpread(_objectSpread({}, tableDefaultProps), props),
    bulkActions = _tableDefaultProps$pr.bulkActions,
    headerChildren = _tableDefaultProps$pr.headerChildren,
    data = _tableDefaultProps$pr.data,
    dataColumns = _tableDefaultProps$pr.dataColumns,
    dataGa = _tableDefaultProps$pr.dataGa,
    _tableDefaultProps$pr2 = _tableDefaultProps$pr.enableColumnPinning,
    enableColumnPinning = _tableDefaultProps$pr2 === void 0 ? tableDefaultProps.enableColumnPinning : _tableDefaultProps$pr2,
    defaultColumnPinning = _tableDefaultProps$pr.columnPinning,
    pinningChangeCb = _tableDefaultProps$pr.onColumnPinningChange,
    _tableDefaultProps$pr3 = _tableDefaultProps$pr.enableColumnVisibility,
    enableColumnVisibility = _tableDefaultProps$pr3 === void 0 ? tableDefaultProps.enableColumnVisibility : _tableDefaultProps$pr3,
    defaultColumnVisibility = _tableDefaultProps$pr.columnVisibility,
    _tableDefaultProps$pr4 = _tableDefaultProps$pr.onColumnVisibilityChange,
    visibilityChangeCb = _tableDefaultProps$pr4 === void 0 ? tableDefaultProps.onColumnVisibilityChange : _tableDefaultProps$pr4,
    defaultColumnSizing = _tableDefaultProps$pr.columnSizing,
    sizingChangeCb = _tableDefaultProps$pr.onColumnSizingChange,
    enablePagination = _tableDefaultProps$pr.enablePagination,
    _tableDefaultProps$pr5 = _tableDefaultProps$pr.enableResizing,
    enableResizing = _tableDefaultProps$pr5 === void 0 ? tableDefaultProps.enableResizing : _tableDefaultProps$pr5,
    enableSelection = _tableDefaultProps$pr.enableSelection,
    enableSubRowSelection = _tableDefaultProps$pr.enableSubRowSelection,
    _tableDefaultProps$pr6 = _tableDefaultProps$pr.rowSelection,
    defaultRowSelection = _tableDefaultProps$pr6 === void 0 ? tableDefaultProps.rowSelection : _tableDefaultProps$pr6,
    rowSelectionChangeCb = _tableDefaultProps$pr.onRowSelectionChange,
    singleRowSelection = _tableDefaultProps$pr.singleRowSelection,
    _tableDefaultProps$pr7 = _tableDefaultProps$pr.expanded,
    defaultExpanded = _tableDefaultProps$pr7 === void 0 ? tableDefaultProps.expanded : _tableDefaultProps$pr7,
    _tableDefaultProps$pr8 = _tableDefaultProps$pr.onExpandedChange,
    expandedChangeCb = _tableDefaultProps$pr8 === void 0 ? tableDefaultProps.onExpandedChange : _tableDefaultProps$pr8,
    _tableDefaultProps$pr9 = _tableDefaultProps$pr.autoResetExpanded,
    autoResetExpanded = _tableDefaultProps$pr9 === void 0 ? false : _tableDefaultProps$pr9,
    enableSorting = _tableDefaultProps$pr.enableSorting,
    sortBy = _tableDefaultProps$pr.sortBy,
    _tableDefaultProps$pr10 = _tableDefaultProps$pr.onSortingChange,
    sortingChangeCb = _tableDefaultProps$pr10 === void 0 ? tableDefaultProps.onSortingChange : _tableDefaultProps$pr10,
    _tableDefaultProps$pr11 = _tableDefaultProps$pr.globalFilter,
    defaultGlobalFilter = _tableDefaultProps$pr11 === void 0 ? tableDefaultProps.globalFilter : _tableDefaultProps$pr11,
    onSearch = _tableDefaultProps$pr.onSearch,
    _tableDefaultProps$pr12 = _tableDefaultProps$pr.globalFilterFn,
    globalFilterFn = _tableDefaultProps$pr12 === void 0 ? tableDefaultProps.globalFilterFn : _tableDefaultProps$pr12,
    enableCustomSearch = _tableDefaultProps$pr.enableCustomSearch,
    defaultGrouping = _tableDefaultProps$pr.grouping,
    groupingChangeCb = _tableDefaultProps$pr.onGroupByChange,
    groupByColumns = _tableDefaultProps$pr.groupByColumns,
    onRowSelected = _tableDefaultProps$pr.onRowSelected,
    _tableDefaultProps$pr13 = _tableDefaultProps$pr.paginationOptions,
    paginationOptions = _tableDefaultProps$pr13 === void 0 ? tableDefaultProps.paginationOptions : _tableDefaultProps$pr13,
    paginationChangeCb = _tableDefaultProps$pr.onPaginationChange,
    _tableDefaultProps$pr14 = _tableDefaultProps$pr.rowActions,
    rowActions = _tableDefaultProps$pr14 === void 0 ? tableDefaultProps.rowActions : _tableDefaultProps$pr14,
    _tableDefaultProps$pr15 = _tableDefaultProps$pr.testPrefix,
    testPrefix = _tableDefaultProps$pr15 === void 0 ? tableDefaultProps.testPrefix : _tableDefaultProps$pr15,
    _tableDefaultProps$pr16 = _tableDefaultProps$pr.meta,
    tableMeta = _tableDefaultProps$pr16 === void 0 ? tableDefaultProps.meta : _tableDefaultProps$pr16,
    title = _tableDefaultProps$pr.title,
    _tableDefaultProps$pr17 = _tableDefaultProps$pr.virtualizeOptions,
    virtualizeOptions = _tableDefaultProps$pr17 === void 0 ? tableDefaultProps.virtualizeOptions : _tableDefaultProps$pr17,
    tableRef = _tableDefaultProps$pr.tableRef,
    className = _tableDefaultProps$pr.className,
    width = _tableDefaultProps$pr.width,
    getRowCanExpand = _tableDefaultProps$pr.getRowCanExpand,
    getRowId = _tableDefaultProps$pr.getRowId,
    ref = _tableDefaultProps$pr.ref,
    rest = _objectWithoutPropertiesLoose(_tableDefaultProps$pr, _excluded);
  var _useVisibility = useVisibility(defaultColumnVisibility, visibilityChangeCb),
    columnVisibility = _useVisibility[0],
    onColumnVisibilityChange = _useVisibility[1];
  var _useSizing = useSizing(defaultColumnSizing, sizingChangeCb),
    columnSizing = _useSizing[0],
    onColumnSizingChange = _useSizing[1];
  var _usePinning = usePinning(defaultColumnPinning, pinningChangeCb),
    columnPinning = _usePinning[0],
    onColumnPinningChange = _usePinning[1];
  var _useExpanding = useExpanding(defaultExpanded, expandedChangeCb),
    expanded = _useExpanding[0],
    onExpandedChange = _useExpanding[1];
  var _useSelecting = useSelecting(defaultRowSelection, rowSelectionChangeCb),
    rowSelection = _useSelecting[0],
    onRowSelectionChange = _useSelecting[1];
  var _useSorting = useSorting(sortBy, sortingChangeCb),
    sorting = _useSorting[0],
    onSortingChange = _useSorting[1];
  var _usePaginating = usePaginating(paginationOptions, paginationChangeCb),
    pagination = _usePaginating[0],
    onPaginationChange = _usePaginating[1];
  var _useGrouping = useGrouping(defaultGrouping, groupingChangeCb),
    grouping = _useGrouping[0],
    onGroupingChange = _useGrouping[1];
  var _useSearching = useSearching(defaultGlobalFilter, onSearch),
    globalFilter = _useSearching[0],
    onGlobalFilterChange = _useSearching[1];
  var columns = useColumns(dataColumns, {
    testPrefix: testPrefix,
    enableSelection: enableSelection,
    singleRowSelection: singleRowSelection,
    enableResizing: enableResizing,
    enableSorting: enableSorting,
    rowActions: rowActions,
    tableMeta: tableMeta
  });
  var table = useReactTable(_objectSpread(_objectSpread({
    columns: columns,
    data: data,
    manualPagination: !enablePagination,
    columnResizeMode: "onEnd",
    filterFns: filterFns,
    state: {
      columnVisibility: columnVisibility,
      columnSizing: columnSizing,
      rowSelection: rowSelection,
      globalFilter: enableCustomSearch ? "" : globalFilter,
      sorting: sorting,
      pagination: pagination,
      columnPinning: columnPinning,
      expanded: expanded,
      grouping: useMemo(function () {
        var _groupByColumns$group;
        return Array.isArray(grouping) ? [grouping].filter(Boolean) : (groupByColumns == null || (_groupByColumns$group = groupByColumns[grouping]) == null ? void 0 : _groupByColumns$group.columns) || [];
      }, [grouping]),
      columnOrder: []
    },
    onExpandedChange: onExpandedChange
  }, !enableCustomSearch && globalFilterFn ? {
    globalFilterFn: globalFilterFn
  } : {}), {}, {
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onRowSelectionChange: onRowSelectionChange,
    onGlobalFilterChange: enableCustomSearch ? undefined : onGlobalFilterChange,
    onSortingChange: onSortingChange,
    enableMultiSorting: true,
    isMultiSortEvent: function isMultiSortEvent(e) {
      return e.ctrlKey || e.shiftKey || e.metaKey;
    },
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
    getRowCanExpand: getRowCanExpand,
    autoResetExpanded: autoResetExpanded,
    getGroupedRowModel: getGroupedRowModel(),
    getSubRows: useCallback(function (row) {
      return row.children;
    }, []),
    onPaginationChange: onPaginationChange,
    onColumnVisibilityChange: onColumnVisibilityChange,
    onColumnSizingChange: onColumnSizingChange,
    onColumnPinningChange: onColumnPinningChange,
    enableSubRowSelection: enableSubRowSelection,
    columnGroupingMode: "reorder",
    getRowId: getRowId
  }));
  var prevStateRef = useRef(table.getState());
  table.isEqual = function (selector) {
    if (selector === void 0) {
      selector = identity;
    }
    if (!prevStateRef.current) {
      prevStateRef.current = table.getState();
      return false;
    }
    var areStatesEqual = isEqual(selector(prevStateRef.current), selector(table.getState()));
    prevStateRef.current = table.getState();
    return areStatesEqual;
  };
  var dispatch = useTableDispatch();
  var dispatchThrottled = useCallback(throttle(300, dispatch), []);
  useLayoutEffect(function () {
    var state = table.getState();
    dispatchThrottled({
      sorting: state.sorting,
      columnSizing: state.columnSizing,
      expanded: state.expanded,
      grouping: state.grouping,
      columnVisibility: state.columnVisibility,
      columnSizingInfo: state.columnSizingInfo,
      rowsById: table.getRowModel().rowsById,
      selectedRows: table.getSelectedRowModel().flatRows,
      allColumns: table == null || table.getAllColumns == null ? void 0 : table.getAllColumns()
    });
  }, [table.getState()]);
  if (tableRef) tableRef.current = table;
  var getHasNextPage = virtualizeOptions.getHasNextPage,
    loading = virtualizeOptions.loading,
    warning = virtualizeOptions.warning;
  return /*#__PURE__*/React.createElement(Flex, {
    height: {
      max: "100%"
    },
    overflow: "hidden",
    column: true,
    flex: "1",
    ref: ref,
    className: className,
    width: width
  }, /*#__PURE__*/React.createElement(Header, {
    q: globalFilter,
    hasSearch: !!onSearch,
    onSearch: onGlobalFilterChange,
    groupByColumns: groupByColumns,
    onGroupBy: onGroupingChange,
    grouping: grouping,
    tableMeta: tableMeta,
    title: title,
    dataColumns: dataColumns,
    enableColumnVisibility: enableColumnVisibility,
    bulkActions: bulkActions,
    enableCustomSearch: enableCustomSearch
  }, headerChildren || null, /*#__PURE__*/React.createElement(HeaderActions, {
    rowSelection: rowSelection,
    bulkActions: bulkActions,
    columnPinning: columnPinning,
    dataGa: dataGa,
    enableColumnVisibility: enableColumnVisibility,
    enableColumnPinning: enableColumnPinning,
    table: table,
    testPrefix: testPrefix,
    onRowSelected: onRowSelected
  })), /*#__PURE__*/React.createElement(Body, _extends({
    table: table,
    dataGa: dataGa,
    testPrefix: testPrefix,
    meta: tableMeta
  }, rest, virtualizeOptions)), !(getHasNextPage != null && getHasNextPage()) && !loading && !!warning && /*#__PURE__*/React.createElement(Flex, {
    alignItems: "center",
    justifyContent: "center",
    gap: 2,
    padding: [4],
    width: "100%"
  }, /*#__PURE__*/React.createElement(Icon, {
    name: "warning_triangle_hollow",
    color: "warning"
  }), " ", /*#__PURE__*/React.createElement(Text, {
    color: "warningText"
  }, warning)), loading && /*#__PURE__*/React.createElement(Layer, {
    backdrop: false,
    position: "bottom",
    margin: [0, 0, 10],
    padding: [0, 0, 10],
    zIndex: 20
  }, /*#__PURE__*/React.createElement(Flex, {
    background: "tooltip",
    padding: [1, 2],
    gap: 2
  }, /*#__PURE__*/React.createElement(Text, {
    strong: true
  }, "Loading more..."))), enablePagination && /*#__PURE__*/React.createElement(Pagination, {
    table: table
  }));
});
var withProvider = function withProvider(Component) {
  return function (props) {
    return /*#__PURE__*/React.createElement(TableProvider, null, /*#__PURE__*/React.createElement(Component, props));
  };
};
export default withProvider(Table);