"use strict";

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

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

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 _ = require("..");

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

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

var _styles = _interopRequireDefault(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 ToggleButton = /*#__PURE__*/_react["default"].forwardRef(function (props, ref) {
  var isChecked = props.isChecked,
      isDisabled = props.isDisabled,
      isFullWidth = props.isFullWidth,
      children = props.children,
      rest = (0, _objectWithoutProperties2["default"])(props, ["isChecked", "isDisabled", "isFullWidth", "children"]);

  var _useToggleGroupStyle = (0, _styles["default"])({
    isChecked: isChecked,
    isFullWidth: isFullWidth
  }),
      toggleButtonStyleProps = _useToggleGroupStyle.toggleButton;

  return __jsx(_.Button, (0, _extends2["default"])({
    ref: ref,
    "aria-checked": isChecked,
    role: "radio",
    id: rest.value,
    isDisabled: isDisabled
  }, toggleButtonStyleProps, rest), children);
});

exports.ToggleButton = ToggleButton;

var ToggleGroup = function ToggleGroup(_ref) {
  var name = _ref.name,
      children = _ref.children,
      defaultValue = _ref.defaultValue,
      controlledValue = _ref.value,
      schema = _ref.schema,
      isFullWidth = _ref.isFullWidth,
      onChange = _ref.onChange,
      isInline = _ref.isInline,
      rest = (0, _objectWithoutProperties2["default"])(_ref, ["name", "children", "defaultValue", "value", "schema", "isFullWidth", "onChange", "isInline"]);
  var fallbackName = "radio-".concat((0, _autoId.useId)());

  var _name = name || fallbackName;

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

  var isControlled = controlledValue != null;

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

  var _value = isControlled ? controlledValue : value;

  var _useToggleGroupStyle2 = (0, _styles["default"])({
    isFullWidth: isFullWidth
  }),
      toggleGroupStyleProps = _useToggleGroupStyle2.root;

  var allNodes = (0, _react.useRef)([]);

  var focusableValues = _react.Children.map(children, function (child) {
    return child.props.isDisabled === true ? null : child.props.value;
  }).filter(function (val) {
    return val != null;
  });

  var allValues = _react.Children.map(children, function (child) {
    return child.props.value;
  });

  var updateIndex = function updateIndex(index, event) {
    var childValue = focusableValues[index];

    var _index = allValues.indexOf(childValue);

    allNodes.current[_index].focus();

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

    if (onChange) {
      onChange(childValue);
    }

    if (formOnChange) {
      formOnChange(event, focusableValues[index]);
    }
  };

  var handleKeyDown = function handleKeyDown(event) {
    if (event.key === 'Tab') {
      return;
    } // Disable page scrolling while navigating with keys


    event.preventDefault();
    var count = focusableValues.length;
    var enabledCheckedIndex = focusableValues.indexOf(_value);

    if (enabledCheckedIndex === -1) {
      enabledCheckedIndex = 0;
    }

    switch (event.key) {
      case 'ArrowRight':
      case 'ArrowDown':
        {
          var nextIndex = (enabledCheckedIndex + 1) % count;
          updateIndex(nextIndex, event);
          break;
        }

      case 'ArrowLeft':
      case 'ArrowUp':
        {
          var _nextIndex = (enabledCheckedIndex - 1 + count) % count;

          updateIndex(_nextIndex, event);
          break;
        }

      default:
        break;
    }
  };

  var clones = _react.Children.map(children, function (child, index) {
    var isFirstChild = index === 0;
    var isChecked = child.props.value === _value;

    var handleClick = function handleClick(e) {
      if (!isControlled) {
        setValue(child.props.value);
      }

      if (onChange) {
        onChange(child.props.value);
      }

      if (formOnChange) {
        formOnChange(e);
      }
    };

    var getTabIndex = function getTabIndex() {
      // If a ToggleGroup has no toggle button selected, the first enabled toggle should be focusable
      if (_value == null) {
        return isFirstChild ? 0 : -1;
      }

      return isChecked ? 0 : -1;
    };

    return /*#__PURE__*/(0, _react.cloneElement)(child, {
      ref: function ref(node) {
        allNodes.current[index] = node;
      },
      name: _name,
      onClick: handleClick,
      tabIndex: getTabIndex(),
      isChecked: isChecked,
      isFullWidth: isFullWidth
    });
  });

  var spacingProps = isInline ? {
    mr: 'spacing'
  } : {
    mb: 'spacing'
  };
  return __jsx(_.FormControlWrapper, (0, _extends2["default"])({
    error: errors
  }, spacingProps, rest), __jsx(_Box.Box, (0, _extends2["default"])({
    role: "radiogroup",
    onKeyDown: handleKeyDown
  }, toggleGroupStyleProps, rest), clones));
};

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