all files / main/util/ Util.js

76.62% Statements 118/154
50.67% Branches 38/75
68.18% Functions 15/22
76.47% Lines 117/153
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436                      21×                                                                                                   15× 15×   15× 15×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
"use strict";
 
Object.defineProperty(exports, "__esModule", {
    value: true
});
 
var _stringify = require("babel-runtime/core-js/json/stringify");
 
var _stringify2 = _interopRequireDefault(_stringify);
 
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
 
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
 
var _createClass2 = require("babel-runtime/helpers/createClass");
 
var _createClass3 = _interopRequireDefault(_createClass2);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 David Heidrich, BowlingX <me@bowlingx.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
 
var PFX = ["webkit", "moz", "MS", "o", ""];
 
var COL_LEFT_CLASS = 'is-collision-left';
 
var COL_RIGHT_CLASS = 'is-collision-right';
 
var COL_BOTTOM_CLASS = 'is-collision-bottom';
 
/**
 * Provides shared DOM-Utility functions
 */
 
var Util = function () {
    function Util() {
        (0, _classCallCheck3.default)(this, Util);
    }
 
    (0, _createClass3.default)(Util, null, [{
        key: "prefixedAnimateEvent",
 
 
        /**
         * Will register the right animation event based on browser
         * @param element
         * @param type
         * @param callback
         */
        value: function prefixedAnimateEvent(element, type, callback) {
            var thisFunction = function thisFunction(e) {
                callback.apply(element, [e, thisFunction]);
            };
 
            for (var p = 0; p < PFX.length; p++) {
                var thisType = type;
                if (!PFX[p]) {
                    thisType = type.toLowerCase();
                }
                var name = PFX[p] + thisType;
                element.addEventListener(name, thisFunction, true);
            }
        }
 
        /**
         * Get correct transitionend event
         * @returns {String}
         * @private
         */
 
    }, {
        key: "whichTransitionEndEvent",
        value: function whichTransitionEndEvent() {
            var t = void 0;
            var el = document.createElement('fake');
 
            var transitions = {
                transition: 'transitionend',
                OTransition: 'oTransitionEnd',
                MozTransition: 'transitionend',
                WebkitTransition: 'webkitTransitionEnd'
            };
 
            for (t in transitions) {
                Eif (el.style[t] !== undefined) {
                    return transitions[t];
                }
            }
        }
 
        /**
         * Check if target is part of parent node
         * @param target
         * @param parent
         * @returns {boolean}
         */
 
    }, {
        key: "isPartOfNode",
        value: function isPartOfNode(target, parent) {
            Iif (!target || !parent) {
                return false;
            }
            var now = target;
            while (now !== parent && now !== null) {
                Iif (now === parent) {
                    break;
                }
                now = now.parentNode;
            }
            return now !== null;
        }
 
        /**
         * Finds the closest element including itself matching a callback
         * @param {Node} el
         * @param {Function} callback
         * @returns {Node|boolean}
         */
 
    }, {
        key: "closestCallback",
        value: function closestCallback(el, callback) {
            var element = el;
            while (element !== null) {
                if (callback(element)) {
                    return element;
                }
                element = element.parentNode;
            }
            return false;
        }
 
        /**
         * Walks the tree until func returns true for given argument
         * @param target
         * @param func
         * @returns {boolean|HTMLElement}
         */
 
    }, {
        key: "parentsUntil",
        value: function parentsUntil(target, func) {
            Iif (!target) {
                return false;
            }
            var now = target;
            while (!func(now) && now !== null) {
                now = now.parentNode;
            }
 
            return now;
        }
 
        /**
         * Generates a unique id
         * @return {String}
         */
 
    }, {
        key: "guid",
        value: function guid() {
            function s4() {
                return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
            }
 
            return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + (s4() + s4() + s4());
        }
 
        /**
         * Detects scrollbar width
         * @see http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
         * @returns {number}
         */
 
    }, {
        key: "getScrollBarWidth",
        value: function getScrollBarWidth() {
            var doc = global.document;
            var inner = doc.createElement('p');
 
            inner.style.width = "100%";
            inner.style.height = "200px";
 
            var outer = doc.createElement('div');
            outer.style.position = "absolute";
            outer.style.top = "0px";
            outer.style.left = "0px";
            outer.style.visibility = "hidden";
            outer.style.width = "200px";
            outer.style.height = "150px";
            outer.style.overflow = "hidden";
            outer.appendChild(inner);
 
            doc.body.appendChild(outer);
            var w1 = inner.offsetWidth;
            outer.style.overflow = 'scroll';
            var w2 = inner.offsetWidth;
            Eif (w1 === w2) {
                w2 = outer.clientWidth;
            }
            doc.body.removeChild(outer);
 
            return w1 - w2;
        }
 
        /**
         * Run an event once
         * @param {String} ev
         * @param {HTMLElement|HTMLDocument} target
         * @param {Function} func
         * @param {boolean} [capture]
         * @return Function created listener
         */
 
    }, {
        key: "addEventOnce",
        value: function addEventOnce(ev, target, func, capture) {
            var thisFunction = function thisFunction(event) {
                func(event, func);
                target.removeEventListener(ev, thisFunction, capture);
            };
            target.addEventListener(ev, thisFunction, capture);
            return thisFunction;
        }
 
        /**
         * Checks if an element is visible
         * @param {HTMLElement} element
         * @returns bool
         */
 
    }, {
        key: "isVisible",
        value: function isVisible(element) {
            return element.offsetWidth > 0 && element.offsetHeight > 0;
        }
 
        /**
         * Creates a camelCaseRepresentation of a dashed string
         * @param {String} str
         * @returns String
         */
 
    }, {
        key: "dashToCamelCase",
        value: function dashToCamelCase(str) {
            return str.replace(/-([a-z])/g, function (g) {
                return g[1].toUpperCase();
            });
        }
 
        /**
         * Creates a copy of `input`
         * @param {*} input
         * @return *
         */
 
    }, {
        key: "copy",
        value: function copy(input) {
            return JSON.parse((0, _stringify2.default)(input));
        }
 
        /**
         * Reads options from element (data attributes) and applies to base
         * @param {HTMLElement} element
         * @param {Object} base
         * @return {Object}
         */
 
    }, {
        key: "applyOptionsFromElement",
        value: function applyOptionsFromElement(element, base) {
            Iif (!element) {
                return base;
            }
            var attrs = element.attributes;
            for (var i = 0; i < attrs.length; i++) {
                var attr = attrs[i];
                Eif (attr) {
                    var s = Util.dashToCamelCase(attr.nodeName.replace('data-', ''));
                    var val = attr.nodeValue;
                    Iif (base.hasOwnProperty(s)) {
                        // skip functions
                        if (typeof base[s] === 'function') {
                            continue;
                        }
                        if (typeof base[s] === 'boolean') {
                            base[s] = parseInt(val || 1, 10) === 1;
                        } else {
                            base[s] = val;
                        }
                    }
                }
            }
            return base;
        }
 
        /**
         * Will position an element directly at given target
         * Is aware of a given collision container to detect edges
         * Will put elementToPosition either to left, center or right edge (prefer right)
         *  and either to bottom or top (prefers bottom)
         *
         * You may overwrite preferred positioned with `centerHorizontal` and `positionTop`
         *
         * @param {HTMLElement|ClientRect} target the target container to align to
         * @param {HTMLElement} elementToPosition the element to position
         * @param {HTMLElement} collisionContainer the outer container to prevent collisions
         * @param {boolean} [centerHorizontal] set true to center element, otherwise it's put on the right border by default
         * @param {boolean} [positionTop] flip top, by default element is positioned to the bottom.
         * @returns {HTMLElement}
         */
 
    }, {
        key: "setupPositionNearby",
        value: function setupPositionNearby(target, elementToPosition, collisionContainer, centerHorizontal, positionTop) {
            // determine relative offsets
            var amountTop = 0;
            var amountLeft = 0;
            Util.parentsUntil(target.parentNode, function (el) {
                if (!(el instanceof HTMLElement)) {
                    return false;
                }
                var style = window.getComputedStyle(el);
                Eif (Util.isPartOfNode(elementToPosition, el)) {
                    Iif (style && style.position === 'relative') {
                        amountTop += el.offsetTop || 0;
                        amountLeft += el.offsetLeft || 0;
                    }
                    return false;
                }
                return true;
            });
 
            var targetPosition = target instanceof HTMLElement ? target.getBoundingClientRect() : target;
            var elementRect = elementToPosition.getBoundingClientRect();
            var colRect = collisionContainer.getBoundingClientRect();
            var targetTop = targetPosition.top - amountTop;
            var targetRight = targetPosition.right;
            var isCollisionTop = targetTop - elementRect.height <= 0;
            var isCollisionBottom = window.innerHeight < targetTop + amountTop + targetPosition.height + elementRect.height;
            var isCollisionLeft = targetRight < elementRect.width;
            var targetLeft = targetPosition.left;
            var isCollisionRight = targetLeft + elementRect.width > colRect.width;
            var classList = elementToPosition.classList;
 
            classList.remove(COL_RIGHT_CLASS);
            classList.remove(COL_LEFT_CLASS);
            classList.remove(COL_BOTTOM_CLASS);
 
            var calcTop = void 0;
            var calcLeft = void 0;
            Iif (isCollisionLeft && !isCollisionRight) {
                // put element to left if collision with left
                calcLeft = targetPosition.left - colRect.left - amountLeft + "px";
                classList.add(COL_LEFT_CLASS);
            } else {
                // maybe center if no collision with either side
                var rightPosition = targetRight - elementRect.width - colRect.left - amountLeft + "px";
                var leftCentered = (targetLeft + targetPosition.width / 2 - elementRect.width / 2 || 0) - colRect.left;
                var collisionCentered = leftCentered + elementRect.width > colRect.width;
                Eif (centerHorizontal && !collisionCentered) {
                    calcLeft = leftCentered + "px";
                } else {
                    classList.add(COL_RIGHT_CLASS);
                    calcLeft = rightPosition;
                }
            }
 
            Iif (isCollisionBottom || positionTop && !isCollisionTop) {
                // Put Element on top if collision
                calcTop = targetTop - elementRect.height - colRect.top + "px";
                classList.add(COL_BOTTOM_CLASS);
            } else {
                calcTop = targetTop + targetPosition.height - colRect.top + "px";
            }
 
            elementToPosition.style.cssText = "top:" + calcTop + ";left:" + calcLeft + ";";
 
            return elementToPosition;
        }
 
        /**
         * Brings a given element into viewport
         * @param {HTMLElement} el
         * @param {int|function}[optionalOffset]
         */
 
    }, {
        key: "scrollToElement",
        value: function scrollToElement(el, optionalOffset) {
            el.scrollIntoView();
            var thisOffset = optionalOffset;
            // optionally use a additional scrollDif
            Iif (thisOffset) {
                if (typeof thisOffset === 'function') {
                    thisOffset = optionalOffset();
                }
                if (thisOffset > 0) {
                    var scrolledY = window.pageYOffset;
                    if (scrolledY) {
                        window.scroll(0, scrolledY - thisOffset);
                    }
                }
            }
        }
    }]);
    return Util;
}();
 
exports.default = Util;