const swipe_elements = new WeakMap();
function readTouch(e) {
    const touch = e.changedTouches[0];
    if (void 0 === touch) return null;
    return [
        touch.clientX,
        touch.clientY
    ];
}
function addListener(element, cb) {
    let elementValues = swipe_elements.get(element);
    if (void 0 === elementValues) {
        const listeners = new Set();
        const handleTouchstart = (e)=>{
            if (void 0 !== elementValues) elementValues.start = readTouch(e);
        };
        const handleTouchend = (e)=>{
            if (void 0 === elementValues) return;
            const start = elementValues.start;
            if (null === start) return;
            const end = readTouch(e);
            for (const listener of listeners)if (null !== end) listener([
                end[0] - start[0],
                end[1] - start[1]
            ], e);
        };
        element.addEventListener('touchstart', handleTouchstart);
        element.addEventListener('touchend', handleTouchend);
        elementValues = {
            handleTouchend,
            handleTouchstart,
            listeners,
            start: null
        };
        swipe_elements.set(element, elementValues);
    }
    elementValues.listeners.add(cb);
    return ()=>{
        deleteListener(element, cb);
    };
}
function deleteListener(element, cb) {
    const elementValues = swipe_elements.get(element);
    if (void 0 === elementValues) return;
    const listeners = elementValues.listeners;
    listeners.delete(cb);
    if (0 === listeners.size) {
        swipe_elements.delete(element);
        element.removeEventListener('touchstart', elementValues.handleTouchstart);
        element.removeEventListener('touchend', elementValues.handleTouchend);
    }
}
function addSwipeLeftListener(element, cb) {
    return addListener(element, (force, e)=>{
        const [x, y] = force;
        if (x < 0 && -x > Math.abs(y)) cb(x, e);
    });
}
function addSwipeRightListener(element, cb) {
    return addListener(element, (force, e)=>{
        const [x, y] = force;
        if (x > 0 && x > Math.abs(y)) cb(x, e);
    });
}
function addSwipeUpListener(element, cb) {
    return addListener(element, (force, e)=>{
        const [x, y] = force;
        if (y < 0 && -y > Math.abs(x)) cb(x, e);
    });
}
function addSwipeDownListener(element, cb) {
    return addListener(element, (force, e)=>{
        const [x, y] = force;
        if (y > 0 && y > Math.abs(x)) cb(x, e);
    });
}
export { addSwipeDownListener, addSwipeLeftListener, addSwipeRightListener, addSwipeUpListener };
