"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useInlineError = useInlineError;
var _InlineError = _interopRequireDefault(require("./InlineError"));
var _classnames = _interopRequireDefault(require("classnames"));
var _config = require("../config");
var _jsxRuntime = require("preact/compat/jsx-runtime");
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) {
  const errorId = props.errorId ?? `${props.id}__error`;
  const {
    errorMessage,
    errorMessageClassName,
    errorPlacement = (0, _config.config)().errorPlacementDefault,
    inversed
  } = props;
  const errorElement = errorMessage ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_InlineError.default, {
    id: errorId,
    inversed: inversed,
    className: (0, _classnames.default)(errorMessageClassName, errorPlacement === 'bottom' && 'ds-c-inline-error--bottom'),
    children: errorMessage
  }) : undefined;
  let topError;
  let bottomError;
  if (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.
  const invalid = props['aria-invalid'] ?? !!errorMessage;
  return {
    errorId: errorMessage ? errorId : undefined,
    invalid,
    topError,
    bottomError
  };
}