"use strict";

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

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

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

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

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

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

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

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

var _Icon = require("../../Icon");

var _PseudoBox = require("../../PseudoBox");

var _Menu = require("../Menu");

var _styles = require("../styles");

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 MenuItemOption = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var isDisabled = _ref.isDisabled,
      children = _ref.children,
      onClick = _ref.onClick,
      type = _ref.type,
      onMouseLeave = _ref.onMouseLeave,
      onMouseEnter = _ref.onMouseEnter,
      onKeyDown = _ref.onKeyDown,
      isChecked = _ref.isChecked,
      rest = (0, _objectWithoutProperties2["default"])(_ref, ["isDisabled", "children", "onClick", "type", "onMouseLeave", "onMouseEnter", "onKeyDown", "isChecked"]);

  // @ts-ignore
  var _useMenuContext = (0, _Menu.useMenuContext)(),
      focusableItems = _useMenuContext.focusableItems,
      focusAtIndex = _useMenuContext.focusAtIndex,
      closeMenu = _useMenuContext.closeMenu,
      closeOnSelect = _useMenuContext.closeOnSelect;

  var role = "menuitem".concat(type);

  var handleSelect = function handleSelect(e) {
    if (onClick) {
      onClick(e);
    }

    if (closeOnSelect) {
      closeMenu();
    }
  };

  var handleClick = function handleClick(event) {
    if (isDisabled) {
      event.stopPropagation();
      event.preventDefault();
      return;
    }

    handleSelect(event);
  };

  var handleKeyDown = function handleKeyDown(event) {
    if (isDisabled) return;

    if (['Enter', ' '].includes(event.key)) {
      event.preventDefault();
      handleSelect(event);
    }

    if (onKeyDown) {
      onKeyDown(event);
    }
  };

  var handleMouseEnter = function handleMouseEnter(event) {
    if (isDisabled) {
      event.stopPropagation();
      event.preventDefault();
      return;
    }

    var nextIndex = focusableItems.current.indexOf(event.currentTarget);
    focusAtIndex(nextIndex);

    if (onMouseEnter) {
      onMouseEnter(event);
    }
  };

  var handleMouseLeave = function handleMouseLeave(event) {
    focusAtIndex(-1);

    if (onMouseLeave) {
      onMouseLeave(event);
    }
  };

  var styleProps = (0, _styles.useMenuItemStyle)(null);
  return __jsx(_PseudoBox.PseudoBox, (0, _extends2["default"])({
    ref: ref,
    as: "button",
    onClick: handleClick,
    role: role,
    tabIndex: -1,
    "aria-checked": isChecked,
    disabled: isDisabled,
    "aria-disabled": isDisabled ? '' : undefined,
    onMouseEnter: handleMouseEnter,
    onMouseLeave: handleMouseLeave,
    onKeyDown: handleKeyDown
  }, styleProps, rest), __jsx(_Icon.Icon, {
    name: "check",
    opacity: isChecked ? 1 : 0,
    color: "currentColor",
    size: "1em",
    ml: "spacing",
    mr: "-4px",
    "aria-hidden": true,
    "data-menuitem-icon": ""
  }), __jsx(_Box.Box, {
    textAlign: "left",
    as: "span",
    mx: "1rem",
    flex: "1"
  }, children));
}); //

exports.MenuItemOption = MenuItemOption;

var MenuOptionGroup = function MenuOptionGroup(_ref2) {
  var children = _ref2.children,
      _ref2$type = _ref2.type,
      type = _ref2$type === void 0 ? 'radio' : _ref2$type,
      name = _ref2.name,
      title = _ref2.title,
      valueProp = _ref2.value,
      defaultValue = _ref2.defaultValue,
      onChange = _ref2.onChange,
      rest = (0, _objectWithoutProperties2["default"])(_ref2, ["children", "type", "name", "title", "value", "defaultValue", "onChange"]);

  var _useState = (0, _react.useState)(defaultValue || ''),
      value = _useState[0],
      setValue = _useState[1];

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

  var derivedValue = isControlled ? valueProp : value;

  var handleChange = function handleChange(_value) {
    if (type === 'radio') {
      if (!isControlled) {
        setValue(_value);
      }

      if (onChange) {
        onChange(_value);
      }
    }

    if (type === 'checkbox') {
      var newValue = derivedValue.includes(_value) ? derivedValue.filter(function (itemValue) {
        return itemValue !== _value;
      }) : [].concat((0, _toConsumableArray2["default"])(derivedValue), [_value]);

      if (!isControlled) {
        setValue(newValue);
      }

      if (onChange) {
        onChange(newValue);
      }
    }
  };

  var fallbackName = "radio-".concat((0, _autoId.useId)());
  return __jsx(_Menu.MenuGroup, (0, _extends2["default"])({
    title: title
  }, rest), _react.Children.map(children, function (child) {
    if (! /*#__PURE__*/(0, _react.isValidElement)(child)) {
      return null;
    }

    if (type === 'radio') {
      return /*#__PURE__*/(0, _react.cloneElement)(child, {
        type: type,
        key: child.props.value,
        onClick: function onClick(event) {
          handleChange(child.props.value);

          if (child.props.onClick) {
            child.props.onClick(event);
          }
        },
        name: name || fallbackName,
        isChecked: child.props.value === derivedValue
      });
    }

    if (type === 'checkbox') {
      return /*#__PURE__*/(0, _react.cloneElement)(child, {
        type: type,
        key: child.props.value,
        onClick: function onClick(event) {
          handleChange(child.props.value);

          if (child.props.onClick) {
            child.props.onClick(event);
          }
        },
        isChecked: derivedValue.includes(child.props.value)
      });
    }

    return null;
  }));
};

exports.MenuOptionGroup = MenuOptionGroup;
//# sourceMappingURL=MenuItemOption.js.map