import clamp from 'lodash-es/clamp';
import { eventScope, getPosition, } from '../utils/';
export function selectHandler(scrollbar) {
    var addEvent = eventScope(scrollbar);
    var containerEl = scrollbar.containerEl, contentEl = scrollbar.contentEl, offset = scrollbar.offset, limit = scrollbar.limit;
    var isSelected = false;
    var animationID;
    function scroll(_a) {
        var x = _a.x, y = _a.y;
        if (!x && !y)
            return;
        // DISALLOW delta transformation
        scrollbar.setMomentum(clamp(offset.x + x, 0, limit.x) - offset.x, clamp(offset.y + y, 0, limit.y) - offset.y);
        animationID = requestAnimationFrame(function () {
            scroll({ x: x, y: y });
        });
    }
    addEvent(window, 'mousemove', function (evt) {
        if (!isSelected)
            return;
        cancelAnimationFrame(animationID);
        var dir = calcMomentum(scrollbar, evt);
        scroll(dir);
    });
    addEvent(contentEl, 'selectstart', function (evt) {
        evt.stopPropagation();
        cancelAnimationFrame(animationID);
        isSelected = true;
    });
    addEvent(window, 'mouseup blur', function () {
        cancelAnimationFrame(animationID);
        isSelected = false;
    });
    // patch for touch devices
    addEvent(containerEl, 'scroll', function (evt) {
        evt.preventDefault();
        containerEl.scrollTop = containerEl.scrollLeft = 0;
    });
}
function calcMomentum(scrollbar, evt) {
    var _a = scrollbar.bounding, top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left;
    var _b = getPosition(evt), x = _b.x, y = _b.y;
    var res = {
        x: 0,
        y: 0,
    };
    var padding = 20;
    if (x === 0 && y === 0)
        return res;
    if (x > right - padding) {
        res.x = (x - right + padding);
    }
    else if (x < left + padding) {
        res.x = (x - left - padding);
    }
    if (y > bottom - padding) {
        res.y = (y - bottom + padding);
    }
    else if (y < top + padding) {
        res.y = (y - top - padding);
    }
    res.x *= 2;
    res.y *= 2;
    return res;
}
//# sourceMappingURL=select.js.map