function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
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) { _defineProperty(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 _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) { o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) { if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(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.
 */

import React, { cloneElement, Component, Children } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { keysOf } from '../../common';
import { get } from '../../../services/objects';
import { OuiFormHelpText } from '../form_help_text';
import { OuiFormErrorText } from '../form_error_text';
import { OuiFormLabel } from '../form_label';
import { htmlIdGenerator } from '../../../services/accessibility';
var displayToClassNameMap = {
  row: null,
  rowCompressed: 'ouiFormRow--compressed',
  columnCompressed: 'ouiFormRow--compressed ouiFormRow--horizontal',
  center: null,
  centerCompressed: 'ouiFormRow--compressed',
  columnCompressedSwitch: 'ouiFormRow--compressed ouiFormRow--horizontal ouiFormRow--hasSwitch'
};
export var DISPLAYS = keysOf(displayToClassNameMap);
export var OuiFormRow = /*#__PURE__*/function (_Component) {
  _inherits(OuiFormRow, _Component);
  var _super = _createSuper(OuiFormRow);
  function OuiFormRow() {
    var _this;
    _classCallCheck(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));
    _defineProperty(_assertThisInitialized(_this), "state", {
      isFocused: false,
      id: _this.props.id || htmlIdGenerator()()
    });
    _defineProperty(_assertThisInitialized(_this), "onFocus", function () {
      // Doing this to allow onFocus to be called correctly from the child input element as this component overrides it
      var onChildFocus = 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;
        }
      });
    });
    _defineProperty(_assertThisInitialized(_this), "onBlur", function () {
      // Doing this to allow onBlur to be called correctly from the child input element as this component overrides it
      var onChildBlur = get(_this.props, 'children.props.onBlur');
      if (onChildBlur) {
        onChildBlur.apply(void 0, arguments);
      }
      _this.setState({
        isFocused: false
      });
    });
    return _this;
  }
  _createClass(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 = _objectWithoutProperties(_this$props, ["children", "helpText", "isInvalid", "error", "label", "labelType", "labelAppend", "hasEmptyLabelSpace", "fullWidth", "className", "describedByIds", "display", "hasChildLabel", "id"]);
      var id = this.state.id;
      var classes = classNames('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.createElement(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.createElement(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.createElement("div", {
          className: "ouiFormRow__labelWrapper"
        }, /*#__PURE__*/React.createElement(OuiFormLabel, _extends({
          className: "ouiFormRow__label",
          isInvalid: isInvalid,
          "aria-invalid": isInvalid
        }, labelProps), label), labelAppend && ' ', labelAppend);
      }
      var optionalProps = {};
      /**
       * Safe use of ! as default prop is []
       */
      var describingIds = _toConsumableArray(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__*/cloneElement(Children.only(children), _objectSpread({
        id: id,
        onFocus: this.onFocus,
        onBlur: this.onBlur
      }, optionalProps));
      var fieldWrapperClasses = classNames('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.createElement(React.Fragment, null, optionalLabel, /*#__PURE__*/React.createElement("div", {
        className: fieldWrapperClasses
      }, field, optionalErrors, optionalHelpTexts));
      return labelType === 'legend' ? /*#__PURE__*/React.createElement("fieldset", _extends({}, sharedProps, rest), contents) : /*#__PURE__*/React.createElement("div", _extends({}, sharedProps, rest), contents);
    }
  }]);
  return OuiFormRow;
}(Component);

// @internal
_defineProperty(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.oneOfType([PropTypes.oneOf(["label"]), PropTypes.oneOf(["legend"])]),
  className: PropTypes.string,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.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.oneOf(["row", "rowCompressed", "columnCompressed", "center", "centerCompressed", "columnCompressedSwitch"]),
  hasEmptyLabelSpace: PropTypes.bool,
  fullWidth: PropTypes.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.arrayOf(PropTypes.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.bool,
  /**
     * ReactElement to render as this component's content
     */
  /**
     * ReactElement to render as this component's content
     */
  children: PropTypes.element.isRequired,
  label: PropTypes.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.any,
  id: PropTypes.string,
  isInvalid: PropTypes.bool,
  error: PropTypes.oneOfType([PropTypes.node.isRequired, PropTypes.arrayOf(PropTypes.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.oneOfType([PropTypes.node.isRequired, PropTypes.arrayOf(PropTypes.node.isRequired).isRequired])
};
// @internal
export var OuiCompressedFormRow = /*#__PURE__*/function (_OuiFormRow) {
  _inherits(OuiCompressedFormRow, _OuiFormRow);
  var _super2 = _createSuper(OuiCompressedFormRow);
  function OuiCompressedFormRow() {
    _classCallCheck(this, OuiCompressedFormRow);
    return _super2.apply(this, arguments);
  }
  return OuiCompressedFormRow;
}(OuiFormRow);

/* OUI -> EUI Aliases: Build-Time */
_defineProperty(OuiCompressedFormRow, "defaultProps", _objectSpread(_objectSpread({}, OuiFormRow.defaultProps), {}, {
  display: 'rowCompressed'
}));
/* OUI -> EUI Aliases: Build-Time */export { EuiFormRow, EuiCompressedFormRow } from '../../../eui_components/form/form_row/form_row';