"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.VIEW_TILE = exports.VIEW_ROW = exports.VIEW_RESPONSIVE = exports.VIEW_EXTENDED = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _utils = require("../utils");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _reactMeasure = _interopRequireDefault(require("react-measure"));
var _constants = require("../../constants");
var _Pagination = _interopRequireDefault(require("../Pagination"));
var _Grid = _interopRequireDefault(require("../Grid"));
var _GridCol = _interopRequireDefault(require("../GridCol"));
var _Button = _interopRequireDefault(require("../Button"));
var _Spinner = _interopRequireDefault(require("../Spinner"));
var _Translate = _interopRequireDefault(require("../Translate"));
var _CardListToolbar = _interopRequireDefault(require("./CardListToolbar"));
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const VIEW_TILE = exports.VIEW_TILE = 'tile';
const VIEW_RESPONSIVE = exports.VIEW_RESPONSIVE = 'responsive';
const VIEW_EXTENDED = exports.VIEW_EXTENDED = 'extended';
const VIEW_ROW = exports.VIEW_ROW = 'row';

/**
 * @deprecated `CardList` was used for displaying list of objects presented in various data formats
 * including images and other interface components.
 * Now it is deprecated and [List should be used](#!/List) instead.
 * @since 0.0.54
 */
class CardList extends _react.Component {
  constructor() {
    super(...arguments);
    (0, _defineProperty2.default)(this, "state", {
      page: this.props.defaultPage,
      totalItems: this.props.totalItems || this.props.items.length,
      pageSize: 10,
      items: this.props.items,
      view: this.props.view
    });
    (0, _defineProperty2.default)(this, "selectAll", () => {
      const {
        items
      } = this.state;
      this.select(items.map(this.getItemKey));
    });
    (0, _defineProperty2.default)(this, "selectNone", () => {
      this.select([]);
    });
    (0, _defineProperty2.default)(this, "getItemKey", item => {
      const {
        itemKey
      } = this.props;
      return item[itemKey];
    });
    (0, _defineProperty2.default)(this, "renderItem", item => {
      const {
        baseClassName,
        itemRender,
        onSelectionChange
      } = this.props;
      const {
        view
      } = this.state;
      return /*#__PURE__*/(0, _react.cloneElement)(itemRender(item), {
        key: this.getItemKey(item),
        view: this.isTile() ? VIEW_TILE : view,
        className: (0, _classnames.default)(`${baseClassName}__list-item`),
        selection: onSelectionChange ? this.itemSelection(item) : null
      });
    });
    (0, _defineProperty2.default)(this, "previousView", null);
    (0, _defineProperty2.default)(this, "handleResize", _ref => {
      let {
        bounds: {
          width
        }
      } = _ref;
      const view = width > 584 ? this.previousView : VIEW_RESPONSIVE;
      if (view === VIEW_RESPONSIVE && !this.previousView) {
        this.previousView = this.state.view;
      } else if (view !== VIEW_RESPONSIVE) {
        this.previousView = null;
      }
      if (view && view !== this.state.view) {
        this.changeView(view);
      }
    });
  }
  static getDerivedStateFromProps(props, state) {
    const {
      items,
      totalItems
    } = props;
    const {
      prevItems,
      prevTotalItems
    } = state;
    const nextState = {};
    if (items !== prevItems) {
      nextState.items = items;
    }
    if (totalItems !== prevTotalItems) {
      nextState.totalItems = totalItems || items.length;
    }
    nextState.prevItems = items;
    nextState.prevTotalItems = totalItems || items.length;
    return nextState;
  }
  componentDidMount() {
    this.fetchItems();
  }
  componentDidUpdate(prevProps) {
    const {
      view
    } = this.props;
    if (view !== prevProps.view && this.state.view !== VIEW_RESPONSIVE) {
      this.fetchItems({
        page: 1,
        view
      });
    }
  }
  totalPages() {
    const {
      totalItems,
      pageSize
    } = this.state;
    return Math.ceil(totalItems / pageSize);
  }
  fetchItems() {
    let {
      page = this.state.page,
      view = this.state.view
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      onItemsFetch
    } = this.props;
    const pageSize = view === VIEW_ROW ? 40 : 10;
    this.setState({
      view,
      page,
      pageSize
    });
    (0, _utils.safeInvoke)(onItemsFetch, {
      page,
      pageSize
    });
  }
  loadMore() {
    const {
      onItemsFetch
    } = this.props;
    const {
      page
    } = this.state;
    const nextPage = page + 1;
    this.setState({
      page: nextPage,
      pageSize: 10
    });
    (0, _utils.safeInvoke)(onItemsFetch, {
      page: nextPage,
      pageSize: 10
    });
  }
  isTile() {
    const {
      view
    } = this.state;
    return view === VIEW_TILE || view === VIEW_RESPONSIVE;
  }
  renderPagination() {
    const {
      baseClassName
    } = this.props;
    const {
      page,
      view
    } = this.state;
    const totalPages = this.totalPages();
    if (totalPages < 2) {
      return null;
    }
    if (view === VIEW_RESPONSIVE && page < totalPages) {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__pagination`,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
          onClick: () => this.loadMore(),
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
            content: 'CardList.loadMore',
            fallback: 'Load more'
          })
        })
      });
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Pagination.default, {
      className: `${baseClassName}__pagination`,
      total: totalPages,
      current: page,
      onSelect: page => this.fetchItems({
        page
      })
    });
  }
  changeView(view) {
    const {
      onViewChange
    } = this.props;
    this.fetchItems({
      page: 1,
      view
    });
    (0, _utils.safeInvoke)(onViewChange, view);
  }
  select(keys) {
    const {
      onSelectionChange
    } = this.props;
    onSelectionChange(keys);
  }
  itemSelection(item) {
    const key = this.getItemKey(item);
    const {
      selection
    } = this.props;
    return {
      isSelected: selection.indexOf(key) > -1,
      onSelectionChange: _ref2 => {
        let {
          isSelected
        } = _ref2;
        const keys = isSelected ? [...selection, key] : selection.filter(k => k !== key);
        this.select(keys);
      }
    };
  }
  renderLoader() {
    const {
      baseClassName,
      loading
    } = this.props;
    if (!loading) {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: `${baseClassName}__content-blocker`,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__loader`,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Spinner.default, {
          className: `${baseClassName}__loader-spinner`
        })
      })
    });
  }
  render() {
    const {
      baseClassName,
      className,
      items,
      onItemsFetch,
      view,
      itemKey,
      itemRender,
      onViewChange,
      selection,
      onSelectionChange,
      selectionButton,
      viewSwitcher,
      toolbarGroups,
      totalItems,
      defaultPage,
      loading,
      ...props
    } = this.props;
    let content = this.state.items.map(this.renderItem);
    if (this.isTile()) {
      content = /*#__PURE__*/(0, _jsxRuntime.jsx)(_Grid.default, {
        minColumnWidth: 400,
        gap: "md",
        children: _react.Children.map(content, child => /*#__PURE__*/(0, _jsxRuntime.jsx)(_GridCol.default, {
          children: child
        }, child.props.key))
      });
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
      bounds: true,
      onResize: this.handleResize,
      children: _ref3 => {
        let {
          measureRef
        } = _ref3;
        return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          ref: measureRef,
          className: (0, _classnames.default)(baseClassName, className),
          ...props,
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_CardListToolbar.default, {
            selection: onSelectionChange && this.state.totalItems > 1 ? {
              ...selectionButton,
              total: this.state.totalItems,
              onSelectAll: this.selectAll,
              onSelectNone: this.selectNone,
              checked: this.state.items.length === selection.length
            } : null,
            onViewChange: viewSwitcher ? view => this.changeView(view) : null,
            currentView: this.state.view,
            groups: toolbarGroups
          }), this.state.items.length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: `${baseClassName}__list ${baseClassName}__list--${this.state.view}`,
            children: content
          }), this.state.items.length === 0 && !loading && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Translate.default, {
            content: "CardList.notFound",
            fallback: "No items found."
          }), this.renderPagination(), this.renderLoader()]
        });
      }
    });
  }
}
CardList.propTypes = {
  /**
   * Array of data items for rendering.
   * @since 0.0.68
   */
  items: _propTypes.default.array.isRequired,
  /**
   * Callback for fetching items.
   * @since 0.0.68
   */
  onItemsFetch: _propTypes.default.func,
  /**
   * Total items. Equal items.length by default.
   * @since 0.0.68
   */
  totalItems: _propTypes.default.number,
  /**
   * Default page number.
   * @since 1.0.1
   */
  defaultPage: _propTypes.default.number,
  /**
   * View mode.
   * @since 0.0.54
   */
  view: _propTypes.default.oneOf([VIEW_EXTENDED, VIEW_TILE, VIEW_ROW, VIEW_RESPONSIVE]),
  /**
   * View change callback.
   * @since 0.0.54
   */
  onViewChange: _propTypes.default.func,
  /**
   * View switcher config.
   * @since 0.0.59
   */
  viewSwitcher: _propTypes.default.bool,
  /**
   * Array of keys of selected cards.
   * @since 0.0.59
   */
  selection: _propTypes.default.array,
  /**
   * Selection change handler for list. Checkboxes will only be rendered if this prop is defined.
   * @since 0.0.59
   */
  onSelectionChange: _propTypes.default.func,
  /**
   * Config for selection button in the toolbar.
   * @since 0.0.59
   */
  selectionButton: _propTypes.default.shape({
    /**
     * See [Badge](#!/Badge) for all props.
     */
    badge: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object]),
    /**
     * Array of additional [MenuItems](#!/MenuItem).
     */
    menuItems: _propTypes.default.arrayOf(_propTypes.default.element)
  }),
  /**
   * Toolbar groups for the toolbar.
   * @since 0.0.59
   */
  toolbarGroups: _propTypes.default.arrayOf(_propTypes.default.element),
  /**
   * Unique key.
   * @since 0.0.59
   */
  itemKey: _propTypes.default.string.isRequired,
  /**
   * Render function for item.
   * @since 0.0.59
   */
  itemRender: _propTypes.default.func.isRequired,
  /**
   * Indicate the loading state of the list.
   * @since 0.0.68
   */
  loading: _propTypes.default.bool,
  /**
   * @ignore
   */
  className: _propTypes.default.string,
  /**
   * @ignore
   */
  baseClassName: _propTypes.default.string
};
CardList.defaultProps = {
  onItemsFetch: null,
  totalItems: null,
  defaultPage: 1,
  view: VIEW_EXTENDED,
  onViewChange: null,
  viewSwitcher: false,
  selection: [],
  onSelectionChange: null,
  selectionButton: {
    badge: null,
    menuItems: []
  },
  toolbarGroups: [],
  loading: false,
  className: null,
  baseClassName: `${_constants.CLS_PREFIX}card-list`
};
var _default = exports.default = CardList;