function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, { useEffect, useMemo, useRef, useState } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { getPositionFromStop, getStopFromMouseLocation, isColorInvalid, isStopInvalid } from './utils';
import { getChromaColor } from '../utils';
import { keys, useMouseMove } from '../../../services';
import { OuiButtonIcon } from '../../button';
import { OuiColorPicker } from '../color_picker';
import { OuiFlexGroup, OuiFlexItem } from '../../flex';
import { OuiFieldNumber, OuiFormRow } from '../../form';
import { OuiI18n } from '../../i18n';
import { OuiPopover } from '../../popover';
import { OuiScreenReaderOnly } from '../../accessibility';
import { OuiSpacer } from '../../spacer';
import { OuiRangeThumb } from '../../form/range/range_thumb';
export var OuiColorStopThumb = function OuiColorStopThumb(_ref) {
  var className = _ref.className,
    stop = _ref.stop,
    color = _ref.color,
    onChange = _ref.onChange,
    onFocus = _ref.onFocus,
    onRemove = _ref.onRemove,
    globalMin = _ref.globalMin,
    globalMax = _ref.globalMax,
    localMin = _ref.localMin,
    localMax = _ref.localMax,
    min = _ref.min,
    max = _ref.max,
    _ref$isRangeMin = _ref.isRangeMin,
    isRangeMin = _ref$isRangeMin === void 0 ? false : _ref$isRangeMin,
    _ref$isRangeMax = _ref.isRangeMax,
    isRangeMax = _ref$isRangeMax === void 0 ? false : _ref$isRangeMax,
    parentRef = _ref.parentRef,
    colorPickerMode = _ref.colorPickerMode,
    colorPickerShowAlpha = _ref.colorPickerShowAlpha,
    colorPickerSwatches = _ref.colorPickerSwatches,
    disabled = _ref.disabled,
    readOnly = _ref.readOnly,
    isPopoverOpen = _ref.isPopoverOpen,
    openPopover = _ref.openPopover,
    closePopover = _ref.closePopover,
    dataIndex = _ref['data-index'],
    ariaValueText = _ref['aria-valuetext'],
    _ref$valueInputProps = _ref.valueInputProps,
    valueInputProps = _ref$valueInputProps === void 0 ? {} : _ref$valueInputProps;
  var background = useMemo(function () {
    var chromaColor = getChromaColor(color, colorPickerShowAlpha);
    return chromaColor ? chromaColor.css() : undefined;
  }, [color, colorPickerShowAlpha]);
  var _useState = useState(isPopoverOpen),
    _useState2 = _slicedToArray(_useState, 2),
    hasFocus = _useState2[0],
    setHasFocus = _useState2[1];
  var _useState3 = useState(isColorInvalid(color, colorPickerShowAlpha)),
    _useState4 = _slicedToArray(_useState3, 2),
    colorIsInvalid = _useState4[0],
    setColorIsInvalid = _useState4[1];
  var _useState5 = useState(isStopInvalid(stop)),
    _useState6 = _slicedToArray(_useState5, 2),
    stopIsInvalid = _useState6[0],
    setStopIsInvalid = _useState6[1];
  var _useState7 = useState(null),
    _useState8 = _slicedToArray(_useState7, 2),
    numberInputRef = _useState8[0],
    setNumberInputRef = _useState8[1];
  var popoverRef = useRef(null);
  useEffect(function () {
    if (isPopoverOpen && popoverRef && popoverRef.current) {
      popoverRef.current.positionPopoverFixed();
    }
  }, [isPopoverOpen, stop]);
  var getStopFromMouseLocationFn = function getStopFromMouseLocationFn(location) {
    // Guard against `null` ref in usage
    return getStopFromMouseLocation(location, parentRef, globalMin, globalMax);
  };
  var getPositionFromStopFn = function getPositionFromStopFn(stop) {
    // Guard against `null` ref in usage
    return getPositionFromStop(stop, parentRef, globalMin, globalMax);
  };
  var handleOnRemove = function handleOnRemove() {
    if (onRemove) {
      closePopover();
      onRemove();
    }
  };
  var handleFocus = function handleFocus() {
    setHasFocus(true);
    if (onFocus) {
      onFocus();
    }
  };
  var setHasFocusTrue = function setHasFocusTrue() {
    return setHasFocus(true);
  };
  var setHasFocusFalse = function setHasFocusFalse() {
    return setHasFocus(false);
  };
  var handleColorChange = function handleColorChange(value) {
    setColorIsInvalid(isColorInvalid(value, colorPickerShowAlpha));
    onChange({
      stop: stop,
      color: value
    });
  };
  var handleStopChange = function handleStopChange(value) {
    var willBeInvalid = value > localMax || value < localMin;
    if (willBeInvalid) {
      if (value > localMax) {
        value = localMax;
      }
      if (value < localMin) {
        value = localMin;
      }
    }
    setStopIsInvalid(isStopInvalid(value));
    onChange({
      stop: value,
      color: color
    });
  };
  var handleStopInputChange = function handleStopInputChange(e) {
    var value = parseFloat(e.target.value);
    var willBeInvalid = value > globalMax || value < globalMin;
    if (willBeInvalid) {
      if (value > globalMax && max != null) {
        value = globalMax;
      }
      if (value < globalMin && min != null) {
        value = globalMin;
      }
    }
    setStopIsInvalid(isStopInvalid(value));
    onChange({
      stop: value,
      color: color
    });
  };
  var handlePointerChange = function handlePointerChange(location, isFirstInteraction) {
    if (isFirstInteraction) return; // Prevents change on the initial MouseDown event
    if (parentRef == null) {
      return;
    }
    var newStop = getStopFromMouseLocationFn(location);
    handleStopChange(newStop);
  };
  var handleKeyDown = function handleKeyDown(event) {
    switch (event.key) {
      case keys.ENTER:
        event.preventDefault();
        openPopover();
        break;
      case keys.ARROW_LEFT:
        event.preventDefault();
        if (readOnly) return;
        handleStopChange(stop - 1);
        break;
      case keys.ARROW_RIGHT:
        event.preventDefault();
        if (readOnly) return;
        handleStopChange(stop + 1);
        break;
    }
  };
  var _useMouseMove = useMouseMove(handlePointerChange),
    _useMouseMove2 = _slicedToArray(_useMouseMove, 2),
    handleMouseDown = _useMouseMove2[0],
    handleInteraction = _useMouseMove2[1];
  var handleOnMouseDown = function handleOnMouseDown(e) {
    if (!readOnly) {
      handleMouseDown(e);
    }
    openPopover();
  };
  var handleTouchInteraction = function handleTouchInteraction(e) {
    if (!readOnly) {
      handleInteraction(e);
    }
  };
  var handleTouchStart = function handleTouchStart(e) {
    handleTouchInteraction(e);
    if (!isPopoverOpen) {
      openPopover();
    }
  };
  var classes = classNames('ouiColorStopPopover', {
    'ouiColorStopPopover-hasFocus': hasFocus || isPopoverOpen
  }, className);
  return /*#__PURE__*/React.createElement(OuiPopover, {
    ref: popoverRef,
    className: classes,
    anchorClassName: "ouiColorStopPopover__anchor",
    panelPaddingSize: "s",
    isOpen: isPopoverOpen,
    closePopover: closePopover,
    initialFocus: numberInputRef || undefined,
    focusTrapProps: {
      clickOutsideDisables: false
    },
    panelClassName: numberInputRef ? undefined : 'ouiColorStopPopover-isLoadingPanel',
    style: {
      left: "".concat(getPositionFromStopFn(stop), "%")
    },
    button: /*#__PURE__*/React.createElement(OuiI18n, {
      tokens: ['ouiColorStopThumb.buttonAriaLabel', 'ouiColorStopThumb.buttonTitle'],
      defaults: ['Press the Enter key to modify this stop. Press Escape to focus the group', 'Click to edit, drag to reposition']
    }, function (_ref2) {
      var _ref3 = _slicedToArray(_ref2, 2),
        buttonAriaLabel = _ref3[0],
        buttonTitle = _ref3[1];
      var ariaLabel = buttonAriaLabel;
      var title = buttonTitle;
      return /*#__PURE__*/React.createElement(OuiRangeThumb, {
        "data-test-subj": "ouiColorStopThumb",
        "data-index": dataIndex,
        min: localMin,
        max: localMax,
        value: stop,
        onFocus: handleFocus,
        onBlur: setHasFocusFalse,
        onMouseOver: setHasFocusTrue,
        onMouseOut: setHasFocusFalse,
        onKeyDown: handleKeyDown,
        onMouseDown: handleOnMouseDown,
        onTouchStart: handleTouchStart,
        onTouchMove: handleTouchInteraction,
        "aria-valuetext": ariaValueText,
        "aria-label": ariaLabel,
        title: title,
        className: "ouiColorStopThumb",
        tabIndex: -1,
        style: {
          background: background
        },
        disabled: disabled
      });
    })
  }, /*#__PURE__*/React.createElement("div", {
    className: "ouiColorStop",
    "data-test-subj": "ouiColorStopPopover"
  }, /*#__PURE__*/React.createElement(OuiScreenReaderOnly, null, /*#__PURE__*/React.createElement("p", {
    "aria-live": "polite"
  }, /*#__PURE__*/React.createElement(OuiI18n, {
    token: "ouiColorStopThumb.screenReaderAnnouncement",
    default: "A popup with a color stop edit form opened. Tab forward to cycle through form controls or press escape to close this popup."
  }))), /*#__PURE__*/React.createElement(OuiFlexGroup, {
    gutterSize: "s",
    responsive: false
  }, /*#__PURE__*/React.createElement(OuiFlexItem, null, /*#__PURE__*/React.createElement(OuiI18n, {
    tokens: ['ouiColorStopThumb.stopLabel', 'ouiColorStopThumb.stopErrorMessage'],
    defaults: ['Stop value', 'Value is out of range']
  }, function (_ref4) {
    var _ref5 = _slicedToArray(_ref4, 2),
      stopLabel = _ref5[0],
      stopErrorMessage = _ref5[1];
    return /*#__PURE__*/React.createElement(OuiFormRow, {
      label: stopLabel,
      display: "rowCompressed",
      isInvalid: stopIsInvalid,
      error: stopIsInvalid ? stopErrorMessage : null
    }, /*#__PURE__*/React.createElement(OuiFieldNumber, _extends({}, valueInputProps, {
      inputRef: setNumberInputRef,
      compressed: true,
      readOnly: readOnly,
      min: isRangeMin || min == null ? undefined : localMin,
      max: isRangeMax || max == null ? undefined : localMax,
      value: isStopInvalid(stop) ? '' : stop,
      isInvalid: stopIsInvalid,
      onChange: handleStopInputChange
    })));
  })), !readOnly && /*#__PURE__*/React.createElement(OuiFlexItem, {
    grow: false
  }, /*#__PURE__*/React.createElement(OuiFormRow, {
    display: "rowCompressed",
    hasEmptyLabelSpace: true
  }, /*#__PURE__*/React.createElement(OuiI18n, {
    token: "ouiColorStopThumb.removeLabel",
    default: "Remove this stop"
  }, function (removeLabel) {
    return /*#__PURE__*/React.createElement(OuiButtonIcon, {
      iconType: "trash",
      color: "danger",
      "aria-label": removeLabel,
      title: removeLabel,
      disabled: !onRemove,
      onClick: handleOnRemove
    });
  })))), !readOnly && /*#__PURE__*/React.createElement(OuiSpacer, {
    size: "s"
  }), /*#__PURE__*/React.createElement(OuiColorPicker, {
    readOnly: readOnly,
    onChange: handleColorChange,
    color: color,
    mode: readOnly ? 'secondaryInput' : colorPickerMode,
    swatches: colorPickerSwatches,
    display: "inline",
    showAlpha: colorPickerShowAlpha,
    isInvalid: colorIsInvalid,
    secondaryInputDisplay: colorPickerMode === 'swatch' ? 'none' : 'bottom'
  })));
};

