all files / src/ scroller.js

83.59% Statements 107/128
83.05% Branches 49/59
100% Functions 28/28
22.22% Lines 6/27
30 statements, 14 functions, 29 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                                                                                                                 
/**
 * Responsible for calculating the new scroll positions
 */
import ReactDOM from 'react-dom';
import AnimateScroll from './animate-scroll';
 
class Scroller {
    constructor() {
        this._elementPanelRegister = {};
    }
 
    registerElementPanel(id, component) {
        this._elementPanelRegister[id] = component;
    }
 
    unregisterElementPanel(id) {
        delete this._elementPanelRegister[id];
    }
 
    getElementPanel(id) {
        return this._elementPanelRegister[id];
    }
 
    prepareToScroll(id) {
        const element = this._elementPanelRegister[id];
 
        if (!element) {
            throw new Error(`Could not find any component with id: ${id}`);
        }
 
        const config = element.getConfig();
        const component = ReactDOM.findDOMNode(element);
 
        const container = config.container || document.body;
 
        const componentCoords = component.getBoundingClientRect();
        const containerCoords = container.getBoundingClientRect();
 
        let scrollOffset = 0;
        if (container === document.body) {
            scrollOffset = componentCoords.top - containerCoords.top;
        } else {
            scrollOffset = componentCoords.top - containerCoords.top + container.scrollTop;
        }
 
        if (!config.animate) {
            container.scrollLeft = 0;
            container.scrollTop = scrollOffset - config.offset;
 
            if (config.events.end) {
                config.events.end(id, component);
            }
        } else {
            const animation = new AnimateScroll(config);
            animation.start(id, component, scrollOffset - config.offset);
        }
    }
}
 
export default new Scroller();