"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = require("react");
var _classnames = _interopRequireDefault(require("classnames"));
var _reactTransitionGroup = require("react-transition-group");
var _memoizeOne = _interopRequireDefault(require("memoize-one"));
var _reactMeasure = _interopRequireDefault(require("react-measure"));
var _constants = require("../../constants");
var _Checkbox = _interopRequireDefault(require("../Checkbox"));
var _Icon = _interopRequireDefault(require("../Icon"));
var _utils = require("../utils");
var _Button = _interopRequireDefault(require("../Button"));
var _Translate = _interopRequireDefault(require("../Translate"));
var _Text = _interopRequireDefault(require("../Text"));
var _Pagination = require("../Pagination");
var _Spinner = _interopRequireDefault(require("../Spinner"));
var _ListOperationContext = _interopRequireDefault(require("./ListOperationContext"));
var _VerticalContext = _interopRequireWildcard(require("../VerticalContext"));
var _ListEmptyView = _interopRequireDefault(require("./ListEmptyView"));
var _Columns = _interopRequireWildcard(require("../Columns"));
var _useFocusVisible = require("use-focus-visible");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } // Copyright 1999-2025. WebPros International GmbH. All rights reserved.
// eslint-disable-next-line func-style
function getRowKey(row, props) {
  const {
    rowKey
  } = props;
  if (typeof rowKey === 'function') {
    return rowKey(row);
  }
  return row[rowKey];
}
const Tbody = _ref => {
  let {
    baseClassName = `${_constants.CLS_PREFIX}list__wrapper`,
    className,
    ...props
  } = _ref;
  const {
    focusVisible,
    onFocus,
    onBlur
  } = (0, _useFocusVisible.useFocusVisible)();
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("tbody", {
    ...props,
    onFocus: (0, _utils.wrapFunction)(props.onFocus, onFocus),
    onBlur: (0, _utils.wrapFunction)(props.onBlur, onBlur),
    className: (0, _classnames.default)(className, {
      [`${baseClassName}--focus-visible`]: focusVisible
    })
  });
};
const getHumanTotalRows = _ref2 => {
  let {
    selectedRows,
    totalRows,
    allRowsSelected,
    translators
  } = _ref2;
  let mode;
  if (!allRowsSelected && selectedRows === 0) {
    mode = 'totalRows';
  } else if (allRowsSelected || selectedRows === totalRows) {
    mode = 'selectedAllRows';
  } else {
    mode = 'selectedRows';
  }
  const wrapToText = element => /*#__PURE__*/(0, _jsxRuntime.jsx)(_Text.default, {
    fontSize: "sm",
    children: element
  });
  switch (mode) {
    case 'totalRows':
      return wrapToText(/*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "List",
        content: "totalRows",
        fallback: "%%totalRows%% items total",
        params: {
          totalRows
        },
        translators: translators
      }));
    case 'selectedRows':
      return wrapToText(/*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "List",
        content: "selectedRows",
        fallback: "%%selectedRows%% of %%totalRows%% items selected",
        params: {
          selectedRows: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Text.default, {
            bold: true,
            children: selectedRows
          }),
          totalRows
        },
        translators: translators
      }));
    case 'selectedAllRows':
      return wrapToText(/*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "List",
        content: "selectedRows",
        fallback: "%%selectedRows%% of %%totalRows%% items selected",
        params: {
          selectedRows: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Text.default, {
            bold: true,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
              namespace: "List",
              content: "all",
              fallback: "All",
              translators: translators
            })
          }),
          totalRows
        },
        translators: translators
      }));
    default:
      return null;
  }
};
/**
 * `List` component is used for displaying a collection of tabular data.
 * [More details about designing of lists.](#!/Sets%20of%20Objects)
 * @since 0.0.42
 */
class List extends _react.Component {
  constructor() {
    super(...arguments);
    (0, _defineProperty2.default)(this, "state", {
      sortInPlace: !this.props.pagination,
      vertical: false,
      expandedRows: this.props.expandedRows ?? [],
      ReorderableList: undefined,
      reorderableItemWidths: [],
      prevExpandedRows: this.props.expandedRows ?? [],
      sortColumn: undefined,
      prevSortColumn: undefined,
      sortDirection: undefined,
      prevSortDirection: undefined,
      selection: this.props.selection ?? [],
      prevSelection: this.props.selection ?? [],
      prevData: [],
      prevPagination: undefined
    });
    (0, _defineProperty2.default)(this, "needScroll", false);
    (0, _defineProperty2.default)(this, "anchorRef", /*#__PURE__*/(0, _react.createRef)());
    (0, _defineProperty2.default)(this, "flatData", data => data.reduce((acc, item) => {
      const {
        data
      } = item;
      const {
        virtual
      } = this.getRowProps(item);
      if (virtual) {
        return [...acc, ...(data ? this.flatData(data) : [])];
      }
      return [...acc, item, ...(data ? this.flatData(data) : [])];
    }, []));
    (0, _defineProperty2.default)(this, "handleRowSelectionChange", (checked, rowKey) => {
      const {
        onAllRowsSelectedChange
      } = this.props;
      let selection;
      if (checked) {
        selection = this.state.selection.slice();
        selection.push(rowKey);
      } else {
        selection = this.state.selection.filter(value => value !== rowKey);
        (0, _utils.safeInvoke)(onAllRowsSelectedChange, false);
      }
      this.setSelection(selection);
    });
    (0, _defineProperty2.default)(this, "handleGlobalSelectionChange", headerChecked => {
      const {
        onAllRowsSelectedChange,
        data
      } = this.props;
      const {
        selection
      } = this.state;
      const nextSelection = [];
      this.flatData(data ?? []).forEach(row => {
        const key = getRowKey(row, this.props);
        if (row.disabled || this.isRowLoading(row)) {
          if (selection.indexOf(key) !== -1) {
            nextSelection.push(key);
          }
          return;
        }
        if (headerChecked) {
          nextSelection.push(key);
        }
      });
      if (!headerChecked) {
        (0, _utils.safeInvoke)(onAllRowsSelectedChange, false);
      }
      this.setSelection(nextSelection);
    });
    (0, _defineProperty2.default)(this, "handleResize", _ref3 => {
      let {
        bounds
      } = _ref3;
      if (bounds && this.props.vertical) {
        this.setState({
          vertical: typeof this.props.vertical === 'boolean' ? this.props.vertical : bounds.width < this.props.vertical
        });
      }
    });
    (0, _defineProperty2.default)(this, "isRowLoading", row => this.props.loadingRows?.indexOf(getRowKey(row, this.props)) !== -1);
    (0, _defineProperty2.default)(this, "getRowTitle", row => {
      const {
        columns
      } = this.props;
      const column = columns.find(c => c.type === 'title');
      if (column && column.key) {
        return row[column.key];
      }
      return undefined;
    });
    (0, _defineProperty2.default)(this, "getRowProps", row => {
      const {
        rowProps
      } = this.props;
      if (typeof rowProps === 'function') {
        return {
          ...rowProps(row)
        };
      }
      return {
        ...rowProps
      };
    });
    (0, _defineProperty2.default)(this, "isAllRowsChecked", (0, _memoizeOne.default)((rows, selectedKeys) => {
      const filteredRows = this.flatData(rows).filter(row => !row.disabled);
      if (filteredRows.length > 0) {
        return filteredRows.every(row => {
          const key = getRowKey(row, this.props);
          return selectedKeys.indexOf(key) !== -1;
        });
      }
      return false;
    }));
    (0, _defineProperty2.default)(this, "isAnyRowsExpanded", (0, _memoizeOne.default)((rows, expandedRows) => this.flatData(rows).some(row => {
      const key = getRowKey(row, this.props);
      return expandedRows.indexOf(key) !== -1;
    })));
    (0, _defineProperty2.default)(this, "handleGlobalExpandingChange", () => {
      const {
        data
      } = this.props;
      const {
        expandedRows
      } = this.state;
      const headerExpanded = this.isAnyRowsExpanded(data, expandedRows);
      const nextExpandedRows = [];
      this.flatData(data ?? []).forEach(row => {
        const key = getRowKey(row, this.props);
        if (!this.isRowExpandable(row)) {
          if (expandedRows.indexOf(key) !== -1) {
            nextExpandedRows.push(key);
          }
          return;
        }
        if (!headerExpanded) {
          nextExpandedRows.push(key);
        }
      });
      this.setExpandedRows(nextExpandedRows);
    });
    (0, _defineProperty2.default)(this, "createRowClickHandler", row => e => {
      if ((0, _utils.isClickable)(e)) {
        return;
      }
      if (this.isRowExpandable(row)) {
        this.handleRowExpandingChange(row);
      }
    });
  }
  static getDerivedStateFromProps(_ref4, _ref5) {
    let {
      sortColumn,
      sortDirection,
      selection,
      expandedRows,
      notExpandableRows,
      renderRowBody,
      data,
      pagination,
      vertical,
      rowKey,
      totalRows,
      filtered
    } = _ref4;
    let {
      prevSortColumn,
      prevSortDirection,
      prevData,
      prevSelection,
      prevPagination,
      prevExpandedRows,
      ...state
    } = _ref5;
    let nextState = {};
    if (prevSortColumn !== sortColumn || prevSortDirection !== sortDirection) {
      nextState = {
        ...nextState,
        sortColumn,
        sortDirection
      };
    }
    const additionalExpanded = [];
    if (prevData !== data) {
      const isSingleElementInCurrentExpanded = () => data && state.expandedRows.includes(getRowKey(data[0], {
        rowKey
      }));
      if (renderRowBody && data?.length === 1 && (!pagination || totalRows === 1) && (!prevData || prevData?.length === 0 || isSingleElementInCurrentExpanded()) && (!filtered || isSingleElementInCurrentExpanded())) {
        const key = getRowKey(data[0], {
          rowKey
        });
        if (notExpandableRows?.indexOf(key) === -1) {
          additionalExpanded.push(key);
        }
      }
      const keys = (data ?? []).map(row => getRowKey(row, {
        rowKey
      }));
      const nextSelection = state.selection.filter(key => keys.indexOf(key) !== -1);
      nextState = {
        ...nextState,
        selection: nextSelection
      };
    }
    if (prevSelection !== selection) {
      nextState = {
        ...nextState,
        selection: selection ?? []
      };
    }
    if (prevExpandedRows !== expandedRows || additionalExpanded.length) {
      nextState = {
        ...nextState,
        expandedRows: [...(expandedRows ?? []), ...additionalExpanded]
      };
    }
    if (prevPagination !== pagination) {
      nextState = {
        ...nextState,
        sortInPlace: !pagination
      };
    }
    if (typeof vertical === 'boolean') {
      nextState.vertical = vertical;
    }
    nextState.prevSortColumn = sortColumn;
    nextState.prevSortDirection = sortDirection;
    nextState.prevData = data;
    nextState.prevSelection = selection;
    nextState.prevPagination = pagination;
    nextState.prevExpandedRows = expandedRows;
    return nextState;
  }
  componentDidMount() {
    if (this.props.reorderable) {
      this.applyReorderableList();
    }
  }
  componentDidUpdate(prevProps) {
    const {
      data
    } = this.props;
    const {
      data: prevData
    } = prevProps;
    if (data !== prevData && this.needScroll && this.anchorRef.current) {
      (0, _utils.scrollIntoView)(this.anchorRef.current, {
        scrollMode: 'if-needed'
      });
      this.needScroll = false;
    }
    if (prevProps.reorderable !== this.props.reorderable && this.props.reorderable) {
      this.applyReorderableList();
    }
  }
  applyReorderableList() {
    Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "react-movable" */'@plesk/react-movable'))).then(_ref6 => {
      let {
        List: ReorderableList
      } = _ref6;
      // @ts-expect-error
      this.setState({
        ReorderableList
      });
    });
  }
  getData() {
    const {
      sortInPlace,
      sortColumn,
      sortDirection
    } = this.state;
    const {
      data,
      columns
    } = this.props;
    if (!data) {
      return [];
    }
    if (!sortInPlace) {
      return data;
    }
    const [column] = columns.filter(_ref7 => {
      let {
        key
      } = _ref7;
      return key === sortColumn;
    });
    const defaultSort = (a, b) => {
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    };
    if (!column || !sortColumn) {
      return data;
    }
    return data.sort((a, b) => (column.sort ? column.sort(a, b) : defaultSort(a[sortColumn], b[sortColumn])) * (sortDirection === 'ASC' ? 1 : -1));
  }
  sort(columnKey) {
    const {
      sortInPlace
    } = this.state;
    const {
      sortColumn,
      sortDirection
    } = this.state;
    const nextSortDirection = sortColumn === columnKey && sortDirection === 'ASC' ? 'DESC' : 'ASC';
    const nextSortColumn = columnKey;
    if (sortInPlace) {
      this.setState({
        sortColumn: nextSortColumn,
        sortDirection: nextSortDirection
      });
    }
    if (this.props.onSortChange) {
      this.props.onSortChange({
        sortColumn: nextSortColumn,
        sortDirection: nextSortDirection
      });
    }
  }
  isRowSelected(row) {
    return this.state.selection.indexOf(getRowKey(row, this.props)) !== -1;
  }
  setSelection(selection) {
    this.setState({
      selection
    });
    if (this.props.onSelectionChange) {
      this.props.onSelectionChange(selection.slice());
    }
  }
  isRowExpanded(row) {
    return this.state.expandedRows.indexOf(getRowKey(row, this.props)) !== -1;
  }
  isRowExpandable(row) {
    const {
      virtual
    } = this.getRowProps(row);
    if (virtual) {
      return false;
    }
    return this.props.notExpandableRows?.indexOf(getRowKey(row, this.props)) === -1;
  }
  handleRowExpandingChange(row) {
    let expandedRows;
    const rowKey = getRowKey(row, this.props);
    if (this.isRowExpanded(row)) {
      expandedRows = this.state.expandedRows.filter(value => value !== rowKey);
    } else {
      expandedRows = this.state.expandedRows.slice();
      expandedRows.push(rowKey);
    }
    this.setExpandedRows(expandedRows);
  }
  setExpandedRows(expandedRows) {
    this.setState({
      expandedRows
    });
    (0, _utils.safeInvoke)(this.props.onExpandedRowsChange, expandedRows.slice());
  }
  renderRow(_ref8) {
    let {
      row,
      index,
      hasTitle,
      realColumn,
      parent,
      isDragged,
      reorderableProps
    } = _ref8;
    const {
      baseClassName,
      renderRowBody,
      reorderable
    } = this.props;
    const {
      vertical,
      reorderableItemWidths
    } = this.state;
    const hasActions = realColumn.some(_ref9 => {
      let {
        type
      } = _ref9;
      return type === 'actions';
    });
    const {
      className,
      virtual,
      ...rowProps
    } = this.getRowProps(row);
    let skipCells = 0;
    const Wrapper = reorderable && !parent ? Tbody : _react.Fragment;
    const element = /*#__PURE__*/(0, _react.createElement)(Wrapper, {
      ...(Wrapper === Tbody && !isDragged ? reorderableProps : undefined),
      key: getRowKey(row, this.props)
    }, /*#__PURE__*/(0, _jsxRuntime.jsx)("tr", {
      className: (0, _classnames.default)({
        'is-selected': this.isRowSelected(row),
        [`${baseClassName}__row--expanded`]: this.isRowExpanded(row),
        [`${baseClassName}__row--expandable`]: renderRowBody && this.isRowExpandable(row),
        [`${baseClassName}__row--parent`]: row.data,
        [`${baseClassName}__row--virtual`]: virtual,
        [`${baseClassName}__row--child`]: parent,
        [`${baseClassName}__row--reorderable`]: reorderable,
        [`${baseClassName}__row--${row.intent}`]: row.intent
      }, className),
      ...rowProps,
      onClick: renderRowBody ? this.createRowClickHandler(row) : undefined,
      children: realColumn.map((_ref10, index) => {
        let {
          key,
          title,
          render,
          width,
          cellProps,
          truncate,
          type
        } = _ref10;
        if (skipCells > 0) {
          skipCells -= 1;
          return null;
        }
        let style;
        if (!hasTitle && width && !vertical) {
          style = {
            width
          };
        }
        if (isDragged && reorderableItemWidths) {
          style = {
            width: reorderableItemWidths[index]
          };
        }
        let content = render ? render(row, {
          parent
        }) : row[key];
        // cell props from render
        if (content && content.children && ! /*#__PURE__*/(0, _react.isValidElement)(content)) {
          const {
            children,
            ...other
          } = content;
          content = children;
          cellProps = {
            ...cellProps,
            ...other
          };
          if (other.colSpan) {
            skipCells += other.colSpan - 1;
          }
        }
        const isCellEmpty = !title && !content;
        if (truncate) {
          content = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: `${baseClassName}__truncate`,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Text.default, {
              truncate: true,
              children: content
            })
          });
        }
        if (vertical) {
          const hasColumnTitle = type !== 'internal' && type !== 'actions' && type !== 'title' && title;
          if (!isCellEmpty && type !== 'internal') {
            content = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
              children: [hasColumnTitle && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                className: `${baseClassName}__cell-inner-title`,
                children: title
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                className: `${baseClassName}__cell-inner-content`,
                children: content
              })]
            });
          }
          if (type === 'actions') {
            content = /*#__PURE__*/(0, _jsxRuntime.jsx)(_VerticalContext.default.Provider, {
              value: true,
              children: content
            });
          }
        }

        // do not render reorderable handler for nested rows
        if (key === 'reorderable' && type === 'internal' && parent) {
          content = null;
        }
        return /*#__PURE__*/(0, _jsxRuntime.jsx)("td", {
          style: style,
          ...cellProps,
          className: (0, _classnames.default)(cellProps && cellProps.className, {
            [`${baseClassName}__cell-controls`]: type === 'controls',
            [`${baseClassName}__cell-actions`]: type === 'actions',
            [`${baseClassName}__cell-title`]: type === 'title',
            [`${baseClassName}__cell-has-actions`]: type === 'title' && hasActions
          }) || undefined,
          children: content
        }, key);
      })
    }), renderRowBody && !virtual && this.renderRowBody({
      row,
      index,
      realColumn,
      parent
    }), row.data ? row.data.map((childRow, index) => this.renderRow({
      row: childRow,
      index,
      hasTitle,
      realColumn,
      parent: row
    })) : null);
    if (isDragged) {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: (0, _classnames.default)(baseClassName, `${baseClassName}--dragged`),
        ...reorderableProps,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("table", {
          className: (0, _classnames.default)(`${baseClassName}__table`, `${baseClassName}__table--reorderable`, {
            [`${baseClassName}--expandable`]: renderRowBody,
            [`${baseClassName}__table--vertical`]: vertical
          }),
          children: element
        })
      });
    }
    return element;
  }
  renderRowBody(_ref11) {
    let {
      row,
      index,
      realColumn,
      parent
    } = _ref11;
    const {
      baseClassName,
      renderRowBody
    } = this.props;
    const {
      vertical
    } = this.state;
    if (!renderRowBody) {
      return null;
    }
    const reorderable = realColumn.find(_ref12 => {
      let {
        key
      } = _ref12;
      return key === 'reorderable';
    });
    const expander = realColumn.find(_ref13 => {
      let {
        key
      } = _ref13;
      return key === 'expander';
    });
    const isRowExpanded = this.isRowExpanded(row);
    const trRef = /*#__PURE__*/(0, _react.createRef)();
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactTransitionGroup.CSSTransition, {
      in: isRowExpanded,
      unmountOnExit: true,
      timeout: {
        enter: 0,
        exit: 300
      },
      classNames: `${baseClassName}__row-body-`,
      nodeRef: trRef,
      children: state => /*#__PURE__*/(0, _jsxRuntime.jsxs)("tr", {
        className: `${baseClassName}__row-body`,
        ref: trRef,
        children: [reorderable ? /*#__PURE__*/(0, _jsxRuntime.jsx)("td", {
          className: `${baseClassName}__cell-reorderable`
        }) : null, expander ? /*#__PURE__*/(0, _jsxRuntime.jsx)("td", {
          className: `${baseClassName}__cell-expander`
        }) : null, /*#__PURE__*/(0, _jsxRuntime.jsx)("td", {
          colSpan: realColumn.length - (reorderable ? 1 : 0) - (expander ? 1 : 0),
          className: `${baseClassName}__cell-body`,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: `${baseClassName}__row-body-content-wrapper`,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
              className: `${baseClassName}__row-body-content ${baseClassName}__row-body-content--${state}`,
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_VerticalContext.default.Provider, {
                value: vertical,
                children: renderRowBody(row, {
                  index,
                  parent
                })
              })
            })
          })
        })]
      })
    });
  }
  renderSelectAllButton() {
    const {
      allRowsSelected,
      totalRows,
      onAllRowsSelectedChange,
      onSelectionChange,
      locale
    } = this.props;
    const {
      selection
    } = this.state;
    if (allRowsSelected || selection.length === totalRows || !onSelectionChange) {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
      ghost: true,
      onClick: () => {
        this.handleGlobalSelectionChange(true);
        (0, _utils.safeInvoke)(onAllRowsSelectedChange, true);
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "List",
        content: "selectAll",
        fallback: "Select all",
        translators: locale
      })
    });
  }
  renderDeselectAllButton() {
    const {
      allRowsSelected,
      onAllRowsSelectedChange,
      onSelectionChange,
      locale
    } = this.props;
    const {
      selection
    } = this.state;
    if (!allRowsSelected && selection.length === 0 || !onSelectionChange) {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
      ghost: true,
      onClick: () => {
        this.handleGlobalSelectionChange(false);
        (0, _utils.safeInvoke)(onAllRowsSelectedChange, false);
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "List",
        content: "deselectAll",
        fallback: "Deselect",
        translators: locale
      })
    });
  }
  renderToolbar() {
    const {
      toolbar,
      allRowsSelected,
      totalRows,
      data,
      locale
    } = this.props;
    const {
      selection
    } = this.state;
    let selectedRowTitle;
    if (selection.length === 1) {
      const row = this.flatData(data).find(row => getRowKey(row, this.props) === selection[0]);
      if (row) {
        selectedRowTitle = this.getRowTitle(row);
      }
    }
    if (!toolbar) {
      return null;
    }
    // eslint-disable-next-line react/jsx-no-constructed-context-values
    const context = {
      selectedRows: allRowsSelected ? totalRows || /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
        namespace: "List",
        content: "all",
        fallback: "all",
        translators: locale
      }) : selection.length,
      selectedRowTitle
    };
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ListOperationContext.default.Provider, {
      value: context,
      children: toolbar
    });
  }
  shouldBePagination() {
    const {
      totalRows,
      pagination
    } = this.props;
    if (!pagination || !totalRows) {
      return false;
    }
    if (totalRows && /*#__PURE__*/(0, _react.isValidElement)(pagination)) {
      const {
        itemsPerPageOptions = _Pagination.ITEMS_PER_PAGE_OPTIONS
      } = pagination.props;
      if (Array.isArray(itemsPerPageOptions)) {
        const numericOptions = itemsPerPageOptions.filter(Number);
        if (numericOptions.length) {
          const min = Math.min(...numericOptions);
          if (totalRows <= min) {
            return false;
          }
        }
      }
    }
    return true;
  }
  renderHeader() {
    const {
      baseClassName,
      allRowsSelected,
      totalRows,
      locale
    } = this.props;
    const {
      selection
    } = this.state;
    const shouldBePagination = this.shouldBePagination();
    if (totalRows === undefined && !shouldBePagination) {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: `${baseClassName}__header`,
      children: [totalRows === undefined ? /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {}) : /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: `${baseClassName}__header-text`,
          children: getHumanTotalRows({
            selectedRows: selection.length,
            totalRows,
            allRowsSelected,
            translators: locale
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
          className: `${baseClassName}__header-buttons`,
          children: [this.renderSelectAllButton(), this.renderDeselectAllButton()]
        })]
      }), shouldBePagination && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__header-text`,
        children: this.renderPagination('header')
      })]
    });
  }
  renderEmptyView() {
    const {
      emptyView,
      filtered
    } = this.props;
    if (emptyView === undefined) {
      return filtered ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_ListEmptyView.default, {
        reason: "filtered"
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_ListEmptyView.default, {});
    }
    return emptyView;
  }
  renderPagination(placement) {
    const {
      pagination,
      loading
    } = this.props;
    if (!pagination) {
      return null;
    }
    const paginationProps = {
      loading
    };
    switch (placement) {
      case 'header':
        paginationProps.view = 'popover';
        break;
      case 'footer':
        paginationProps.onSelect = current => {
          this.needScroll = true;
          (0, _utils.safeInvoke)(pagination.props.onSelect, current);
        };
        if (pagination.props.onItemsPerPageChange) {
          paginationProps.onItemsPerPageChange = itemsPerPage => {
            this.needScroll = true;
            (0, _utils.safeInvoke)(pagination.props.onItemsPerPageChange, itemsPerPage);
          };
        }
        break;
    }
    return /*#__PURE__*/(0, _react.cloneElement)(pagination, {
      ...paginationProps
    });
  }
  render() {
    const {
      baseClassName,
      className,
      data,
      columns,
      sortColumn,
      sortDirection,
      onSortChange,
      selection,
      onSelectionChange,
      renderSelectionCheckbox,
      rowKey,
      renderRowBody,
      expandedRows,
      notExpandableRows,
      onExpandedRowsChange,
      loadingRows,
      pagination,
      totalRows,
      toolbar,
      allRowsSelected,
      onAllRowsSelectedChange,
      filtered,
      emptyView,
      emptyViewMode,
      sidebar,
      locale,
      vertical: verticalProp,
      loading,
      rowProps,
      reorderable,
      onReorderEnd,
      ...props
    } = this.props;
    const {
      vertical
    } = this.state;
    if (!(data && data.length > 0) && !filtered && emptyViewMode === 'all') {
      return this.renderEmptyView();
    }
    const realColumn = columns.map((column, i) => {
      const classList = [];
      const cellClassList = [];
      if (i === 0) {
        cellClassList.push(`${baseClassName}__cell-first`);
      }
      if (column.align && !vertical) {
        const className = `${baseClassName}__cell-${column.align}`;
        classList.push(className);
        cellClassList.push(className);
      }
      if (column.className) {
        classList.push(column.className);
        cellClassList.push(column.className);
      }
      const newColumn = {
        ...column
      };
      if (classList.length) {
        newColumn.className = (0, _classnames.default)(...classList);
      }
      if (cellClassList.length) {
        newColumn.cellProps = {
          className: (0, _classnames.default)(...cellClassList)
        };
      }
      return newColumn;
    });
    if (onSelectionChange) {
      const headerChecked = this.isAllRowsChecked(data, this.state.selection);
      const headerCheckboxProps = {
        checked: headerChecked,
        onChange: this.handleGlobalSelectionChange
      };
      realColumn.unshift({
        key: 'selection',
        type: 'internal',
        className: `${baseClassName}__cell-selection`,
        cellProps: {
          className: `${baseClassName}__cell-selection`
        },
        title: typeof renderSelectionCheckbox === 'function' ? renderSelectionCheckbox(headerCheckboxProps) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Checkbox.default, {
          ...headerCheckboxProps
        }),
        render: row => {
          const {
            virtual
          } = this.getRowProps(row);
          if (virtual) {
            return null;
          }
          if (this.isRowLoading(row)) {
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Spinner.default, {
              className: `${baseClassName}__spinner`
            });
          }
          const checkboxProps = {
            checked: this.isRowSelected(row),
            disabled: row.disabled,
            onChange: checked => this.handleRowSelectionChange(checked, getRowKey(row, this.props)),
            inputProps: {
              value: getRowKey(row, this.props)
            }
          };
          if (typeof renderSelectionCheckbox === 'function') {
            return renderSelectionCheckbox(checkboxProps, row);
          }
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Checkbox.default, {
            ...checkboxProps
          });
        }
      });
    }
    if (renderRowBody) {
      realColumn.unshift({
        key: 'expander',
        type: 'internal',
        className: `${baseClassName}__cell-expander`,
        cellProps: {
          className: `${baseClassName}__cell-expander`
        },
        title: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
          ghost: true,
          className: `${baseClassName}__row-expander`,
          icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
            className: `${baseClassName}__row-expander-icon`,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("svg", {
              xmlns: "http://www.w3.org/2000/svg",
              viewBox: "0 0 10 10",
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
                fill: "none",
                stroke: "currentColor",
                strokeLinecap: "round",
                strokeLinejoin: "round",
                d: "M1.5 1.4L5 4.9l3.5-3.5M1.5 5.1L5 8.6l3.5-3.5"
              })
            })
          }),
          onClick: this.handleGlobalExpandingChange
        }),
        render: row => this.isRowExpandable(row) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
          ghost: true,
          className: `${baseClassName}__row-expander`,
          icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
            className: `${baseClassName}__row-expander-icon`,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("svg", {
              xmlns: "http://www.w3.org/2000/svg",
              viewBox: "0 0 10 10",
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
                fill: "none",
                stroke: "currentColor",
                strokeLinecap: "round",
                strokeLinejoin: "round",
                d: "M1.5 3.2L5 6.7l3.5-3.5"
              })
            })
          }),
          onClick: () => this.handleRowExpandingChange(row)
        })
      });
    }
    if (reorderable) {
      realColumn.unshift({
        key: 'reorderable',
        type: 'internal',
        className: `${baseClassName}__cell-reorderable`,
        cellProps: {
          className: `${baseClassName}__cell-reorderable`
        },
        title: null,
        render: () => /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: `${baseClassName}__cell-reorderable-indicator`,
          "data-movable-handle": true,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("svg", {
            width: "6",
            height: "14",
            fill: "none",
            xmlns: "http://www.w3.org/2000/svg",
            "aria-hidden": "true",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
              d: "M0 0h2v2H0zM0 4h2v2H0zM0 8h2v2H0zM0 12h2v2H0zM4 0h2v2H4zM4 4h2v2H4zM4 8h2v2H4zM4 12h2v2H4z",
              fill: "currentColor"
            })
          })
        })
      });
    }
    const hasTitle = !vertical && columns.some(column => column.title);
    let content;
    if (!(data && data.length > 0) && (filtered || emptyViewMode === 'items')) {
      content = this.renderEmptyView();
    } else {
      const renderList = _ref14 => {
        let {
          children,
          props: reorderableProps
        } = _ref14;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_useFocusVisible.FocusVisibleManager, {
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("table", {
            className: (0, _classnames.default)(`${baseClassName}__table`, {
              [`${baseClassName}--expandable`]: renderRowBody,
              [`${baseClassName}__table--vertical`]: vertical,
              [`${baseClassName}__table--reorderable`]: reorderable
            }),
            ...reorderableProps,
            children: [hasTitle && /*#__PURE__*/(0, _jsxRuntime.jsx)("thead", {
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)("tr", {
                className: (0, _classnames.default)(`${baseClassName}__table-thead`, {
                  [`${baseClassName}__row--expanded`]: this.isAnyRowsExpanded(data, this.state.expandedRows)
                }),
                children: realColumn.map(_ref15 => {
                  let {
                    key,
                    title,
                    sortable,
                    sort,
                    width,
                    render,
                    truncate,
                    type,
                    cellProps,
                    ...headerProps
                  } = _ref15;
                  if (sortable) {
                    title = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                      className: "th__action",
                      children: title
                    });
                    headerProps.className = (0, _classnames.default)({
                      'is-sortable': sortable,
                      'is-sorted is-sorted--up': this.state.sortColumn === key && this.state.sortDirection === 'ASC',
                      'is-sorted is-sorted--down': this.state.sortColumn === key && this.state.sortDirection === 'DESC'
                    }, headerProps.className);
                    headerProps.onClick = () => this.sort(key);
                  }
                  if (width) {
                    headerProps.style = {
                      ...headerProps.style,
                      width
                    };
                  }
                  return /*#__PURE__*/(0, _jsxRuntime.jsx)("th", {
                    ...headerProps,
                    children: title
                  }, key);
                })
              })
            }), reorderable ? children : /*#__PURE__*/(0, _jsxRuntime.jsx)("tbody", {
              children: children
            })]
          })
        });
      };
      const renderItem = _ref16 => {
        let {
          value: {
            row
          },
          index,
          props: reorderableProps,
          isDragged
        } = _ref16;
        return this.renderRow({
          row,
          index,
          hasTitle,
          realColumn,
          reorderableProps,
          isDragged
        });
      };
      if (reorderable && this.state.ReorderableList) {
        const {
          ReorderableList
        } = this.state;
        content = /*#__PURE__*/(0, _jsxRuntime.jsx)(ReorderableList, {
          beforeDrag: _ref17 => {
            let {
              elements,
              index
            } = _ref17;
            const cells = Array.from(elements[index].firstElementChild.children);
            const reorderableItemWidths = cells.map(cell => window.getComputedStyle(cell).width);
            this.setState({
              reorderableItemWidths
            });
          },
          onChange: _ref18 => {
            let {
              oldIndex,
              newIndex
            } = _ref18;
            (0, _utils.safeInvoke)(onReorderEnd, {
              oldIndex,
              newIndex
            });
          },
          values: this.getData().map(row => ({
            row
          })),
          renderList: renderList,
          renderItem: renderItem,
          lockVertically: true,
          hooks: {
            getChildren: children =>
            // @ts-expect-error
            children.filter(node => node.nodeName !== 'THEAD')
          },
          useDragHandle: false
        });
      } else {
        content = renderList({
          children: this.getData().map((row, index) => renderItem({
            value: {
              row
            },
            index
          }))
        });
      }
    }
    content = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _classnames.default)(`${baseClassName}__table-container`, {
        [`${baseClassName}__table-container--loading`]: loading
      }),
      children: content
    });
    if (sidebar) {
      content = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Columns.default, {
        gap: "md",
        className: (0, _classnames.default)(`${baseClassName}__content`, {
          [`${baseClassName}__content--vertical`]: vertical
        }),
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Columns.Column, {
          fill: true,
          children: content
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Columns.Column, {
          className: `${baseClassName}__sidebar`,
          children: sidebar
        })]
      });
    }
    const shouldBePagination = this.shouldBePagination();
    const createRoot = ref => /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      ref: ref,
      className: (0, _classnames.default)(baseClassName, className),
      ...props,
      children: [this.renderHeader(), this.renderToolbar(), shouldBePagination && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        ref: this.anchorRef
      }), content, shouldBePagination && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__footer`,
        children: this.renderPagination('footer')
      })]
    });
    if (typeof verticalProp === 'number') {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
        bounds: true,
        onResize: this.handleResize,
        children: _ref19 => {
          let {
            measureRef
          } = _ref19;
          return createRoot(measureRef);
        }
      });
    }
    return createRoot();
  }
}
(0, _defineProperty2.default)(List, "defaultProps", {
  data: [],
  sortColumn: undefined,
  sortDirection: 'ASC',
  onSortChange: undefined,
  onSelectionChange: undefined,
  selection: [],
  renderSelectionCheckbox: undefined,
  rowKey: 'key',
  renderRowBody: undefined,
  expandedRows: [],
  notExpandableRows: [],
  onExpandedRowsChange: undefined,
  loadingRows: [],
  className: '',
  baseClassName: `${_constants.CLS_PREFIX}list`,
  pagination: undefined,
  totalRows: undefined,
  toolbar: undefined,
  allRowsSelected: false,
  onAllRowsSelectedChange: undefined,
  filtered: false,
  emptyView: undefined,
  emptyViewMode: 'all',
  sidebar: undefined,
  locale: undefined,
  vertical: _VerticalContext.VERTICAL_BREAKPOINT,
  loading: false,
  rowProps: undefined,
  reorderable: false,
  onReorderEnd: undefined
});
var _default = exports.default = List;