"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.scrollLeftTo = scrollLeftTo;
exports.scrollTopTo = scrollTopTo;

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

var _scroll = _interopRequireDefault(require("../utils/dom/scroll"));

/**
 * @author Wuner
 * @date 2020/9/21 11:36
 * @description
 */
var scrollLeftRafId;

function scrollLeftTo(scroller, to, duration) {
  (0, _raf.cancel)(scrollLeftRafId);
  var count = 0;
  var from = scroller.scrollLeft;
  var frames = duration === 0 ? 1 : Math.round(duration * 1000 / 16);

  function animate() {
    scroller.scrollLeft += (to - from) / frames;

    if (++count < frames) {
      scrollLeftRafId = (0, _raf.raf)(animate);
    }
  }

  animate();
}

function scrollTopTo(scroller, to, duration, callback) {
  var current = _scroll.default.getScrollTop(scroller);

  var isDown = current < to;
  var frames = duration === 0 ? 1 : Math.round(duration * 1000 / 16);
  var step = (to - current) / frames;

  function animate() {
    current += step;

    if (isDown && current > to || !isDown && current < to) {
      current = to;
    }

    _scroll.default.setScrollTop(scroller, current);

    if (isDown && current < to || !isDown && current > to) {
      (0, _raf.raf)(animate);
    } else if (callback) {
      (0, _raf.raf)(callback);
    }
  }

  animate();
}