"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "ErrorPlacement", {
  enumerable: true,
  get: function get() {
    return _flags.ErrorPlacement;
  }
});
exports.useInlineError = useInlineError;
var _compat = _interopRequireDefault(require("preact/compat"));
var _InlineError = _interopRequireDefault(require("./InlineError"));
var _classnames = _interopRequireDefault(require("classnames"));
var _flags = require("../flags");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// TODO: We should conditionally return an errorId, because we want to be able
// to include it in the aria-describedby without conditional logic in the component

/**
 * Hook that takes the props for a form field component, extracts the props relevant
 * to the error message, and conditionally renders an `InlineError` in the `topError`
 * or `bottomError` property based on the `errorPlacement` and the presence of an
 * `errorMessage`.
 */
function useInlineError(props) {
  var _props$errorId, _props$ariaInvalid;
  var errorId = (_props$errorId = props.errorId) !== null && _props$errorId !== void 0 ? _props$errorId : "".concat(props.id, "__error");
  var errorMessage = props.errorMessage,
    errorMessageClassName = props.errorMessageClassName,
    _props$errorPlacement = props.errorPlacement,
    errorPlacement = _props$errorPlacement === void 0 ? (0, _flags.errorPlacementDefault)() : _props$errorPlacement,
    inversed = props.inversed;
  var errorElement = errorMessage ? /*#__PURE__*/_compat.default.createElement(_InlineError.default, {
    id: errorId,
    inversed: inversed,
    className: (0, _classnames.default)(errorMessageClassName, errorPlacement === _flags.ErrorPlacement.Bottom && 'ds-c-inline-error--bottom')
  }, errorMessage) : undefined;
  var topError;
  var bottomError;
  if (errorPlacement === _flags.ErrorPlacement.Top) {
    topError = errorElement;
  } else {
    bottomError = errorElement;
  }

  // If the user has provided an `aria-invalid` attribute, use that as the source
  // of truth; otherwise, it's invalid if there's an error message.
  var invalid = (_props$ariaInvalid = props['aria-invalid']) !== null && _props$ariaInvalid !== void 0 ? _props$ariaInvalid : !!errorMessage;
  return {
    errorId: errorMessage ? errorId : undefined,
    invalid: invalid,
    topError: topError,
    bottomError: bottomError
  };
}