"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _autoId = require("@reach/auto-id");

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

var _Box = require("../Box");

var _Form = require("../Form");

var _FormControl = require("../FormControl");

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; }

var __jsx = _react["default"].createElement;

var CheckboxGroup = function CheckboxGroup(_ref) {
  var onChange = _ref.onChange,
      name = _ref.name,
      variantColor = _ref.variantColor,
      size = _ref.size,
      defaultValue = _ref.defaultValue,
      isInline = _ref.isInline,
      valueProp = _ref.value,
      schema = _ref.schema,
      children = _ref.children,
      rest = (0, _objectWithoutProperties2["default"])(_ref, ["onChange", "name", "variantColor", "size", "defaultValue", "isInline", "value", "schema", "children"]);

  var _useFormField = (0, _Form.useFormField)({
    name: name,
    onChange: onChange,
    schema: schema
  }),
      formOnChange = _useFormField.onChange,
      initialCheckboxGroupValues = _useFormField.value,
      errors = _useFormField.errors;

  var _useState = (0, _react.useState)(defaultValue || initialCheckboxGroupValues || []),
      values = _useState[0],
      setValues = _useState[1];

  var _useRef = (0, _react.useRef)(valueProp != null),
      isControlled = _useRef.current;

  var _values = isControlled ? valueProp : values;

  var _onChange = function _onChange(event, boxName) {
    var checked = event.target.checked;
    var newValues;

    if (checked) {
      newValues = [].concat((0, _toConsumableArray2["default"])(_values), [boxName]);
    } else {
      newValues = _values.filter(function (val) {
        return val !== boxName;
      });
    } // If CheckboxGroup is passed a name, child checkbox values are contained within one array.


    if (name && formOnChange) {
      formOnChange(null, newValues);
    }

    if (!isControlled) {
      setValues(newValues);
    }

    if (onChange) {
      onChange(newValues);
    }
  }; // If no name is passed, we'll generate a random, unique name


  var fallbackName = "checkbox-".concat((0, _autoId.useId)());

  var _name = name || fallbackName;

  var firstChildName = null;

  var clones = _react.Children.map(children, function (child, index) {
    if (! /*#__PURE__*/(0, _react.isValidElement)(child)) {
      return null;
    }

    if (!firstChildName) {
      firstChildName = child.props.name;
    }

    var isLastCheckbox = children.length === index + 1;
    var spacingProps = isInline ? {
      mr: 'spacing-xs'
    } : {
      mb: 'spacing-xs'
    };
    var defCheckboxName = "".concat(_name, "-").concat(index);
    return __jsx(_Box.Box, (0, _extends2["default"])({
      display: isInline ? 'inline-block' : 'block'
    }, !isLastCheckbox && spacingProps), /*#__PURE__*/(0, _react.cloneElement)(child, {
      size: size,
      variantColor: variantColor,
      name: child.props.name || defCheckboxName,
      onChange: function onChange(e) {
        _onChange(e, child.props.name || defCheckboxName);

        if (typeof child.props.onChange === 'function') {
          child.props.onChange(e);
        }
      },
      isChecked: child.props.isChild || name ? _values.includes(child.props.name || defCheckboxName) : child.props.isChecked,
      skipFormChange: !!name
    }));
  });

  var spacingProps = isInline ? {
    mr: 'spacing'
  } : {
    mb: 'spacing'
  };
  return __jsx(_FormControl.FormControlWrapper, (0, _extends2["default"])({
    id: firstChildName,
    error: errors
  }, spacingProps, rest), __jsx(_Box.Box, (0, _extends2["default"])({
    role: "group"
  }, rest), clones));
};

exports.CheckboxGroup = CheckboxGroup;
//# sourceMappingURL=CheckboxGroup.js.map