"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiFormRow", {
  enumerable: true,
  get: function get() {
    return _form_row.EuiFormRow;
  }
});
Object.defineProperty(exports, "EuiCompressedFormRow", {
  enumerable: true,
  get: function get() {
    return _form_row.EuiCompressedFormRow;
  }
});
exports.OuiCompressedFormRow = exports.OuiFormRow = exports.DISPLAYS = void 0;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
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 _common = require("../../common");
var _objects = require("../../../services/objects");
var _form_help_text = require("../form_help_text");
var _form_error_text = require("../form_error_text");
var _form_label = require("../form_label");
var _accessibility = require("../../../services/accessibility");
var _form_row = require("../../../eui_components/form/form_row/form_row");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = (0, _getPrototypeOf2.default)(t); if (r) { var s = (0, _getPrototypeOf2.default)(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return (0, _possibleConstructorReturn2.default)(this, e); }; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var displayToClassNameMap = {
  row: null,
  rowCompressed: 'ouiFormRow--compressed',
  columnCompressed: 'ouiFormRow--compressed ouiFormRow--horizontal',
  center: null,
  centerCompressed: 'ouiFormRow--compressed',
  columnCompressedSwitch: 'ouiFormRow--compressed ouiFormRow--horizontal ouiFormRow--hasSwitch'
};
var DISPLAYS = (0, _common.keysOf)(displayToClassNameMap);
exports.DISPLAYS = DISPLAYS;
var OuiFormRow = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(OuiFormRow, _Component);
  var _super = _createSuper(OuiFormRow);
  function OuiFormRow() {
    var _this;
    (0, _classCallCheck2.default)(this, OuiFormRow);
    for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
      _args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(_args));
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
      isFocused: false,
      id: _this.props.id || (0, _accessibility.htmlIdGenerator)()()
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onFocus", function () {
      // Doing this to allow onFocus to be called correctly from the child input element as this component overrides it
      var onChildFocus = (0, _objects.get)(_this.props, 'children.props.onFocus');
      if (onChildFocus) {
        onChildFocus.apply(void 0, arguments);
      }
      _this.setState(function (_ref) {
        var isFocused = _ref.isFocused;
        if (!isFocused) {
          return {
            isFocused: true
          };
        } else {
          return null;
        }
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onBlur", function () {
      // Doing this to allow onBlur to be called correctly from the child input element as this component overrides it
      var onChildBlur = (0, _objects.get)(_this.props, 'children.props.onBlur');
      if (onChildBlur) {
        onChildBlur.apply(void 0, arguments);
      }
      _this.setState({
        isFocused: false
      });
    });
    return _this;
  }
  (0, _createClass2.default)(OuiFormRow, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
        children = _this$props.children,
        helpText = _this$props.helpText,
        isInvalid = _this$props.isInvalid,
        error = _this$props.error,
        label = _this$props.label,
        labelType = _this$props.labelType,
        labelAppend = _this$props.labelAppend,
        hasEmptyLabelSpace = _this$props.hasEmptyLabelSpace,
        fullWidth = _this$props.fullWidth,
        className = _this$props.className,
        describedByIds = _this$props.describedByIds,
        display = _this$props.display,
        hasChildLabel = _this$props.hasChildLabel,
        propsId = _this$props.id,
        rest = (0, _objectWithoutProperties2.default)(_this$props, ["children", "helpText", "isInvalid", "error", "label", "labelType", "labelAppend", "hasEmptyLabelSpace", "fullWidth", "className", "describedByIds", "display", "hasChildLabel", "id"]);
      var id = this.state.id;
      var classes = (0, _classnames.default)('ouiFormRow', {
        'ouiFormRow--hasEmptyLabelSpace': hasEmptyLabelSpace,
        'ouiFormRow--fullWidth': fullWidth
      }, displayToClassNameMap[display],
      // Safe use of ! as default prop is 'row'
      className);
      var optionalHelpTexts;
      if (helpText) {
        var helpTexts = Array.isArray(helpText) ? helpText : [helpText];
        optionalHelpTexts = helpTexts.map(function (helpText, i) {
          var key = typeof helpText === 'string' ? helpText : i;
          return /*#__PURE__*/_react.default.createElement(_form_help_text.OuiFormHelpText, {
            key: key,
            id: "".concat(id, "-help-").concat(i),
            className: "ouiFormRow__text"
          }, helpText);
        });
      }
      var optionalErrors;
      if (error && isInvalid) {
        var errorTexts = Array.isArray(error) ? error : [error];
        optionalErrors = errorTexts.map(function (error, i) {
          var key = typeof error === 'string' ? error : i;
          return /*#__PURE__*/_react.default.createElement(_form_error_text.OuiFormErrorText, {
            key: key,
            id: "".concat(id, "-error-").concat(i),
            className: "ouiFormRow__text"
          }, error);
        });
      }
      var optionalLabel;
      var isLegend = label && labelType === 'legend' ? true : false;
      if (label || labelAppend) {
        var labelProps = {};
        if (isLegend) {
          labelProps = {
            type: labelType
          };
        } else {
          labelProps = {
            htmlFor: hasChildLabel ? id : undefined,
            isFocused: this.state.isFocused,
            type: labelType
          };
        }
        optionalLabel = /*#__PURE__*/_react.default.createElement("div", {
          className: "ouiFormRow__labelWrapper"
        }, /*#__PURE__*/_react.default.createElement(_form_label.OuiFormLabel, (0, _extends2.default)({
          className: "ouiFormRow__label",
          isInvalid: isInvalid,
          "aria-invalid": isInvalid
        }, labelProps), label), labelAppend && ' ', labelAppend);
      }
      var optionalProps = {};
      /**
       * Safe use of ! as default prop is []
       */
      var describingIds = (0, _toConsumableArray2.default)(describedByIds);
      if (optionalHelpTexts) {
        optionalHelpTexts.forEach(function (optionalHelpText) {
          return describingIds.push(optionalHelpText.props.id);
        });
      }
      if (optionalErrors) {
        optionalErrors.forEach(function (error) {
          return describingIds.push(error.props.id);
        });
      }
      if (describingIds.length > 0) {
        optionalProps['aria-describedby'] = describingIds.join(' ');
      }
      var field = /*#__PURE__*/(0, _react.cloneElement)(_react.Children.only(children), _objectSpread({
        id: id,
        onFocus: this.onFocus,
        onBlur: this.onBlur
      }, optionalProps));
      var fieldWrapperClasses = (0, _classnames.default)('ouiFormRow__fieldWrapper', {
        ouiFormRow__fieldWrapperDisplayOnly:
        /**
         * Safe use of ! as default prop is 'row'
         */
        display.startsWith('center')
      });
      var sharedProps = {
        className: classes,
        id: "".concat(id, "-row")
      };
      var contents = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, optionalLabel, /*#__PURE__*/_react.default.createElement("div", {
        className: fieldWrapperClasses
      }, field, optionalErrors, optionalHelpTexts));
      return labelType === 'legend' ? /*#__PURE__*/_react.default.createElement("fieldset", (0, _extends2.default)({}, sharedProps, rest), contents) : /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({}, sharedProps, rest), contents);
    }
  }]);
  return OuiFormRow;
}(_react.Component); // @internal
exports.OuiFormRow = OuiFormRow;
(0, _defineProperty2.default)(OuiFormRow, "defaultProps", {
  display: 'row',
  hasEmptyLabelSpace: false,
  fullWidth: false,
  describedByIds: [],
  labelType: 'label',
  hasChildLabel: true
});
OuiFormRow.propTypes = {
  /**
     * Defaults to rendering a `<label>` but if passed `'legend'` for labelType,
     * will render both a `<legend>` and the surrounding container as a `<fieldset>`
     */
  labelType: _propTypes.default.oneOfType([_propTypes.default.oneOf(["label"]), _propTypes.default.oneOf(["legend"])]),
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  /**
     * When `rowCompressed`, just tightens up the spacing;
     * Set to `columnCompressed` if compressed
     * and horizontal layout is needed.
     * Set to `center` or `centerCompressed` to align non-input
     * content better with inline rows.
     * Set to `columnCompressedSwitch` if the form control being passed
     * as the child is a switch.
     */
  /**
     * When `rowCompressed`, just tightens up the spacing;
     * Set to `columnCompressed` if compressed
     * and horizontal layout is needed.
     * Set to `center` or `centerCompressed` to align non-input
     * content better with inline rows.
     * Set to `columnCompressedSwitch` if the form control being passed
     * as the child is a switch.
     */
  display: _propTypes.default.oneOf(["row", "rowCompressed", "columnCompressed", "center", "centerCompressed", "columnCompressedSwitch"]),
  hasEmptyLabelSpace: _propTypes.default.bool,
  fullWidth: _propTypes.default.bool,
  /**
     * IDs of additional elements that should be part of children's `aria-describedby`
     */
  /**
     * IDs of additional elements that should be part of children's `aria-describedby`
     */
  describedByIds: _propTypes.default.arrayOf(_propTypes.default.string.isRequired),
  /**
     * Escape hatch to not render duplicate labels if the child also renders a label
     */
  /**
     * Escape hatch to not render duplicate labels if the child also renders a label
     */
  hasChildLabel: _propTypes.default.bool,
  /**
     * ReactElement to render as this component's content
     */
  /**
     * ReactElement to render as this component's content
     */
  children: _propTypes.default.element.isRequired,
  label: _propTypes.default.node,
  /**
     * Adds an extra node to the right of the form label without
     * being contained inside the form label. Good for things
     * like documentation links.
     */
  /**
     * Adds an extra node to the right of the form label without
     * being contained inside the form label. Good for things
     * like documentation links.
     */
  labelAppend: _propTypes.default.any,
  id: _propTypes.default.string,
  isInvalid: _propTypes.default.bool,
  error: _propTypes.default.oneOfType([_propTypes.default.node.isRequired, _propTypes.default.arrayOf(_propTypes.default.node.isRequired).isRequired]),
  /**
     *  Adds a single node/string or an array of nodes/strings below the input
     */
  /**
     *  Adds a single node/string or an array of nodes/strings below the input
     */
  helpText: _propTypes.default.oneOfType([_propTypes.default.node.isRequired, _propTypes.default.arrayOf(_propTypes.default.node.isRequired).isRequired])
};
// @internal
var OuiCompressedFormRow = /*#__PURE__*/function (_OuiFormRow) {
  (0, _inherits2.default)(OuiCompressedFormRow, _OuiFormRow);
  var _super2 = _createSuper(OuiCompressedFormRow);
  function OuiCompressedFormRow() {
    (0, _classCallCheck2.default)(this, OuiCompressedFormRow);
    return _super2.apply(this, arguments);
  }
  return OuiCompressedFormRow;
}(OuiFormRow);
/* OUI -> EUI Aliases: Build-Time */
exports.OuiCompressedFormRow = OuiCompressedFormRow;
(0, _defineProperty2.default)(OuiCompressedFormRow, "defaultProps", _objectSpread(_objectSpread({}, OuiFormRow.defaultProps), {}, {
  display: 'rowCompressed'
}));
/* OUI -> EUI Aliases: Build-Time */