// we need to measure the scrollbar to stop it jumping:
// see https://davidwalsh.name/detect-scrollbar-width
// Remember to import reset.less so you have access to .measure-scrollbar

function measureScrollbar() {
    const scrollDiv = document.createElement('div');

    scrollDiv.classList.add('measure-scrollbar');
    document.body.appendChild(scrollDiv);

    const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;

    document.body.removeChild(scrollDiv);

    return scrollbarWidth;
}

/**\
    For certain components such as Card, Modal, Pane, we want to make the body
    unscrollable while these components are open. This is a helper function
    that measures the width of the scrollbar and applies appropriate padding to
    the body so that when overflow is set to hidden, it doesn't "jump".

    Usage:
        when you want to freeze the body: bodyFreezer.freeze()
        when you want to unfreeze the body: bodyFreezer.unfreeze()

    Requirements:
        reset.less must be imported in the less file of the component.

\**/
const bodyFreezer = {
    padding: 0,

    freeze() {
        const scrollbar = measureScrollbar();

        this.padding = parseInt(document.body.style.paddingRight || 0, 10);

        /* istanbul ignore next: test manually */
        if (document.body.clientWidth < window.innerWidth) {
            document.body.style.paddingRight = `${this.padding + scrollbar}px`;
        }

        document.body.classList.add('freeze');
    },

    /* istanbul ignore next: test manually */
    unfreeze() {
        document.body.style.paddingRight = this.padding;
        document.body.classList.remove('freeze');
    }
};

export default bodyFreezer;
