"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.SECTION_BASE_CLASS_NAME = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classnames = _interopRequireDefault(require("classnames"));
var _react = require("react");
var _reactMeasure = _interopRequireDefault(require("react-measure"));
var _constants = require("../../constants");
var _Button = _interopRequireDefault(require("../Button"));
var _FormContext = _interopRequireDefault(require("../Form/FormContext"));
var _InPlaceEdit = _interopRequireDefault(require("../InPlaceEdit"));
var _utils = require("../utils");
var _VerticalContext = _interopRequireWildcard(require("../VerticalContext"));
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 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;
};
const SECTION_BASE_CLASS_NAME = exports.SECTION_BASE_CLASS_NAME = `${_constants.CLS_PREFIX}section`;
const DEFAULT_PROPS = {
  title: undefined,
  intent: undefined,
  collapsible: false,
  collapsed: false,
  onTitleChange: undefined,
  onClose: undefined,
  onToggle: undefined,
  buttons: undefined,
  vertical: undefined,
  children: undefined,
  className: undefined,
  baseClassName: SECTION_BASE_CLASS_NAME,
  form: undefined
};
class Section extends _react.Component {
  constructor() {
    super(...arguments);
    (0, _defineProperty2.default)(this, "state", {
      vertical: false
    });
    (0, _defineProperty2.default)(this, "handleResize", _ref => {
      let {
        bounds
      } = _ref;
      if (this.props.vertical !== undefined || !bounds) {
        return;
      }
      this.setState({
        vertical: bounds.width < _VerticalContext.VERTICAL_BREAKPOINT
      });
    });
    (0, _defineProperty2.default)(this, "handleCollapse", e => {
      if ((0, _utils.isClickable)(e)) {
        return;
      }
      this.setState(_ref2 => {
        let {
          collapsed
        } = _ref2;
        return {
          collapsed: !collapsed
        };
      }, () => {
        this.props.onToggle?.(this.state.collapsed ?? false);
      });
    });
  }
  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(_ref3) {
    let {
      baseClassName,
      collapsible
    } = _ref3;
    const {
      collapsed
    } = this.state;
    return collapsible && /*#__PURE__*/(0, _jsxRuntime.jsx)(_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(_ref4) {
    let {
      baseClassName,
      onClose,
      buttons
    } = _ref4;
    return (onClose || buttons) && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: `${baseClassName}__header-buttons`,
      children: [buttons, onClose && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
        ghost: true,
        className: (0, _classnames.default)(`${baseClassName}__control-button`, `${baseClassName}__control-button--close`),
        onClick: onClose,
        icon: "cross-mark"
      })]
    });
  }
  renderTitle(_ref5) {
    let {
      baseClassName,
      title,
      onTitleChange
    } = _ref5;
    return title && /*#__PURE__*/(0, _jsxRuntime.jsx)(_InPlaceEdit.default, {
      className: `${baseClassName}__title`,
      value: title,
      onChange: onTitleChange,
      onClick: e => {
        const button = e.target?.closest(`.${baseClassName}__header`)?.querySelector(`.${baseClassName}__control-button`);
        button?.click();
      }
    });
  }
  renderContent(_ref6) {
    let {
      collapsible,
      children
    } = _ref6;
    const {
      collapsed
    } = this.state;
    if (collapsible && collapsed) {
      return null;
    }
    return children;
  }
  render() {
    const {
      baseClassName = SECTION_BASE_CLASS_NAME,
      className,
      intent,
      collapsible = false,
      title,
      collapsed,
      onTitleChange,
      onClose,
      onToggle,
      buttons,
      vertical: verticalProp,
      children,
      form,
      ...props
    } = this.props;
    const vertical = verticalProp === undefined ? this.state.vertical : verticalProp;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_VerticalContext.default.Provider, {
      value: vertical,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
        onResize: this.handleResize,
        bounds: true,
        children: _ref7 => {
          let {
            measureRef
          } = _ref7;
          return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            ref: measureRef,
            className: (0, _classnames.default)(baseClassName, {
              [`${baseClassName}--${intent}`]: intent,
              [`${baseClassName}--collapsible`]: collapsible,
              [`${baseClassName}--collapsed`]: this.state.collapsed,
              [`${baseClassName}--vertical`]: vertical
            }, className),
            ...props,
            children: [title && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
              className: `${baseClassName}__header`,
              children: [this.renderCollapseButton({
                baseClassName,
                collapsible
              }), this.renderTitle({
                baseClassName,
                title,
                onTitleChange
              }), this.renderCloseButton({
                baseClassName,
                onClose,
                buttons
              })]
            }), this.renderContent({
              collapsible,
              children
            })]
          });
        }
      })
    });
  }
}

/**
 * `Section` component is used for dividing of complex content into groups for better readability
 * and comprehension of the presented information.
 * @since 0.0.54
 */
(0, _defineProperty2.default)(Section, "defaultProps", DEFAULT_PROPS);
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__*/(0, _jsxRuntime.jsx)(Section, {
    ...props,
    form: form,
    vertical: vertical
  });
};
SectionWrapper.displayName = 'Section';
SectionWrapper.defaultProps = DEFAULT_PROPS;
SectionWrapper.WrappedComponent = Section;
var _default = exports.default = SectionWrapper;