"use strict";

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

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

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

var _randomstring = _interopRequireDefault(require("randomstring"));

var _styledComponents = _interopRequireWildcard(require("styled-components"));

var _primitives = require("../../../../primitives");

var _typography = require("../../../typography");

var _selectorContext = require("../selector-context");

var _radioOption = require("../../../icon/radio-option");

var _checkbox = require("../../../icon/checkbox");

var _selector = require("../selector.component");

var _selectorItem = require("./selector-item.css-rules");

var _branding = require("../../../../mixins/branding");

var _focus = require("../../../../mixins/focus");

var _unstyledButton = require("../../../behaviors/unstyled-button");

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _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) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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; }

var handleMouseDown = function handleMouseDown(event) {
  event.preventDefault();

  if (document.activeElement) {
    document.activeElement.blur();
  }
};

var isSmallSvgCss = (0, _styledComponents.css)(["svg{width:32px;height:32px;}"]);

var InputContainer = _styledComponents["default"].div.withConfig({
  displayName: "InputContainer",
  componentId: "sc-8771r9-0"
})(["position:absolute;display:flex;align-items:center;right:10px;margin:0;top:0;left:0;width:100%;height:100%;", ""], function (_ref) {
  var isSmall = _ref.isSmall;
  return isSmall ? isSmallSvgCss : '';
});

var GenericInput = _styledComponents["default"].input.withConfig({
  displayName: "GenericInput",
  componentId: "sc-8771r9-1"
})(["appearance:none;width:100%;height:100%;margin:0;&:not([disabled]):hover{cursor:pointer;}", " ", "{border-top:inherit;border-bottom:inherit;border-radius:inherit;box-shadow:", ",", " ", ";}"], (0, _focus.getBaseFocusState)({
  hoverTransition: false,
  activeTransition: false
}), _focus.FOCUS_VISIBLE_SELECTOR, _focus.focusedBoxShadow, _focus.focusedBorderShadow, _focus.focusedBorderColor);

var optionStyling = (0, _styledComponents.css)(["position:absolute;right:10px;top:0;bottom:0;margin:auto;pointer-events:none;"]);
var StyledRadioOption = (0, _styledComponents["default"])(_radioOption.RadioOption).withConfig({
  displayName: "StyledRadioOption",
  componentId: "sc-8771r9-2"
})(["", ""], optionStyling);
var StyledCheckbox = (0, _styledComponents["default"])(_checkbox.Checkbox).withConfig({
  displayName: "StyledCheckbox",
  componentId: "sc-8771r9-3"
})(["", ""], optionStyling);
var SelectorItemRow = (0, _styledComponents["default"])(_unstyledButton.UnstyledButton).withConfig({
  displayName: "SelectorItemRow",
  componentId: "sc-8771r9-4"
})(["width:100%;margin:0;align-items:center;display:flex;flex-grow:1;justify-content:space-between;position:relative;background:", ";"], (0, _branding.getPaletteColor)('white'));
var BoxFlex = (0, _styledComponents["default"])(_primitives.Box).withConfig({
  displayName: "BoxFlex",
  componentId: "sc-8771r9-5"
})(["flex:1;padding:", ";z-index:1;"], _selectorItem.getBoxPadding);

var LabelWrapper = _styledComponents["default"].div.withConfig({
  displayName: "LabelWrapper",
  componentId: "sc-8771r9-6"
})(["align-items:center;display:flex;flex-wrap:wrap;min-height:24px;padding-right:44px;justify-content:space-between;margin:", ";"], function (_ref2) {
  var isSmall = _ref2.isSmall,
      theme = _ref2.theme;
  return isSmall ? "5px 0" : "".concat(theme.spacing.s1, " 0");
});

var LabelText = (0, _styledComponents["default"])(_typography.Text).withConfig({
  displayName: "LabelText",
  componentId: "sc-8771r9-7"
})(["margin:0;", ""], function (_ref3) {
  var disabled = _ref3.disabled;
  return disabled && (0, _styledComponents.css)(["color:", ";"], _selectorItem.getDisabledLabelTextColor);
});
var PrimaryLabelText = (0, _styledComponents["default"])(LabelText).withConfig({
  displayName: "PrimaryLabelText",
  componentId: "sc-8771r9-8"
})(["font-size:", ";font-family:", ";font-weight:", ";"], _selectorItem.getPrimaryLabelFontSize, _selectorItem.getPrimaryLabelFontFamily, _selectorItem.getPrimaryLabelFontWeight);
/**
 * Depending on if this is a <Selector type="radio"> (default) or
 * <Selector type="checkbox"> then we manage the value differently
 */

