"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var React = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _generateRandomString = _interopRequireDefault(require("../../../js/generateRandomString"));

var _utils = require("../../utils");

var _Text = _interopRequireDefault(require("../../text/Text"));

var _CheckboxIcon = require("./CheckboxIcon");

var _ErrorMessage = _interopRequireDefault(require("../ErrorMessage"));

var _useFirstPaint = require("../../utils/useFirstPaint");

var _excluded = ["checked", "children", "className", "color", "defaultChecked", "description", "disabled", "errorMessage", "id", "indeterminate", "invalid", "labelSize", "required", "name", "onChange", "style", "value", "aria-labelledby"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var Checkbox = function Checkbox(_ref) {
  var _classNames;

  var checked = _ref.checked,
      children = _ref.children,
      className = _ref.className,
      _ref$color = _ref.color,
      color = _ref$color === void 0 ? 'dark' : _ref$color,
      _ref$defaultChecked = _ref.defaultChecked,
      defaultChecked = _ref$defaultChecked === void 0 ? false : _ref$defaultChecked,
      description = _ref.description,
      _ref$disabled = _ref.disabled,
      disabled = _ref$disabled === void 0 ? false : _ref$disabled,
      errorMessage = _ref.errorMessage,
      id = _ref.id,
      _ref$indeterminate = _ref.indeterminate,
      indeterminate = _ref$indeterminate === void 0 ? false : _ref$indeterminate,
      _ref$invalid = _ref.invalid,
      invalid = _ref$invalid === void 0 ? false : _ref$invalid,
      _ref$labelSize = _ref.labelSize,
      labelSize = _ref$labelSize === void 0 ? 'medium' : _ref$labelSize,
      _ref$required = _ref.required,
      required = _ref$required === void 0 ? false : _ref$required,
      name = _ref.name,
      onChange = _ref.onChange,
      style = _ref.style,
      value = _ref.value,
      ariaLabelledBy = _ref['aria-labelledby'],
      props = _objectWithoutProperties(_ref, _excluded);

  var checkboxIconRef = React.useRef();

  var _React$useRef = React.useRef(id === undefined || id === '' ? (0, _generateRandomString.default)() : id),
      checkboxId = _React$useRef.current;

  var isControlled = checked !== undefined;

  var _React$useState = React.useState(isControlled ? checked : defaultChecked),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      isChecked = _React$useState2[0],
      setIsChecked = _React$useState2[1];

  var inputRef = React.useRef(null);
  var iconRef = React.useRef(null);
  var shouldAnimate = React.useRef(false);
  (0, _useFirstPaint.useFirstPaint)(function () {
    shouldAnimate.current = true;
  });
  React.useEffect(function () {
    if (inputRef.current) inputRef.current.indeterminate = indeterminate;
  }, [inputRef, indeterminate]);
  React.useEffect(function () {
    if (isControlled && checked !== isChecked) {
      setIsChecked(checked);

      if (shouldAnimate.current && checkboxIconRef.current) {
        checkboxIconRef.current.classList.add('sg-checkbox__icon--with-animation');
      }
    }
  }, [checked, isControlled, isChecked]);
  var onInputChange = React.useCallback(function (e) {
    if (!isControlled) {
      setIsChecked(function (val) {
        return !val;
      });
    }

    if (onChange) onChange(e);

    if (shouldAnimate.current && checkboxIconRef.current) {
      checkboxIconRef.current.classList.add('sg-checkbox__icon--with-animation');
    }
  }, [onChange, isControlled, checkboxIconRef]);

  if (_utils.__DEV__) {
    (0, _utils.invariant)(!(errorMessage && !invalid), "Using 'errorMessage' property has no effect when 'invalid' property is not set.");
    (0, _utils.invariant)(!(errorMessage && !children), "Using 'errorMessage' property should be used along with 'children' property (label).");
  }

  var hasContent = description || invalid && errorMessage;
  var hasLabel = children !== undefined && children !== null;
  var isInputOnly = !hasLabel && !hasContent;
  var checkboxClass = (0, _classnames.default)('sg-checkbox', className, (_classNames = {
    'sg-checkbox--disabled': disabled
  }, _defineProperty(_classNames, "sg-checkbox--".concat(String(color)), color), _defineProperty(_classNames, "sg-checkbox--with-padding", !isInputOnly), _classNames));
  var labelClass = (0, _classnames.default)('sg-checkbox__label', _defineProperty({
    'sg-checkbox__label--with-padding-bottom': description || errorMessage
  }, "sg-checkbox__label--".concat(String(labelSize)), labelSize));
  var iconClass = (0, _classnames.default)('sg-checkbox__icon');
  var errorTextId = "".concat(checkboxId, "-errorText");
  var descriptionId = "".concat(checkboxId, "-description");
  var describedbyIds = React.useMemo(function () {
    var ids = [];

    if (invalid && errorMessage) {
      ids.push(errorTextId);
    }

    if (description) {
      ids.push(descriptionId);
    }

    return ids.join(' ');
  }, [errorTextId, descriptionId, invalid, errorMessage, description]);
  var checkboxIcon = null;
  if (isChecked && !indeterminate) checkboxIcon = /*#__PURE__*/React.createElement(_CheckboxIcon.CheckIcon, {
    ref: iconRef
  });
  if (indeterminate) checkboxIcon = /*#__PURE__*/React.createElement(_CheckboxIcon.IndeterminateIcon, {
    ref: iconRef
  });
  React.useEffect(function () {
    requestAnimationFrame(function () {
      if (iconRef.current) {
        iconRef.current.getBoundingClientRect(); // force a reflow so checkbox icon gets painted and transition can be seen

        if (iconRef.current instanceof window.SVGElement) {
          iconRef.current.style.strokeDashoffset = '0';
        }
      }
    });
  }, [checkboxIcon]);
  return /*#__PURE__*/React.createElement("div", {
    className: checkboxClass,
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__wrapper"
  }, /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__element"
  }, /*#__PURE__*/React.createElement("input", _extends({}, props, {
    ref: inputRef,
    className: "sg-checkbox__input",
    id: checkboxId,
    type: "checkbox",
    checked: isChecked,
    disabled: disabled,
    name: name,
    onChange: onInputChange,
    required: required,
    value: value,
    "aria-checked": indeterminate ? 'mixed' : isChecked,
    "aria-invalid": invalid ? true : undefined,
    "aria-describedby": describedbyIds,
    "aria-labelledby": ariaLabelledBy
  })), /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__icon-wrapper"
  }, /*#__PURE__*/React.createElement("span", {
    className: iconClass // This element is purely decorative so
    ,
    ref: checkboxIconRef // we hide it for screen readers
    ,
    "aria-hidden": "true"
  }, checkboxIcon))), !ariaLabelledBy && hasLabel && /*#__PURE__*/React.createElement(_Text.default, {
    htmlFor: checkboxId,
    as: "label",
    size: labelSize,
    weight: "bold",
    className: labelClass
  }, children, required && /*#__PURE__*/React.createElement("span", {
    "aria-hidden": "true"
  }, "\xA0*"))), hasContent && /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__content"
  }, description && /*#__PURE__*/React.createElement(_Text.default, {
    id: descriptionId,
    className: "sg-checkbox__description",
    size: "small",
    as: "span",
    breakWords: true
  }, description), invalid && errorMessage && /*#__PURE__*/React.createElement(_ErrorMessage.default, {
    id: errorTextId,
    color: color === 'light' ? 'text-red-40' : undefined
  }, errorMessage)));
};

var _default = Checkbox;
exports.default = _default;