"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _reactMeasure = _interopRequireDefault(require("react-measure"));

var _constants = require("../../constants");

var _utils = require("../utils");

var _InPlaceEdit = _interopRequireDefault(require("../InPlaceEdit"));

var _Button = _interopRequireDefault(require("../Button"));

var _VerticalContext = _interopRequireWildcard(require("../VerticalContext"));

var _FormContext = _interopRequireDefault(require("../Form/FormContext"));

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-2020. Plesk International GmbH. All rights reserved.

/* eslint-disable react/no-deprecated */
const getErrorsForChildren = (form, children) => {
  let errors = {};

  _react.Children.forEach(children, child => {
    if (! /*#__PURE__*/(0, _react.isValidElement)(child)) {
      return;
    }

    if (child.props.name) {
      errors = { ...errors,
        ...form.getErrors(child.props.name)
      };
    }

    if (child.props.children) {
      errors = { ...errors,
        ...getErrorsForChildren(form, child.props.children)
      };
    }
  });

  return errors;
};

class Section extends _react.Component {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "state", {
      vertical: false
    });
    (0, _defineProperty2.default)(this, "handleResize", ({
      bounds
    }) => {
      if (this.props.vertical !== undefined) {
        return;
      }

      this.setState({
        vertical: bounds.width < _VerticalContext.VERTICAL_BREAKPOINT
      });
    });
    (0, _defineProperty2.default)(this, "handleCollapse", e => {
      if ((0, _utils.isClickable)(e)) {
        return;
      }

      this.setState(({
        collapsed
      }) => ({
        collapsed: !collapsed
      }), () => {
        if (this.props.onToggle) {
          this.props.onToggle(this.state.collapsed);
        }
      });
    });
  }

  static getDerivedStateFromProps(props, state) {
    const {
      collapsible,
      collapsed,
      form,
      children
    } = props;
    const {
      prevCollapsed,
      prevErrors
    } = state;
    const nextState = {};

    if (collapsed !== prevCollapsed) {
      nextState.collapsed = collapsed;
    }

    nextState.prevCollapsed = collapsed;

    if (collapsible && form) {
      const errors = getErrorsForChildren(form, children);

      if (JSON.stringify(errors) !== JSON.stringify(prevErrors) && Object.keys(errors).length > 0) {
        nextState.collapsed = false;
      }

      nextState.prevErrors = errors;
    }

    return nextState;
  }

  renderCollapseButton({
    baseClassName,
    collapsible
  }) {
    const {
      collapsed
    } = this.state;
    return collapsible && /*#__PURE__*/_react.default.createElement(_Button.default, {
      ghost: true,
      className: (0, _classnames.default)(`${baseClassName}__control-button`, `${baseClassName}__control-button--collapse`),
      icon: {
        name: 'chevron-up',
        flipVertical: collapsed
      },
      onClick: this.handleCollapse
    });
  }

  renderCloseButton({
    baseClassName,
    onClose,
    buttons
  }) {
    return (onClose || buttons) && /*#__PURE__*/_react.default.createElement("div", {
      className: `${baseClassName}__header-buttons`
    }, buttons, onClose && /*#__PURE__*/_react.default.createElement(_Button.default, {
      ghost: true,
      className: (0, _classnames.default)(`${baseClassName}__control-button`, `${baseClassName}__control-button--close`),
      onClick: onClose,
      icon: "cross-mark"
    }));
  }

  renderTitle({
    baseClassName,
    title,
    onTitleChange
  }) {
    return title && /*#__PURE__*/_react.default.createElement(_InPlaceEdit.default, {
      className: `${baseClassName}__title`,
      value: title,
      onChange: onTitleChange,
      onClick: e => {
        var _e$target$closest$que;

        (_e$target$closest$que = e.target.closest(`.${baseClassName}__header`).querySelector(`.${baseClassName}__control-button`)) === null || _e$target$closest$que === void 0 ? void 0 : _e$target$closest$que.click();
      }
    });
  }

  renderContent({
    collapsible,
    children
  }) {
    const {
      collapsed
    } = this.state;

    if (collapsible && collapsed) {
      return null;
    }

    return children;
  }

  render() {
    const {
      baseClassName,
      className,
      intent,
      collapsible,
      title,
      collapsed,
      onTitleChange,
      onClose,
      onToggle,
      buttons,
      vertical: verticalProp,
      children,
      form,
      ...props
    } = this.props;
    const vertical = verticalProp === undefined ? this.state.vertical : verticalProp;
    return /*#__PURE__*/_react.default.createElement(_VerticalContext.default.Provider, {
      value: vertical
    }, /*#__PURE__*/_react.default.createElement(_reactMeasure.default, {
      onResize: this.handleResize,
      bounds: true
    }, ({
      measureRef
    }) => /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
      ref: measureRef,
      className: (0, _classnames.default)(baseClassName, {
        [`${baseClassName}--${intent}`]: intent,
        [`${baseClassName}--collapsible`]: collapsible,
        [`${baseClassName}--collapsed`]: this.state.collapsed,
        [`${baseClassName}--vertical`]: vertical
      }, className)
    }, props), title && /*#__PURE__*/_react.default.createElement("div", {
      className: `${baseClassName}__header`
    }, this.renderCollapseButton({
      baseClassName,
      collapsible
    }), this.renderTitle({
      baseClassName,
      title,
      onTitleChange
    }), this.renderCloseButton({
      baseClassName,
      onClose,
      buttons
    })), this.renderContent({
      collapsible,
      children
    }))));
  }

}

