/**
 * ldesign v0.2.2
 * (c) 2022年9月20日 swimly
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var VueCompositionAPI = require('@vue/composition-api');
var cloneDeep = require('lodash/cloneDeep');
var constants = require('../../../chunks/constants.js');
var color = require('../../../chunks/color.js');
require('@babel/runtime/helpers/classCallCheck');
require('@babel/runtime/helpers/createClass');
var components_inputNumber_index = require('../../input-number/index.js');
var components_colorPicker_hooks_index = require('../hooks/index.js');
var hooks_useCommonClassname = require('../../../hooks/use-common-classname.js');
var components_colorPicker_panel_baseProps = require('./base-props.js');
require('@babel/runtime/helpers/slicedToArray');
require('../../../chunks/defineProperty-28395935.js');
require('@babel/runtime/helpers/typeof');
require('../../input-number/input-number.js');
require('../../../chunks/helper.js');
require('@ldesign/icons-vue');
require('../../button/index.js');
require('../../button/button.js');
require('../../loading/index.js');
require('../../loading/loading.js');
require('../../loading/icon/gradient.js');
require('vue');
require('../../../chunks/set-style.js');
require('../../../chunks/helper2.js');
require('@babel/runtime/helpers/toConsumableArray');
require('../../../config.js');
require('../../../utils/dom.js');
require('raf');
require('lodash/isString');
require('../../../utils/easing.js');
require('../../../utils/render-node.js');
require('lodash/camelCase');
require('lodash/kebabCase');
require('../../../utils/transfer-dom.js');
require('../../loading/props.js');
require('../../config-provider/config-receiver.js');
require('lodash/mergeWith');
require('lodash');
require('../../config-provider/context.js');
require('../../../chunks/zh_CN.js');
require('../../../utils/mixins.js');
require('../../../utils/with-install.js');
require('../../loading/plugin.js');
require('../../button/props.js');
require('../../../utils/ripple.js');
require('../../input/index.js');
require('../../input/input.js');
require('../../../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('../../../utils/event.js');
require('../../input/props.js');
require('../../input/group.js');
require('../../../utils/map-props.js');
require('../../input-number/props.js');
require('../../input-number/hooks/use-input-number.js');
require('../../../chunks/isObjectLike-2443c6ff.js');
require('../../../chunks/_commonjsHelpers-ea2bee21.js');
require('../../../chunks/isArray-b0f0e351.js');
require('../../../chunks/log.js');
require('../../../hooks/use-vmodel.js');
require('../../../hooks/use-form-disabled.js');
require('../../config-provider/useConfig.js');
require('../../../hooks/use-global-icon.js');
require('../../../hooks/use-config.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var cloneDeep__default = /*#__PURE__*/_interopDefaultLegacy(cloneDeep);

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var DELETE_KEYS = ["delete", "backspace"];
var LinearGradient = VueCompositionAPI.defineComponent({
  name: "LinearGradient",
  components: {
    LInputNumber: components_inputNumber_index.InputNumber
  },
  inheritAttrs: false,
  props: _objectSpread({}, components_colorPicker_panel_baseProps["default"]),
  setup: function setup(props) {
    var baseClassName = components_colorPicker_hooks_index.useBaseClassName();

    var _useCommonClassName = hooks_useCommonClassname["default"](),
        statusClassNames = _useCommonClassName.statusClassNames;

    var refSlider = VueCompositionAPI.ref(null);
    var sliderRect = VueCompositionAPI.reactive({
      left: 0,
      width: constants.GRADIENT_SLIDER_DEFAULT_WIDTH
    });
    var isDragging = VueCompositionAPI.ref(false);
    var isMoved = VueCompositionAPI.ref(false);
    var colorInstance = VueCompositionAPI.computed(function () {
      return cloneDeep__default["default"](props.color);
    });
    var degree = VueCompositionAPI.ref(colorInstance.value.gradientDegree);
    var selectedId = VueCompositionAPI.ref(colorInstance.value.gradientSelectedId);
    var colors = VueCompositionAPI.ref(cloneDeep__default["default"](colorInstance.value.gradientColors));
    VueCompositionAPI.watch(function () {
      return props.color.gradientDegree;
    }, function (value) {
      return degree.value = value;
    });
    VueCompositionAPI.watch(function () {
      return props.color.gradientSelectedId;
    }, function (value) {
      return selectedId.value = value;
    });
    VueCompositionAPI.watch(function () {
      return props.color.gradientColors;
    }, function (value) {
      colors.value = cloneDeep__default["default"](value);
    }, {
      deep: true
    });

    var handleChange = function handleChange(key, payload, addUsedColor) {
      if (props.disabled) {
        return;
      }

      props.handleChange({
        key: key,
        payload: payload,
        addUsedColor: addUsedColor
      });
    };

    var handleDegreeChange = function handleDegreeChange(value) {
      if (props.disabled || value === colorInstance.value.gradientDegree) {
        return;
      }

      degree.value = value;
      handleChange("degree", value, true);
    };

    var handleSelectedIdChange = function handleSelectedIdChange(value) {
      if (props.disabled) {
        return;
      }

      selectedId.value = value;
      handleChange("selectedId", value);
    };

    var handleColorsChange = function handleColorsChange(value, isEnded) {
      if (props.disabled) {
        return;
      }

      colors.value = value;
      handleChange("colors", value, isEnded);
    };

    var updateActiveThumbLeft = function updateActiveThumbLeft(left) {
      var index = colors.value.findIndex(function (c) {
        return c.id === selectedId.value;
      });

      if (index === -1) {
        return;
      }

      var point = colors.value[index];
      left = Math.max(0, Math.min(sliderRect.width, left));
      var percentLeft = left / sliderRect.width * 100;
      colors.value.splice(index, 1, {
        color: point.color,
        left: percentLeft,
        id: point.id
      });
      handleColorsChange(colors.value);
    };

    var handleStart = function handleStart(id, e) {
      var rect = refSlider.value.getBoundingClientRect();
      sliderRect.left = rect.left;
      sliderRect.width = rect.width || constants.GRADIENT_SLIDER_DEFAULT_WIDTH;

      if (isDragging.value || props.disabled) {
        return;
      }

      isMoved.value = false;
      isDragging.value = true;
      e.preventDefault();
      e.stopPropagation();
      handleSelectedIdChange(id);
      refSlider.value.focus();
      window.addEventListener("mousemove", handleMove, false);
      window.addEventListener("mouseup", handleEnd, false);
      window.addEventListener("contextmenu", handleEnd, false);
    };

    var handleMove = function handleMove(e) {
      if (!isDragging.value || props.disabled) {
        return;
      }

      var left = e.clientX - sliderRect.left;
      isMoved.value = true;
      updateActiveThumbLeft(left);
    };

    var handleEnd = function handleEnd() {
      if (!isDragging.value) {
        return;
      }

      setTimeout(function () {
        isDragging.value = false;
      }, 0);

      if (isMoved.value) {
        handleColorsChange(colors.value, true);
        isMoved.value = false;
      }

      window.removeEventListener("mousemove", handleMove, false);
      window.removeEventListener("mouseup", handleEnd, false);
      window.removeEventListener("contextmenu", handleEnd, false);
    };

    var handleKeyup = function handleKeyup(e) {
      if (props.disabled) {
        return;
      }

      var points = colors.value;
      var pos = points.findIndex(function (c) {
        return c.id === selectedId.value;
      });
      var length = points.length;

      if (DELETE_KEYS.includes(e.key.toLocaleLowerCase()) && length > 2 && pos >= 0 && pos <= length - 1) {
        points.splice(pos, 1);

        if (!points[pos]) {
          pos = points[pos + 1] ? pos + 1 : points[pos - 1] ? pos - 1 : 0;
        }

        var current = points[pos];
        handleColorsChange(points, true);
        handleSelectedIdChange(current === null || current === void 0 ? void 0 : current.id);
      }
    };

    var handleThumbBarClick = function handleThumbBarClick(e) {
      if (props.disabled) {
        return;
      }

      var left = e.clientX - sliderRect.left;
      left = Math.max(0, Math.min(sliderRect.width, left));
      var percentLeft = left / sliderRect.width * 100;
      var newPoint = color.genGradientPoint(percentLeft, colorInstance.value.rgba);
      colors.value.push(newPoint);
      handleColorsChange(colors.value, true);
      handleSelectedIdChange(newPoint.id);
    };

    VueCompositionAPI.onMounted(function () {
      var rect = refSlider.value.getBoundingClientRect();
      sliderRect.left = rect.left;
      sliderRect.width = rect.width || constants.GRADIENT_SLIDER_DEFAULT_WIDTH;
    });
    VueCompositionAPI.onBeforeUnmount(function () {
      window.removeEventListener("mousemove", handleMove, false);
      window.removeEventListener("mouseup", handleEnd, false);
      window.removeEventListener("contextmenu", handleEnd, false);
    });
    return {
      baseClassName: baseClassName,
      statusClassNames: statusClassNames,
      refSlider: refSlider,
      degree: degree,
      selectedId: selectedId,
      colors: colors,
      colorInstance: colorInstance,
      handleDegreeChange: handleDegreeChange,
      handleStart: handleStart,
      handleMove: handleMove,
      handleEnd: handleEnd,
      handleKeyup: handleKeyup,
      handleThumbBarClick: handleThumbBarClick
    };
  },
  render: function render() {
    var _this = this;

    var h = arguments[0];
    var _this$colorInstance = this.colorInstance,
        linearGradient = _this$colorInstance.linearGradient,
        gradientColors = _this$colorInstance.gradientColors;
    var colors = this.colors,
        selectedId = this.selectedId,
        degree = this.degree,
        disabled = this.disabled,
        baseClassName = this.baseClassName,
        statusClassNames = this.statusClassNames;
    var thumbBackground = color.gradientColors2string({
      points: gradientColors,
      degree: 90
    });
    return h("div", {
      "class": "".concat(baseClassName, "__gradient")
    }, [h("div", {
      "class": "".concat(baseClassName, "__gradient-slider")
    }, [h("div", {
      "class": ["".concat(baseClassName, "__slider"), "".concat(baseClassName, "--bg-alpha")],
      "on": {
        "keyup": this.handleKeyup
      },
      "attrs": {
        "tabindex": 0
      },
      "ref": "refSlider"
    }, [h("ul", {
      "class": "gradient-thumbs",
      "on": {
        "click": this.handleThumbBarClick
      },
      "style": {
        background: thumbBackground
      }
    }, [colors.map(function (t) {
      var left = "".concat(Math.round(t.left * 100) / 100, "%");
      return h("li", {
        "class": ["".concat(baseClassName, "__thumb"), "gradient-thumbs__item", selectedId === t.id ? statusClassNames.active : ""],
        "key": t.id,
        "attrs": {
          "title": "".concat(t.color, " ").concat(left)
        },
        "style": {
          color: t.color,
          left: left
        },
        "on": {
          "click": function click(e) {
            return e.stopPropagation();
          },
          "mousedown": function mousedown(e) {
            return _this.handleStart(t.id, e);
          }
        }
      }, [h("span", {
        "class": ["gradient-thumbs__item-inner", "".concat(baseClassName, "--bg-alpha")]
      })]);
    })])])]), h("div", {
      "class": "".concat(baseClassName, "__gradient-degree"),
      "attrs": {
        "title": "".concat(degree, "deg")
      }
    }, [h("l-input-number", {
      "attrs": {
        "theme": "normal",
        "size": "small",
        "min": 0,
        "max": 360,
        "step": 1,
        "format": function format(value) {
          return "".concat(value, "\xB0");
        },
        "disabled": disabled
      },
      "on": {
        "blur": this.handleDegreeChange,
        "enter": this.handleDegreeChange
      },
      "model": {
        value: _this.degree,
        callback: function callback($$v) {
          _this.degree = $$v;
        }
      }
    })]), h("div", {
      "class": ["".concat(baseClassName, "__gradient-preview"), "".concat(baseClassName, "--bg-alpha")]
    }, [h("span", {
      "class": "preview-inner",
      "style": {
        background: linearGradient
      }
    })])]);
  }
});

exports["default"] = LinearGradient;
//# sourceMappingURL=linear-gradient.js.map
