import { jsx } from '@emotion/core';
import { Fragment } from 'react';
import { visuallyHiddenCss } from '../../../stylesheets/a11y.esm.js';
import { getErrorAriaLiveAttribute, getHintId, getErrorId } from '../utils/index.esm.js';

/** @jsx jsx */

/**
 * "group" fields (radio buttons and checkbox groups) are more complicated
 * than "single" ones when it comes to aria-attributes
 *
 * Apparently, we cannot just put aria-invalid and aria-describedby to each option's input,
 * as this would result in too many screen reader announcements
 *
 * Atatching those aria- attributes to only the first option kinda works but not entirely without issues
 *
 * So instead we are going to require the actual hint and error messages and put them (visually hidden) in the group label,
 * while marking the actual visible messages as hidden from screen readers
 * For more details see this article: https://blog.tenon.io/accessible-validation-of-checkbox-and-radiobutton-groups
 */
function useAriaFormGroupField(fieldId, _ref) {
  var _ref$required = _ref.required,
      required = _ref$required === void 0 ? false : _ref$required,
      error = _ref.error,
      hint = _ref.hint,
      _ref$hasError = _ref.hasError,
      hasError = _ref$hasError === void 0 ? Boolean(error) : _ref$hasError,
      _ref$hasHint = _ref.hasHint,
      hasHint = _ref$hasHint === void 0 ? Boolean(hint) : _ref$hasHint,
      validationMode = _ref.validationMode;
  var hintId = getHintId(fieldId);
  var errorId = getErrorId(fieldId);
  return {
    getLegendProps: function getLegendProps(label) {
      return {
        children: jsx(Fragment, null, label, jsx("div", {
          css: visuallyHiddenCss
        }, jsx("div", null, hint), jsx("div", null, error)))
      };
    },
    getOptionControlProps: function getOptionControlProps(optionValue) {
      return {
        id: getGroupOptionId(fieldId, optionValue),
        required: required
      };
    },
    getOptionLabelProps: function getOptionLabelProps(optionValue) {
      return {
        htmlFor: getGroupOptionId(fieldId, optionValue)
      };
    },
    hintProps: {
      id: hintId,
      hidden: !hasHint,
      "aria-hidden": true
    },
    errorProps: {
      id: errorId,
      hidden: !hasError,
      "aria-hidden": true,
      "aria-live": getErrorAriaLiveAttribute(validationMode)
    },
    meta: {
      required: required
    }
  };
}

function getGroupOptionId(fieldId, optionValue) {
  return "".concat(fieldId, "__option--").concat(optionValue);
}

export { useAriaFormGroupField };
//# sourceMappingURL=useAriaFormGroupField.esm.js.map