const propTypes = {
  /**
   * Title of the section.
   * @since 0.0.54
   */
  title: _propTypes.default.node,

  /**
   * Visual intent color to apply to component.
   * @since 0.0.54
   */
  intent: _propTypes.default.oneOf(['danger', 'warning', 'success', 'inactive']),

  /**
   * Is section collapsible.
   * @since 0.0.54
   */
  collapsible: _propTypes.default.bool,

  /**
   * Is section collapsed now.
   * @since 0.0.54
   */
  collapsed: _propTypes.default.bool,

  /**
   * Event handler of title change with inline editing form.
   * @since 0.0.54
   */
  onTitleChange: _propTypes.default.func,

  /**
   * Event handler of closing section with X-sign at the right.
   * @since 0.0.54
   */
  onClose: _propTypes.default.func,

  /**
   * A callback executed when the section collapsing.
   * @since 3.26.0
   */
  onToggle: _propTypes.default.func,

  /**
   * Array of custom section action button at the right.
   * @since 0.0.54
   */
  buttons: _propTypes.default.arrayOf(_propTypes.default.element),

  /**
   * Vertical or horizontal section view.
   * Section view will be automatically switched if this parameter is not specified explicitly.
   * @since 0.3.0
   */
  vertical: _propTypes.default.bool,

  /**
   * Content of the `Section`.
   * @since 0.0.54
   */
  children: _propTypes.default.node,

  /**
   * @ignore
   */
  className: _propTypes.default.string,

  /**
   * @ignore
   */
  baseClassName: _propTypes.default.string,

  /**
   * @ignore
   */
  form: _propTypes.default.object
};
const defaultProps = {
  title: undefined,
  intent: undefined,
  collapsible: false,
  collapsed: false,
  onTitleChange: undefined,
  onClose: undefined,
  onToggle: undefined,
  buttons: undefined,
  vertical: undefined,
  children: undefined,
  className: undefined,
  baseClassName: `${_constants.CLS_PREFIX}section`,
  form: undefined
};
Section.propTypes = propTypes;
Section.defaultProps = defaultProps;
/**
 * `Section` component is used for dividing of complex content into groups for better readability
 * and comprehension of the presented information.
 * @since 0.0.54
 */

const SectionWrapper = props => {
  const form = (0, _react.useContext)(_FormContext.default);
  const verticalContext = (0, _react.useContext)(_VerticalContext.default);
  const vertical = props.vertical === undefined ? verticalContext : props.vertical;
  return /*#__PURE__*/_react.default.createElement(Section, (0, _extends2.default)({}, props, {
    form: form,
    vertical: vertical
  }));
};

SectionWrapper.displayName = 'Section';
SectionWrapper.propTypes = propTypes;
SectionWrapper.defaultProps = defaultProps;
SectionWrapper.WrappedComponent = Section;
var _default = SectionWrapper;
exports.default = _default;