"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireDefault(require("react"));
var _react2 = require("@emotion/react");
var _analyticsNext = require("@atlaskit/analytics-next");
var _button = _interopRequireDefault(require("@atlaskit/button"));
var _chevronDown = _interopRequireDefault(require("@atlaskit/icon/glyph/chevron-down"));
var _colors = require("@atlaskit/theme/colors");
var _tooltip = _interopRequireDefault(require("@atlaskit/tooltip"));
var _analytics = require("../../analytics");
var _uiColor = require("../../ui-color");
var _Popup = _interopRequireDefault(require("../../ui/Popup"));
var _withOuterListeners = _interopRequireDefault(require("../../ui/with-outer-listeners"));
var _ArrowKeyNavigationProvider = require("../ArrowKeyNavigationProvider");
var _types = require("../ArrowKeyNavigationProvider/types");
/** @jsx jsx */

// helps adjusts position of popup
var colorPickerButtonWrapper = (0, _react2.css)({
  position: 'relative'
});
var colorPickerExpandContainer = (0, _react2.css)({
  margin: "0px ".concat("var(--ds-space-negative-050, -4px)")
});

// Control the size of color picker buttons and preview
// TODO: https://product-fabric.atlassian.net/browse/DSP-4134
/* eslint-disable @atlaskit/design-system/ensure-design-token-usage */
var colorPickerWrapper = function colorPickerWrapper() {
  return (0, _react2.css)({
    borderRadius: "var(--ds-border-radius, 3px)",
    backgroundColor: "var(--ds-surface-overlay, ".concat(_colors.N0, ")"),
    boxShadow: "var(--ds-shadow-overlay, ".concat("0 4px 8px -2px ".concat(_colors.N60A, ", 0 0 1px ").concat(_colors.N60A), ")"),
    padding: "var(--ds-space-100, 8px)".concat(" 0px")
  });
};
/* eslint-enable @atlaskit/design-system/ensure-design-token-usage */