/* OUI -> EUI Aliases: Build-Time */
OuiColorStopThumb.propTypes = {
  className: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  onFocus: PropTypes.func,
  onRemove: PropTypes.func,
  globalMin: PropTypes.number.isRequired,
  globalMax: PropTypes.number.isRequired,
  localMin: PropTypes.number.isRequired,
  localMax: PropTypes.number.isRequired,
  min: PropTypes.number,
  max: PropTypes.number,
  isRangeMin: PropTypes.bool,
  isRangeMax: PropTypes.bool,
  parentRef: PropTypes.oneOfType([PropTypes.any.isRequired, PropTypes.oneOf([null])]),
  colorPickerMode: PropTypes.oneOf(["default", "swatch", "picker", "secondaryInput"]).isRequired,
  colorPickerShowAlpha: PropTypes.bool,
  colorPickerSwatches: PropTypes.arrayOf(PropTypes.string.isRequired),
  disabled: PropTypes.bool,
  readOnly: PropTypes.bool,
  isPopoverOpen: PropTypes.bool.isRequired,
  openPopover: PropTypes.func.isRequired,
  closePopover: PropTypes.func.isRequired,
  "data-index": PropTypes.string,
  "aria-valuetext": PropTypes.string,
  valueInputProps: PropTypes.any,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.string,
  stop: PropTypes.number.isRequired,
  color: PropTypes.string.isRequired
};
export { EuiColorStopThumb } from '../../../eui_components/color_picker/color_stops/color_stop_thumb';