"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 _constants = require("../../constants");
var _Grid = _interopRequireDefault(require("../Grid"));
var _GridCol = _interopRequireDefault(require("../GridCol"));
var _utils = require("../utils");
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 getNextSelectedValue = (value, prevValue, toggleable) => {
  if (Array.isArray(prevValue)) {
    if (prevValue.indexOf(value) !== -1) {
      if (toggleable) {
        return prevValue.filter(v => v !== value);
      }
      return prevValue;
    }
    return [...prevValue, value];
  }
  if (toggleable && prevValue === value) {
    return null;
  }
  return value;
};
/**
 * `ItemList` component is used for displaying list of [Items](#!/Item)
 * according to [Grid](#!/Grid) principle.
 * @since 0.0.48
 */
class ItemList extends _react.Component {
  constructor(_props) {
    super(_props);
    // eslint-disable-next-line react/state-in-constructor
    (0, _defineProperty2.default)(this, "createItemProps", item => {
      const {
        baseClassName,
        selectable,
        onSelect,
        reorderable,
        hoverable
      } = this.props;
      const classNameList = [`${baseClassName}__item`];
      const props = {};
      if (selectable && item.props.value !== undefined) {
        const {
          value
        } = this.state;
        const itemValue = item.props.value;
        if (Array.isArray(value) && value.indexOf(itemValue) !== -1) {
          classNameList.push(`${baseClassName}__item--selected`);
        } else if (value === itemValue) {
          classNameList.push(`${baseClassName}__item--selected`);
        }
        props.onClick = e => {
          (0, _utils.safeInvoke)(item.props.onClick, e);
          const nextValue = getNextSelectedValue(itemValue, value, selectable === 'toggleable' || selectable === 'multiple');
          this.setState({
            value: nextValue
          });
          (0, _utils.safeInvoke)(onSelect, nextValue);
        };
      }

      // Extends hoverable behavior from the ItemList in case if its child doesn't have its own
      if (item.props.hoverable === undefined) {
        props.hoverable = hoverable && this.canManageHoverableState();
      }
      if (reorderable) {
        classNameList.push(`${baseClassName}__item--reorderable`);
      }
      classNameList.push(item.props.className);
      props.className = (0, _classnames.default)(...classNameList);
      return props;
    });
    this.state = {
      ReorderableGrid: null,
      ReorderableGridCol: null,
      value: typeof _props.defaultValue === 'undefined' ? null : _props.defaultValue
    };
  }
  static getDerivedStateFromProps(_ref, state) {
    let {
      selectable,
      value: propValue
    } = _ref;
    if (selectable) {
      const multiple = selectable === 'multiple';
      const safeValue = multiple ? [] : null;
      const value = typeof propValue === 'undefined' ? state.value : propValue;
      if (multiple && !Array.isArray(value)) {
        if (value) {
          return {
            value: [value]
          };
        }
        return {
          value: safeValue
        };
      } else if (!multiple && Array.isArray(value)) {
        if (value[0]) {
          return {
            value: value[0]
          };
        }
        return {
          value: safeValue
        };
      }
      return {
        value
      };
    }
    return null;
  }
  componentDidMount() {
    const {
      reorderable
    } = this.props;
    if (reorderable) {
      // @ts-ignore
      Promise.resolve().then(() => _interopRequireWildcard(require( /* webpackChunkName: "react-sortable-hoc" */'react-sortable-hoc'))).then(_ref2 => {
        let {
          sortableContainer,
          sortableElement
        } = _ref2;
        this.setState({
          ReorderableGrid: sortableContainer(_Grid.default),
          ReorderableGridCol: sortableElement(_GridCol.default)
        });
      });
    }
  }
  renderNormal(_ref3) {
    let {
      baseClassName,
      children,
      ...props
    } = _ref3;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Grid.default, {
      ...props,
      children: _react.Children.map(children, child => {
        if ( /*#__PURE__*/(0, _react.isValidElement)(child)) {
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(_GridCol.default, {
            className: (0, _classnames.default)(`${baseClassName}__col`),
            children: /*#__PURE__*/(0, _react.cloneElement)(child, this.createItemProps(child))
          });
        }
        return null;
      })
    });
  }
  someChild(predicate) {
    let result = false;
    _react.Children.forEach(this.props.children, child => {
      if (child && predicate(child)) {
        result = true;
      }
    });
    return result;
  }

  /**
   * There are some states where we can't manage hoverable state
   */
  canManageHoverableState() {
    const {
      reorderable,
      selectable
    } = this.props;
    return !reorderable && !selectable;
  }
  isHoverable() {
    if (!this.canManageHoverableState()) {
      return false;
    }
    return this.props.hoverable || this.hasHoverableCard();
  }
  hasViewCard() {
    return this.someChild(child => child.props && child.props.view === 'card');
  }
  hasHoverableCard() {
    return this.someChild(child => child.props && !!child.props.hoverable);
  }
  renderReorderable(_ref4) {
    let {
      baseClassName,
      onReorderEnd,
      children,
      ...props
    } = _ref4;
    const {
      ReorderableGrid,
      ReorderableGridCol
    } = this.state;
    if (!ReorderableGrid) {
      return null;
    }
    const helperClass = (0, _classnames.default)({
      [`${baseClassName}__col--gap-xs`]: props.gap === 'xs',
      [`${baseClassName}__col--gap-sm`]: props.gap === 'sm',
      [`${baseClassName}__col--gap-md`]: props.gap === 'md',
      [`${baseClassName}__col--gap-lg`]: props.gap === 'lg',
      [`${baseClassName}__col--gap-xl`]: props.gap === 'xl'
    });
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(ReorderableGrid, {
      axis: "xy",
      helperClass: helperClass,
      onSortEnd: onReorderEnd,
      ...props,
      children: _react.Children.map(children, (child, index) => {
        if ( /*#__PURE__*/(0, _react.isValidElement)(child)) {
          const {
            disabled
          } = child.props;
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(ReorderableGridCol, {
            index: index,
            className: (0, _classnames.default)(`${baseClassName}__col`),
            disabled: disabled,
            children: /*#__PURE__*/(0, _react.cloneElement)(child, this.createItemProps(child))
          });
        }
        return null;
      })
    });
  }
  render() {
    const {
      className,
      reorderable,
      hoverable,
      stretchable,
      selectable,
      onSelect,
      value,
      defaultValue,
      onReorderEnd,
      ...props
    } = this.props;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _classnames.default)(this.props.baseClassName, {
        [`${this.props.baseClassName}--hoverable`]: this.isHoverable(),
        [`${this.props.baseClassName}--stretchable`]: stretchable,
        [`${this.props.baseClassName}--selectable`]: selectable,
        [`${this.props.baseClassName}--cards`]: this.hasViewCard()
      }, className),
      children: reorderable ? this.renderReorderable({
        onReorderEnd,
        ...props
      }) : this.renderNormal(props)
    });
  }
}
(0, _defineProperty2.default)(ItemList, "defaultProps", {
  hoverable: true,
  stretchable: false,
  reorderable: false,
  selectable: false,
  baseClassName: `${_constants.CLS_PREFIX}item-list`
});
var _default = exports.default = ItemList;