"use strict";

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

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

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

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

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

var _deepClone = require("../utils/deep-clone");

var _hooks = require("../hooks");

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

var _raf = require("../utils/raf");

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 DEFAULT_DURATION = 200; // 惯性滑动思路:
// 在手指离开屏幕时，如果和上一次 move 时的间隔小于 `MOMENTUM_LIMIT_TIME` 且 move
// 距离大于 `MOMENTUM_LIMIT_DISTANCE` 时，执行惯性滑动

var MOMENTUM_LIMIT_TIME = 300;
var MOMENTUM_LIMIT_DISTANCE = 15;

function getElementTranslateY(element) {
  var style = window.getComputedStyle(element);
  var transform = style.transform || style.webkitTransform;
  var translateY = transform.slice(7, transform.length - 1).split(', ')[5];
  return Number(translateY);
}

function isOptionDisabled(option) {
  return (0, _utils.isObject)(option) && option.disabled;
}

var PickerColumn = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('picker-column', prefixCls),
      bem = _createNamespace[0];

  var itemHeight = props.itemHeight,
      visibleItemCount = props.visibleItemCount,
      defaultIndex = props.defaultIndex,
      initialOptions = props.initialOptions;
  var root = (0, _react.useRef)(null);
  var wrapper = (0, _react.useRef)(null);
  var moving = (0, _react.useRef)(false);
  var startOffset = (0, _react.useRef)(0);
  var transitionEndTrigger = (0, _react.useRef)(null);
  var touchStartTime = (0, _react.useRef)(0);
  var momentumOffset = (0, _react.useRef)(0);

  var _useSetState = (0, _hooks.useSetState)({
    index: defaultIndex,
    offset: 0,
    duration: 0,
    options: (0, _deepClone.deepClone)(initialOptions)
  }),
      state = _useSetState[0],
      updateState = _useSetState[1];

  var touch = (0, _useTouch.default)();
  var count = (0, _react.useMemo)(function () {
    return state.options.length;
  }, [state.options.length]);
  var baseOffset = (0, _react.useMemo)(function () {
    // 默认转入第一个选项的位置
    return itemHeight * (+visibleItemCount - 1) / 2;
  }, [itemHeight, visibleItemCount]);

  var adjustIndex = function adjustIndex(index) {
    index = (0, _utils.range)(index, 0, count);

    for (var i = index; i < count; i += 1) {
      if (!isOptionDisabled(state.options[i])) return i;
    }

    for (var _i = index - 1; _i >= 0; _i -= 1) {
      if (!isOptionDisabled(state.options[_i])) return _i;
    }

    return null;
  };

  var setIndex = function setIndex(index, emitChange) {
    index = adjustIndex(index) || 0;
    var offset = -index * props.itemHeight;

    var trigger = function trigger() {
      if (index !== state.index) {
        updateState({
          index: index
        });

        if (emitChange && props.onChange) {
          (0, _raf.raf)(function () {
            props.onChange(index);
          });
        }
      }
    }; // trigger the change event after transitionend when moving


    if (moving.current && offset !== state.offset) {
      transitionEndTrigger.current = trigger;
    } else {
      trigger();
    }

    updateState({
      offset: offset
    });
  };

  var setOptions = function setOptions(options) {
    if (JSON.stringify(options) !== JSON.stringify(state.options)) {
      updateState({
        options: (0, _deepClone.deepClone)(options)
      });
      setIndex(props.defaultIndex);
    }
  };

  var onClickItem = function onClickItem(index) {
    if (moving.current || props.readonly) {
      return;
    }

    transitionEndTrigger.current = null;
    updateState({
      duration: DEFAULT_DURATION
    });
    setIndex(index, true);
  };

  var getOptionText = function getOptionText(option) {
    if ((0, _utils.isObject)(option) && props.textKey in option) {
      return option[props.textKey];
    }

    return option;
  };

  var getIndexByOffset = function getIndexByOffset(offset) {
    return (0, _utils.range)(Math.round(-offset / props.itemHeight), 0, count - 1);
  };

  var momentum = function momentum(distance, _duration) {
    var speed = Math.abs(distance / _duration);
    distance = state.offset + speed / 0.003 * (distance < 0 ? -1 : 1);
    var index = getIndexByOffset(distance);
    updateState({
      duration: +props.swipeDuration
    });
    setIndex(index, true);
  };

  var stopMomentum = function stopMomentum() {
    moving.current = false;
    updateState({
      duration: 0
    });

    if (transitionEndTrigger.current) {
      transitionEndTrigger.current();
      transitionEndTrigger.current = null;
    }
  };

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

    touch.start(event);
    var offset = state.offset;

    if (moving.current) {
      var translateY = getElementTranslateY(wrapper.current);
      offset = Math.min(0, translateY - baseOffset);
      startOffset.current = offset;
    } else {
      startOffset.current = offset;
    }

    updateState({
      duration: 0,
      offset: offset
    });
    touchStartTime.current = Date.now();
    momentumOffset.current = startOffset.current;
    transitionEndTrigger.current = null;
  };

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

    touch.move(event);

    if (touch.isVertical()) {
      moving.current = true;
    }

    var offset = (0, _utils.range)(startOffset.current + touch.deltaY, -(count * props.itemHeight), props.itemHeight);
    updateState({
      offset: offset
    });
    var now = Date.now();

    if (now - touchStartTime.current > MOMENTUM_LIMIT_TIME) {
      touchStartTime.current = now;
      momentumOffset.current = offset;
    }
  };

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

    var distance = state.offset - momentumOffset.current;
    var duration = Date.now() - touchStartTime.current;
    var allowMomentum = duration < MOMENTUM_LIMIT_TIME && Math.abs(distance) > MOMENTUM_LIMIT_DISTANCE;

    if (allowMomentum) {
      momentum(distance, duration);
      return;
    }

    var index = getIndexByOffset(state.offset);
    updateState({
      duration: DEFAULT_DURATION
    });
    setIndex(index, true); // compatible with desktop scenario
    // use setTimeout to skip the click event triggered after touchstart

    setTimeout(function () {
      moving.current = false;
    }, 0);
  };

  var renderOptions = function renderOptions() {
    var optionStyle = {
      height: props.itemHeight + "px"
    };
    return state.options.map(function (option, index) {
      var text = getOptionText(option);
      var disabled = isOptionDisabled(option);
      var data = {
        role: 'button',
        style: optionStyle,
        tabIndex: disabled ? -1 : 0,
        className: (0, _clsx.default)(bem('item', {
          disabled: disabled,
          selected: index === state.index
        })),
        onClick: function onClick() {
          onClickItem(index);
        }
      };
      var childData = {
        className: 'rv-ellipsis',
        children: text
      };
      return /*#__PURE__*/_react.default.createElement("li", _extends({}, data, {
        key: index
      }), props.optionRender ? props.optionRender(option) : /*#__PURE__*/_react.default.createElement("div", _extends({}, childData)));
    });
  };

  var setValue = function setValue(value) {
    var options = state.options;

    for (var i = 0; i < options.length; i += 1) {
      if (getOptionText(options[i]) === value) {
        return setIndex(i);
      }
    }

    return null;
  };

  var getValue = (0, _react.useCallback)(function () {
    return state.options[state.index];
  }, [state.index, state.options]);
  (0, _react.useEffect)(function () {
    setIndex(defaultIndex);
  }, [defaultIndex]);
  (0, _hooks.useUpdateEffect)(function () {
    setOptions(initialOptions);
  }, [initialOptions]);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      state: state,
      setIndex: setIndex,
      getValue: getValue,
      setValue: setValue,
      setOptions: setOptions,
      stopMomentum: stopMomentum
    };
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: root,
    className: (0, _clsx.default)(bem(), props.className),
    onTouchStart: onTouchStart,
    onTouchMove: onTouchMove,
    onTouchEnd: onTouchEnd,
    onTouchCancel: onTouchEnd
  }, /*#__PURE__*/_react.default.createElement("ul", {
    ref: wrapper,
    style: {
      transform: "translate3d(0, " + (state.offset + baseOffset) + "px, 0)",
      transitionDuration: state.duration + "ms",
      transitionProperty: state.duration ? 'all' : 'none'
    },
    className: (0, _clsx.default)(bem('wrapper')),
    onTransitionEnd: stopMomentum
  }, renderOptions()));
});
PickerColumn.defaultProps = {
  initialOptions: [],
  defaultIndex: 0
};
var _default = PickerColumn;
exports.default = _default;