"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 _reactIntlNext = require("react-intl-next");
var _withAnalyticsContext = _interopRequireDefault(require("@atlaskit/analytics-next/withAnalyticsContext"));
var _withAnalyticsEvents = _interopRequireDefault(require("@atlaskit/analytics-next/withAnalyticsEvents"));
var _new = _interopRequireDefault(require("@atlaskit/button/new"));
var _chevronDown = _interopRequireDefault(require("@atlaskit/icon/core/chevron-down"));
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _primitives = require("@atlaskit/primitives");
var _experiments = require("@atlaskit/tmp-editor-statsig/experiments");
var _tooltip = _interopRequireDefault(require("@atlaskit/tooltip"));
var _analytics = require("../../analytics");
var _colorPickerButton = require("../../messages/color-picker-button");
var _uiColor = require("../../ui-color");
var _uiReact = require("../../ui-react");
var _Popup = _interopRequireDefault(require("../../ui/Popup"));
var _ArrowKeyNavigationProvider = require("../ArrowKeyNavigationProvider");
var _types = require("../ArrowKeyNavigationProvider/types");
/**
 * @jsxRuntime classic
 * @jsx jsx
 */

// eslint-disable-next-line @atlaskit/ui-styling-standard/use-compiled -- Ignored via go/DSP-18766

// eslint-disable-next-line @atlaskit/design-system/no-emotion-primitives -- to be migrated to @atlaskit/primitives/compiled – go/akcss

// helps adjusts position of popup
var colorPickerButtonWrapper = (0, _react2.css)({
  position: 'relative'
});
var colorPickerExpandContainerVisualRefresh = (0, _primitives.xcss)({
  marginTop: 'space.negative.025',
  marginRight: 'space.negative.050'
});
var colorPickerButtonStyle = (0, _react2.css)({
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors
  button: {
    '&::after': {
      border: 'none'
    },
    '&:hover': {
      backgroundColor: "var(--ds-background-selected, #E9F2FE)"
    }
  }
});

// Control the size of color picker buttons and preview
// TODO: DSP-4134 - Color picking UI
/* eslint-disable @atlaskit/design-system/ensure-design-token-usage */
// eslint-disable-next-line @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var colorPickerWrapper = function colorPickerWrapper() {
  return (0, _react2.css)({
    borderRadius: "var(--ds-radius-small, 3px)",
    backgroundColor: "var(--ds-surface-overlay, #FFFFFF)",
    boxShadow: "var(--ds-shadow-overlay, 0px 8px 12px #1E1F2126, 0px 0px 1px #1E1F214f)",
    padding: "var(--ds-space-100, 8px)".concat(" 0px")
  });
};
/* eslint-enable @atlaskit/design-system/ensure-design-token-usage */

var ColorPaletteWithReactViewListeners = (0, _uiReact.withReactEditorViewOuterListeners)(_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 _useIntl = (0, _reactIntlNext.useIntl)(),
    formatMessage = _useIntl.formatMessage;
  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
      // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- Ignored via go/ees017 (to be fixed)
      ,
      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: (0, _platformFeatureFlags.fg)('_editor_a11y_aria_label_removal_popup') ? formatMessage(_colorPickerButton.colorPickerButtonMessages.colorPickerMenuLabel) : '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
      // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- Ignored via go/ees017 (to be fixed)
      ,
      handleClose: function handleClose() {
        return setIsPopupOpen(false);
      },
      isOpenedByKeyboard: isOpenedByKeyboard,
      isPopupPositioned: isPopupPositioned,
      ignoreEscapeKey: props.returnEscToButton
    }, (0, _react2.jsx)(ColorPaletteWithReactViewListeners, {
      cols: props.cols,
      selectedColor: selectedColor,
      onClick: onColorSelected,
      handleClickOutside: togglePopup,
      handleEscapeKeydown: handleEsc
      // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- Ignored via go/ees017 (to be fixed)
      ,
      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 buttonStyleVisualRefresh = function buttonStyleVisualRefresh() {
    var _props$size, _props$size2, _props$size3;
    return (0, _react2.css)({
      // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
      height: "".concat(!!((_props$size = props.size) !== null && _props$size !== void 0 && _props$size.height) ? 'inherit' : ''),
      // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-selectors -- Ignored via go/DSP-18766
      '&:before': {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        alignSelf: 'center',
        content: "''",
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
        border: "var(--ds-border-width, 1px)".concat(" solid ", _uiColor.DEFAULT_BORDER_COLOR),
        borderRadius: "var(--ds-radius-small, 3px)",
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
        backgroundColor: currentColor || 'transparent',
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
        width: ((_props$size2 = props.size) === null || _props$size2 === void 0 ? void 0 : _props$size2.width) || '14px',
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
        height: ((_props$size3 = props.size) === null || _props$size3 === void 0 ? void 0 : _props$size3.height) || '14px',
        marginTop: "var(--ds-space-025, 2px)"
      }
    });
  };
  return (0, _react2.jsx)("div", {
    css: colorPickerButtonWrapper
  }, (0, _react2.jsx)(_tooltip.default, {
    content: title,
    position: "top"
  }, (0, _react2.jsx)("div", {
    css: colorPickerButtonStyle
  }, (0, _react2.jsx)(_new.default, {
    appearance: 'subtle',
    ref: buttonRef,
    "aria-label": title,
    "aria-expanded": props.isAriaExpanded ? isPopupOpen : undefined,
    spacing: (0, _experiments.editorExperiment)('platform_editor_controls', 'variant1') ? 'default' : 'compact',
    onClick: togglePopup
    // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- Ignored via go/ees017 (to be fixed)
    ,
    onKeyDown: function onKeyDown(event) {
      if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        togglePopup();
        setIsOpenedByKeyboard(true);
      }
    },
    "data-selected-color": props.currentColor,
    isSelected: isPopupOpen
  }, (0, _react2.jsx)(_primitives.Inline, {
    alignBlock: "start"
  }, (0, _react2.jsx)("span", {
    // eslint-disable-next-line @atlaskit/design-system/consistent-css-prop-usage
    css: buttonStyleVisualRefresh
  }), (0, _react2.jsx)(_primitives.Box, {
    xcss: colorPickerExpandContainerVisualRefresh
  }, (0, _react2.jsx)(_chevronDown.default, {
    color: "currentColor",
    spacing: "spacious",
    label: "color-picker-chevron-down",
    size: "small"
  })))))), renderPopup());
};
var _default_1 = (0, _withAnalyticsContext.default)({
  source: 'ConfigPanel'
})((0, _withAnalyticsEvents.default)()(ColorPickerButton));
var _default = exports.default = _default_1;