"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _clsx = _interopRequireDefault(require("clsx"));

var _utils = require("../utils");

var _useTouch = _interopRequireDefault(require("../hooks/use-touch"));

var _useRect = require("../hooks/use-rect");

var _useEventListener = _interopRequireDefault(require("../hooks/use-event-listener"));

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var Slider = function Slider(props) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('slider', prefixCls),
      bem = _createNamespace[0];

  var _useState = (0, _react.useState)(null),
      buttonRef1 = _useState[0],
      setButtonRef1 = _useState[1];

  var _useState2 = (0, _react.useState)(null),
      buttonRef2 = _useState2[0],
      setButtonRef2 = _useState2[1];

  var buttonIndex = (0, _react.useRef)();
  var startValue = (0, _react.useRef)();
  var currentValue = (0, _react.useRef)(props.value);
  var root = (0, _react.useRef)();
  var dragStatus = (0, _react.useRef)();
  var touch = (0, _useTouch.default)(true);
  var scope = (0, _react.useMemo)(function () {
    return Number(props.max) - Number(props.min);
  }, [props.max, props.min]);
  var wrapperStyle = (0, _react.useMemo)(function () {
    var _extends2;

    var crossAxis = props.vertical ? 'width' : 'height';
    return _extends((_extends2 = {
      background: props.inactiveColor
    }, _extends2[crossAxis] = (0, _utils.addUnit)(props.barHeight), _extends2), props.style);
  }, [props.vertical, props.barHeight, props.inactiveColor, props.style]);

  var isRange = function isRange(val) {
    return props.range && Array.isArray(val);
  }; // 计算选中条的长度百分比


  var calcMainAxis = function calcMainAxis() {
    var value = props.value,
        min = props.min;

    if (isRange(value)) {
      return (value[1] - value[0]) * 100 / scope + "%";
    }

    return (+value - Number(min)) * 100 / scope + "%";
  }; // 计算选中条的开始位置的偏移量


  var calcOffset = function calcOffset() {
    var value = props.value,
        min = props.min;

    if (isRange(value)) {
      return (value[0] - Number(min)) * 100 / scope + "%";
    }

    return '0%';
  };

  var barStyle = (0, _react.useMemo)(function () {
    var _style;

    var mainAxis = props.vertical ? 'height' : 'width';
    var style = (_style = {}, _style[mainAxis] = calcMainAxis(), _style.background = props.activeColor, _style);

    if (dragStatus.current) {
      style.transition = 'none';
    }

    var getPositionKey = function getPositionKey() {
      if (props.vertical) {
        return props.reverse ? 'bottom' : 'top';
      }

      return props.reverse ? 'right' : 'left';
    };

    style[getPositionKey()] = calcOffset();
    return style;
  }, [calcOffset]);

  var format = function format(value) {
    var min = +props.min;
    var max = +props.max;
    var step = +props.step;
    value = (0, _utils.range)(value, min, max);
    var diff = Math.round((value - min) / step) * step;
    return (0, _utils.addNumber)(min, diff);
  };

  var isSameValue = function isSameValue(newValue, oldValue) {
    return JSON.stringify(newValue) === JSON.stringify(oldValue);
  };

  var handleRangeValue = function handleRangeValue(value) {
    var _value$, _value$2;

    // 设置默认值
    var left = (_value$ = value[0]) != null ? _value$ : Number(props.min);
    var right = (_value$2 = value[1]) != null ? _value$2 : Number(props.max); // 处理两个滑块重叠之后的情况

    return left > right ? [right, left] : [left, right];
  };

  var updateValue = function updateValue(value, end) {
    if (isRange(value)) {
      value = handleRangeValue(value).map(format);
    } else {
      value = format(value);
    }

    if (!isSameValue(value, props.value)) {
      props.onChange == null ? void 0 : props.onChange(value);
    }

    if (end && !isSameValue(value, startValue.current)) {
      props.onChangeAfter == null ? void 0 : props.onChangeAfter(value);
    }

    return value;
  };

  var onClick = function onClick(event) {
    event.stopPropagation();

    if (props.disabled || props.readonly) {
      return;
    }

    var min = props.min,
        reverse = props.reverse,
        vertical = props.vertical,
        modelValue = props.value;
    var rect = (0, _useRect.getRect)(root.current);

    var getDelta = function getDelta() {
      if (vertical) {
        if (reverse) {
          return rect.bottom - event.clientY;
        }

        return event.clientY - rect.top;
      }

      if (reverse) {
        return rect.right - event.clientX;
      }

      return event.clientX - rect.left;
    };

    var total = vertical ? rect.height : rect.width;
    var value = Number(min) + getDelta() / total * scope;

    if (isRange(modelValue)) {
      var left = modelValue[0],
          right = modelValue[1];
      var middle = (left + right) / 2;

      if (value <= middle) {
        updateValue([value, right], true);
      } else {
        updateValue([left, value], true);
      }
    } else {
      updateValue(value, true);
    }
  };

  var _onTouchStart = function onTouchStart(event) {
    if (props.disabled || props.readonly) {
      return;
    }

    touch.start(event);
    currentValue.current = JSON.parse(JSON.stringify(props.value));

    if (isRange(currentValue.current)) {
      startValue.current = currentValue.current.map(format);
    } else {
      startValue.current = format(currentValue.current);
    }

    dragStatus.current = 'start';
  };

  var onTouchMove = function onTouchMove(event) {
    if (props.disabled || props.readonly) {
      return;
    }

    if (dragStatus.current === 'start') {
      props.onDragStart == null ? void 0 : props.onDragStart(event, startValue.current);
    }

    (0, _utils.preventDefault)(event, true);
    touch.move(event);
    dragStatus.current = 'dragging';
    var rect = (0, _useRect.getRect)(root.current);
    var delta = props.vertical ? touch.deltaY : touch.deltaX;
    var total = props.vertical ? rect.height : rect.width;
    var diff = delta / total * scope;

    if (props.reverse) {
      diff = -diff;
    }

    if (isRange(startValue.current)) {
      var index = props.reverse ? 1 - buttonIndex.current : buttonIndex.current;
      currentValue.current[index] = startValue.current[index] + diff;
    } else {
      currentValue.current = +startValue.current + diff;
    }

    updateValue(currentValue.current);
  };

  var onTouchEnd = function onTouchEnd(event) {
    if (props.disabled || props.readonly) {
      return;
    }

    if (dragStatus.current === 'dragging') {
      var value = updateValue(currentValue.current, true);
      props.onDragEnd == null ? void 0 : props.onDragEnd(event, value);
    }

    dragStatus.current = '';
  };

  var getButtonClassName = function getButtonClassName(index) {
    if (typeof index === 'number') {
      var position = ['left', 'right'];
      return bem('button-wrapper', position[index]);
    }

    return bem('button-wrapper', props.reverse ? 'left' : 'right');
  };

  var renderButtonContent = function renderButtonContent(value, index) {
    if (typeof index === 'number') {
      var slot = props[index === 0 ? 'leftButton' : 'rightButton'];

      if (slot) {
        return slot;
      }
    }

    if (typeof props.button === 'function') {
      return props.button({
        value: value
      });
    }

    if (props.button) {
      return props.button;
    }

    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _clsx.default)(bem('button')),
      style: (0, _utils.getSizeStyle)(props.buttonSize)
    });
  };

  var renderButton = function renderButton(buttounRef, index) {
    var value = typeof index === 'number' ? props.value[index] : props.value;
    return /*#__PURE__*/_react.default.createElement("div", {
      ref: buttounRef,
      key: index,
      role: "slider",
      className: (0, _clsx.default)(getButtonClassName(index)),
      tabIndex: props.disabled || props.readonly ? -1 : 0,
      "aria-valuemin": props.min,
      "aria-valuenow": value,
      "aria-valuemax": props.max,
      "aria-orientation": props.vertical ? 'vertical' : 'horizontal',
      onTouchStart: function onTouchStart(event) {
        if (typeof index === 'number') {
          // save index of current button
          buttonIndex.current = index;
        }

        _onTouchStart(event);
      },
      onTouchEnd: onTouchEnd,
      onTouchCancel: onTouchEnd,
      onClick: _utils.stopPropagation
    }, renderButtonContent(currentValue.current, index));
  };

  (0, _useEventListener.default)('touchmove', onTouchMove, {
    target: buttonRef1,
    depends: [touch.deltaX, touch.deltaY, props.disabled, props.readonly]
  });
  (0, _useEventListener.default)('touchmove', onTouchMove, {
    target: buttonRef2,
    depends: [touch.deltaX, touch.deltaY, props.disabled, props.readonly]
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: root,
    style: wrapperStyle,
    className: (0, _clsx.default)(props.className, bem({
      vertical: props.vertical,
      disabled: props.disabled
    })),
    onClick: onClick
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.default)(bem('bar')),
    style: barStyle
  }, props.range ? [renderButton(setButtonRef1, 0), renderButton(setButtonRef2, 1)] : renderButton(setButtonRef1)));
};

Slider.defaultProps = {
  min: 0,
  max: 100,
  step: 1
};
var _default = Slider;
exports.default = _default;