All files / src/lib DivElement.js

100% Statements 24/24
100% Branches 5/5
100% Functions 7/7
100% Lines 23/23
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 522x 4x           5x 5x 5x       8x 2x             45x 3x   45x 45x   45x       3x 3x 3x       3x 3x 3x 3x 3x 3x   3x         2x    
const lengthOf = (style, element) => {
    return parseInt(window.getComputedStyle(element, null)[style], 0);
};
 
 
export class Size {
    constructor(lengthOfFunction = null) {
        this.lengthOf = lengthOfFunction ? lengthOfFunction : lengthOf;
        this.element = null;
        this.content = null;
    }
 
    _getSizeOf(element) {
        const lengthOf = (style) => this.lengthOf(style, element);
        return {
            width: element.offsetWidth + lengthOf('marginLeft') + lengthOf('marginRight'),
            height: element.offsetHeight + lengthOf('marginTop') + lengthOf('marginBottom'),
        };
    }
 
    ofDivWith(item, classes) {
        if (!this.element) {
            this._createElementWhenBodyExists();
        }
        this.element.classList = classes;
        this.content.nodeValue = item.label;
 
        return this._getSizeOf(this.element);
    }
 
    _createElementWhenBodyExists() {
        const { element, content } = this._createHiddenElement();
        this.element = element;
        this.content = content;
    }
 
    _createHiddenElement() {
        const element = document.createElement('div');
        const content = document.createTextNode('');
        element.appendChild(content);
        element.style.left = "-1000px";
        element.style.position = 'absolute';
        document.body.appendChild(element);
 
        return { element, content };
    }
}
 
 
export const size = new Size();