var ColorPaletteWithListeners = (0, _withOuterListeners.default)(_uiColor.ColorPalette);
var ColorPickerButton = function ColorPickerButton(props) {
  var buttonRef = _react.default.useRef(null);
  var _React$useState = _react.default.useState(false),
    _React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
    isPopupOpen = _React$useState2[0],
    setIsPopupOpen = _React$useState2[1];
  var _React$useState3 = _react.default.useState(false),
    _React$useState4 = (0, _slicedToArray2.default)(_React$useState3, 2),
    isPopupPositioned = _React$useState4[0],
    setIsPopupPositioned = _React$useState4[1];
  var _React$useState5 = _react.default.useState(false),
    _React$useState6 = (0, _slicedToArray2.default)(_React$useState5, 2),
    isOpenedByKeyboard = _React$useState6[0],
    setIsOpenedByKeyboard = _React$useState6[1];
  var togglePopup = function togglePopup() {
    setIsPopupOpen(!isPopupOpen);
    if (!isPopupOpen) {
      setIsOpenedByKeyboard(false);
      setIsPopupPositioned(false);
    }
  };
  _react.default.useEffect(function () {
    if (props.setDisableParentScroll) {
      props.setDisableParentScroll(isPopupOpen);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isPopupOpen]);
  var focusButton = function focusButton() {
    var _buttonRef$current;
    (_buttonRef$current = buttonRef.current) === null || _buttonRef$current === void 0 || _buttonRef$current.focus();
  };
  var handleEsc = _react.default.useCallback(function () {
    setIsOpenedByKeyboard(false);
    setIsPopupPositioned(false);
    setIsPopupOpen(false);
    focusButton();
  }, []);
  var onPositionCalculated = _react.default.useCallback(function (position) {
    setIsPopupPositioned(true);
    return position;
  }, []);
  var onChange = props.onChange,
    createAnalyticsEvent = props.createAnalyticsEvent,
    colorPalette = props.colorPalette,
    placement = props.placement,
    skipFocusButtonAfterPick = props.skipFocusButtonAfterPick;
  var onColorSelected = _react.default.useCallback(function (color, label) {
    setIsOpenedByKeyboard(false);
    setIsPopupOpen(false);
    setIsPopupPositioned(false);
    if (onChange) {
      if (createAnalyticsEvent) {
        // fire analytics
        var payload = {
          action: _analytics.ACTION.UPDATED,
          actionSubject: _analytics.ACTION_SUBJECT.PICKER,
          actionSubjectId: _analytics.ACTION_SUBJECT_ID.PICKER_COLOR,
          attributes: {
            color: color,
            label: label,
            placement: placement
          },
          eventType: _analytics.EVENT_TYPE.TRACK
        };
        createAnalyticsEvent(payload).fire(_analytics.editorAnalyticsChannel);
      }
      var newPalette = colorPalette.find(function (colorPalette) {
        return colorPalette.value === color;
      });
      newPalette && onChange(newPalette);
    }
    if (!skipFocusButtonAfterPick) {
      focusButton();
    }
  }, [colorPalette, onChange, createAnalyticsEvent, placement, skipFocusButtonAfterPick]);
  var renderPopup = function renderPopup() {
    if (!isPopupOpen || !buttonRef.current) {
      return;
    }
    var selectedColor = props.currentColor || null;
    var _getSelectedRowAndCol = (0, _uiColor.getSelectedRowAndColumnFromPalette)(props.colorPalette, selectedColor, props.cols),
      selectedRowIndex = _getSelectedRowAndCol.selectedRowIndex,
      selectedColumnIndex = _getSelectedRowAndCol.selectedColumnIndex;
    return (0, _react2.jsx)(_Popup.default, {
      target: buttonRef.current,
      fitHeight: 350,
      fitWidth: 350,
      offset: [0, 10],
      alignX: props.alignX,
      mountTo: props.setDisableParentScroll ? props.mountPoint : undefined,
      absoluteOffset: props.absoluteOffset
      // Confluence inline comment editor has z-index: 500
      // if the toolbar is scrollable, this will be mounted in the root editor
      // we need an index of > 500 to display over it
      ,
      zIndex: props.setDisableParentScroll ? 600 : undefined,
      ariaLabel: "Color picker popup",
      onPositionCalculated: onPositionCalculated
    }, (0, _react2.jsx)("div", {
      css: colorPickerWrapper,
      "data-test-id": "color-picker-menu"
    }, (0, _react2.jsx)(_ArrowKeyNavigationProvider.ArrowKeyNavigationProvider, {
      type: _types.ArrowKeyNavigationType.COLOR,
      selectedRowIndex: selectedRowIndex,
      selectedColumnIndex: selectedColumnIndex,
      closeOnTab: true,
      handleClose: function handleClose() {
        return setIsPopupOpen(false);
      },
      isOpenedByKeyboard: isOpenedByKeyboard,
      isPopupPositioned: isPopupPositioned,
      ignoreEscapeKey: props.returnEscToButton
    }, (0, _react2.jsx)(ColorPaletteWithListeners, {
      cols: props.cols,
      selectedColor: selectedColor,
      onClick: onColorSelected,
      handleClickOutside: togglePopup,
      handleEscapeKeydown: handleEsc,
      paletteOptions: {
        palette: props.colorPalette,
        hexToPaletteColor: props.hexToPaletteColor,
        paletteColorTooltipMessages: props.paletteColorTooltipMessages
      }
    }))));
  };
  var title = props.title || '';
  var currentColor = props.currentColor && props.hexToPaletteColor ? props.hexToPaletteColor(props.currentColor) : props.currentColor;
  var buttonStyle = function buttonStyle() {
    var _props$size, _props$size2, _props$size3;
    return (0, _react2.css)({
      padding: "var(--ds-space-075, 6px)".concat(" 10px"),
      backgroundColor: "var(--ds-background-neutral-subtle, transparent)",
      height: "".concat(!!((_props$size = props.size) !== null && _props$size !== void 0 && _props$size.height) ? 'inherit' : ''),
      '&:before': {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        alignSelf: 'center',
        content: "''",
        border: "1px solid ".concat(_uiColor.DEFAULT_BORDER_COLOR),
        borderRadius: "var(--ds-border-radius, 3px)",
        backgroundColor: currentColor || 'transparent',
        width: ((_props$size2 = props.size) === null || _props$size2 === void 0 ? void 0 : _props$size2.width) || '14px',
        height: ((_props$size3 = props.size) === null || _props$size3 === void 0 ? void 0 : _props$size3.height) || '14px',
        padding: 0,
        margin: "0px ".concat("var(--ds-space-025, 2px)")
      },
      '&:hover': {
        background: "var(--ds-background-neutral-subtle-hovered, ".concat(_colors.N30A, ")")
      }
    });
  };
  return (0, _react2.jsx)("div", {
    css: colorPickerButtonWrapper
  }, (0, _react2.jsx)(_tooltip.default, {
    content: title,
    position: "top"
  }, (0, _react2.jsx)(_button.default, {
    ref: buttonRef,
    "aria-label": title,
    "aria-expanded": props.isAriaExpanded ? isPopupOpen : undefined,
    spacing: "compact",
    onClick: togglePopup,
    onKeyDown: function onKeyDown(event) {
      if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        togglePopup();
        setIsOpenedByKeyboard(true);
      }
    },
    css: buttonStyle,
    iconAfter: (0, _react2.jsx)("span", {
      css: colorPickerExpandContainer
    }, (0, _react2.jsx)(_chevronDown.default, {
      label: ""
    })),
    "data-selected-color": props.currentColor
  })), renderPopup());
};
var _default = exports.default = (0, _analyticsNext.withAnalyticsContext)({
  source: 'ConfigPanel'
})((0, _analyticsNext.withAnalyticsEvents)()(ColorPickerButton));