var getCheckedState = function getCheckedState(type, value, managedValue) {
  if (type === 'checkbox' && Array.isArray(managedValue)) {
    return managedValue.includes(value);
  }

  return value === managedValue || String(value) === String(managedValue);
};

var SelectorItem = function SelectorItem(_ref4) {
  var id = _ref4.id,
      value = _ref4.value,
      label = _ref4.label,
      hideLabel = _ref4.hideLabel,
      secondaryLabel = _ref4.secondaryLabel,
      checked = _ref4.checked,
      disabled = _ref4.disabled,
      _ref4$noInput = _ref4.noInput,
      noInput = _ref4$noInput === void 0 ? false : _ref4$noInput,
      large = _ref4.large,
      children = _ref4.children,
      _ref4$onRef = _ref4.onRef,
      onRef = _ref4$onRef === void 0 ? function (_) {} : _ref4$onRef,
      _ref4$childElementSpa = _ref4.childElementSpacing,
      childElementSpacing = _ref4$childElementSpa === void 0 ? ['mr2'] : _ref4$childElementSpa;
  var size = (0, _react.useContext)(_selector.SizeContext);
  var isLarge = large || size === 'lg'; // TODO: deprecate the large prop

  var isSmall = size === 'sm';

  var _useState = (0, _react.useState)(null),
      _useState2 = _slicedToArray(_useState, 2),
      selectorItemRef = _useState2[0],
      setSelectorItemRef = _useState2[1];

  var _useSelectorContext = (0, _selectorContext.useSelectorContext)(),
      name = _useSelectorContext.name,
      stateful = _useSelectorContext.stateful,
      managedValue = _useSelectorContext.managedValue,
      type = _useSelectorContext.type,
      onChange = _useSelectorContext.onChange;

  var elementId = "SelectorItem-".concat(id, "-").concat(_randomstring["default"].generate(5));
  var generatedName = "Selector-field--".concat(name, "-").concat(_randomstring["default"].generate(5));
  var isChecked = stateful ? getCheckedState(type, value, managedValue) : checked;
  var childElement = children != null ? /*#__PURE__*/_react["default"].createElement(_primitives.Box, {
    spacing: childElementSpacing
  }, children) : null;
  var secondaryLabelElement = secondaryLabel != null ? /*#__PURE__*/_react["default"].createElement(LabelText, {
    disabled: disabled,
    fontSize: "f1",
    spacing: "m0"
  }, secondaryLabel) : null;
  var labelElement = label != null ? /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: elementId
  }, /*#__PURE__*/_react["default"].createElement(LabelWrapper, {
    isSmall: isSmall
  }, /*#__PURE__*/_react["default"].createElement(PrimaryLabelText, {
    disabled: disabled,
    large: isLarge
  }, label), secondaryLabelElement)) : null;
  var input;

  if (noInput && disabled) {
    input = null;
  } else {
    input = type === 'radio' ? /*#__PURE__*/_react["default"].createElement(StyledRadioOption, {
      checked: isChecked
    }) : /*#__PURE__*/_react["default"].createElement(StyledCheckbox, {
      selected: isChecked
    });
  }

  return /*#__PURE__*/_react["default"].createElement(SelectorItemRow, {
    tabIndex: "-1",
    onClick: function onClick() {
      if (selectorItemRef != null) {
        selectorItemRef.click();
      }
    }
  }, /*#__PURE__*/_react["default"].createElement(BoxFlex, {
    stacked: "column",
    large: isLarge
  }, hideLabel ? /*#__PURE__*/_react["default"].createElement(_primitives.HideAccessibly, null, labelElement) : labelElement, childElement), /*#__PURE__*/_react["default"].createElement(InputContainer, {
    isSmall: isSmall
  }, /*#__PURE__*/_react["default"].createElement(GenericInput, {
    ref: function ref(r) {
      setSelectorItemRef(r);
      onRef(r);
    },
    id: elementId,
    name: generatedName,
    type: type,
    onChange: onChange,
    checked: isChecked,
    disabled: disabled,
    value: value,
    onMouseDown: handleMouseDown
  }), input));
};

exports.SelectorItem = SelectorItem;
SelectorItem.displayName = 'SelectorItem';