/**
* vis.js
* https://github.com/almende/vis
*
* A dynamic, browser-based visualization library.
*
* @version 4.21.0
* @date 2017-10-12
*
* @license
* Copyright (C) 2011-2017 Almende B.V, http://almende.com
*
* Vis.js is dual licensed under both
*
* * The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* * The MIT License
* http://opensource.org/licenses/MIT
*
* Vis.js may be distributed under either license.
*/
"use strict";
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["vis"] = factory();
else
root["vis"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 123);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _defineProperty = __webpack_require__(169);
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _getIterator2 = __webpack_require__(77);
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _create = __webpack_require__(29);
var _create2 = _interopRequireDefault(_create);
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
// utility functions
// first check if moment.js is already loaded in the browser window, if so,
// use this instance. Else, load via commonjs.
var moment = __webpack_require__(9);
var uuid = __webpack_require__(157);
/**
* Test whether given object is a number
* @param {*} object
* @return {Boolean} isNumber
*/
exports.isNumber = function (object) {
return object instanceof Number || typeof object == 'number';
};
/**
* Remove everything in the DOM object
* @param {Element} DOMobject
*/
exports.recursiveDOMDelete = function (DOMobject) {
if (DOMobject) {
while (DOMobject.hasChildNodes() === true) {
exports.recursiveDOMDelete(DOMobject.firstChild);
DOMobject.removeChild(DOMobject.firstChild);
}
}
};
/**
* this function gives you a range between 0 and 1 based on the min and max values in the set, the total sum of all values and the current value.
*
* @param {number} min
* @param {number} max
* @param {number} total
* @param {number} value
* @returns {number}
*/
exports.giveRange = function (min, max, total, value) {
if (max == min) {
return 0.5;
} else {
var scale = 1 / (max - min);
return Math.max(0, (value - min) * scale);
}
};
/**
* Test whether given object is a string
* @param {*} object
* @return {Boolean} isString
*/
exports.isString = function (object) {
return object instanceof String || typeof object == 'string';
};
/**
* Test whether given object is a Date, or a String containing a Date
* @param {Date | String} object
* @return {Boolean} isDate
*/
exports.isDate = function (object) {
if (object instanceof Date) {
return true;
} else if (exports.isString(object)) {
// test whether this string contains a date
var match = ASPDateRegex.exec(object);
if (match) {
return true;
} else if (!isNaN(Date.parse(object))) {
return true;
}
}
return false;
};
/**
* Create a semi UUID
* source: http://stackoverflow.com/a/105074/1262753
* @return {string} uuid
*/
exports.randomUUID = function () {
return uuid.v4();
};
/**
* assign all keys of an object that are not nested objects to a certain value (used for color objects).
* @param {object} obj
* @param {number} value
*/
exports.assignAllKeys = function (obj, value) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if ((0, _typeof3['default'])(obj[prop]) !== 'object') {
obj[prop] = value;
}
}
}
};
/**
* Copy property from b to a if property present in a.
* If property in b explicitly set to null, delete it if `allowDeletion` set.
*
* Internal helper routine, should not be exported. Not added to `exports` for that reason.
*
* @param {object} a target object
* @param {object} b source object
* @param {string} prop name of property to copy to a
* @param {boolean} allowDeletion if true, delete property in a if explicitly set to null in b
* @private
*/
function copyOrDelete(a, b, prop, allowDeletion) {
var doDeletion = false;
if (allowDeletion === true) {
doDeletion = b[prop] === null && a[prop] !== undefined;
}
if (doDeletion) {
delete a[prop];
} else {
a[prop] = b[prop]; // Remember, this is a reference copy!
}
}
/**
* Fill an object with a possibly partially defined other object.
*
* Only copies values for the properties already present in a.
* That means an object is not created on a property if only the b object has it.
*
* @param {object} a
* @param {object} b
* @param {boolean} [allowDeletion=false] if true, delete properties in a that are explicitly set to null in b
*/
exports.fillIfDefined = function (a, b) {
var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
// NOTE: iteration of properties of a
// NOTE: prototype properties iterated over as well
for (var prop in a) {
if (b[prop] !== undefined) {
if (b[prop] === null || (0, _typeof3['default'])(b[prop]) !== 'object') {
// Note: typeof null === 'object'
copyOrDelete(a, b, prop, allowDeletion);
} else {
if ((0, _typeof3['default'])(a[prop]) === 'object') {
exports.fillIfDefined(a[prop], b[prop], allowDeletion);
}
}
}
}
};
/**
* Extend object a with the properties of object b or a series of objects
* Only properties with defined values are copied
* @param {Object} a
* @param {...Object} b
* @return {Object} a
*/
exports.extend = function (a, b) {
// eslint-disable-line no-unused-vars
for (var i = 1; i < arguments.length; i++) {
var other = arguments[i];
for (var prop in other) {
if (other.hasOwnProperty(prop)) {
a[prop] = other[prop];
}
}
}
return a;
};
/**
* Extend object a with selected properties of object b or a series of objects
* Only properties with defined values are copied
* @param {Array.} props
* @param {Object} a
* @param {Object} b
* @return {Object} a
*/
exports.selectiveExtend = function (props, a, b) {
// eslint-disable-line no-unused-vars
if (!Array.isArray(props)) {
throw new Error('Array with property names expected as first argument');
}
for (var i = 2; i < arguments.length; i++) {
var other = arguments[i];
for (var p = 0; p < props.length; p++) {
var prop = props[p];
if (other && other.hasOwnProperty(prop)) {
a[prop] = other[prop];
}
}
}
return a;
};
/**
* Extend object a with selected properties of object b.
* Only properties with defined values are copied.
*
* **Note:** Previous version of this routine implied that multiple source objects
* could be used; however, the implementation was **wrong**.
* Since multiple (>1) sources weren't used anywhere in the `vis.js` code,
* this has been removed
*
* @param {Array.} props names of first-level properties to copy over
* @param {object} a target object
* @param {object} b source object
* @param {boolean} [allowDeletion=false] if true, delete property in a if explicitly set to null in b
* @returns {Object} a
*/
exports.selectiveDeepExtend = function (props, a, b) {
var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError('Arrays are not supported by deepExtend');
}
for (var p = 0; p < props.length; p++) {
var prop = props[p];
if (b.hasOwnProperty(prop)) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
exports.deepExtend(a[prop], b[prop], false, allowDeletion);
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
throw new TypeError('Arrays are not supported by deepExtend');
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
}
return a;
};
/**
* Extend object `a` with properties of object `b`, ignoring properties which are explicitly
* specified to be excluded.
*
* The properties of `b` are considered for copying.
* Properties which are themselves objects are are also extended.
* Only properties with defined values are copied
*
* @param {Array.} propsToExclude names of properties which should *not* be copied
* @param {Object} a object to extend
* @param {Object} b object to take properties from for extension
* @param {boolean} [allowDeletion=false] if true, delete properties in a that are explicitly set to null in b
* @return {Object} a
*/
exports.selectiveNotDeepExtend = function (propsToExclude, a, b) {
var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
// TODO: add support for Arrays to deepExtend
// NOTE: array properties have an else-below; apparently, there is a problem here.
if (Array.isArray(b)) {
throw new TypeError('Arrays are not supported by deepExtend');
}
for (var prop in b) {
if (!b.hasOwnProperty(prop)) continue; // Handle local properties only
if (propsToExclude.indexOf(prop) !== -1) continue; // In exclusion list, skip
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
exports.deepExtend(a[prop], b[prop]); // NOTE: allowDeletion not propagated!
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
a[prop] = [];
for (var i = 0; i < b[prop].length; i++) {
a[prop].push(b[prop][i]);
}
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
return a;
};
/**
* Deep extend an object a with the properties of object b
*
* @param {Object} a
* @param {Object} b
* @param {boolean} [protoExtend=false] If true, the prototype values will also be extended.
* (ie. the options objects that inherit from others will also get the inherited options)
* @param {boolean} [allowDeletion=false] If true, the values of fields that are null will be deleted
* @returns {Object}
*/
exports.deepExtend = function (a, b) {
var protoExtend = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
for (var prop in b) {
if (b.hasOwnProperty(prop) || protoExtend === true) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
exports.deepExtend(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
} else if (Array.isArray(b[prop])) {
a[prop] = [];
for (var i = 0; i < b[prop].length; i++) {
a[prop].push(b[prop][i]);
}
} else {
copyOrDelete(a, b, prop, allowDeletion);
}
}
}
return a;
};
/**
* Test whether all elements in two arrays are equal.
* @param {Array} a
* @param {Array} b
* @return {boolean} Returns true if both arrays have the same length and same
* elements.
*/
exports.equalArray = function (a, b) {
if (a.length != b.length) return false;
for (var i = 0, len = a.length; i < len; i++) {
if (a[i] != b[i]) return false;
}
return true;
};
/**
* Convert an object to another type
* @param {boolean | number | string | Date | Moment | Null | undefined} object
* @param {string | undefined} type Name of the type. Available types:
* 'Boolean', 'Number', 'String',
* 'Date', 'Moment', ISODate', 'ASPDate'.
* @return {*} object
* @throws Error
*/
exports.convert = function (object, type) {
var match;
if (object === undefined) {
return undefined;
}
if (object === null) {
return null;
}
if (!type) {
return object;
}
if (!(typeof type === 'string') && !(type instanceof String)) {
throw new Error('Type must be a string');
}
//noinspection FallthroughInSwitchStatementJS
switch (type) {
case 'boolean':
case 'Boolean':
return Boolean(object);
case 'number':
case 'Number':
if (exports.isString(object) && !isNaN(Date.parse(object))) {
return moment(object).valueOf();
} else {
return Number(object.valueOf());
}
case 'string':
case 'String':
return String(object);
case 'Date':
if (exports.isNumber(object)) {
return new Date(object);
}
if (object instanceof Date) {
return new Date(object.valueOf());
} else if (moment.isMoment(object)) {
return new Date(object.valueOf());
}
if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return new Date(Number(match[1])); // parse number
} else {
return moment(new Date(object)).toDate(); // parse string
}
} else {
throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date');
}
case 'Moment':
if (exports.isNumber(object)) {
return moment(object);
}
if (object instanceof Date) {
return moment(object.valueOf());
} else if (moment.isMoment(object)) {
return moment(object);
}
if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return moment(Number(match[1])); // parse number
} else {
return moment(object); // parse string
}
} else {
throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date');
}
case 'ISODate':
if (exports.isNumber(object)) {
return new Date(object);
} else if (object instanceof Date) {
return object.toISOString();
} else if (moment.isMoment(object)) {
return object.toDate().toISOString();
} else if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return new Date(Number(match[1])).toISOString(); // parse number
} else {
return moment(object).format(); // ISO 8601
}
} else {
throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ISODate');
}
case 'ASPDate':
if (exports.isNumber(object)) {
return '/Date(' + object + ')/';
} else if (object instanceof Date) {
return '/Date(' + object.valueOf() + ')/';
} else if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
var value;
if (match) {
// object is an ASP date
value = new Date(Number(match[1])).valueOf(); // parse number
} else {
value = new Date(object).valueOf(); // parse string
}
return '/Date(' + value + ')/';
} else {
throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate');
}
default:
throw new Error('Unknown type "' + type + '"');
}
};
// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
/**
* Get the type of an object, for example exports.getType([]) returns 'Array'
* @param {*} object
* @return {string} type
*/
exports.getType = function (object) {
var type = typeof object === 'undefined' ? 'undefined' : (0, _typeof3['default'])(object);
if (type == 'object') {
if (object === null) {
return 'null';
}
if (object instanceof Boolean) {
return 'Boolean';
}
if (object instanceof Number) {
return 'Number';
}
if (object instanceof String) {
return 'String';
}
if (Array.isArray(object)) {
return 'Array';
}
if (object instanceof Date) {
return 'Date';
}
return 'Object';
} else if (type == 'number') {
return 'Number';
} else if (type == 'boolean') {
return 'Boolean';
} else if (type == 'string') {
return 'String';
} else if (type === undefined) {
return 'undefined';
}
return type;
};
/**
* Used to extend an array and copy it. This is used to propagate paths recursively.
*
* @param {Array} arr
* @param {*} newValue
* @returns {Array}
*/
exports.copyAndExtendArray = function (arr, newValue) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
newArr.push(newValue);
return newArr;
};
/**
* Used to extend an array and copy it. This is used to propagate paths recursively.
*
* @param {Array} arr
* @returns {Array}
*/
exports.copyArray = function (arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
return newArr;
};
/**
* Retrieve the absolute left value of a DOM element
* @param {Element} elem A dom element, for example a div
* @return {number} left The absolute left position of this element
* in the browser page.
*/
exports.getAbsoluteLeft = function (elem) {
return elem.getBoundingClientRect().left;
};
exports.getAbsoluteRight = function (elem) {
return elem.getBoundingClientRect().right;
};
/**
* Retrieve the absolute top value of a DOM element
* @param {Element} elem A dom element, for example a div
* @return {number} top The absolute top position of this element
* in the browser page.
*/
exports.getAbsoluteTop = function (elem) {
return elem.getBoundingClientRect().top;
};
/**
* add a className to the given elements style
* @param {Element} elem
* @param {string} classNames
*/
exports.addClassName = function (elem, classNames) {
var classes = elem.className.split(' ');
var newClasses = classNames.split(' ');
classes = classes.concat(newClasses.filter(function (className) {
return classes.indexOf(className) < 0;
}));
elem.className = classes.join(' ');
};
/**
* add a className to the given elements style
* @param {Element} elem
* @param {string} classNames
*/
exports.removeClassName = function (elem, classNames) {
var classes = elem.className.split(' ');
var oldClasses = classNames.split(' ');
classes = classes.filter(function (className) {
return oldClasses.indexOf(className) < 0;
});
elem.className = classes.join(' ');
};
/**
* For each method for both arrays and objects.
* In case of an array, the built-in Array.forEach() is applied. (**No, it's not!**)
* In case of an Object, the method loops over all properties of the object.
* @param {Object | Array} object An Object or Array
* @param {function} callback Callback method, called for each item in
* the object or array with three parameters:
* callback(value, index, object)
*/
exports.forEach = function (object, callback) {
var i, len;
if (Array.isArray(object)) {
// array
for (i = 0, len = object.length; i < len; i++) {
callback(object[i], i, object);
}
} else {
// object
for (i in object) {
if (object.hasOwnProperty(i)) {
callback(object[i], i, object);
}
}
}
};
/**
* Convert an object into an array: all objects properties are put into the
* array. The resulting array is unordered.
* @param {Object} object
* @returns {Array} array
*/
exports.toArray = function (object) {
var array = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) array.push(object[prop]);
}
return array;
};
/**
* Update a property in an object
* @param {Object} object
* @param {string} key
* @param {*} value
* @return {Boolean} changed
*/
exports.updateProperty = function (object, key, value) {
if (object[key] !== value) {
object[key] = value;
return true;
} else {
return false;
}
};
/**
* Throttle the given function to be only executed once per animation frame
* @param {function} fn
* @returns {function} Returns the throttled function
*/
exports.throttle = function (fn) {
var scheduled = false;
return function throttled() {
if (!scheduled) {
scheduled = true;
requestAnimationFrame(function () {
scheduled = false;
fn();
});
}
};
};
/**
* Add and event listener. Works for all browsers
* @param {Element} element An html element
* @param {string} action The action, for example "click",
* without the prefix "on"
* @param {function} listener The callback function to be executed
* @param {boolean} [useCapture]
*/
exports.addEventListener = function (element, action, listener, useCapture) {
if (element.addEventListener) {
if (useCapture === undefined) useCapture = false;
if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
action = "DOMMouseScroll"; // For Firefox
}
element.addEventListener(action, listener, useCapture);
} else {
element.attachEvent("on" + action, listener); // IE browsers
}
};
/**
* Remove an event listener from an element
* @param {Element} element An html dom element
* @param {string} action The name of the event, for example "mousedown"
* @param {function} listener The listener function
* @param {boolean} [useCapture]
*/
exports.removeEventListener = function (element, action, listener, useCapture) {
if (element.removeEventListener) {
// non-IE browsers
if (useCapture === undefined) useCapture = false;
if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
action = "DOMMouseScroll"; // For Firefox
}
element.removeEventListener(action, listener, useCapture);
} else {
// IE browsers
element.detachEvent("on" + action, listener);
}
};
/**
* Cancels the event if it is cancelable, without stopping further propagation of the event.
* @param {Event} event
*/
exports.preventDefault = function (event) {
if (!event) event = window.event;
if (event.preventDefault) {
event.preventDefault(); // non-IE browsers
} else {
event.returnValue = false; // IE browsers
}
};
/**
* Get HTML element which is the target of the event
* @param {Event} event
* @return {Element} target element
*/
exports.getTarget = function (event) {
// code from http://www.quirksmode.org/js/events_properties.html
if (!event) {
event = window.event;
}
var target;
if (event.target) {
target = event.target;
} else if (event.srcElement) {
target = event.srcElement;
}
if (target.nodeType != undefined && target.nodeType == 3) {
// defeat Safari bug
target = target.parentNode;
}
return target;
};
/**
* Check if given element contains given parent somewhere in the DOM tree
* @param {Element} element
* @param {Element} parent
* @returns {boolean}
*/
exports.hasParent = function (element, parent) {
var e = element;
while (e) {
if (e === parent) {
return true;
}
e = e.parentNode;
}
return false;
};
exports.option = {};
/**
* Convert a value into a boolean
* @param {Boolean | function | undefined} value
* @param {boolean} [defaultValue]
* @returns {Boolean} bool
*/
exports.option.asBoolean = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (value != null) {
return value != false;
}
return defaultValue || null;
};
/**
* Convert a value into a number
* @param {Boolean | function | undefined} value
* @param {number} [defaultValue]
* @returns {number} number
*/
exports.option.asNumber = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (value != null) {
return Number(value) || defaultValue || null;
}
return defaultValue || null;
};
/**
* Convert a value into a string
* @param {string | function | undefined} value
* @param {string} [defaultValue]
* @returns {String} str
*/
exports.option.asString = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (value != null) {
return String(value);
}
return defaultValue || null;
};
/**
* Convert a size or location into a string with pixels or a percentage
* @param {string | number | function | undefined} value
* @param {string} [defaultValue]
* @returns {String} size
*/
exports.option.asSize = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (exports.isString(value)) {
return value;
} else if (exports.isNumber(value)) {
return value + 'px';
} else {
return defaultValue || null;
}
};
/**
* Convert a value into a DOM element
* @param {HTMLElement | function | undefined} value
* @param {HTMLElement} [defaultValue]
* @returns {HTMLElement | null} dom
*/
exports.option.asElement = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
return value || defaultValue || null;
};
/**
* http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
*
* @param {string} hex
* @returns {{r: *, g: *, b: *}} | 255 range
*/
exports.hexToRGB = function (hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function (m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
};
/**
* This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string.
* @param {string} color
* @param {number} opacity
* @returns {String}
*/
exports.overrideOpacity = function (color, opacity) {
var rgb;
if (color.indexOf("rgba") != -1) {
return color;
} else if (color.indexOf("rgb") != -1) {
rgb = color.substr(color.indexOf("(") + 1).replace(")", "").split(",");
return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
} else {
rgb = exports.hexToRGB(color);
if (rgb == null) {
return color;
} else {
return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")";
}
}
};
/**
*
* @param {number} red 0 -- 255
* @param {number} green 0 -- 255
* @param {number} blue 0 -- 255
* @returns {String}
* @constructor
*/
exports.RGBToHex = function (red, green, blue) {
return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
};
/**
* Parse a color property into an object with border, background, and
* highlight colors
* @param {Object | String} color
* @return {Object} colorObject
*/
exports.parseColor = function (color) {
var c;
if (exports.isString(color) === true) {
if (exports.isValidRGB(color) === true) {
var rgb = color.substr(4).substr(0, color.length - 5).split(',').map(function (value) {
return parseInt(value);
});
color = exports.RGBToHex(rgb[0], rgb[1], rgb[2]);
}
if (exports.isValidHex(color) === true) {
var hsv = exports.hexToHSV(color);
var lighterColorHSV = { h: hsv.h, s: hsv.s * 0.8, v: Math.min(1, hsv.v * 1.02) };
var darkerColorHSV = { h: hsv.h, s: Math.min(1, hsv.s * 1.25), v: hsv.v * 0.8 };
var darkerColorHex = exports.HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
var lighterColorHex = exports.HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
c = {
background: color,
border: darkerColorHex,
highlight: {
background: lighterColorHex,
border: darkerColorHex
},
hover: {
background: lighterColorHex,
border: darkerColorHex
}
};
} else {
c = {
background: color,
border: color,
highlight: {
background: color,
border: color
},
hover: {
background: color,
border: color
}
};
}
} else {
c = {};
c.background = color.background || undefined;
c.border = color.border || undefined;
if (exports.isString(color.highlight)) {
c.highlight = {
border: color.highlight,
background: color.highlight
};
} else {
c.highlight = {};
c.highlight.background = color.highlight && color.highlight.background || undefined;
c.highlight.border = color.highlight && color.highlight.border || undefined;
}
if (exports.isString(color.hover)) {
c.hover = {
border: color.hover,
background: color.hover
};
} else {
c.hover = {};
c.hover.background = color.hover && color.hover.background || undefined;
c.hover.border = color.hover && color.hover.border || undefined;
}
}
return c;
};
/**
* http://www.javascripter.net/faq/rgb2hsv.htm
*
* @param {number} red
* @param {number} green
* @param {number} blue
* @returns {{h: number, s: number, v: number}}
* @constructor
*/
exports.RGBToHSV = function (red, green, blue) {
red = red / 255;green = green / 255;blue = blue / 255;
var minRGB = Math.min(red, Math.min(green, blue));
var maxRGB = Math.max(red, Math.max(green, blue));
// Black-gray-white
if (minRGB == maxRGB) {
return { h: 0, s: 0, v: minRGB };
}
// Colors other than black-gray-white:
var d = red == minRGB ? green - blue : blue == minRGB ? red - green : blue - red;
var h = red == minRGB ? 3 : blue == minRGB ? 1 : 5;
var hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
var saturation = (maxRGB - minRGB) / maxRGB;
var value = maxRGB;
return { h: hue, s: saturation, v: value };
};
var cssUtil = {
// split a string with css styles into an object with key/values
split: function split(cssText) {
var styles = {};
cssText.split(';').forEach(function (style) {
if (style.trim() != '') {
var parts = style.split(':');
var key = parts[0].trim();
var value = parts[1].trim();
styles[key] = value;
}
});
return styles;
},
// build a css text string from an object with key/values
join: function join(styles) {
return (0, _keys2['default'])(styles).map(function (key) {
return key + ': ' + styles[key];
}).join('; ');
}
};
/**
* Append a string with css styles to an element
* @param {Element} element
* @param {string} cssText
*/
exports.addCssText = function (element, cssText) {
var currentStyles = cssUtil.split(element.style.cssText);
var newStyles = cssUtil.split(cssText);
var styles = exports.extend(currentStyles, newStyles);
element.style.cssText = cssUtil.join(styles);
};
/**
* Remove a string with css styles from an element
* @param {Element} element
* @param {string} cssText
*/
exports.removeCssText = function (element, cssText) {
var styles = cssUtil.split(element.style.cssText);
var removeStyles = cssUtil.split(cssText);
for (var key in removeStyles) {
if (removeStyles.hasOwnProperty(key)) {
delete styles[key];
}
}
element.style.cssText = cssUtil.join(styles);
};
/**
* https://gist.github.com/mjijackson/5311256
* @param {number} h
* @param {number} s
* @param {number} v
* @returns {{r: number, g: number, b: number}}
* @constructor
*/
exports.HSVToRGB = function (h, s, v) {
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v, g = t, b = p;break;
case 1:
r = q, g = v, b = p;break;
case 2:
r = p, g = v, b = t;break;
case 3:
r = p, g = q, b = v;break;
case 4:
r = t, g = p, b = v;break;
case 5:
r = v, g = p, b = q;break;
}
return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) };
};
exports.HSVToHex = function (h, s, v) {
var rgb = exports.HSVToRGB(h, s, v);
return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
};
exports.hexToHSV = function (hex) {
var rgb = exports.hexToRGB(hex);
return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
};
exports.isValidHex = function (hex) {
var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
return isOk;
};
exports.isValidRGB = function (rgb) {
rgb = rgb.replace(" ", "");
var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
return isOk;
};
exports.isValidRGBA = function (rgba) {
rgba = rgba.replace(" ", "");
var isOk = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(rgba);
return isOk;
};
/**
* This recursively redirects the prototype of JSON objects to the referenceObject
* This is used for default options.
*
* @param {Array.} fields
* @param {Object} referenceObject
* @returns {*}
*/
exports.selectiveBridgeObject = function (fields, referenceObject) {
if (referenceObject !== null && (typeof referenceObject === 'undefined' ? 'undefined' : (0, _typeof3['default'])(referenceObject)) === "object") {
// !!! typeof null === 'object'
var objectTo = (0, _create2['default'])(referenceObject);
for (var i = 0; i < fields.length; i++) {
if (referenceObject.hasOwnProperty(fields[i])) {
if ((0, _typeof3['default'])(referenceObject[fields[i]]) == "object") {
objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
}
}
}
return objectTo;
} else {
return null;
}
};
/**
* This recursively redirects the prototype of JSON objects to the referenceObject
* This is used for default options.
*
* @param {Object} referenceObject
* @returns {*}
*/
exports.bridgeObject = function (referenceObject) {
if (referenceObject !== null && (typeof referenceObject === 'undefined' ? 'undefined' : (0, _typeof3['default'])(referenceObject)) === "object") {
// !!! typeof null === 'object'
var objectTo = (0, _create2['default'])(referenceObject);
if (referenceObject instanceof Element) {
// Avoid bridging DOM objects
objectTo = referenceObject;
} else {
objectTo = (0, _create2['default'])(referenceObject);
for (var i in referenceObject) {
if (referenceObject.hasOwnProperty(i)) {
if ((0, _typeof3['default'])(referenceObject[i]) == "object") {
objectTo[i] = exports.bridgeObject(referenceObject[i]);
}
}
}
}
return objectTo;
} else {
return null;
}
};
/**
* This method provides a stable sort implementation, very fast for presorted data
*
* @param {Array} a the array
* @param {function} compare an order comparator
* @returns {Array}
*/
exports.insertSort = function (a, compare) {
for (var i = 0; i < a.length; i++) {
var k = a[i];
for (var j = i; j > 0 && compare(k, a[j - 1]) < 0; j--) {
a[j] = a[j - 1];
}
a[j] = k;
}
return a;
};
/**
* This is used to set the options of subobjects in the options object.
*
* A requirement of these subobjects is that they have an 'enabled' element
* which is optional for the user but mandatory for the program.
*
* The added value here of the merge is that option 'enabled' is set as required.
*
*
* @param {object} mergeTarget | either this.options or the options used for the groups.
* @param {object} options | options
* @param {string} option | option key in the options argument
* @param {object} globalOptions | global options, passed in to determine value of option 'enabled'
*/
exports.mergeOptions = function (mergeTarget, options, option) {
var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
// Local helpers
var isPresent = function isPresent(obj) {
return obj !== null && obj !== undefined;
};
var isObject = function isObject(obj) {
return obj !== null && (typeof obj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(obj)) === 'object';
};
// https://stackoverflow.com/a/34491287/1223531
var isEmpty = function isEmpty(obj) {
for (var x in obj) {
if (obj.hasOwnProperty(x)) return false;
}
return true;
};
// Guards
if (!isObject(mergeTarget)) {
throw new Error('Parameter mergeTarget must be an object');
}
if (!isObject(options)) {
throw new Error('Parameter options must be an object');
}
if (!isPresent(option)) {
throw new Error('Parameter option must have a value');
}
if (!isObject(globalOptions)) {
throw new Error('Parameter globalOptions must be an object');
}
//
// Actual merge routine, separated from main logic
// Only a single level of options is merged. Deeper levels are ref'd. This may actually be an issue.
//
var doMerge = function doMerge(target, options, option) {
if (!isObject(target[option])) {
target[option] = {};
}
var src = options[option];
var dst = target[option];
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
dst[prop] = src[prop];
}
}
};
// Local initialization
var srcOption = options[option];
var globalPassed = isObject(globalOptions) && !isEmpty(globalOptions);
var globalOption = globalPassed ? globalOptions[option] : undefined;
var globalEnabled = globalOption ? globalOption.enabled : undefined;
/////////////////////////////////////////
// Main routine
/////////////////////////////////////////
if (srcOption === undefined) {
return; // Nothing to do
}
if (typeof srcOption === 'boolean') {
if (!isObject(mergeTarget[option])) {
mergeTarget[option] = {};
}
mergeTarget[option].enabled = srcOption;
return;
}
if (srcOption === null && !isObject(mergeTarget[option])) {
// If possible, explicit copy from globals
if (isPresent(globalOption)) {
mergeTarget[option] = (0, _create2['default'])(globalOption);
} else {
return; // Nothing to do
}
}
if (!isObject(srcOption)) {
return;
}
//
// Ensure that 'enabled' is properly set. It is required internally
// Note that the value from options will always overwrite the existing value
//
var enabled = true; // default value
if (srcOption.enabled !== undefined) {
enabled = srcOption.enabled;
} else {
// Take from globals, if present
if (globalEnabled !== undefined) {
enabled = globalOption.enabled;
}
}
doMerge(mergeTarget, options, option);
mergeTarget[option].enabled = enabled;
};
/**
* This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
* this function will then iterate in both directions over this sorted list to find all visible items.
*
* @param {Item[]} orderedItems | Items ordered by start
* @param {function} comparator | -1 is lower, 0 is equal, 1 is higher
* @param {string} field
* @param {string} field2
* @returns {number}
* @private
*/
exports.binarySearchCustom = function (orderedItems, comparator, field, field2) {
var maxIterations = 10000;
var iteration = 0;
var low = 0;
var high = orderedItems.length - 1;
while (low <= high && iteration < maxIterations) {
var middle = Math.floor((low + high) / 2);
var item = orderedItems[middle];
var value = field2 === undefined ? item[field] : item[field][field2];
var searchResult = comparator(value);
if (searchResult == 0) {
// jihaa, found a visible item!
return middle;
} else if (searchResult == -1) {
// it is too small --> increase low
low = middle + 1;
} else {
// it is too big --> decrease high
high = middle - 1;
}
iteration++;
}
return -1;
};
/**
* This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
* two values, we return either the one before or the one after, depending on user input
* If it is found, we return the index, else -1.
*
* @param {Array} orderedItems
* @param {{start: number, end: number}} target
* @param {string} field
* @param {string} sidePreference 'before' or 'after'
* @param {function} comparator an optional comparator, returning -1,0,1 for <,==,>.
* @returns {number}
* @private
*/
exports.binarySearchValue = function (orderedItems, target, field, sidePreference, comparator) {
var maxIterations = 10000;
var iteration = 0;
var low = 0;
var high = orderedItems.length - 1;
var prevValue, value, nextValue, middle;
comparator = comparator != undefined ? comparator : function (a, b) {
return a == b ? 0 : a < b ? -1 : 1;
};
while (low <= high && iteration < maxIterations) {
// get a new guess
middle = Math.floor(0.5 * (high + low));
prevValue = orderedItems[Math.max(0, middle - 1)][field];
value = orderedItems[middle][field];
nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
if (comparator(value, target) == 0) {
// we found the target
return middle;
} else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) {
// target is in between of the previous and the current
return sidePreference == 'before' ? Math.max(0, middle - 1) : middle;
} else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) {
// target is in between of the current and the next
return sidePreference == 'before' ? middle : Math.min(orderedItems.length - 1, middle + 1);
} else {
// didnt find the target, we need to change our boundaries.
if (comparator(value, target) < 0) {
// it is too small --> increase low
low = middle + 1;
} else {
// it is too big --> decrease high
high = middle - 1;
}
}
iteration++;
}
// didnt find anything. Return -1.
return -1;
};
/*
* Easing Functions - inspired from http://gizma.com/easing/
* only considering the t value for the range [0, 1] => [0, 1]
* https://gist.github.com/gre/1650294
*/
exports.easingFunctions = {
// no easing, no acceleration
linear: function linear(t) {
return t;
},
// accelerating from zero velocity
easeInQuad: function easeInQuad(t) {
return t * t;
},
// decelerating to zero velocity
easeOutQuad: function easeOutQuad(t) {
return t * (2 - t);
},
// acceleration until halfway, then deceleration
easeInOutQuad: function easeInOutQuad(t) {
return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
},
// accelerating from zero velocity
easeInCubic: function easeInCubic(t) {
return t * t * t;
},
// decelerating to zero velocity
easeOutCubic: function easeOutCubic(t) {
return --t * t * t + 1;
},
// acceleration until halfway, then deceleration
easeInOutCubic: function easeInOutCubic(t) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
},
// accelerating from zero velocity
easeInQuart: function easeInQuart(t) {
return t * t * t * t;
},
// decelerating to zero velocity
easeOutQuart: function easeOutQuart(t) {
return 1 - --t * t * t * t;
},
// acceleration until halfway, then deceleration
easeInOutQuart: function easeInOutQuart(t) {
return t < .5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
},
// accelerating from zero velocity
easeInQuint: function easeInQuint(t) {
return t * t * t * t * t;
},
// decelerating to zero velocity
easeOutQuint: function easeOutQuint(t) {
return 1 + --t * t * t * t * t;
},
// acceleration until halfway, then deceleration
easeInOutQuint: function easeInOutQuint(t) {
return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
}
};
exports.getScrollBarWidth = function () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.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);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return w1 - w2;
};
exports.topMost = function (pile, accessors) {
var candidate = void 0;
if (!Array.isArray(accessors)) {
accessors = [accessors];
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3['default'])(pile), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var member = _step.value;
if (member) {
candidate = member[accessors[0]];
for (var i = 1; i < accessors.length; i++) {
if (candidate) {
candidate = candidate[accessors[i]];
} else {
continue;
}
}
if (typeof candidate != 'undefined') {
break;
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return candidate;
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(194), __esModule: true };
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _setPrototypeOf = __webpack_require__(196);
var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
var _create = __webpack_require__(29);
var _create2 = _interopRequireDefault(_create);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
}
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _iterator = __webpack_require__(142);
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = __webpack_require__(144);
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
/***/ }),
/* 7 */
/***/ (function(module, exports) {
var core = module.exports = { version: '2.5.1' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(140), __esModule: true };
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// first check if moment.js is already loaded in the browser window, if so,
// use this instance. Else, load via commonjs.
module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(154);
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Setup a mock hammer.js object, for unit testing.
*
* Inspiration: https://github.com/uber/deck.gl/pull/658
*
* @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
*/
function hammerMock() {
var noop = function noop() {};
return {
on: noop,
off: noop,
destroy: noop,
emit: noop,
get: function get(m) {
//eslint-disable-line no-unused-vars
return {
set: noop
};
}
};
}
if (typeof window !== 'undefined') {
var propagating = __webpack_require__(175);
var Hammer = window['Hammer'] || __webpack_require__(176);
module.exports = propagating(Hammer, {
preventDefault: 'mouse'
});
} else {
module.exports = function () {
// hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
return hammerMock();
};
}
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _stringify = __webpack_require__(19);
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var Queue = __webpack_require__(43);
/**
* DataSet
* // TODO: add a DataSet constructor DataSet(data, options)
*
* Usage:
* var dataSet = new DataSet({
* fieldId: '_id',
* type: {
* // ...
* }
* });
*
* dataSet.add(item);
* dataSet.add(data);
* dataSet.update(item);
* dataSet.update(data);
* dataSet.remove(id);
* dataSet.remove(ids);
* var data = dataSet.get();
* var data = dataSet.get(id);
* var data = dataSet.get(ids);
* var data = dataSet.get(ids, options, data);
* dataSet.clear();
*
* A data set can:
* - add/remove/update data
* - gives triggers upon changes in the data
* - can import/export data in various data formats
*
* @param {Array} [data] Optional array with initial data
* @param {Object} [options] Available options:
* {string} fieldId Field name of the id in the
* items, 'id' by default.
* {Object.} addedIds Array with the ids of the added items
*/
DataSet.prototype.add = function (data, senderId) {
var addedIds = [],
id,
me = this;
if (Array.isArray(data)) {
// Array
for (var i = 0, len = data.length; i < len; i++) {
id = me._addItem(data[i]);
addedIds.push(id);
}
} else if (data && (typeof data === 'undefined' ? 'undefined' : (0, _typeof3['default'])(data)) === 'object') {
// Single item
id = me._addItem(data);
addedIds.push(id);
} else {
throw new Error('Unknown dataType');
}
if (addedIds.length) {
this._trigger('add', { items: addedIds }, senderId);
}
return addedIds;
};
/**
* Update existing items. When an item does not exist, it will be created
* @param {Object | Array} data
* @param {string} [senderId] Optional sender id
* @return {Array.} updatedIds The ids of the added or updated items
* @throws {Error} Unknown Datatype
*/
DataSet.prototype.update = function (data, senderId) {
var addedIds = [];
var updatedIds = [];
var oldData = [];
var updatedData = [];
var me = this;
var fieldId = me._fieldId;
var addOrUpdate = function addOrUpdate(item) {
var id = item[fieldId];
if (me._data[id]) {
var oldItem = util.extend({}, me._data[id]);
// update item
id = me._updateItem(item);
updatedIds.push(id);
updatedData.push(item);
oldData.push(oldItem);
} else {
// add new item
id = me._addItem(item);
addedIds.push(id);
}
};
if (Array.isArray(data)) {
// Array
for (var i = 0, len = data.length; i < len; i++) {
if (data[i] && (0, _typeof3['default'])(data[i]) === 'object') {
addOrUpdate(data[i]);
} else {
console.warn('Ignoring input item, which is not an object at index ' + i);
}
}
} else if (data && (typeof data === 'undefined' ? 'undefined' : (0, _typeof3['default'])(data)) === 'object') {
// Single item
addOrUpdate(data);
} else {
throw new Error('Unknown dataType');
}
if (addedIds.length) {
this._trigger('add', { items: addedIds }, senderId);
}
if (updatedIds.length) {
var props = { items: updatedIds, oldData: oldData, data: updatedData };
// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
// 'get': (function() {
// console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
// return updatedData;
// }).bind(this)
//});
this._trigger('update', props, senderId);
}
return addedIds.concat(updatedIds);
};
/**
* Get a data item or multiple items.
*
* Usage:
*
* get()
* get(options: Object)
*
* get(id: number | string)
* get(id: number | string, options: Object)
*
* get(ids: number[] | string[])
* get(ids: number[] | string[], options: Object)
*
* Where:
*
* {number | string} id The id of an item
* {number[] | string{}} ids An array with ids of items
* {Object} options An Object with options. Available options:
* {string} [returnType] Type of data to be returned.
* Can be 'Array' (default) or 'Object'.
* {Object.} [type]
* {string[]} [fields] field names to be returned
* {function} [filter] filter items
* {string | function} [order] Order the items by a field name or custom sort function.
* @param {Array} args
* @returns {DataSet}
* @throws Error
*/
DataSet.prototype.get = function (args) {
// eslint-disable-line no-unused-vars
var me = this;
// parse the arguments
var id, ids, options;
var firstType = util.getType(arguments[0]);
if (firstType == 'String' || firstType == 'Number') {
// get(id [, options])
id = arguments[0];
options = arguments[1];
} else if (firstType == 'Array') {
// get(ids [, options])
ids = arguments[0];
options = arguments[1];
} else {
// get([, options])
options = arguments[0];
}
// determine the return type
var returnType;
if (options && options.returnType) {
var allowedValues = ['Array', 'Object'];
returnType = allowedValues.indexOf(options.returnType) == -1 ? 'Array' : options.returnType;
} else {
returnType = 'Array';
}
// build options
var type = options && options.type || this._options.type;
var filter = options && options.filter;
var items = [],
item,
itemIds,
itemId,
i,
len;
// convert items
if (id != undefined) {
// return a single item
item = me._getItem(id, type);
if (item && filter && !filter(item)) {
item = null;
}
} else if (ids != undefined) {
// return a subset of items
for (i = 0, len = ids.length; i < len; i++) {
item = me._getItem(ids[i], type);
if (!filter || filter(item)) {
items.push(item);
}
}
} else {
// return all items
itemIds = (0, _keys2['default'])(this._data);
for (i = 0, len = itemIds.length; i < len; i++) {
itemId = itemIds[i];
item = me._getItem(itemId, type);
if (!filter || filter(item)) {
items.push(item);
}
}
}
// order the results
if (options && options.order && id == undefined) {
this._sort(items, options.order);
}
// filter fields of the items
if (options && options.fields) {
var fields = options.fields;
if (id != undefined) {
item = this._filterFields(item, fields);
} else {
for (i = 0, len = items.length; i < len; i++) {
items[i] = this._filterFields(items[i], fields);
}
}
}
// return the results
if (returnType == 'Object') {
var result = {},
resultant;
for (i = 0, len = items.length; i < len; i++) {
resultant = items[i];
result[resultant.id] = resultant;
}
return result;
} else {
if (id != undefined) {
// a single item
return item;
} else {
// just return our array
return items;
}
}
};
/**
* Get ids of all items or from a filtered set of items.
* @param {Object} [options] An Object with options. Available options:
* {function} [filter] filter items
* {string | function} [order] Order the items by
* a field name or custom sort function.
* @return {Array.} ids
*/
DataSet.prototype.getIds = function (options) {
var data = this._data,
filter = options && options.filter,
order = options && options.order,
type = options && options.type || this._options.type,
itemIds = (0, _keys2['default'])(data),
i,
len,
id,
item,
items,
ids = [];
if (filter) {
// get filtered items
if (order) {
// create ordered list
items = [];
for (i = 0, len = itemIds.length; i < len; i++) {
id = itemIds[i];
item = this._getItem(id, type);
if (filter(item)) {
items.push(item);
}
}
this._sort(items, order);
for (i = 0, len = items.length; i < len; i++) {
ids.push(items[i][this._fieldId]);
}
} else {
// create unordered list
for (i = 0, len = itemIds.length; i < len; i++) {
id = itemIds[i];
item = this._getItem(id, type);
if (filter(item)) {
ids.push(item[this._fieldId]);
}
}
}
} else {
// get all items
if (order) {
// create an ordered list
items = [];
for (i = 0, len = itemIds.length; i < len; i++) {
id = itemIds[i];
items.push(data[id]);
}
this._sort(items, order);
for (i = 0, len = items.length; i < len; i++) {
ids.push(items[i][this._fieldId]);
}
} else {
// create unordered list
for (i = 0, len = itemIds.length; i < len; i++) {
id = itemIds[i];
item = data[id];
ids.push(item[this._fieldId]);
}
}
}
return ids;
};
/**
* Returns the DataSet itself. Is overwritten for example by the DataView,
* which returns the DataSet it is connected to instead.
* @returns {DataSet}
*/
DataSet.prototype.getDataSet = function () {
return this;
};
/**
* Execute a callback function for every item in the dataset.
* @param {function} callback
* @param {Object} [options] Available options:
* {Object.} [type]
* {string[]} [fields] filter fields
* {function} [filter] filter items
* {string | function} [order] Order the items by
* a field name or custom sort function.
*/
DataSet.prototype.forEach = function (callback, options) {
var filter = options && options.filter,
type = options && options.type || this._options.type,
data = this._data,
itemIds = (0, _keys2['default'])(data),
i,
len,
item,
id;
if (options && options.order) {
// execute forEach on ordered list
var items = this.get(options);
for (i = 0, len = items.length; i < len; i++) {
item = items[i];
id = item[this._fieldId];
callback(item, id);
}
} else {
// unordered
for (i = 0, len = itemIds.length; i < len; i++) {
id = itemIds[i];
item = this._getItem(id, type);
if (!filter || filter(item)) {
callback(item, id);
}
}
}
};
/**
* Map every item in the dataset.
* @param {function} callback
* @param {Object} [options] Available options:
* {Object.} [type]
* {string[]} [fields] filter fields
* {function} [filter] filter items
* {string | function} [order] Order the items by
* a field name or custom sort function.
* @return {Object[]} mappedItems
*/
DataSet.prototype.map = function (callback, options) {
var filter = options && options.filter,
type = options && options.type || this._options.type,
mappedItems = [],
data = this._data,
itemIds = (0, _keys2['default'])(data),
i,
len,
id,
item;
// convert and filter items
for (i = 0, len = itemIds.length; i < len; i++) {
id = itemIds[i];
item = this._getItem(id, type);
if (!filter || filter(item)) {
mappedItems.push(callback(item, id));
}
}
// order items
if (options && options.order) {
this._sort(mappedItems, options.order);
}
return mappedItems;
};
/**
* Filter the fields of an item
* @param {Object | null} item
* @param {string[]} fields Field names
* @return {Object | null} filteredItem or null if no item is provided
* @private
*/
DataSet.prototype._filterFields = function (item, fields) {
if (!item) {
// item is null
return item;
}
var filteredItem = {},
itemFields = (0, _keys2['default'])(item),
len = itemFields.length,
i,
field;
if (Array.isArray(fields)) {
for (i = 0; i < len; i++) {
field = itemFields[i];
if (fields.indexOf(field) != -1) {
filteredItem[field] = item[field];
}
}
} else {
for (i = 0; i < len; i++) {
field = itemFields[i];
if (fields.hasOwnProperty(field)) {
filteredItem[fields[field]] = item[field];
}
}
}
return filteredItem;
};
/**
* Sort the provided array with items
* @param {Object[]} items
* @param {string | function} order A field name or custom sort function.
* @private
*/
DataSet.prototype._sort = function (items, order) {
if (util.isString(order)) {
// order by provided field name
var name = order; // field name
items.sort(function (a, b) {
var av = a[name];
var bv = b[name];
return av > bv ? 1 : av < bv ? -1 : 0;
});
} else if (typeof order === 'function') {
// order by sort function
items.sort(order);
}
// TODO: extend order by an Object {field:string, direction:string}
// where direction can be 'asc' or 'desc'
else {
throw new TypeError('Order must be a function or a string');
}
};
/**
* Remove an object by pointer or by id
* @param {string | number | Object | Array.} id Object or id, or an array with
* objects or ids to be removed
* @param {string} [senderId] Optional sender id
* @return {Array.} removedIds
*/
DataSet.prototype.remove = function (id, senderId) {
var removedIds = [],
removedItems = [],
ids = [],
i,
len,
itemId,
item;
// force everything to be an array for simplicity
ids = Array.isArray(id) ? id : [id];
for (i = 0, len = ids.length; i < len; i++) {
item = this._remove(ids[i]);
if (item) {
itemId = item[this._fieldId];
if (itemId != undefined) {
removedIds.push(itemId);
removedItems.push(item);
}
}
}
if (removedIds.length) {
this._trigger('remove', { items: removedIds, oldData: removedItems }, senderId);
}
return removedIds;
};
/**
* Remove an item by its id
* @param {number | string | Object} id id or item
* @returns {number | string | null} id
* @private
*/
DataSet.prototype._remove = function (id) {
var item, ident;
// confirm the id to use based on the args type
if (util.isNumber(id) || util.isString(id)) {
ident = id;
} else if (id && (typeof id === 'undefined' ? 'undefined' : (0, _typeof3['default'])(id)) === 'object') {
ident = id[this._fieldId]; // look for the identifier field using _fieldId
}
// do the remove if the item is found
if (ident !== undefined && this._data[ident]) {
item = this._data[ident];
delete this._data[ident];
this.length--;
return item;
}
return null;
};
/**
* Clear the data
* @param {string} [senderId] Optional sender id
* @return {Array.} removedIds The ids of all removed items
*/
DataSet.prototype.clear = function (senderId) {
var i, len;
var ids = (0, _keys2['default'])(this._data);
var items = [];
for (i = 0, len = ids.length; i < len; i++) {
items.push(this._data[ids[i]]);
}
this._data = {};
this.length = 0;
this._trigger('remove', { items: ids, oldData: items }, senderId);
return ids;
};
/**
* Find the item with maximum value of a specified field
* @param {string} field
* @return {Object | null} item Item containing max value, or null if no items
*/
DataSet.prototype.max = function (field) {
var data = this._data,
itemIds = (0, _keys2['default'])(data),
max = null,
maxField = null,
i,
len;
for (i = 0, len = itemIds.length; i < len; i++) {
var id = itemIds[i];
var item = data[id];
var itemField = item[field];
if (itemField != null && (!max || itemField > maxField)) {
max = item;
maxField = itemField;
}
}
return max;
};
/**
* Find the item with minimum value of a specified field
* @param {string} field
* @return {Object | null} item Item containing max value, or null if no items
*/
DataSet.prototype.min = function (field) {
var data = this._data,
itemIds = (0, _keys2['default'])(data),
min = null,
minField = null,
i,
len;
for (i = 0, len = itemIds.length; i < len; i++) {
var id = itemIds[i];
var item = data[id];
var itemField = item[field];
if (itemField != null && (!min || itemField < minField)) {
min = item;
minField = itemField;
}
}
return min;
};
/**
* Find all distinct values of a specified field
* @param {string} field
* @return {Array} values Array containing all distinct values. If data items
* do not contain the specified field are ignored.
* The returned array is unordered.
*/
DataSet.prototype.distinct = function (field) {
var data = this._data;
var itemIds = (0, _keys2['default'])(data);
var values = [];
var fieldType = this._options.type && this._options.type[field] || null;
var count = 0;
var i, j, len;
for (i = 0, len = itemIds.length; i < len; i++) {
var id = itemIds[i];
var item = data[id];
var value = item[field];
var exists = false;
for (j = 0; j < count; j++) {
if (values[j] == value) {
exists = true;
break;
}
}
if (!exists && value !== undefined) {
values[count] = value;
count++;
}
}
if (fieldType) {
for (i = 0, len = values.length; i < len; i++) {
values[i] = util.convert(values[i], fieldType);
}
}
return values;
};
/**
* Add a single item. Will fail when an item with the same id already exists.
* @param {Object} item
* @return {string} id
* @private
*/
DataSet.prototype._addItem = function (item) {
var id = item[this._fieldId];
if (id != undefined) {
// check whether this id is already taken
if (this._data[id]) {
// item already exists
throw new Error('Cannot add item: item with id ' + id + ' already exists');
}
} else {
// generate an id
id = util.randomUUID();
item[this._fieldId] = id;
}
var d = {},
fields = (0, _keys2['default'])(item),
i,
len;
for (i = 0, len = fields.length; i < len; i++) {
var field = fields[i];
var fieldType = this._type[field]; // type may be undefined
d[field] = util.convert(item[field], fieldType);
}
this._data[id] = d;
this.length++;
return id;
};
/**
* Get an item. Fields can be converted to a specific type
* @param {string} id
* @param {Object.} [types] field types to convert
* @return {Object | null} item
* @private
*/
DataSet.prototype._getItem = function (id, types) {
var field, value, i, len;
// get the item from the dataset
var raw = this._data[id];
if (!raw) {
return null;
}
// convert the items field types
var converted = {},
fields = (0, _keys2['default'])(raw);
if (types) {
for (i = 0, len = fields.length; i < len; i++) {
field = fields[i];
value = raw[field];
converted[field] = util.convert(value, types[field]);
}
} else {
// no field types specified, no converting needed
for (i = 0, len = fields.length; i < len; i++) {
field = fields[i];
value = raw[field];
converted[field] = value;
}
}
if (!converted[this._fieldId]) {
converted[this._fieldId] = raw.id;
}
return converted;
};
/**
* Update a single item: merge with existing item.
* Will fail when the item has no id, or when there does not exist an item
* with the same id.
* @param {Object} item
* @return {string} id
* @private
*/
DataSet.prototype._updateItem = function (item) {
var id = item[this._fieldId];
if (id == undefined) {
throw new Error('Cannot update item: item has no id (item: ' + (0, _stringify2['default'])(item) + ')');
}
var d = this._data[id];
if (!d) {
// item doesn't exist
throw new Error('Cannot update item: no item with id ' + id + ' found');
}
// merge with current item
var fields = (0, _keys2['default'])(item);
for (var i = 0, len = fields.length; i < len; i++) {
var field = fields[i];
var fieldType = this._type[field]; // type may be undefined
d[field] = util.convert(item[field], fieldType);
}
return id;
};
module.exports = DataSet;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var DataSet = __webpack_require__(11);
/**
* DataView
*
* a dataview offers a filtered view on a dataset or an other dataview.
*
* @param {DataSet | DataView} data
* @param {Object} [options] Available options: see method get
*
* @constructor DataView
*/
function DataView(data, options) {
this._data = null;
this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
this.length = 0; // number of items in the DataView
this._options = options || {};
this._fieldId = 'id'; // name of the field containing id
this._subscribers = {}; // event subscribers
var me = this;
this.listener = function () {
me._onEvent.apply(me, arguments);
};
this.setData(data);
}
// TODO: implement a function .config() to dynamically update things like configured filter
// and trigger changes accordingly
/**
* Set a data source for the view
* @param {DataSet | DataView} data
*/
DataView.prototype.setData = function (data) {
var ids, id, i, len, items;
if (this._data) {
// unsubscribe from current dataset
if (this._data.off) {
this._data.off('*', this.listener);
}
// trigger a remove of all items in memory
ids = this._data.getIds({ filter: this._options && this._options.filter });
items = [];
for (i = 0, len = ids.length; i < len; i++) {
items.push(this._data._data[ids[i]]);
}
this._ids = {};
this.length = 0;
this._trigger('remove', { items: ids, oldData: items });
}
this._data = data;
if (this._data) {
// update fieldId
this._fieldId = this._options.fieldId || this._data && this._data.options && this._data.options.fieldId || 'id';
// trigger an add of all added items
ids = this._data.getIds({ filter: this._options && this._options.filter });
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
this._ids[id] = true;
}
this.length = ids.length;
this._trigger('add', { items: ids });
// subscribe to new dataset
if (this._data.on) {
this._data.on('*', this.listener);
}
}
};
/**
* Refresh the DataView. Useful when the DataView has a filter function
* containing a variable parameter.
*/
DataView.prototype.refresh = function () {
var id, i, len;
var ids = this._data.getIds({ filter: this._options && this._options.filter }),
oldIds = (0, _keys2['default'])(this._ids),
newIds = {},
addedIds = [],
removedIds = [],
removedItems = [];
// check for additions
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
newIds[id] = true;
if (!this._ids[id]) {
addedIds.push(id);
this._ids[id] = true;
}
}
// check for removals
for (i = 0, len = oldIds.length; i < len; i++) {
id = oldIds[i];
if (!newIds[id]) {
removedIds.push(id);
removedItems.push(this._data._data[id]);
delete this._ids[id];
}
}
this.length += addedIds.length - removedIds.length;
// trigger events
if (addedIds.length) {
this._trigger('add', { items: addedIds });
}
if (removedIds.length) {
this._trigger('remove', { items: removedIds, oldData: removedItems });
}
};
/**
* Get data from the data view
*
* Usage:
*
* get()
* get(options: Object)
* get(options: Object, data: Array | DataTable)
*
* get(id: Number)
* get(id: Number, options: Object)
* get(id: Number, options: Object, data: Array | DataTable)
*
* get(ids: Number[])
* get(ids: Number[], options: Object)
* get(ids: Number[], options: Object, data: Array | DataTable)
*
* Where:
*
* {number | string} id The id of an item
* {number[] | string{}} ids An array with ids of items
* {Object} options An Object with options. Available options:
* {string} [type] Type of data to be returned. Can
* be 'DataTable' or 'Array' (default)
* {Object.} [convert]
* {string[]} [fields] field names to be returned
* {function} [filter] filter items
* {string | function} [order] Order the items by
* a field name or custom sort function.
* {Array | DataTable} [data] If provided, items will be appended to this
* array or table. Required in case of Google
* DataTable.
* @param {Array} args
* @return {DataSet|DataView}
*/
DataView.prototype.get = function (args) {
// eslint-disable-line no-unused-vars
var me = this;
// parse the arguments
var ids, options, data;
var firstType = util.getType(arguments[0]);
if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
// get(id(s) [, options] [, data])
ids = arguments[0]; // can be a single id or an array with ids
options = arguments[1];
data = arguments[2];
} else {
// get([, options] [, data])
options = arguments[0];
data = arguments[1];
}
// extend the options with the default options and provided options
var viewOptions = util.extend({}, this._options, options);
// create a combined filter method when needed
if (this._options.filter && options && options.filter) {
viewOptions.filter = function (item) {
return me._options.filter(item) && options.filter(item);
};
}
// build up the call to the linked data set
var getArguments = [];
if (ids != undefined) {
getArguments.push(ids);
}
getArguments.push(viewOptions);
getArguments.push(data);
return this._data && this._data.get.apply(this._data, getArguments);
};
/**
* Get ids of all items or from a filtered set of items.
* @param {Object} [options] An Object with options. Available options:
* {function} [filter] filter items
* {string | function} [order] Order the items by
* a field name or custom sort function.
* @return {Array.} ids
*/
DataView.prototype.getIds = function (options) {
var ids;
if (this._data) {
var defaultFilter = this._options.filter;
var filter;
if (options && options.filter) {
if (defaultFilter) {
filter = function filter(item) {
return defaultFilter(item) && options.filter(item);
};
} else {
filter = options.filter;
}
} else {
filter = defaultFilter;
}
ids = this._data.getIds({
filter: filter,
order: options && options.order
});
} else {
ids = [];
}
return ids;
};
/**
* Map every item in the dataset.
* @param {function} callback
* @param {Object} [options] Available options:
* {Object.} [type]
* {string[]} [fields] filter fields
* {function} [filter] filter items
* {string | function} [order] Order the items by
* a field name or custom sort function.
* @return {Object[]} mappedItems
*/
DataView.prototype.map = function (callback, options) {
var mappedItems = [];
if (this._data) {
var defaultFilter = this._options.filter;
var filter;
if (options && options.filter) {
if (defaultFilter) {
filter = function filter(item) {
return defaultFilter(item) && options.filter(item);
};
} else {
filter = options.filter;
}
} else {
filter = defaultFilter;
}
mappedItems = this._data.map(callback, {
filter: filter,
order: options && options.order
});
} else {
mappedItems = [];
}
return mappedItems;
};
/**
* Get the DataSet to which this DataView is connected. In case there is a chain
* of multiple DataViews, the root DataSet of this chain is returned.
* @return {DataSet} dataSet
*/
DataView.prototype.getDataSet = function () {
var dataSet = this;
while (dataSet instanceof DataView) {
dataSet = dataSet._data;
}
return dataSet || null;
};
/**
* Event listener. Will propagate all events from the connected data set to
* the subscribers of the DataView, but will filter the items and only trigger
* when there are changes in the filtered data set.
* @param {string} event
* @param {Object | null} params
* @param {string} senderId
* @private
*/
DataView.prototype._onEvent = function (event, params, senderId) {
var i, len, id, item;
var ids = params && params.items;
var addedIds = [],
updatedIds = [],
removedIds = [],
oldItems = [],
updatedItems = [],
removedItems = [];
if (ids && this._data) {
switch (event) {
case 'add':
// filter the ids of the added items
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
item = this.get(id);
if (item) {
this._ids[id] = true;
addedIds.push(id);
}
}
break;
case 'update':
// determine the event from the views viewpoint: an updated
// item can be added, updated, or removed from this view.
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
item = this.get(id);
if (item) {
if (this._ids[id]) {
updatedIds.push(id);
updatedItems.push(params.data[i]);
oldItems.push(params.oldData[i]);
} else {
this._ids[id] = true;
addedIds.push(id);
}
} else {
if (this._ids[id]) {
delete this._ids[id];
removedIds.push(id);
removedItems.push(params.oldData[i]);
} else {
// nothing interesting for me :-(
}
}
}
break;
case 'remove':
// filter the ids of the removed items
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
if (this._ids[id]) {
delete this._ids[id];
removedIds.push(id);
removedItems.push(params.oldData[i]);
}
}
break;
}
this.length += addedIds.length - removedIds.length;
if (addedIds.length) {
this._trigger('add', { items: addedIds }, senderId);
}
if (updatedIds.length) {
this._trigger('update', { items: updatedIds, oldData: oldItems, data: updatedItems }, senderId);
}
if (removedIds.length) {
this._trigger('remove', { items: removedIds, oldData: removedItems }, senderId);
}
}
};
// copy subscription functionality from DataSet
DataView.prototype.on = DataSet.prototype.on;
DataView.prototype.off = DataSet.prototype.off;
DataView.prototype._trigger = DataSet.prototype._trigger;
// TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
DataView.prototype.subscribe = DataView.prototype.on;
DataView.prototype.unsubscribe = DataView.prototype.off;
module.exports = DataView;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(57)('wks');
var uid = __webpack_require__(40);
var Symbol = __webpack_require__(18).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// DOM utility methods
/**
* this prepares the JSON container for allocating SVG elements
* @param {Object} JSONcontainer
* @private
*/
exports.prepareElements = function (JSONcontainer) {
// cleanup the redundant svgElements;
for (var elementType in JSONcontainer) {
if (JSONcontainer.hasOwnProperty(elementType)) {
JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
JSONcontainer[elementType].used = [];
}
}
};
/**
* this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
* which to remove the redundant elements.
*
* @param {Object} JSONcontainer
* @private
*/
exports.cleanupElements = function (JSONcontainer) {
// cleanup the redundant svgElements;
for (var elementType in JSONcontainer) {
if (JSONcontainer.hasOwnProperty(elementType)) {
if (JSONcontainer[elementType].redundant) {
for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
}
JSONcontainer[elementType].redundant = [];
}
}
}
};
/**
* Ensures that all elements are removed first up so they can be recreated cleanly
* @param {Object} JSONcontainer
*/
exports.resetElements = function (JSONcontainer) {
exports.prepareElements(JSONcontainer);
exports.cleanupElements(JSONcontainer);
exports.prepareElements(JSONcontainer);
};
/**
* Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
* the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
*
* @param {string} elementType
* @param {Object} JSONcontainer
* @param {Object} svgContainer
* @returns {Element}
* @private
*/
exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
var element;
// allocate SVG element, if it doesnt yet exist, create one.
if (JSONcontainer.hasOwnProperty(elementType)) {
// this element has been created before
// check if there is an redundant element
if (JSONcontainer[elementType].redundant.length > 0) {
element = JSONcontainer[elementType].redundant[0];
JSONcontainer[elementType].redundant.shift();
} else {
// create a new element and add it to the SVG
element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
svgContainer.appendChild(element);
}
} else {
// create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
JSONcontainer[elementType] = { used: [], redundant: [] };
svgContainer.appendChild(element);
}
JSONcontainer[elementType].used.push(element);
return element;
};
/**
* Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
* the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
*
* @param {string} elementType
* @param {Object} JSONcontainer
* @param {Element} DOMContainer
* @param {Element} insertBefore
* @returns {*}
*/
exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
var element;
// allocate DOM element, if it doesnt yet exist, create one.
if (JSONcontainer.hasOwnProperty(elementType)) {
// this element has been created before
// check if there is an redundant element
if (JSONcontainer[elementType].redundant.length > 0) {
element = JSONcontainer[elementType].redundant[0];
JSONcontainer[elementType].redundant.shift();
} else {
// create a new element and add it to the SVG
element = document.createElement(elementType);
if (insertBefore !== undefined) {
DOMContainer.insertBefore(element, insertBefore);
} else {
DOMContainer.appendChild(element);
}
}
} else {
// create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
element = document.createElement(elementType);
JSONcontainer[elementType] = { used: [], redundant: [] };
if (insertBefore !== undefined) {
DOMContainer.insertBefore(element, insertBefore);
} else {
DOMContainer.appendChild(element);
}
}
JSONcontainer[elementType].used.push(element);
return element;
};
/**
* Draw a point object. This is a separate function because it can also be called by the legend.
* The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
* as well.
*
* @param {number} x
* @param {number} y
* @param {Object} groupTemplate: A template containing the necessary information to draw the datapoint e.g., {style: 'circle', size: 5, className: 'className' }
* @param {Object} JSONcontainer
* @param {Object} svgContainer
* @param {Object} labelObj
* @returns {vis.PointItem}
*/
exports.drawPoint = function (x, y, groupTemplate, JSONcontainer, svgContainer, labelObj) {
var point;
if (groupTemplate.style == 'circle') {
point = exports.getSVGElement('circle', JSONcontainer, svgContainer);
point.setAttributeNS(null, "cx", x);
point.setAttributeNS(null, "cy", y);
point.setAttributeNS(null, "r", 0.5 * groupTemplate.size);
} else {
point = exports.getSVGElement('rect', JSONcontainer, svgContainer);
point.setAttributeNS(null, "x", x - 0.5 * groupTemplate.size);
point.setAttributeNS(null, "y", y - 0.5 * groupTemplate.size);
point.setAttributeNS(null, "width", groupTemplate.size);
point.setAttributeNS(null, "height", groupTemplate.size);
}
if (groupTemplate.styles !== undefined) {
point.setAttributeNS(null, "style", groupTemplate.styles);
}
point.setAttributeNS(null, "class", groupTemplate.className + " vis-point");
//handle label
if (labelObj) {
var label = exports.getSVGElement('text', JSONcontainer, svgContainer);
if (labelObj.xOffset) {
x = x + labelObj.xOffset;
}
if (labelObj.yOffset) {
y = y + labelObj.yOffset;
}
if (labelObj.content) {
label.textContent = labelObj.content;
}
if (labelObj.className) {
label.setAttributeNS(null, "class", labelObj.className + " vis-label");
}
label.setAttributeNS(null, "x", x);
label.setAttributeNS(null, "y", y);
}
return point;
};
/**
* draw a bar SVG element centered on the X coordinate
*
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {string} className
* @param {Object} JSONcontainer
* @param {Object} svgContainer
* @param {string} style
*/
exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer, style) {
if (height != 0) {
if (height < 0) {
height *= -1;
y -= height;
}
var rect = exports.getSVGElement('rect', JSONcontainer, svgContainer);
rect.setAttributeNS(null, "x", x - 0.5 * width);
rect.setAttributeNS(null, "y", y);
rect.setAttributeNS(null, "width", width);
rect.setAttributeNS(null, "height", height);
rect.setAttributeNS(null, "class", className);
if (style) {
rect.setAttributeNS(null, "style", style);
}
}
};
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.printStyle = undefined;
var _stringify = __webpack_require__(19);
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var errorFound = false;
var allOptions = void 0;
var printStyle = 'background: #FFeeee; color: #dd0000';
/**
* Used to validate options.
*/
var Validator = function () {
/**
* @ignore
*/
function Validator() {
(0, _classCallCheck3['default'])(this, Validator);
}
/**
* Main function to be called
* @param {Object} options
* @param {Object} referenceOptions
* @param {Object} subObject
* @returns {boolean}
* @static
*/
(0, _createClass3['default'])(Validator, null, [{
key: 'validate',
value: function validate(options, referenceOptions, subObject) {
errorFound = false;
allOptions = referenceOptions;
var usedOptions = referenceOptions;
if (subObject !== undefined) {
usedOptions = referenceOptions[subObject];
}
Validator.parse(options, usedOptions, []);
return errorFound;
}
/**
* Will traverse an object recursively and check every value
* @param {Object} options
* @param {Object} referenceOptions
* @param {array} path | where to look for the actual option
* @static
*/
}, {
key: 'parse',
value: function parse(options, referenceOptions, path) {
for (var option in options) {
if (options.hasOwnProperty(option)) {
Validator.check(option, options, referenceOptions, path);
}
}
}
/**
* Check every value. If the value is an object, call the parse function on that object.
* @param {string} option
* @param {Object} options
* @param {Object} referenceOptions
* @param {array} path | where to look for the actual option
* @static
*/
}, {
key: 'check',
value: function check(option, options, referenceOptions, path) {
if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) {
Validator.getSuggestion(option, referenceOptions, path);
return;
}
var referenceOption = option;
var is_object = true;
if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
// NOTE: This only triggers if the __any__ is in the top level of the options object.
// THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
// TODO: Examine if needed, remove if possible
// __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
referenceOption = '__any__';
// if the any-subgroup is not a predefined object in the configurator,
// we do not look deeper into the object.
is_object = Validator.getType(options[option]) === 'object';
} else {
// Since all options in the reference are objects, we can check whether
// they are supposed to be the object to look for the __type__ field.
// if this is an object, we check if the correct type has been supplied to account for shorthand options.
}
var refOptionObj = referenceOptions[referenceOption];
if (is_object && refOptionObj.__type__ !== undefined) {
refOptionObj = refOptionObj.__type__;
}
Validator.checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path);
}
/**
*
* @param {string} option | the option property
* @param {Object} options | The supplied options object
* @param {Object} referenceOptions | The reference options containing all options and their allowed formats
* @param {string} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
* @param {string} refOptionObj | This is the type object from the reference options
* @param {Array} path | where in the object is the option
* @static
*/
}, {
key: 'checkFields',
value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
var log = function log(message) {
console.log('%c' + message + Validator.printLocation(path, option), printStyle);
};
var optionType = Validator.getType(options[option]);
var refOptionType = refOptionObj[optionType];
if (refOptionType !== undefined) {
// if the type is correct, we check if it is supposed to be one of a few select values
if (Validator.getType(refOptionType) === 'array' && refOptionType.indexOf(options[option]) === -1) {
log('Invalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ');
errorFound = true;
} else if (optionType === 'object' && referenceOption !== "__any__") {
path = util.copyAndExtendArray(path, option);
Validator.parse(options[option], referenceOptions[referenceOption], path);
}
} else if (refOptionObj['any'] === undefined) {
// type of the field is incorrect and the field cannot be any
log('Invalid type received for "' + option + '". Expected: ' + Validator.print((0, _keys2['default'])(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"');
errorFound = true;
}
}
/**
*
* @param {Object|boolean|number|string|Array.|Date|Node|Moment|undefined|null} object
* @returns {string}
* @static
*/
}, {
key: 'getType',
value: function getType(object) {
var type = typeof object === 'undefined' ? 'undefined' : (0, _typeof3['default'])(object);
if (type === 'object') {
if (object === null) {
return 'null';
}
if (object instanceof Boolean) {
return 'boolean';
}
if (object instanceof Number) {
return 'number';
}
if (object instanceof String) {
return 'string';
}
if (Array.isArray(object)) {
return 'array';
}
if (object instanceof Date) {
return 'date';
}
if (object.nodeType !== undefined) {
return 'dom';
}
if (object._isAMomentObject === true) {
return 'moment';
}
return 'object';
} else if (type === 'number') {
return 'number';
} else if (type === 'boolean') {
return 'boolean';
} else if (type === 'string') {
return 'string';
} else if (type === undefined) {
return 'undefined';
}
return type;
}
/**
* @param {string} option
* @param {Object} options
* @param {Array.} path
* @static
*/
}, {
key: 'getSuggestion',
value: function getSuggestion(option, options, path) {
var localSearch = Validator.findInOptions(option, options, path, false);
var globalSearch = Validator.findInOptions(option, allOptions, [], true);
var localSearchThreshold = 8;
var globalSearchThreshold = 4;
var msg = void 0;
if (localSearch.indexMatch !== undefined) {
msg = ' in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n';
} else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
msg = ' in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, '');
} else if (localSearch.distance <= localSearchThreshold) {
msg = '. Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option);
} else {
msg = '. Did you mean one of these: ' + Validator.print((0, _keys2['default'])(options)) + Validator.printLocation(path, option);
}
console.log('%cUnknown option detected: "' + option + '"' + msg, printStyle);
errorFound = true;
}
/**
* traverse the options in search for a match.
* @param {string} option
* @param {Object} options
* @param {Array} path | where to look for the actual option
* @param {boolean} [recursive=false]
* @returns {{closestMatch: string, path: Array, distance: number}}
* @static
*/
}, {
key: 'findInOptions',
value: function findInOptions(option, options, path) {
var recursive = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var min = 1e9;
var closestMatch = '';
var closestMatchPath = [];
var lowerCaseOption = option.toLowerCase();
var indexMatch = undefined;
for (var op in options) {
// eslint-disable-line guard-for-in
var distance = void 0;
if (options[op].__type__ !== undefined && recursive === true) {
var result = Validator.findInOptions(option, options[op], util.copyAndExtendArray(path, op));
if (min > result.distance) {
closestMatch = result.closestMatch;
closestMatchPath = result.path;
min = result.distance;
indexMatch = result.indexMatch;
}
} else {
if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
indexMatch = op;
}
distance = Validator.levenshteinDistance(option, op);
if (min > distance) {
closestMatch = op;
closestMatchPath = util.copyArray(path);
min = distance;
}
}
}
return { closestMatch: closestMatch, path: closestMatchPath, distance: min, indexMatch: indexMatch };
}
/**
* @param {Array.} path
* @param {Object} option
* @param {string} prefix
* @returns {String}
* @static
*/
}, {
key: 'printLocation',
value: function printLocation(path, option) {
var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Problem value found at: \n';
var str = '\n\n' + prefix + 'options = {\n';
for (var i = 0; i < path.length; i++) {
for (var j = 0; j < i + 1; j++) {
str += ' ';
}
str += path[i] + ': {\n';
}
for (var _j = 0; _j < path.length + 1; _j++) {
str += ' ';
}
str += option + '\n';
for (var _i = 0; _i < path.length + 1; _i++) {
for (var _j2 = 0; _j2 < path.length - _i; _j2++) {
str += ' ';
}
str += '}\n';
}
return str + '\n\n';
}
/**
* @param {Object} options
* @returns {String}
* @static
*/
}, {
key: 'print',
value: function print(options) {
return (0, _stringify2['default'])(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, "").replace(/(\,)/g, ', ');
}
/**
* Compute the edit distance between the two given strings
* http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
*
* Copyright (c) 2011 Andrei Mackenzie
*
* 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.
*
* @param {string} a
* @param {string} b
* @returns {Array.>}}
* @static
*/
}, {
key: 'levenshteinDistance',
value: function levenshteinDistance(a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
var matrix = [];
// increment along the first column of each row
var i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
// increment each column in the first row
var j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) == a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
Math.min(matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1)); // deletion
}
}
}
return matrix[b.length][a.length];
}
}]);
return Validator;
}();
exports['default'] = Validator;
exports.printStyle = printStyle;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(2);
/**
* Prototype for visual components
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
* @param {Object} [options]
*/
function Component(body, options) {
// eslint-disable-line no-unused-vars
this.options = null;
this.props = null;
}
/**
* Set options for the component. The new options will be merged into the
* current options.
* @param {Object} options
*/
Component.prototype.setOptions = function (options) {
if (options) {
util.extend(this.options, options);
}
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
Component.prototype.redraw = function () {
// should be implemented by the component
return false;
};
/**
* Destroy the component. Cleanup DOM and event listeners
*/
Component.prototype.destroy = function () {
// should be implemented by the component
};
/**
* Test whether the component is resized since the last time _isResized() was
* called.
* @return {Boolean} Returns true if the component is resized
* @protected
*/
Component.prototype._isResized = function () {
var resized = this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height;
this.props._previousWidth = this.props.width;
this.props._previousHeight = this.props.height;
return resized;
};
module.exports = Component;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(18);
var core = __webpack_require__(7);
var ctx = __webpack_require__(80);
var hide = __webpack_require__(26);
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
var key, own, out;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if (own && key in exports) continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function (C) {
var F = function (a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0: return new C();
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if (IS_PROTO) {
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 18 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(160), __esModule: true };
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(27);
var IE8_DOM_DEFINE = __webpack_require__(81);
var toPrimitive = __webpack_require__(53);
var dP = Object.defineProperty;
exports.f = __webpack_require__(21) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(28)(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 22 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* The Base class for all Nodes.
*/
var NodeBase = function () {
/**
* @param {Object} options
* @param {Object} body
* @param {Label} labelModule
*/
function NodeBase(options, body, labelModule) {
(0, _classCallCheck3['default'])(this, NodeBase);
this.body = body;
this.labelModule = labelModule;
this.setOptions(options);
this.top = undefined;
this.left = undefined;
this.height = undefined;
this.width = undefined;
this.radius = undefined;
this.margin = undefined;
this.refreshNeeded = true;
this.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 };
}
/**
*
* @param {Object} options
*/
(0, _createClass3['default'])(NodeBase, [{
key: 'setOptions',
value: function setOptions(options) {
this.options = options;
}
/**
*
* @param {Label} labelModule
* @private
*/
}, {
key: '_setMargins',
value: function _setMargins(labelModule) {
this.margin = {};
if (this.options.margin) {
if ((0, _typeof3['default'])(this.options.margin) == 'object') {
this.margin.top = this.options.margin.top;
this.margin.right = this.options.margin.right;
this.margin.bottom = this.options.margin.bottom;
this.margin.left = this.options.margin.left;
} else {
this.margin.top = this.options.margin;
this.margin.right = this.options.margin;
this.margin.bottom = this.options.margin;
this.margin.left = this.options.margin;
}
}
labelModule.adjustSizes(this.margin);
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle
* @returns {number}
* @private
*/
}, {
key: '_distanceToBorder',
value: function _distanceToBorder(ctx, angle) {
var borderWidth = this.options.borderWidth;
this.resize(ctx);
return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'enableShadow',
value: function enableShadow(ctx, values) {
if (values.shadow) {
ctx.shadowColor = values.shadowColor;
ctx.shadowBlur = values.shadowSize;
ctx.shadowOffsetX = values.shadowX;
ctx.shadowOffsetY = values.shadowY;
}
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'disableShadow',
value: function disableShadow(ctx, values) {
if (values.shadow) {
ctx.shadowColor = 'rgba(0,0,0,0)';
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
}
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'enableBorderDashes',
value: function enableBorderDashes(ctx, values) {
if (values.borderDashes !== false) {
if (ctx.setLineDash !== undefined) {
var dashes = values.borderDashes;
if (dashes === true) {
dashes = [5, 15];
}
ctx.setLineDash(dashes);
} else {
console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");
this.options.shapeProperties.borderDashes = false;
values.borderDashes = false;
}
}
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'disableBorderDashes',
value: function disableBorderDashes(ctx, values) {
if (values.borderDashes !== false) {
if (ctx.setLineDash !== undefined) {
ctx.setLineDash([0]);
} else {
console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");
this.options.shapeProperties.borderDashes = false;
values.borderDashes = false;
}
}
}
/**
* Determine if the shape of a node needs to be recalculated.
*
* @param {boolean} selected
* @param {boolean} hover
* @returns {boolean}
* @protected
*/
}, {
key: 'needsRefresh',
value: function needsRefresh(selected, hover) {
if (this.refreshNeeded === true) {
// This is probably not the best location to reset this member.
// However, in the current logic, it is the most convenient one.
this.refreshNeeded = false;
return true;
}
return this.width === undefined || this.labelModule.differentState(selected, hover);
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'initContextForDraw',
value: function initContextForDraw(ctx, values) {
var borderWidth = values.borderWidth / this.body.view.scale;
ctx.lineWidth = Math.min(this.width, borderWidth);
ctx.strokeStyle = values.borderColor;
ctx.fillStyle = values.color;
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'performStroke',
value: function performStroke(ctx, values) {
var borderWidth = values.borderWidth / this.body.view.scale;
//draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
ctx.save();
// if borders are zero width, they will be drawn with width 1 by default. This prevents that
if (borderWidth > 0) {
this.enableBorderDashes(ctx, values);
//draw the border
ctx.stroke();
//disable dashed border for other elements
this.disableBorderDashes(ctx, values);
}
ctx.restore();
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'performFill',
value: function performFill(ctx, values) {
// draw shadow if enabled
this.enableShadow(ctx, values);
// draw the background
ctx.fill();
// disable shadows for other elements.
this.disableShadow(ctx, values);
this.performStroke(ctx, values);
}
/**
*
* @param {number} margin
* @private
*/
}, {
key: '_addBoundingBoxMargin',
value: function _addBoundingBoxMargin(margin) {
this.boundingBox.left -= margin;
this.boundingBox.top -= margin;
this.boundingBox.bottom += margin;
this.boundingBox.right += margin;
}
/**
* Actual implementation of this method call.
*
* Doing it like this makes it easier to override
* in the child classes.
*
* @param {number} x width
* @param {number} y height
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
* @private
*/
}, {
key: '_updateBoundingBox',
value: function _updateBoundingBox(x, y, ctx, selected, hover) {
if (ctx !== undefined) {
this.resize(ctx, selected, hover);
}
this.left = x - this.width / 2;
this.top = y - this.height / 2;
this.boundingBox.left = this.left;
this.boundingBox.top = this.top;
this.boundingBox.bottom = this.top + this.height;
this.boundingBox.right = this.left + this.width;
}
/**
* Default implementation of this method call.
* This acts as a stub which can be overridden.
*
* @param {number} x width
* @param {number} y height
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} selected
* @param {boolean} hover
*/
}, {
key: 'updateBoundingBox',
value: function updateBoundingBox(x, y, ctx, selected, hover) {
this._updateBoundingBox(x, y, ctx, selected, hover);
}
/**
* Determine the dimensions to use for nodes with an internal label
*
* Currently, these are: Circle, Ellipse, Database, Box
* The other nodes have external labels, and will not call this method
*
* If there is no label, decent default values are supplied.
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
* @returns {{width:number, height:number}}
*/
}, {
key: 'getDimensionsFromLabel',
value: function getDimensionsFromLabel(ctx, selected, hover) {
// NOTE: previously 'textSize' was not put in 'this' for Ellipse
// TODO: examine the consequences.
this.textSize = this.labelModule.getTextSize(ctx, selected, hover);
var width = this.textSize.width;
var height = this.textSize.height;
var DEFAULT_SIZE = 14;
if (width === 0) {
// This happens when there is no label text set
width = DEFAULT_SIZE; // use a decent default
height = DEFAULT_SIZE; // if width zero, then height also always zero
}
return { width: width, height: height };
}
}]);
return NodeBase;
}();
exports['default'] = NodeBase;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = __webpack_require__(3);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(4);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(5);
var _inherits3 = _interopRequireDefault(_inherits2);
var _NodeBase2 = __webpack_require__(23);
var _NodeBase3 = _interopRequireDefault(_NodeBase2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Base class for constructing Node/Cluster Shapes.
*
* @extends NodeBase
*/
var ShapeBase = function (_NodeBase) {
(0, _inherits3['default'])(ShapeBase, _NodeBase);
/**
* @param {Object} options
* @param {Object} body
* @param {Label} labelModule
*/
function ShapeBase(options, body, labelModule) {
(0, _classCallCheck3['default'])(this, ShapeBase);
return (0, _possibleConstructorReturn3['default'])(this, (ShapeBase.__proto__ || (0, _getPrototypeOf2['default'])(ShapeBase)).call(this, options, body, labelModule));
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {boolean} [selected]
* @param {boolean} [hover]
* @param {Object} [values={size: this.options.size}]
*/
(0, _createClass3['default'])(ShapeBase, [{
key: 'resize',
value: function resize(ctx) {
var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { size: this.options.size };
if (this.needsRefresh(selected, hover)) {
this.labelModule.getTextSize(ctx, selected, hover);
var size = 2 * values.size;
this.width = size;
this.height = size;
this.radius = 0.5 * this.width;
}
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {string} shape
* @param {number} sizeMultiplier - Unused! TODO: Remove next major release
* @param {number} x
* @param {number} y
* @param {boolean} selected
* @param {boolean} hover
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
* @private
*/
}, {
key: '_drawShape',
value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover, values) {
this.resize(ctx, selected, hover, values);
this.left = x - this.width / 2;
this.top = y - this.height / 2;
this.initContextForDraw(ctx, values);
ctx[shape](x, y, values.size);
this.performFill(ctx, values);
if (this.options.label !== undefined) {
// Need to call following here in order to ensure value for `this.labelModule.size.height`
this.labelModule.calculateLabelSize(ctx, selected, hover, x, y, 'hanging');
var yLabel = y + 0.5 * this.height + 0.5 * this.labelModule.size.height;
this.labelModule.draw(ctx, x, yLabel, selected, hover, 'hanging');
}
this.updateBoundingBox(x, y);
}
/**
*
* @param {number} x
* @param {number} y
*/
}, {
key: 'updateBoundingBox',
value: function updateBoundingBox(x, y) {
this.boundingBox.top = y - this.options.size;
this.boundingBox.left = x - this.options.size;
this.boundingBox.right = x + this.options.size;
this.boundingBox.bottom = y + this.options.size;
if (this.options.label !== undefined && this.labelModule.size.width > 0) {
this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height);
}
}
}]);
return ShapeBase;
}(_NodeBase3['default']);
exports['default'] = ShapeBase;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(78);
var defined = __webpack_require__(51);
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(20);
var createDesc = __webpack_require__(39);
module.exports = __webpack_require__(21) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(32);
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 28 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(138), __esModule: true };
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _isIterable2 = __webpack_require__(188);
var _isIterable3 = _interopRequireDefault(_isIterable2);
var _getIterator2 = __webpack_require__(77);
var _getIterator3 = _interopRequireDefault(_getIterator2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if ((0, _isIterable3.default)(Object(arr))) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
/***/ }),
/* 31 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 32 */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(84);
var enumBugKeys = __webpack_require__(58);
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @prototype Point3d
* @param {number} [x]
* @param {number} [y]
* @param {number} [z]
*/
function Point3d(x, y, z) {
this.x = x !== undefined ? x : 0;
this.y = y !== undefined ? y : 0;
this.z = z !== undefined ? z : 0;
}
/**
* Subtract the two provided points, returns a-b
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} a-b
*/
Point3d.subtract = function (a, b) {
var sub = new Point3d();
sub.x = a.x - b.x;
sub.y = a.y - b.y;
sub.z = a.z - b.z;
return sub;
};
/**
* Add the two provided points, returns a+b
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} a+b
*/
Point3d.add = function (a, b) {
var sum = new Point3d();
sum.x = a.x + b.x;
sum.y = a.y + b.y;
sum.z = a.z + b.z;
return sum;
};
/**
* Calculate the average of two 3d points
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} The average, (a+b)/2
*/
Point3d.avg = function (a, b) {
return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2);
};
/**
* Calculate the cross product of the two provided points, returns axb
* Documentation: http://en.wikipedia.org/wiki/Cross_product
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} cross product axb
*/
Point3d.crossProduct = function (a, b) {
var crossproduct = new Point3d();
crossproduct.x = a.y * b.z - a.z * b.y;
crossproduct.y = a.z * b.x - a.x * b.z;
crossproduct.z = a.x * b.y - a.y * b.x;
return crossproduct;
};
/**
* Rtrieve the length of the vector (or the distance from this point to the origin
* @return {number} length
*/
Point3d.prototype.length = function () {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
module.exports = Point3d;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
/**
* Created by Alex on 11/6/2014.
*/
// https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
// if the module has no dependencies, the above pattern can be simplified to
(function (root, factory) {
if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.keycharm = factory();
}
}(this, function () {
function keycharm(options) {
var preventDefault = options && options.preventDefault || false;
var container = options && options.container || window;
var _exportFunctions = {};
var _bound = {keydown:{}, keyup:{}};
var _keys = {};
var i;
// a - z
for (i = 97; i <= 122; i++) {_keys[String.fromCharCode(i)] = {code:65 + (i - 97), shift: false};}
// A - Z
for (i = 65; i <= 90; i++) {_keys[String.fromCharCode(i)] = {code:i, shift: true};}
// 0 - 9
for (i = 0; i <= 9; i++) {_keys['' + i] = {code:48 + i, shift: false};}
// F1 - F12
for (i = 1; i <= 12; i++) {_keys['F' + i] = {code:111 + i, shift: false};}
// num0 - num9
for (i = 0; i <= 9; i++) {_keys['num' + i] = {code:96 + i, shift: false};}
// numpad misc
_keys['num*'] = {code:106, shift: false};
_keys['num+'] = {code:107, shift: false};
_keys['num-'] = {code:109, shift: false};
_keys['num/'] = {code:111, shift: false};
_keys['num.'] = {code:110, shift: false};
// arrows
_keys['left'] = {code:37, shift: false};
_keys['up'] = {code:38, shift: false};
_keys['right'] = {code:39, shift: false};
_keys['down'] = {code:40, shift: false};
// extra keys
_keys['space'] = {code:32, shift: false};
_keys['enter'] = {code:13, shift: false};
_keys['shift'] = {code:16, shift: undefined};
_keys['esc'] = {code:27, shift: false};
_keys['backspace'] = {code:8, shift: false};
_keys['tab'] = {code:9, shift: false};
_keys['ctrl'] = {code:17, shift: false};
_keys['alt'] = {code:18, shift: false};
_keys['delete'] = {code:46, shift: false};
_keys['pageup'] = {code:33, shift: false};
_keys['pagedown'] = {code:34, shift: false};
// symbols
_keys['='] = {code:187, shift: false};
_keys['-'] = {code:189, shift: false};
_keys[']'] = {code:221, shift: false};
_keys['['] = {code:219, shift: false};
var down = function(event) {handleEvent(event,'keydown');};
var up = function(event) {handleEvent(event,'keyup');};
// handle the actualy bound key with the event
var handleEvent = function(event,type) {
if (_bound[type][event.keyCode] !== undefined) {
var bound = _bound[type][event.keyCode];
for (var i = 0; i < bound.length; i++) {
if (bound[i].shift === undefined) {
bound[i].fn(event);
}
else if (bound[i].shift == true && event.shiftKey == true) {
bound[i].fn(event);
}
else if (bound[i].shift == false && event.shiftKey == false) {
bound[i].fn(event);
}
}
if (preventDefault == true) {
event.preventDefault();
}
}
};
// bind a key to a callback
_exportFunctions.bind = function(key, callback, type) {
if (type === undefined) {
type = 'keydown';
}
if (_keys[key] === undefined) {
throw new Error("unsupported key: " + key);
}
if (_bound[type][_keys[key].code] === undefined) {
_bound[type][_keys[key].code] = [];
}
_bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift});
};
// bind all keys to a call back (demo purposes)
_exportFunctions.bindAll = function(callback, type) {
if (type === undefined) {
type = 'keydown';
}
for (var key in _keys) {
if (_keys.hasOwnProperty(key)) {
_exportFunctions.bind(key,callback,type);
}
}
};
// get the key label from an event
_exportFunctions.getKey = function(event) {
for (var key in _keys) {
if (_keys.hasOwnProperty(key)) {
if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
return key;
}
else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
return key;
}
else if (event.keyCode == _keys[key].code && key == 'shift') {
return key;
}
}
}
return "unknown key, currently not supported";
};
// unbind either a specific callback from a key or all of them (by leaving callback undefined)
_exportFunctions.unbind = function(key, callback, type) {
if (type === undefined) {
type = 'keydown';
}
if (_keys[key] === undefined) {
throw new Error("unsupported key: " + key);
}
if (callback !== undefined) {
var newBindings = [];
var bound = _bound[type][_keys[key].code];
if (bound !== undefined) {
for (var i = 0; i < bound.length; i++) {
if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
newBindings.push(_bound[type][_keys[key].code][i]);
}
}
}
_bound[type][_keys[key].code] = newBindings;
}
else {
_bound[type][_keys[key].code] = [];
}
};
// reset all bound variables.
_exportFunctions.reset = function() {
_bound = {keydown:{}, keyup:{}};
};
// unbind all listeners and reset all variables.
_exportFunctions.destroy = function() {
_bound = {keydown:{}, keyup:{}};
container.removeEventListener('keydown', down, true);
container.removeEventListener('keyup', up, true);
};
// create listeners.
container.addEventListener('keydown',down,true);
container.addEventListener('keyup',up,true);
// return the public functions.
return _exportFunctions;
}
return keycharm;
}));
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* used in Core to convert the options into a volatile variable
*
* @param {function} moment
* @param {Object} body
* @param {Array | Object} hiddenDates
* @returns {number}
*/
exports.convertHiddenOptions = function (moment, body, hiddenDates) {
if (hiddenDates && !Array.isArray(hiddenDates)) {
return exports.convertHiddenOptions(moment, body, [hiddenDates]);
}
body.hiddenDates = [];
if (hiddenDates) {
if (Array.isArray(hiddenDates) == true) {
for (var i = 0; i < hiddenDates.length; i++) {
if (hiddenDates[i].repeat === undefined) {
var dateItem = {};
dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
body.hiddenDates.push(dateItem);
}
}
body.hiddenDates.sort(function (a, b) {
return a.start - b.start;
}); // sort by start time
}
}
};
/**
* create new entrees for the repeating hidden dates
*
* @param {function} moment
* @param {Object} body
* @param {Array | Object} hiddenDates
* @returns {null}
*/
exports.updateHiddenDates = function (moment, body, hiddenDates) {
if (hiddenDates && !Array.isArray(hiddenDates)) {
return exports.updateHiddenDates(moment, body, [hiddenDates]);
}
if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
exports.convertHiddenOptions(moment, body, hiddenDates);
var start = moment(body.range.start);
var end = moment(body.range.end);
var totalRange = body.range.end - body.range.start;
var pixelTime = totalRange / body.domProps.centerContainer.width;
for (var i = 0; i < hiddenDates.length; i++) {
if (hiddenDates[i].repeat !== undefined) {
var startDate = moment(hiddenDates[i].start);
var endDate = moment(hiddenDates[i].end);
if (startDate._d == "Invalid Date") {
throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
}
if (endDate._d == "Invalid Date") {
throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
}
var duration = endDate - startDate;
if (duration >= 4 * pixelTime) {
var offset = 0;
var runUntil = end.clone();
switch (hiddenDates[i].repeat) {
case "daily":
// case of time
if (startDate.day() != endDate.day()) {
offset = 1;
}
startDate.dayOfYear(start.dayOfYear());
startDate.year(start.year());
startDate.subtract(7, 'days');
endDate.dayOfYear(start.dayOfYear());
endDate.year(start.year());
endDate.subtract(7 - offset, 'days');
runUntil.add(1, 'weeks');
break;
case "weekly":
var dayOffset = endDate.diff(startDate, 'days');
var day = startDate.day();
// set the start date to the range.start
startDate.date(start.date());
startDate.month(start.month());
startDate.year(start.year());
endDate = startDate.clone();
// force
startDate.day(day);
endDate.day(day);
endDate.add(dayOffset, 'days');
startDate.subtract(1, 'weeks');
endDate.subtract(1, 'weeks');
runUntil.add(1, 'weeks');
break;
case "monthly":
if (startDate.month() != endDate.month()) {
offset = 1;
}
startDate.month(start.month());
startDate.year(start.year());
startDate.subtract(1, 'months');
endDate.month(start.month());
endDate.year(start.year());
endDate.subtract(1, 'months');
endDate.add(offset, 'months');
runUntil.add(1, 'months');
break;
case "yearly":
if (startDate.year() != endDate.year()) {
offset = 1;
}
startDate.year(start.year());
startDate.subtract(1, 'years');
endDate.year(start.year());
endDate.subtract(1, 'years');
endDate.add(offset, 'years');
runUntil.add(1, 'years');
break;
default:
console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
return;
}
while (startDate < runUntil) {
body.hiddenDates.push({ start: startDate.valueOf(), end: endDate.valueOf() });
switch (hiddenDates[i].repeat) {
case "daily":
startDate.add(1, 'days');
endDate.add(1, 'days');
break;
case "weekly":
startDate.add(1, 'weeks');
endDate.add(1, 'weeks');
break;
case "monthly":
startDate.add(1, 'months');
endDate.add(1, 'months');
break;
case "yearly":
startDate.add(1, 'y');
endDate.add(1, 'y');
break;
default:
console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
return;
}
}
body.hiddenDates.push({ start: startDate.valueOf(), end: endDate.valueOf() });
}
}
}
// remove duplicates, merge where possible
exports.removeDuplicates(body);
// ensure the new positions are not on hidden dates
var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
var endHidden = exports.isHidden(body.range.end, body.hiddenDates);
var rangeStart = body.range.start;
var rangeEnd = body.range.end;
if (startHidden.hidden == true) {
rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;
}
if (endHidden.hidden == true) {
rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;
}
if (startHidden.hidden == true || endHidden.hidden == true) {
body.range._applyRange(rangeStart, rangeEnd);
}
}
};
/**
* remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
* Scales with N^2
*
* @param {Object} body
*/
exports.removeDuplicates = function (body) {
var hiddenDates = body.hiddenDates;
var safeDates = [];
for (var i = 0; i < hiddenDates.length; i++) {
for (var j = 0; j < hiddenDates.length; j++) {
if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
// j inside i
if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
hiddenDates[j].remove = true;
}
// j start inside i
else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
hiddenDates[i].end = hiddenDates[j].end;
hiddenDates[j].remove = true;
}
// j end inside i
else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
hiddenDates[i].start = hiddenDates[j].start;
hiddenDates[j].remove = true;
}
}
}
}
for (i = 0; i < hiddenDates.length; i++) {
if (hiddenDates[i].remove !== true) {
safeDates.push(hiddenDates[i]);
}
}
body.hiddenDates = safeDates;
body.hiddenDates.sort(function (a, b) {
return a.start - b.start;
}); // sort by start time
};
exports.printDates = function (dates) {
for (var i = 0; i < dates.length; i++) {
console.log(i, new Date(dates[i].start), new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
}
};
/**
* Used in TimeStep to avoid the hidden times.
* @param {function} moment
* @param {TimeStep} timeStep
* @param {Date} previousTime
*/
exports.stepOverHiddenDates = function (moment, timeStep, previousTime) {
var stepInHidden = false;
var currentValue = timeStep.current.valueOf();
for (var i = 0; i < timeStep.hiddenDates.length; i++) {
var startDate = timeStep.hiddenDates[i].start;
var endDate = timeStep.hiddenDates[i].end;
if (currentValue >= startDate && currentValue < endDate) {
stepInHidden = true;
break;
}
}
if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
var prevValue = moment(previousTime);
var newValue = moment(endDate);
//check if the next step should be major
if (prevValue.year() != newValue.year()) {
timeStep.switchedYear = true;
} else if (prevValue.month() != newValue.month()) {
timeStep.switchedMonth = true;
} else if (prevValue.dayOfYear() != newValue.dayOfYear()) {
timeStep.switchedDay = true;
}
timeStep.current = newValue;
}
};
///**
// * Used in TimeStep to avoid the hidden times.
// * @param timeStep
// * @param previousTime
// */
//exports.checkFirstStep = function(timeStep) {
// var stepInHidden = false;
// var currentValue = timeStep.current.valueOf();
// for (var i = 0; i < timeStep.hiddenDates.length; i++) {
// var startDate = timeStep.hiddenDates[i].start;
// var endDate = timeStep.hiddenDates[i].end;
// if (currentValue >= startDate && currentValue < endDate) {
// stepInHidden = true;
// break;
// }
// }
//
// if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
// var newValue = moment(endDate);
// timeStep.current = newValue.toDate();
// }
//};
/**
* replaces the Core toScreen methods
*
* @param {vis.Core} Core
* @param {Date} time
* @param {number} width
* @returns {number}
*/
exports.toScreen = function (Core, time, width) {
var conversion;
if (Core.body.hiddenDates.length == 0) {
conversion = Core.range.conversion(width);
return (time.valueOf() - conversion.offset) * conversion.scale;
} else {
var hidden = exports.isHidden(time, Core.body.hiddenDates);
if (hidden.hidden == true) {
time = hidden.startDate;
}
var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
if (time < Core.range.start) {
conversion = Core.range.conversion(width, duration);
var hiddenBeforeStart = exports.getHiddenDurationBeforeStart(Core.body.hiddenDates, time, conversion.offset);
time = Core.options.moment(time).toDate().valueOf();
time = time + hiddenBeforeStart;
return -(conversion.offset - time.valueOf()) * conversion.scale;
} else if (time > Core.range.end) {
var rangeAfterEnd = { start: Core.range.start, end: time };
time = exports.correctTimeForHidden(Core.options.moment, Core.body.hiddenDates, rangeAfterEnd, time);
conversion = Core.range.conversion(width, duration);
return (time.valueOf() - conversion.offset) * conversion.scale;
} else {
time = exports.correctTimeForHidden(Core.options.moment, Core.body.hiddenDates, Core.range, time);
conversion = Core.range.conversion(width, duration);
return (time.valueOf() - conversion.offset) * conversion.scale;
}
}
};
/**
* Replaces the core toTime methods
*
* @param {vis.Core} Core
* @param {number} x
* @param {number} width
* @returns {Date}
*/
exports.toTime = function (Core, x, width) {
if (Core.body.hiddenDates.length == 0) {
var conversion = Core.range.conversion(width);
return new Date(x / conversion.scale + conversion.offset);
} else {
var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
var partialDuration = totalDuration * x / width;
var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
return new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
}
};
/**
* Support function
*
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {number} start
* @param {number} end
* @returns {number}
*/
exports.getHiddenDurationBetween = function (hiddenDates, start, end) {
var duration = 0;
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
// if time after the cutout, and the
if (startDate >= start && endDate < end) {
duration += endDate - startDate;
}
}
return duration;
};
/**
* Support function
*
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {number} start
* @param {number} end
* @returns {number}
*/
exports.getHiddenDurationBeforeStart = function (hiddenDates, start, end) {
var duration = 0;
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
if (startDate >= start && endDate <= end) {
duration += endDate - startDate;
}
}
return duration;
};
/**
* Support function
* @param {function} moment
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {{start: number, end: number}} range
* @param {Date} time
* @returns {number}
*/
exports.correctTimeForHidden = function (moment, hiddenDates, range, time) {
time = moment(time).toDate().valueOf();
time -= exports.getHiddenDurationBefore(moment, hiddenDates, range, time);
return time;
};
exports.getHiddenDurationBefore = function (moment, hiddenDates, range, time) {
var timeOffset = 0;
time = moment(time).toDate().valueOf();
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
// if time after the cutout, and the
if (startDate >= range.start && endDate < range.end) {
if (time >= endDate) {
timeOffset += endDate - startDate;
}
}
}
return timeOffset;
};
/**
* sum the duration from start to finish, including the hidden duration,
* until the required amount has been reached, return the accumulated hidden duration
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {{start: number, end: number}} range
* @param {number} [requiredDuration=0]
* @returns {number}
*/
exports.getAccumulatedHiddenDuration = function (hiddenDates, range, requiredDuration) {
var hiddenDuration = 0;
var duration = 0;
var previousPoint = range.start;
//exports.printDates(hiddenDates)
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
// if time after the cutout, and the
if (startDate >= range.start && endDate < range.end) {
duration += startDate - previousPoint;
previousPoint = endDate;
if (duration >= requiredDuration) {
break;
} else {
hiddenDuration += endDate - startDate;
}
}
}
return hiddenDuration;
};
/**
* used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @param {Date} time
* @param {number} direction
* @param {boolean} correctionEnabled
* @returns {Date|number}
*/
exports.snapAwayFromHidden = function (hiddenDates, time, direction, correctionEnabled) {
var isHidden = exports.isHidden(time, hiddenDates);
if (isHidden.hidden == true) {
if (direction < 0) {
if (correctionEnabled == true) {
return isHidden.startDate - (isHidden.endDate - time) - 1;
} else {
return isHidden.startDate - 1;
}
} else {
if (correctionEnabled == true) {
return isHidden.endDate + (time - isHidden.startDate) + 1;
} else {
return isHidden.endDate + 1;
}
}
} else {
return time;
}
};
/**
* Check if a time is hidden
*
* @param {Date} time
* @param {Array.<{start: Window.start, end: *}>} hiddenDates
* @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
*/
exports.isHidden = function (time, hiddenDates) {
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
if (time >= startDate && time < endDate) {
// if the start is entering a hidden zone
return { hidden: true, startDate: startDate, endDate: endDate };
}
}
return { hidden: false, startDate: startDate, endDate: endDate };
};
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Register a touch event, taking place before a gesture
* @param {Hammer} hammer A hammer instance
* @param {function} callback Callback, called as callback(event)
*/
exports.onTouch = function (hammer, callback) {
callback.inputHandler = function (event) {
if (event.isFirst) {
callback(event);
}
};
hammer.on('hammer.input', callback.inputHandler);
};
/**
* Register a release event, taking place after a gesture
* @param {Hammer} hammer A hammer instance
* @param {function} callback Callback, called as callback(event)
* @returns {*}
*/
exports.onRelease = function (hammer, callback) {
callback.inputHandler = function (event) {
if (event.isFinal) {
callback(event);
}
};
return hammer.on('hammer.input', callback.inputHandler);
};
/**
* Unregister a touch event, taking place before a gesture
* @param {Hammer} hammer A hammer instance
* @param {function} callback Callback, called as callback(event)
*/
exports.offTouch = function (hammer, callback) {
hammer.off('hammer.input', callback.inputHandler);
};
/**
* Unregister a release event, taking place before a gesture
* @param {Hammer} hammer A hammer instance
* @param {function} callback Callback, called as callback(event)
*/
exports.offRelease = exports.offTouch;
/**
* Hack the PinchRecognizer such that it doesn't prevent default behavior
* for vertical panning.
*
* Yeah ... this is quite a hack ... see https://github.com/hammerjs/hammer.js/issues/932
*
* @param {Hammer.Pinch} pinchRecognizer
* @return {Hammer.Pinch} returns the pinchRecognizer
*/
exports.disablePreventDefaultVertically = function (pinchRecognizer) {
var TOUCH_ACTION_PAN_Y = 'pan-y';
pinchRecognizer.getTouchAction = function () {
// default method returns [TOUCH_ACTION_NONE]
return [TOUCH_ACTION_PAN_Y];
};
return pinchRecognizer;
};
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Hammer = __webpack_require__(10);
var util = __webpack_require__(2);
var moment = __webpack_require__(9);
/**
* @constructor Item
* @param {Object} data Object containing (optional) parameters type,
* start, end, content, group, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} options Configuration options
* // TODO: describe available options
*/
function Item(data, conversion, options) {
this.id = null;
this.parent = null;
this.data = data;
this.dom = null;
this.conversion = conversion || {};
this.options = options || {};
this.selected = false;
this.displayed = false;
this.groupShowing = true;
this.dirty = true;
this.top = null;
this.right = null;
this.left = null;
this.width = null;
this.height = null;
this.editable = null;
this._updateEditStatus();
}
Item.prototype.stack = true;
/**
* Select current item
*/
Item.prototype.select = function () {
this.selected = true;
this.dirty = true;
if (this.displayed) this.redraw();
};
/**
* Unselect current item
*/
Item.prototype.unselect = function () {
this.selected = false;
this.dirty = true;
if (this.displayed) this.redraw();
};
/**
* Set data for the item. Existing data will be updated. The id should not
* be changed. When the item is displayed, it will be redrawn immediately.
* @param {Object} data
*/
Item.prototype.setData = function (data) {
var groupChanged = data.group != undefined && this.data.group != data.group;
if (groupChanged && this.parent != null) {
this.parent.itemSet._moveToGroup(this, data.group);
}
if (this.parent) {
this.parent.stackDirty = true;
}
var subGroupChanged = data.subgroup != undefined && this.data.subgroup != data.subgroup;
if (subGroupChanged && this.parent != null) {
this.parent.changeSubgroup(this, this.data.subgroup, data.subgroup);
}
this.data = data;
this._updateEditStatus();
this.dirty = true;
if (this.displayed) this.redraw();
};
/**
* Set a parent for the item
* @param {Group} parent
*/
Item.prototype.setParent = function (parent) {
if (this.displayed) {
this.hide();
this.parent = parent;
if (this.parent) {
this.show();
}
} else {
this.parent = parent;
}
};
/**
* Check whether this item is visible inside given range
* @param {vis.Range} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
Item.prototype.isVisible = function (range) {
// eslint-disable-line no-unused-vars
return false;
};
/**
* Show the Item in the DOM (when not already visible)
* @return {Boolean} changed
*/
Item.prototype.show = function () {
return false;
};
/**
* Hide the Item from the DOM (when visible)
* @return {Boolean} changed
*/
Item.prototype.hide = function () {
return false;
};
/**
* Repaint the item
*/
Item.prototype.redraw = function () {
// should be implemented by the item
};
/**
* Reposition the Item horizontally
*/
Item.prototype.repositionX = function () {
// should be implemented by the item
};
/**
* Reposition the Item vertically
*/
Item.prototype.repositionY = function () {
// should be implemented by the item
};
/**
* Repaint a drag area on the center of the item when the item is selected
* @protected
*/
Item.prototype._repaintDragCenter = function () {
if (this.selected && this.options.editable.updateTime && !this.dom.dragCenter) {
var me = this;
// create and show drag area
var dragCenter = document.createElement('div');
dragCenter.className = 'vis-drag-center';
dragCenter.dragCenterItem = this;
var hammer = new Hammer(dragCenter);
hammer.on('tap', function (event) {
me.parent.itemSet.body.emitter.emit('click', {
event: event,
item: me.id
});
});
hammer.on('doubletap', function (event) {
event.stopPropagation();
me.parent.itemSet._onUpdateItem(me);
me.parent.itemSet.body.emitter.emit('doubleClick', {
event: event,
item: me.id
});
});
if (this.dom.box) {
if (this.dom.dragLeft) {
this.dom.box.insertBefore(dragCenter, this.dom.dragLeft);
} else {
this.dom.box.appendChild(dragCenter);
}
} else if (this.dom.point) {
this.dom.point.appendChild(dragCenter);
}
this.dom.dragCenter = dragCenter;
} else if (!this.selected && this.dom.dragCenter) {
// delete drag area
if (this.dom.dragCenter.parentNode) {
this.dom.dragCenter.parentNode.removeChild(this.dom.dragCenter);
}
this.dom.dragCenter = null;
}
};
/**
* Repaint a delete button on the top right of the item when the item is selected
* @param {HTMLElement} anchor
* @protected
*/
Item.prototype._repaintDeleteButton = function (anchor) {
var editable = (this.options.editable.overrideItems || this.editable == null) && this.options.editable.remove || !this.options.editable.overrideItems && this.editable != null && this.editable.remove;
if (this.selected && editable && !this.dom.deleteButton) {
// create and show button
var me = this;
var deleteButton = document.createElement('div');
if (this.options.rtl) {
deleteButton.className = 'vis-delete-rtl';
} else {
deleteButton.className = 'vis-delete';
}
deleteButton.title = 'Delete this item';
// TODO: be able to destroy the delete button
new Hammer(deleteButton).on('tap', function (event) {
event.stopPropagation();
me.parent.removeFromDataSet(me);
});
anchor.appendChild(deleteButton);
this.dom.deleteButton = deleteButton;
} else if (!this.selected && this.dom.deleteButton) {
// remove button
if (this.dom.deleteButton.parentNode) {
this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
}
this.dom.deleteButton = null;
}
};
/**
* Repaint a onChange tooltip on the top right of the item when the item is selected
* @param {HTMLElement} anchor
* @protected
*/
Item.prototype._repaintOnItemUpdateTimeTooltip = function (anchor) {
if (!this.options.tooltipOnItemUpdateTime) return;
var editable = (this.options.editable.updateTime || this.data.editable === true) && this.data.editable !== false;
if (this.selected && editable && !this.dom.onItemUpdateTimeTooltip) {
var onItemUpdateTimeTooltip = document.createElement('div');
onItemUpdateTimeTooltip.className = 'vis-onUpdateTime-tooltip';
anchor.appendChild(onItemUpdateTimeTooltip);
this.dom.onItemUpdateTimeTooltip = onItemUpdateTimeTooltip;
} else if (!this.selected && this.dom.onItemUpdateTimeTooltip) {
// remove button
if (this.dom.onItemUpdateTimeTooltip.parentNode) {
this.dom.onItemUpdateTimeTooltip.parentNode.removeChild(this.dom.onItemUpdateTimeTooltip);
}
this.dom.onItemUpdateTimeTooltip = null;
}
// position onChange tooltip
if (this.dom.onItemUpdateTimeTooltip) {
// only show when editing
this.dom.onItemUpdateTimeTooltip.style.visibility = this.parent.itemSet.touchParams.itemIsDragging ? 'visible' : 'hidden';
// position relative to item's content
if (this.options.rtl) {
this.dom.onItemUpdateTimeTooltip.style.right = this.dom.content.style.right;
} else {
this.dom.onItemUpdateTimeTooltip.style.left = this.dom.content.style.left;
}
// position above or below the item depending on the item's position in the window
var tooltipOffset = 50; // TODO: should be tooltip height (depends on template)
var scrollTop = this.parent.itemSet.body.domProps.scrollTop;
// TODO: this.top for orientation:true is actually the items distance from the bottom...
// (should be this.bottom)
var itemDistanceFromTop;
if (this.options.orientation.item == 'top') {
itemDistanceFromTop = this.top;
} else {
itemDistanceFromTop = this.parent.height - this.top - this.height;
}
var isCloseToTop = itemDistanceFromTop + this.parent.top - tooltipOffset < -scrollTop;
if (isCloseToTop) {
this.dom.onItemUpdateTimeTooltip.style.bottom = "";
this.dom.onItemUpdateTimeTooltip.style.top = this.height + 2 + "px";
} else {
this.dom.onItemUpdateTimeTooltip.style.top = "";
this.dom.onItemUpdateTimeTooltip.style.bottom = this.height + 2 + "px";
}
// handle tooltip content
var content;
var templateFunction;
if (this.options.tooltipOnItemUpdateTime && this.options.tooltipOnItemUpdateTime.template) {
templateFunction = this.options.tooltipOnItemUpdateTime.template.bind(this);
content = templateFunction(this.data);
} else {
content = 'start: ' + moment(this.data.start).format('MM/DD/YYYY hh:mm');
if (this.data.end) {
content += ' end: ' + moment(this.data.end).format('MM/DD/YYYY hh:mm');
}
}
this.dom.onItemUpdateTimeTooltip.innerHTML = content;
}
};
/**
* Set HTML contents for the item
* @param {Element} element HTML element to fill with the contents
* @private
*/
Item.prototype._updateContents = function (element) {
var content;
var changed;
var templateFunction;
var itemVisibleFrameContent;
var visibleFrameTemplateFunction;
var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
var frameElement = this.dom.box || this.dom.point;
var itemVisibleFrameContentElement = frameElement.getElementsByClassName('vis-item-visible-frame')[0];
if (this.options.visibleFrameTemplate) {
visibleFrameTemplateFunction = this.options.visibleFrameTemplate.bind(this);
itemVisibleFrameContent = visibleFrameTemplateFunction(itemData, frameElement);
} else {
itemVisibleFrameContent = '';
}
if (itemVisibleFrameContentElement) {
if (itemVisibleFrameContent instanceof Object && !(itemVisibleFrameContent instanceof Element)) {
visibleFrameTemplateFunction(itemData, itemVisibleFrameContentElement);
} else {
changed = this._contentToString(this.itemVisibleFrameContent) !== this._contentToString(itemVisibleFrameContent);
if (changed) {
// only replace the content when changed
if (itemVisibleFrameContent instanceof Element) {
itemVisibleFrameContentElement.innerHTML = '';
itemVisibleFrameContentElement.appendChild(itemVisibleFrameContent);
} else if (itemVisibleFrameContent != undefined) {
itemVisibleFrameContentElement.innerHTML = itemVisibleFrameContent;
} else {
if (!(this.data.type == 'background' && this.data.content === undefined)) {
throw new Error('Property "content" missing in item ' + this.id);
}
}
this.itemVisibleFrameContent = itemVisibleFrameContent;
}
}
}
if (this.options.template) {
templateFunction = this.options.template.bind(this);
content = templateFunction(itemData, element, this.data);
} else {
content = this.data.content;
}
if (content instanceof Object && !(content instanceof Element)) {
templateFunction(itemData, element);
} else {
changed = this._contentToString(this.content) !== this._contentToString(content);
if (changed) {
// only replace the content when changed
if (content instanceof Element) {
element.innerHTML = '';
element.appendChild(content);
} else if (content != undefined) {
element.innerHTML = content;
} else {
if (!(this.data.type == 'background' && this.data.content === undefined)) {
throw new Error('Property "content" missing in item ' + this.id);
}
}
this.content = content;
}
}
};
/**
* Process dataAttributes timeline option and set as data- attributes on dom.content
* @param {Element} element HTML element to which the attributes will be attached
* @private
*/
Item.prototype._updateDataAttributes = function (element) {
if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
var attributes = [];
if (Array.isArray(this.options.dataAttributes)) {
attributes = this.options.dataAttributes;
} else if (this.options.dataAttributes == 'all') {
attributes = (0, _keys2['default'])(this.data);
} else {
return;
}
for (var i = 0; i < attributes.length; i++) {
var name = attributes[i];
var value = this.data[name];
if (value != null) {
element.setAttribute('data-' + name, value);
} else {
element.removeAttribute('data-' + name);
}
}
}
};
/**
* Update custom styles of the element
* @param {Element} element
* @private
*/
Item.prototype._updateStyle = function (element) {
// remove old styles
if (this.style) {
util.removeCssText(element, this.style);
this.style = null;
}
// append new styles
if (this.data.style) {
util.addCssText(element, this.data.style);
this.style = this.data.style;
}
};
/**
* Stringify the items contents
* @param {string | Element | undefined} content
* @returns {string | undefined}
* @private
*/
Item.prototype._contentToString = function (content) {
if (typeof content === 'string') return content;
if (content && 'outerHTML' in content) return content.outerHTML;
return content;
};
/**
* Update the editability of this item.
*/
Item.prototype._updateEditStatus = function () {
if (this.options) {
if (typeof this.options.editable === 'boolean') {
this.editable = {
updateTime: this.options.editable,
updateGroup: this.options.editable,
remove: this.options.editable
};
} else if ((0, _typeof3['default'])(this.options.editable) === 'object') {
this.editable = {};
util.selectiveExtend(['updateTime', 'updateGroup', 'remove'], this.editable, this.options.editable);
}
}
// Item data overrides, except if options.editable.overrideItems is set.
if (!this.options || !this.options.editable || this.options.editable.overrideItems !== true) {
if (this.data) {
if (typeof this.data.editable === 'boolean') {
this.editable = {
updateTime: this.data.editable,
updateGroup: this.data.editable,
remove: this.data.editable
};
} else if ((0, _typeof3['default'])(this.data.editable) === 'object') {
// TODO: in vis.js 5.0, we should change this to not reset options from the timeline configuration.
// Basically just remove the next line...
this.editable = {};
util.selectiveExtend(['updateTime', 'updateGroup', 'remove'], this.editable, this.data.editable);
}
}
}
};
/**
* Return the width of the item left from its start date
* @return {number}
*/
Item.prototype.getWidthLeft = function () {
return 0;
};
/**
* Return the width of the item right from the max of its start and end date
* @return {number}
*/
Item.prototype.getWidthRight = function () {
return 0;
};
/**
* Return the title of the item
* @return {string | undefined}
*/
Item.prototype.getTitle = function () {
return this.data.title;
};
module.exports = Item;
/***/ }),
/* 39 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 40 */
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(51);
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/* 42 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* A queue
* @param {Object} options
* Available options:
* - delay: number When provided, the queue will be flushed
* automatically after an inactivity of this delay
* in milliseconds.
* Default value is null.
* - max: number When the queue exceeds the given maximum number
* of entries, the queue is flushed automatically.
* Default value of max is Infinity.
* @constructor Queue
*/
function Queue(options) {
// options
this.delay = null;
this.max = Infinity;
// properties
this._queue = [];
this._timeout = null;
this._extended = null;
this.setOptions(options);
}
/**
* Update the configuration of the queue
* @param {Object} options
* Available options:
* - delay: number When provided, the queue will be flushed
* automatically after an inactivity of this delay
* in milliseconds.
* Default value is null.
* - max: number When the queue exceeds the given maximum number
* of entries, the queue is flushed automatically.
* Default value of max is Infinity.
*/
Queue.prototype.setOptions = function (options) {
if (options && typeof options.delay !== 'undefined') {
this.delay = options.delay;
}
if (options && typeof options.max !== 'undefined') {
this.max = options.max;
}
this._flushIfNeeded();
};
/**
* Extend an object with queuing functionality.
* The object will be extended with a function flush, and the methods provided
* in options.replace will be replaced with queued ones.
* @param {Object} object
* @param {Object} options
* Available options:
* - replace: Array.
* A list with method names of the methods
* on the object to be replaced with queued ones.
* - delay: number When provided, the queue will be flushed
* automatically after an inactivity of this delay
* in milliseconds.
* Default value is null.
* - max: number When the queue exceeds the given maximum number
* of entries, the queue is flushed automatically.
* Default value of max is Infinity.
* @return {Queue} Returns the created queue
*/
Queue.extend = function (object, options) {
var queue = new Queue(options);
if (object.flush !== undefined) {
throw new Error('Target object already has a property flush');
}
object.flush = function () {
queue.flush();
};
var methods = [{
name: 'flush',
original: undefined
}];
if (options && options.replace) {
for (var i = 0; i < options.replace.length; i++) {
var name = options.replace[i];
methods.push({
name: name,
original: object[name]
});
queue.replace(object, name);
}
}
queue._extended = {
object: object,
methods: methods
};
return queue;
};
/**
* Destroy the queue. The queue will first flush all queued actions, and in
* case it has extended an object, will restore the original object.
*/
Queue.prototype.destroy = function () {
this.flush();
if (this._extended) {
var object = this._extended.object;
var methods = this._extended.methods;
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
if (method.original) {
object[method.name] = method.original;
} else {
delete object[method.name];
}
}
this._extended = null;
}
};
/**
* Replace a method on an object with a queued version
* @param {Object} object Object having the method
* @param {string} method The method name
*/
Queue.prototype.replace = function (object, method) {
var me = this;
var original = object[method];
if (!original) {
throw new Error('Method ' + method + ' undefined');
}
object[method] = function () {
// create an Array with the arguments
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
// add this call to the queue
me.queue({
args: args,
fn: original,
context: this
});
};
};
/**
* Queue a call
* @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
*/
Queue.prototype.queue = function (entry) {
if (typeof entry === 'function') {
this._queue.push({ fn: entry });
} else {
this._queue.push(entry);
}
this._flushIfNeeded();
};
/**
* Check whether the queue needs to be flushed
* @private
*/
Queue.prototype._flushIfNeeded = function () {
// flush when the maximum is exceeded.
if (this._queue.length > this.max) {
this.flush();
}
// flush after a period of inactivity when a delay is configured
clearTimeout(this._timeout);
if (this.queue.length > 0 && typeof this.delay === 'number') {
var me = this;
this._timeout = setTimeout(function () {
me.flush();
}, this.delay);
}
};
/**
* Flush all queued calls
*/
Queue.prototype.flush = function () {
while (this._queue.length > 0) {
var entry = this._queue.shift();
entry.fn.apply(entry.context || entry.fn, entry.args || []);
}
};
module.exports = Queue;
/***/ }),
/* 44 */
/***/ (function(module, exports) {
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var Component = __webpack_require__(16);
var TimeStep = __webpack_require__(66);
var DateUtil = __webpack_require__(36);
var moment = __webpack_require__(9);
/**
* A horizontal time axis
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
* @param {Object} [options] See TimeAxis.setOptions for the available
* options.
* @constructor TimeAxis
* @extends Component
*/
function TimeAxis(body, options) {
this.dom = {
foreground: null,
lines: [],
majorTexts: [],
minorTexts: [],
redundant: {
lines: [],
majorTexts: [],
minorTexts: []
}
};
this.props = {
range: {
start: 0,
end: 0,
minimumStep: 0
},
lineTop: 0
};
this.defaultOptions = {
orientation: {
axis: 'bottom'
}, // axis orientation: 'top' or 'bottom'
showMinorLabels: true,
showMajorLabels: true,
maxMinorChars: 7,
format: TimeStep.FORMAT,
moment: moment,
timeAxis: null
};
this.options = util.extend({}, this.defaultOptions);
this.body = body;
// create the HTML DOM
this._create();
this.setOptions(options);
}
TimeAxis.prototype = new Component();
/**
* Set options for the TimeAxis.
* Parameters will be merged in current options.
* @param {Object} options Available options:
* {string} [orientation.axis]
* {boolean} [showMinorLabels]
* {boolean} [showMajorLabels]
*/
TimeAxis.prototype.setOptions = function (options) {
if (options) {
// copy all options that we know
util.selectiveExtend(['showMinorLabels', 'showMajorLabels', 'maxMinorChars', 'hiddenDates', 'timeAxis', 'moment', 'rtl'], this.options, options);
// deep copy the format options
util.selectiveDeepExtend(['format'], this.options, options);
if ('orientation' in options) {
if (typeof options.orientation === 'string') {
this.options.orientation.axis = options.orientation;
} else if ((0, _typeof3['default'])(options.orientation) === 'object' && 'axis' in options.orientation) {
this.options.orientation.axis = options.orientation.axis;
}
}
// apply locale to moment.js
// TODO: not so nice, this is applied globally to moment.js
if ('locale' in options) {
if (typeof moment.locale === 'function') {
// moment.js 2.8.1+
moment.locale(options.locale);
} else {
moment.lang(options.locale);
}
}
}
};
/**
* Create the HTML DOM for the TimeAxis
*/
TimeAxis.prototype._create = function () {
this.dom.foreground = document.createElement('div');
this.dom.background = document.createElement('div');
this.dom.foreground.className = 'vis-time-axis vis-foreground';
this.dom.background.className = 'vis-time-axis vis-background';
};
/**
* Destroy the TimeAxis
*/
TimeAxis.prototype.destroy = function () {
// remove from DOM
if (this.dom.foreground.parentNode) {
this.dom.foreground.parentNode.removeChild(this.dom.foreground);
}
if (this.dom.background.parentNode) {
this.dom.background.parentNode.removeChild(this.dom.background);
}
this.body = null;
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
TimeAxis.prototype.redraw = function () {
var props = this.props;
var foreground = this.dom.foreground;
var background = this.dom.background;
// determine the correct parent DOM element (depending on option orientation)
var parent = this.options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom;
var parentChanged = foreground.parentNode !== parent;
// calculate character width and height
this._calculateCharSize();
// TODO: recalculate sizes only needed when parent is resized or options is changed
var showMinorLabels = this.options.showMinorLabels && this.options.orientation.axis !== 'none';
var showMajorLabels = this.options.showMajorLabels && this.options.orientation.axis !== 'none';
// determine the width and height of the elemens for the axis
props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
props.height = props.minorLabelHeight + props.majorLabelHeight;
props.width = foreground.offsetWidth;
props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (this.options.orientation.axis == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
props.minorLineWidth = 1; // TODO: really calculate width
props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
props.majorLineWidth = 1; // TODO: really calculate width
// take foreground and background offline while updating (is almost twice as fast)
var foregroundNextSibling = foreground.nextSibling;
var backgroundNextSibling = background.nextSibling;
foreground.parentNode && foreground.parentNode.removeChild(foreground);
background.parentNode && background.parentNode.removeChild(background);
foreground.style.height = this.props.height + 'px';
this._repaintLabels();
// put DOM online again (at the same place)
if (foregroundNextSibling) {
parent.insertBefore(foreground, foregroundNextSibling);
} else {
parent.appendChild(foreground);
}
if (backgroundNextSibling) {
this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
} else {
this.body.dom.backgroundVertical.appendChild(background);
}
return this._isResized() || parentChanged;
};
/**
* Repaint major and minor text labels and vertical grid lines
* @private
*/
TimeAxis.prototype._repaintLabels = function () {
var orientation = this.options.orientation.axis;
// calculate range and step (step such that we have space for 7 characters per label)
var start = util.convert(this.body.range.start, 'Number');
var end = util.convert(this.body.range.end, 'Number');
var timeLabelsize = this.body.util.toTime((this.props.minorCharWidth || 10) * this.options.maxMinorChars).valueOf();
var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this.body.range, timeLabelsize);
minimumStep -= this.body.util.toTime(0).valueOf();
var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates, this.options);
step.setMoment(this.options.moment);
if (this.options.format) {
step.setFormat(this.options.format);
}
if (this.options.timeAxis) {
step.setScale(this.options.timeAxis);
}
this.step = step;
// Move all DOM elements to a "redundant" list, where they
// can be picked for re-use, and clear the lists with lines and texts.
// At the end of the function _repaintLabels, left over elements will be cleaned up
var dom = this.dom;
dom.redundant.lines = dom.lines;
dom.redundant.majorTexts = dom.majorTexts;
dom.redundant.minorTexts = dom.minorTexts;
dom.lines = [];
dom.majorTexts = [];
dom.minorTexts = [];
var current; // eslint-disable-line no-unused-vars
var next;
var x;
var xNext;
var isMajor;
var nextIsMajor; // eslint-disable-line no-unused-vars
var showMinorGrid;
var width = 0,
prevWidth;
var line;
var labelMinor;
var xFirstMajorLabel = undefined;
var count = 0;
var MAX = 1000;
var className;
step.start();
next = step.getCurrent();
xNext = this.body.util.toScreen(next);
while (step.hasNext() && count < MAX) {
count++;
isMajor = step.isMajor();
className = step.getClassName();
labelMinor = step.getLabelMinor();
current = next;
x = xNext;
step.next();
next = step.getCurrent();
nextIsMajor = step.isMajor();
xNext = this.body.util.toScreen(next);
prevWidth = width;
width = xNext - x;
switch (step.scale) {
case 'week':
showMinorGrid = true;break;
default:
showMinorGrid = width >= prevWidth * 0.4;break; // prevent displaying of the 31th of the month on a scale of 5 days
}
if (this.options.showMinorLabels && showMinorGrid) {
var label = this._repaintMinorText(x, labelMinor, orientation, className);
label.style.width = width + 'px'; // set width to prevent overflow
}
if (isMajor && this.options.showMajorLabels) {
if (x > 0) {
if (xFirstMajorLabel == undefined) {
xFirstMajorLabel = x;
}
label = this._repaintMajorText(x, step.getLabelMajor(), orientation, className);
}
line = this._repaintMajorLine(x, width, orientation, className);
} else {
// minor line
if (showMinorGrid) {
line = this._repaintMinorLine(x, width, orientation, className);
} else {
if (line) {
// adjust the width of the previous grid
line.style.width = parseInt(line.style.width) + width + 'px';
}
}
}
}
if (count === MAX && !warnedForOverflow) {
console.warn('Something is wrong with the Timeline scale. Limited drawing of grid lines to ' + MAX + ' lines.');
warnedForOverflow = true;
}
// create a major label on the left when needed
if (this.options.showMajorLabels) {
var leftTime = this.body.util.toTime(0),
leftText = step.getLabelMajor(leftTime),
widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
this._repaintMajorText(0, leftText, orientation, className);
}
}
// Cleanup leftover DOM elements from the redundant list
util.forEach(this.dom.redundant, function (arr) {
while (arr.length) {
var elem = arr.pop();
if (elem && elem.parentNode) {
elem.parentNode.removeChild(elem);
}
}
});
};
/**
* Create a minor label for the axis at position x
* @param {number} x
* @param {string} text
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the HTML element of the created label
* @private
*/
TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) {
// reuse redundant label
var label = this.dom.redundant.minorTexts.shift();
if (!label) {
// create new label
var content = document.createTextNode('');
label = document.createElement('div');
label.appendChild(content);
this.dom.foreground.appendChild(label);
}
this.dom.minorTexts.push(label);
label.innerHTML = text;
label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0';
if (this.options.rtl) {
label.style.left = "";
label.style.right = x + 'px';
} else {
label.style.left = x + 'px';
}
label.className = 'vis-text vis-minor ' + className;
//label.title = title; // TODO: this is a heavy operation
return label;
};
/**
* Create a Major label for the axis at position x
* @param {number} x
* @param {string} text
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the HTML element of the created label
* @private
*/
TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) {
// reuse redundant label
var label = this.dom.redundant.majorTexts.shift();
if (!label) {
// create label
var content = document.createElement('div');
label = document.createElement('div');
label.appendChild(content);
this.dom.foreground.appendChild(label);
}
label.childNodes[0].innerHTML = text;
label.className = 'vis-text vis-major ' + className;
//label.title = title; // TODO: this is a heavy operation
label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px';
if (this.options.rtl) {
label.style.left = "";
label.style.right = x + 'px';
} else {
label.style.left = x + 'px';
}
this.dom.majorTexts.push(label);
return label;
};
/**
* Create a minor line for the axis at position x
* @param {number} x
* @param {number} width
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the created line
* @private
*/
TimeAxis.prototype._repaintMinorLine = function (x, width, orientation, className) {
// reuse redundant line
var line = this.dom.redundant.lines.shift();
if (!line) {
// create vertical line
line = document.createElement('div');
this.dom.background.appendChild(line);
}
this.dom.lines.push(line);
var props = this.props;
if (orientation == 'top') {
line.style.top = props.majorLabelHeight + 'px';
} else {
line.style.top = this.body.domProps.top.height + 'px';
}
line.style.height = props.minorLineHeight + 'px';
if (this.options.rtl) {
line.style.left = "";
line.style.right = x - props.minorLineWidth / 2 + 'px';
line.className = 'vis-grid vis-vertical-rtl vis-minor ' + className;
} else {
line.style.left = x - props.minorLineWidth / 2 + 'px';
line.className = 'vis-grid vis-vertical vis-minor ' + className;
}
line.style.width = width + 'px';
return line;
};
/**
* Create a Major line for the axis at position x
* @param {number} x
* @param {number} width
* @param {string} orientation "top" or "bottom" (default)
* @param {string} className
* @return {Element} Returns the created line
* @private
*/
TimeAxis.prototype._repaintMajorLine = function (x, width, orientation, className) {
// reuse redundant line
var line = this.dom.redundant.lines.shift();
if (!line) {
// create vertical line
line = document.createElement('div');
this.dom.background.appendChild(line);
}
this.dom.lines.push(line);
var props = this.props;
if (orientation == 'top') {
line.style.top = '0';
} else {
line.style.top = this.body.domProps.top.height + 'px';
}
if (this.options.rtl) {
line.style.left = "";
line.style.right = x - props.majorLineWidth / 2 + 'px';
line.className = 'vis-grid vis-vertical-rtl vis-major ' + className;
} else {
line.style.left = x - props.majorLineWidth / 2 + 'px';
line.className = 'vis-grid vis-vertical vis-major ' + className;
}
line.style.height = props.majorLineHeight + 'px';
line.style.width = width + 'px';
return line;
};
/**
* Determine the size of text on the axis (both major and minor axis).
* The size is calculated only once and then cached in this.props.
* @private
*/
TimeAxis.prototype._calculateCharSize = function () {
// Note: We calculate char size with every redraw. Size may change, for
// example when any of the timelines parents had display:none for example.
// determine the char width and height on the minor axis
if (!this.dom.measureCharMinor) {
this.dom.measureCharMinor = document.createElement('DIV');
this.dom.measureCharMinor.className = 'vis-text vis-minor vis-measure';
this.dom.measureCharMinor.style.position = 'absolute';
this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
this.dom.foreground.appendChild(this.dom.measureCharMinor);
}
this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
// determine the char width and height on the major axis
if (!this.dom.measureCharMajor) {
this.dom.measureCharMajor = document.createElement('DIV');
this.dom.measureCharMajor.className = 'vis-text vis-major vis-measure';
this.dom.measureCharMajor.style.position = 'absolute';
this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
this.dom.foreground.appendChild(this.dom.measureCharMajor);
}
this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
};
var warnedForOverflow = false;
module.exports = TimeAxis;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Hammer = __webpack_require__(10);
var util = __webpack_require__(2);
var Component = __webpack_require__(16);
var moment = __webpack_require__(9);
var locales = __webpack_require__(98);
/**
* A custom time bar
* @param {{range: Range, dom: Object}} body
* @param {Object} [options] Available parameters:
* {number | string} id
* {string} locales
* {string} locale
* @constructor CustomTime
* @extends Component
*/
function CustomTime(body, options) {
this.body = body;
// default options
this.defaultOptions = {
moment: moment,
locales: locales,
locale: 'en',
id: undefined,
title: undefined
};
this.options = util.extend({}, this.defaultOptions);
if (options && options.time) {
this.customTime = options.time;
} else {
this.customTime = new Date();
}
this.eventParams = {}; // stores state parameters while dragging the bar
this.setOptions(options);
// create the DOM
this._create();
}
CustomTime.prototype = new Component();
/**
* Set options for the component. Options will be merged in current options.
* @param {Object} options Available parameters:
* {number | string} id
* {string} locales
* {string} locale
*/
CustomTime.prototype.setOptions = function (options) {
if (options) {
// copy all options that we know
util.selectiveExtend(['moment', 'locale', 'locales', 'id'], this.options, options);
}
};
/**
* Create the DOM for the custom time
* @private
*/
CustomTime.prototype._create = function () {
var bar = document.createElement('div');
bar['custom-time'] = this;
bar.className = 'vis-custom-time ' + (this.options.id || '');
bar.style.position = 'absolute';
bar.style.top = '0px';
bar.style.height = '100%';
this.bar = bar;
var drag = document.createElement('div');
drag.style.position = 'relative';
drag.style.top = '0px';
drag.style.left = '-10px';
drag.style.height = '100%';
drag.style.width = '20px';
/**
*
* @param {WheelEvent} e
*/
function onMouseWheel(e) {
this.body.range._onMouseWheel(e);
}
if (drag.addEventListener) {
// IE9, Chrome, Safari, Opera
drag.addEventListener("mousewheel", onMouseWheel.bind(this), false);
// Firefox
drag.addEventListener("DOMMouseScroll", onMouseWheel.bind(this), false);
} else {
// IE 6/7/8
drag.attachEvent("onmousewheel", onMouseWheel.bind(this));
}
bar.appendChild(drag);
// attach event listeners
this.hammer = new Hammer(drag);
this.hammer.on('panstart', this._onDragStart.bind(this));
this.hammer.on('panmove', this._onDrag.bind(this));
this.hammer.on('panend', this._onDragEnd.bind(this));
this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
};
/**
* Destroy the CustomTime bar
*/
CustomTime.prototype.destroy = function () {
this.hide();
this.hammer.destroy();
this.hammer = null;
this.body = null;
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
CustomTime.prototype.redraw = function () {
var parent = this.body.dom.backgroundVertical;
if (this.bar.parentNode != parent) {
// attach to the dom
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
parent.appendChild(this.bar);
}
var x = this.body.util.toScreen(this.customTime);
var locale = this.options.locales[this.options.locale];
if (!locale) {
if (!this.warned) {
console.log('WARNING: options.locales[\'' + this.options.locale + '\'] not found. See http://visjs.org/docs/timeline/#Localization');
this.warned = true;
}
locale = this.options.locales['en']; // fall back on english when not available
}
var title = this.options.title;
// To hide the title completely use empty string ''.
if (title === undefined) {
title = locale.time + ': ' + this.options.moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
title = title.charAt(0).toUpperCase() + title.substring(1);
} else if (typeof title === "function") {
title = title.call(this.customTime);
}
this.bar.style.left = x + 'px';
this.bar.title = title;
return false;
};
/**
* Remove the CustomTime from the DOM
*/
CustomTime.prototype.hide = function () {
// remove the line from the DOM
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
};
/**
* Set custom time.
* @param {Date | number | string} time
*/
CustomTime.prototype.setCustomTime = function (time) {
this.customTime = util.convert(time, 'Date');
this.redraw();
};
/**
* Retrieve the current custom time.
* @return {Date} customTime
*/
CustomTime.prototype.getCustomTime = function () {
return new Date(this.customTime.valueOf());
};
/**
* Set custom title.
* @param {Date | number | string} title
*/
CustomTime.prototype.setCustomTitle = function (title) {
this.options.title = title;
};
/**
* Start moving horizontally
* @param {Event} event
* @private
*/
CustomTime.prototype._onDragStart = function (event) {
this.eventParams.dragging = true;
this.eventParams.customTime = this.customTime;
event.stopPropagation();
};
/**
* Perform moving operating.
* @param {Event} event
* @private
*/
CustomTime.prototype._onDrag = function (event) {
if (!this.eventParams.dragging) return;
var x = this.body.util.toScreen(this.eventParams.customTime) + event.deltaX;
var time = this.body.util.toTime(x);
this.setCustomTime(time);
// fire a timechange event
this.body.emitter.emit('timechange', {
id: this.options.id,
time: new Date(this.customTime.valueOf()),
event: event
});
event.stopPropagation();
};
/**
* Stop moving operating.
* @param {Event} event
* @private
*/
CustomTime.prototype._onDragEnd = function (event) {
if (!this.eventParams.dragging) return;
// fire a timechanged event
this.body.emitter.emit('timechanged', {
id: this.options.id,
time: new Date(this.customTime.valueOf()),
event: event
});
event.stopPropagation();
};
/**
* Find a custom time from an event target:
* searches for the attribute 'custom-time' in the event target's element tree
* @param {Event} event
* @return {CustomTime | null} customTime
*/
CustomTime.customTimeFromTarget = function (event) {
var target = event.target;
while (target) {
if (target.hasOwnProperty('custom-time')) {
return target['custom-time'];
}
target = target.parentNode;
}
return null;
};
module.exports = CustomTime;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var Label = __webpack_require__(117)['default'];
var ComponentUtil = __webpack_require__(48)['default'];
var Box = __webpack_require__(193)['default'];
var Circle = __webpack_require__(200)['default'];
var CircularImage = __webpack_require__(201)['default'];
var Database = __webpack_require__(202)['default'];
var Diamond = __webpack_require__(203)['default'];
var Dot = __webpack_require__(204)['default'];
var Ellipse = __webpack_require__(205)['default'];
var Icon = __webpack_require__(206)['default'];
var Image = __webpack_require__(207)['default'];
var Square = __webpack_require__(208)['default'];
var Hexagon = __webpack_require__(209)['default'];
var Star = __webpack_require__(210)['default'];
var Text = __webpack_require__(211)['default'];
var Triangle = __webpack_require__(212)['default'];
var TriangleDown = __webpack_require__(213)['default'];
var _require = __webpack_require__(15),
printStyle = _require.printStyle;
/**
* A node. A node can be connected to other nodes via one or multiple edges.
*/
var Node = function () {
/**
*
* @param {object} options An object containing options for the node. All
* options are optional, except for the id.
* {number} id Id of the node. Required
* {string} label Text label for the node
* {number} x Horizontal position of the node
* {number} y Vertical position of the node
* {string} shape Node shape
* {string} image An image url
* {string} title A title text, can be HTML
* {anytype} group A group name or number
*
* @param {Object} body Shared state of current network instance
* @param {Network.Images} imagelist A list with images. Only needed when the node has an image
* @param {Groups} grouplist A list with groups. Needed for retrieving group options
* @param {Object} globalOptions Current global node options; these serve as defaults for the node instance
* @param {Object} defaultOptions Global default options for nodes; note that this is also the prototype
* for parameter `globalOptions`.
*/
function Node(options, body, imagelist, grouplist, globalOptions, defaultOptions) {
(0, _classCallCheck3['default'])(this, Node);
this.options = util.bridgeObject(globalOptions);
this.globalOptions = globalOptions;
this.defaultOptions = defaultOptions;
this.body = body;
this.edges = []; // all edges connected to this node
// set defaults for the options
this.id = undefined;
this.imagelist = imagelist;
this.grouplist = grouplist;
// state options
this.x = undefined;
this.y = undefined;
this.baseSize = this.options.size;
this.baseFontSize = this.options.font.size;
this.predefinedPosition = false; // used to check if initial fit should just take the range or approximate
this.selected = false;
this.hover = false;
this.labelModule = new Label(this.body, this.options, false /* Not edge label */);
this.setOptions(options);
}
/**
* Attach a edge to the node
* @param {Edge} edge
*/
(0, _createClass3['default'])(Node, [{
key: 'attachEdge',
value: function attachEdge(edge) {
if (this.edges.indexOf(edge) === -1) {
this.edges.push(edge);
}
}
/**
* Detach a edge from the node
*
* @param {Edge} edge
*/
}, {
key: 'detachEdge',
value: function detachEdge(edge) {
var index = this.edges.indexOf(edge);
if (index != -1) {
this.edges.splice(index, 1);
}
}
/**
* Set or overwrite options for the node
*
* @param {Object} options an object with options
* @returns {null|boolean}
*/
}, {
key: 'setOptions',
value: function setOptions(options) {
var currentShape = this.options.shape;
if (!options) {
return; // Note that the return value will be 'undefined'! This is OK.
}
// basic options
if (options.id !== undefined) {
this.id = options.id;
}
if (this.id === undefined) {
throw new Error("Node must have an id");
}
Node.checkMass(options, this.id);
// set these options locally
// clear x and y positions
if (options.x !== undefined) {
if (options.x === null) {
this.x = undefined;this.predefinedPosition = false;
} else {
this.x = parseInt(options.x);this.predefinedPosition = true;
}
}
if (options.y !== undefined) {
if (options.y === null) {
this.y = undefined;this.predefinedPosition = false;
} else {
this.y = parseInt(options.y);this.predefinedPosition = true;
}
}
if (options.size !== undefined) {
this.baseSize = options.size;
}
if (options.value !== undefined) {
options.value = parseFloat(options.value);
}
// this transforms all shorthands into fully defined options
Node.parseOptions(this.options, options, true, this.globalOptions, this.grouplist);
var pile = [options, this.options, this.defaultOptions];
this.chooser = ComponentUtil.choosify('node', pile);
this._load_images();
this.updateLabelModule(options);
this.updateShape(currentShape);
return options.hidden !== undefined || options.physics !== undefined;
}
/**
* Load the images from the options, for the nodes that need them.
*
* TODO: The imageObj members should be moved to CircularImageBase.
* It's the only place where they are required.
*
* @private
*/
}, {
key: '_load_images',
value: function _load_images() {
// Don't bother loading for nodes without images
if (this.options.shape !== 'circularImage' && this.options.shape !== 'image') {
return;
}
if (this.options.image === undefined) {
throw new Error("Option image must be defined for node type '" + this.options.shape + "'");
}
if (this.imagelist === undefined) {
throw new Error("Internal Error: No images provided");
}
if (typeof this.options.image === 'string') {
this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id);
} else {
if (this.options.image.unselected === undefined) {
throw new Error("No unselected image provided");
}
this.imageObj = this.imagelist.load(this.options.image.unselected, this.options.brokenImage, this.id);
if (this.options.image.selected !== undefined) {
this.imageObjAlt = this.imagelist.load(this.options.image.selected, this.options.brokenImage, this.id);
} else {
this.imageObjAlt = undefined;
}
}
}
/**
* Copy group option values into the node options.
*
* The group options override the global node options, so the copy of group options
* must happen *after* the global node options have been set.
*
* This method must also be called also if the global node options have changed and the group options did not.
*
* @param {Object} parentOptions
* @param {Object} newOptions new values for the options, currently only passed in for check
* @param {Object} groupList
*/
}, {
key: 'getFormattingValues',
/**
*
* @returns {{color: *, borderWidth: *, borderColor: *, size: *, borderDashes: (boolean|Array|allOptions.nodes.shapeProperties.borderDashes|{boolean, array}), borderRadius: (number|allOptions.nodes.shapeProperties.borderRadius|{number}|Array), shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *}}
*/
value: function getFormattingValues() {
var values = {
color: this.options.color.background,
borderWidth: this.options.borderWidth,
borderColor: this.options.color.border,
size: this.options.size,
borderDashes: this.options.shapeProperties.borderDashes,
borderRadius: this.options.shapeProperties.borderRadius,
shadow: this.options.shadow.enabled,
shadowColor: this.options.shadow.color,
shadowSize: this.options.shadow.size,
shadowX: this.options.shadow.x,
shadowY: this.options.shadow.y
};
if (this.selected || this.hover) {
if (this.chooser === true) {
if (this.selected) {
values.borderWidth *= 2;
values.color = this.options.color.highlight.background;
values.borderColor = this.options.color.highlight.border;
values.shadow = this.options.shadow.enabled;
} else if (this.hover) {
values.color = this.options.color.hover.background;
values.borderColor = this.options.color.hover.border;
values.shadow = this.options.shadow.enabled;
}
} else if (typeof this.chooser === 'function') {
this.chooser(values, this.options.id, this.selected, this.hover);
if (values.shadow === false) {
if (values.shadowColor !== this.options.shadow.color || values.shadowSize !== this.options.shadow.size || values.shadowX !== this.options.shadow.x || values.shadowY !== this.options.shadow.y) {
values.shadow = true;
}
}
}
} else {
values.shadow = this.options.shadow.enabled;
}
return values;
}
/**
*
* @param {Object} options
*/
}, {
key: 'updateLabelModule',
value: function updateLabelModule(options) {
if (this.options.label === undefined || this.options.label === null) {
this.options.label = '';
}
Node.updateGroupOptions(this.options, options, this.grouplist);
//
// Note:The prototype chain for this.options is:
//
// this.options -> NodesHandler.options -> NodesHandler.defaultOptions
// (also: this.globalOptions)
//
// Note that the prototypes are mentioned explicitly in the pile list below;
// WE DON'T WANT THE ORDER OF THE PROTOTYPES!!!! At least, not for font handling of labels.
// This is a good indication that the prototype usage of options is deficient.
//
var currentGroup = this.grouplist.get(this.options.group, false);
var pile = [options, // new options
this.options, // current node options, see comment above for prototype
currentGroup, // group options, if any
this.globalOptions, // Currently set global node options
this.defaultOptions // Default global node options
];
this.labelModule.update(this.options, pile);
if (this.labelModule.baseSize !== undefined) {
this.baseFontSize = this.labelModule.baseSize;
}
}
/**
*
* @param {string} currentShape
*/
}, {
key: 'updateShape',
value: function updateShape(currentShape) {
if (currentShape === this.options.shape && this.shape) {
this.shape.setOptions(this.options, this.imageObj, this.imageObjAlt);
} else {
// choose draw method depending on the shape
switch (this.options.shape) {
case 'box':
this.shape = new Box(this.options, this.body, this.labelModule);
break;
case 'circle':
this.shape = new Circle(this.options, this.body, this.labelModule);
break;
case 'circularImage':
this.shape = new CircularImage(this.options, this.body, this.labelModule, this.imageObj, this.imageObjAlt);
break;
case 'database':
this.shape = new Database(this.options, this.body, this.labelModule);
break;
case 'diamond':
this.shape = new Diamond(this.options, this.body, this.labelModule);
break;
case 'dot':
this.shape = new Dot(this.options, this.body, this.labelModule);
break;
case 'ellipse':
this.shape = new Ellipse(this.options, this.body, this.labelModule);
break;
case 'icon':
this.shape = new Icon(this.options, this.body, this.labelModule);
break;
case 'image':
this.shape = new Image(this.options, this.body, this.labelModule, this.imageObj, this.imageObjAlt);
break;
case 'square':
this.shape = new Square(this.options, this.body, this.labelModule);
break;
case 'hexagon':
this.shape = new Hexagon(this.options, this.body, this.labelModule);
break;
case 'star':
this.shape = new Star(this.options, this.body, this.labelModule);
break;
case 'text':
this.shape = new Text(this.options, this.body, this.labelModule);
break;
case 'triangle':
this.shape = new Triangle(this.options, this.body, this.labelModule);
break;
case 'triangleDown':
this.shape = new TriangleDown(this.options, this.body, this.labelModule);
break;
default:
this.shape = new Ellipse(this.options, this.body, this.labelModule);
break;
}
}
this.needsRefresh();
}
/**
* select this node
*/
}, {
key: 'select',
value: function select() {
this.selected = true;
this.needsRefresh();
}
/**
* unselect this node
*/
}, {
key: 'unselect',
value: function unselect() {
this.selected = false;
this.needsRefresh();
}
/**
* Reset the calculated size of the node, forces it to recalculate its size
*/
}, {
key: 'needsRefresh',
value: function needsRefresh() {
this.shape.refreshNeeded = true;
}
/**
* get the title of this node.
* @return {string} title The title of the node, or undefined when no title
* has been set.
*/
}, {
key: 'getTitle',
value: function getTitle() {
return this.options.title;
}
/**
* Calculate the distance to the border of the Node
* @param {CanvasRenderingContext2D} ctx
* @param {number} angle Angle in radians
* @returns {number} distance Distance to the border in pixels
*/
}, {
key: 'distanceToBorder',
value: function distanceToBorder(ctx, angle) {
return this.shape.distanceToBorder(ctx, angle);
}
/**
* Check if this node has a fixed x and y position
* @return {boolean} true if fixed, false if not
*/
}, {
key: 'isFixed',
value: function isFixed() {
return this.options.fixed.x && this.options.fixed.y;
}
/**
* check if this node is selecte
* @return {boolean} selected True if node is selected, else false
*/
}, {
key: 'isSelected',
value: function isSelected() {
return this.selected;
}
/**
* Retrieve the value of the node. Can be undefined
* @return {number} value
*/
}, {
key: 'getValue',
value: function getValue() {
return this.options.value;
}
/**
* Get the current dimensions of the label
*
* @return {rect}
*/
}, {
key: 'getLabelSize',
value: function getLabelSize() {
return this.labelModule.size();
}
/**
* Adjust the value range of the node. The node will adjust it's size
* based on its value.
* @param {number} min
* @param {number} max
* @param {number} total
*/
}, {
key: 'setValueRange',
value: function setValueRange(min, max, total) {
if (this.options.value !== undefined) {
var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
var sizeDiff = this.options.scaling.max - this.options.scaling.min;
if (this.options.scaling.label.enabled === true) {
var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
}
this.options.size = this.options.scaling.min + scale * sizeDiff;
} else {
this.options.size = this.baseSize;
this.options.font.size = this.baseFontSize;
}
this.updateLabelModule();
}
/**
* Draw this node in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
*/
}, {
key: 'draw',
value: function draw(ctx) {
var values = this.getFormattingValues();
this.shape.draw(ctx, this.x, this.y, this.selected, this.hover, values);
}
/**
* Update the bounding box of the shape
* @param {CanvasRenderingContext2D} ctx
*/
}, {
key: 'updateBoundingBox',
value: function updateBoundingBox(ctx) {
this.shape.updateBoundingBox(this.x, this.y, ctx);
}
/**
* Recalculate the size of this node in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
*/
}, {
key: 'resize',
value: function resize(ctx) {
var values = this.getFormattingValues();
this.shape.resize(ctx, this.selected, this.hover, values);
}
/**
* Determine all visual elements of this node instance, in which the given
* point falls within the bounding shape.
*
* @param {point} point
* @returns {Array.} list with the items which are on the point
*/
}, {
key: 'getItemsOnPoint',
value: function getItemsOnPoint(point) {
var ret = [];
if (this.labelModule.visible()) {
if (ComponentUtil.pointInRect(this.labelModule.getSize(), point)) {
ret.push({ nodeId: this.id, labelId: 0 });
}
}
if (ComponentUtil.pointInRect(this.shape.boundingBox, point)) {
ret.push({ nodeId: this.id });
}
return ret;
}
/**
* Check if this object is overlapping with the provided object
* @param {Object} obj an object with parameters left, top, right, bottom
* @return {boolean} True if location is located on node
*/
}, {
key: 'isOverlappingWith',
value: function isOverlappingWith(obj) {
return this.shape.left < obj.right && this.shape.left + this.shape.width > obj.left && this.shape.top < obj.bottom && this.shape.top + this.shape.height > obj.top;
}
/**
* Check if this object is overlapping with the provided object
* @param {Object} obj an object with parameters left, top, right, bottom
* @return {boolean} True if location is located on node
*/
}, {
key: 'isBoundingBoxOverlappingWith',
value: function isBoundingBoxOverlappingWith(obj) {
return this.shape.boundingBox.left < obj.right && this.shape.boundingBox.right > obj.left && this.shape.boundingBox.top < obj.bottom && this.shape.boundingBox.bottom > obj.top;
}
/**
* Check valid values for mass
*
* The mass may not be negative or zero. If it is, reset to 1
*
* @param {object} options
* @param {Node.id} id
* @static
*/
}], [{
key: 'updateGroupOptions',
value: function updateGroupOptions(parentOptions, newOptions, groupList) {
if (groupList === undefined) return; // No groups, nothing to do
var group = parentOptions.group;
// paranoia: the selected group is already merged into node options, check.
if (newOptions !== undefined && newOptions.group !== undefined && group !== newOptions.group) {
throw new Error("updateGroupOptions: group values in options don't match.");
}
var hasGroup = typeof group === 'number' || typeof group === 'string' && group != '';
if (!hasGroup) return; // current node has no group, no need to merge
var groupObj = groupList.get(group);
// Skip merging of group font options into parent; these are required to be distinct for labels
// TODO: It might not be a good idea either to merge the rest of the options, investigate this.
util.selectiveNotDeepExtend(['font'], parentOptions, groupObj);
// the color object needs to be completely defined.
// Since groups can partially overwrite the colors, we parse it again, just in case.
parentOptions.color = util.parseColor(parentOptions.color);
}
/**
* This process all possible shorthands in the new options and makes sure that the parentOptions are fully defined.
* Static so it can also be used by the handler.
*
* @param {Object} parentOptions
* @param {Object} newOptions
* @param {boolean} [allowDeletion=false]
* @param {Object} [globalOptions={}]
* @param {Object} [groupList]
* @static
*/
}, {
key: 'parseOptions',
value: function parseOptions(parentOptions, newOptions) {
var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var groupList = arguments[4];
var fields = ['color', 'fixed', 'shadow'];
util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion);
Node.checkMass(newOptions);
// merge the shadow options into the parent.
util.mergeOptions(parentOptions, newOptions, 'shadow', globalOptions);
// individual shape newOptions
if (newOptions.color !== undefined && newOptions.color !== null) {
var parsedColor = util.parseColor(newOptions.color);
util.fillIfDefined(parentOptions.color, parsedColor);
} else if (allowDeletion === true && newOptions.color === null) {
parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
}
// handle the fixed options
if (newOptions.fixed !== undefined && newOptions.fixed !== null) {
if (typeof newOptions.fixed === 'boolean') {
parentOptions.fixed.x = newOptions.fixed;
parentOptions.fixed.y = newOptions.fixed;
} else {
if (newOptions.fixed.x !== undefined && typeof newOptions.fixed.x === 'boolean') {
parentOptions.fixed.x = newOptions.fixed.x;
}
if (newOptions.fixed.y !== undefined && typeof newOptions.fixed.y === 'boolean') {
parentOptions.fixed.y = newOptions.fixed.y;
}
}
}
if (allowDeletion === true && newOptions.font === null) {
parentOptions.font = util.bridgeObject(globalOptions.font); // set the object back to the global options
}
Node.updateGroupOptions(parentOptions, newOptions, groupList);
// handle the scaling options, specifically the label part
if (newOptions.scaling !== undefined) {
util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', globalOptions.scaling);
}
}
}, {
key: 'checkMass',
value: function checkMass(options, id) {
if (options.mass !== undefined && options.mass <= 0) {
var strId = '';
if (id !== undefined) {
strId = ' in node id: ' + id;
}
console.log('%cNegative or zero mass disallowed' + strId + ', setting mass to 1.', printStyle);
options.mass = 1;
}
}
}]);
return Node;
}();
exports['default'] = Node;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Definitions for param's in jsdoc.
* These are more or less global within Network. Putting them here until I can figure out
* where to really put them
*
* @typedef {string|number} Id
* @typedef {Id} NodeId
* @typedef {Id} EdgeId
* @typedef {Id} LabelId
*
* @typedef {{x: number, y: number}} point
* @typedef {{left: number, top: number, width: number, height: number}} rect
* @typedef {{x: number, y:number, angle: number}} rotationPoint
* - point to rotate around and the angle in radians to rotate. angle == 0 means no rotation
* @typedef {{nodeId:NodeId}} nodeClickItem
* @typedef {{nodeId:NodeId, labelId:LabelId}} nodeLabelClickItem
* @typedef {{edgeId:EdgeId}} edgeClickItem
* @typedef {{edgeId:EdgeId, labelId:LabelId}} edgeLabelClickItem
*/
var util = __webpack_require__(2);
/**
* Helper functions for components
* @class
*/
var ComponentUtil = function () {
function ComponentUtil() {
(0, _classCallCheck3['default'])(this, ComponentUtil);
}
(0, _createClass3['default'])(ComponentUtil, null, [{
key: 'choosify',
/**
* Determine values to use for (sub)options of 'chosen'.
*
* This option is either a boolean or an object whose values should be examined further.
* The relevant structures are:
*
* - chosen:
* - chosen: { subOption: }
*
* Where subOption is 'node', 'edge' or 'label'.
*
* The intention of this method appears to be to set a specific priority to the options;
* Since most properties are either bridged or merged into the local options objects, there
* is not much point in handling them separately.
* TODO: examine if 'most' in previous sentence can be replaced with 'all'. In that case, we
* should be able to get rid of this method.
*
* @param {string} subOption option within object 'chosen' to consider; either 'node', 'edge' or 'label'
* @param {Object} pile array of options objects to consider
*
* @return {boolean|function} value for passed subOption of 'chosen' to use
*/
value: function choosify(subOption, pile) {
// allowed values for subOption
var allowed = ['node', 'edge', 'label'];
var value = true;
var chosen = util.topMost(pile, 'chosen');
if (typeof chosen === 'boolean') {
value = chosen;
} else if ((typeof chosen === 'undefined' ? 'undefined' : (0, _typeof3['default'])(chosen)) === 'object') {
if (allowed.indexOf(subOption) === -1) {
throw new Error('choosify: subOption \'' + subOption + '\' should be one of ' + "'" + allowed.join("', '") + "'");
}
var chosenEdge = util.topMost(pile, ['chosen', subOption]);
if (typeof chosenEdge === 'boolean' || typeof chosenEdge === 'function') {
value = chosenEdge;
}
}
return value;
}
/**
* Check if the point falls within the given rectangle.
*
* @param {rect} rect
* @param {point} point
* @param {rotationPoint} [rotationPoint] if specified, the rotation that applies to the rectangle.
* @returns {boolean} true if point within rectangle, false otherwise
* @static
*/
}, {
key: 'pointInRect',
value: function pointInRect(rect, point, rotationPoint) {
if (rect.width <= 0 || rect.height <= 0) {
return false; // early out
}
if (rotationPoint !== undefined) {
// Rotate the point the same amount as the rectangle
var tmp = {
x: point.x - rotationPoint.x,
y: point.y - rotationPoint.y
};
if (rotationPoint.angle !== 0) {
// In order to get the coordinates the same, you need to
// rotate in the reverse direction
var angle = -rotationPoint.angle;
var tmp2 = {
x: Math.cos(angle) * tmp.x - Math.sin(angle) * tmp.y,
y: Math.sin(angle) * tmp.x + Math.cos(angle) * tmp.y
};
point = tmp2;
} else {
point = tmp;
}
// Note that if a rotation is specified, the rectangle coordinates
// are **not* the full canvas coordinates. They are relative to the
// rotationPoint. Hence, the point coordinates need not be translated
// back in this case.
}
var right = rect.x + rect.width;
var bottom = rect.y + rect.width;
return rect.left < point.x && right > point.x && rect.top < point.y && bottom > point.y;
}
/**
* Check if given value is acceptable as a label text.
*
* @param {*} text value to check; can be anything at this point
* @returns {boolean} true if valid label value, false otherwise
*/
}, {
key: 'isValidLabel',
value: function isValidLabel(text) {
// Note that this is quite strict: types that *might* be converted to string are disallowed
return typeof text === 'string' && text !== '';
}
}]);
return ComponentUtil;
}();
exports['default'] = ComponentUtil;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(125);
var global = __webpack_require__(18);
var hide = __webpack_require__(26);
var Iterators = __webpack_require__(31);
var TO_STRING_TAG = __webpack_require__(13)('toStringTag');
var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
'TextTrackList,TouchList').split(',');
for (var i = 0; i < DOMIterables.length; i++) {
var NAME = DOMIterables[i];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
/***/ }),
/* 50 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 51 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 52 */
/***/ (function(module, exports) {
module.exports = true;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(32);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(27);
var dPs = __webpack_require__(130);
var enumBugKeys = __webpack_require__(58);
var IE_PROTO = __webpack_require__(56)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(82)('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__(134).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 55 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(57)('keys');
var uid = __webpack_require__(40);
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(18);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
module.exports = function (key) {
return store[key] || (store[key] = {});
};
/***/ }),
/* 58 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__(20).f;
var has = __webpack_require__(22);
var TAG = __webpack_require__(13)('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__(135)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(79)(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(13);
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(18);
var core = __webpack_require__(7);
var LIBRARY = __webpack_require__(52);
var wksExt = __webpack_require__(61);
var defineProperty = __webpack_require__(20).f;
module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
/***/ }),
/* 63 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
var _stringify = __webpack_require__(19);
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var moment = __webpack_require__(9);
var Component = __webpack_require__(16);
var DateUtil = __webpack_require__(36);
/**
* A Range controls a numeric range with a start and end value.
* The Range adjusts the range based on mouse events or programmatic changes,
* and triggers events when the range is changing or has been changed.
* @param {{dom: Object, domProps: Object, emitter: Emitter}} body
* @param {Object} [options] See description at Range.setOptions
* @constructor Range
* @extends Component
*/
function Range(body, options) {
var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
var start = now.clone().add(-3, 'days').valueOf();
var end = now.clone().add(3, 'days').valueOf();
this.millisecondsPerPixelCache = undefined;
if (options === undefined) {
this.start = start;
this.end = end;
} else {
this.start = options.start || start;
this.end = options.end || end;
}
this.rolling = false;
this.body = body;
this.deltaDifference = 0;
this.scaleOffset = 0;
this.startToFront = false;
this.endToFront = true;
// default options
this.defaultOptions = {
rtl: false,
start: null,
end: null,
moment: moment,
direction: 'horizontal', // 'horizontal' or 'vertical'
moveable: true,
zoomable: true,
min: null,
max: null,
zoomMin: 10, // milliseconds
zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
rollingMode: {
follow: false,
offset: 0.5
}
};
this.options = util.extend({}, this.defaultOptions);
this.props = {
touch: {}
};
this.animationTimer = null;
// drag listeners for dragging
this.body.emitter.on('panstart', this._onDragStart.bind(this));
this.body.emitter.on('panmove', this._onDrag.bind(this));
this.body.emitter.on('panend', this._onDragEnd.bind(this));
// mouse wheel for zooming
this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
// pinch to zoom
this.body.emitter.on('touch', this._onTouch.bind(this));
this.body.emitter.on('pinch', this._onPinch.bind(this));
// on click of rolling mode button
this.body.dom.rollingModeBtn.addEventListener('click', this.startRolling.bind(this));
this.setOptions(options);
}
Range.prototype = new Component();
/**
* Set options for the range controller
* @param {Object} options Available options:
* {number | Date | String} start Start date for the range
* {number | Date | String} end End date for the range
* {number} min Minimum value for start
* {number} max Maximum value for end
* {number} zoomMin Set a minimum value for
* (end - start).
* {number} zoomMax Set a maximum value for
* (end - start).
* {boolean} moveable Enable moving of the range
* by dragging. True by default
* {boolean} zoomable Enable zooming of the range
* by pinching/scrolling. True by default
*/
Range.prototype.setOptions = function (options) {
if (options) {
// copy the options that we know
var fields = ['animation', 'direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'moment', 'activate', 'hiddenDates', 'zoomKey', 'rtl', 'showCurrentTime', 'rollingMode', 'horizontalScroll'];
util.selectiveExtend(fields, this.options, options);
if (options.rollingMode && options.rollingMode.follow) {
this.startRolling();
}
if ('start' in options || 'end' in options) {
// apply a new range. both start and end are optional
this.setRange(options.start, options.end);
}
}
};
/**
* Test whether direction has a valid value
* @param {string} direction 'horizontal' or 'vertical'
*/
function validateDirection(direction) {
if (direction != 'horizontal' && direction != 'vertical') {
throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".');
}
}
/**
* Start auto refreshing the current time bar
*/
Range.prototype.startRolling = function () {
var me = this;
/**
* Updates the current time.
*/
function update() {
me.stopRolling();
me.rolling = true;
var interval = me.end - me.start;
var t = util.convert(new Date(), 'Date').valueOf();
var start = t - interval * me.options.rollingMode.offset;
var end = t + interval * (1 - me.options.rollingMode.offset);
var options = {
animation: false
};
me.setRange(start, end, options);
// determine interval to refresh
var scale = me.conversion(me.body.domProps.center.width).scale;
interval = 1 / scale / 10;
if (interval < 30) interval = 30;
if (interval > 1000) interval = 1000;
me.body.dom.rollingModeBtn.style.visibility = "hidden";
// start a renderTimer to adjust for the new time
me.currentTimeTimer = setTimeout(update, interval);
}
update();
};
/**
* Stop auto refreshing the current time bar
*/
Range.prototype.stopRolling = function () {
if (this.currentTimeTimer !== undefined) {
clearTimeout(this.currentTimeTimer);
this.rolling = false;
this.body.dom.rollingModeBtn.style.visibility = "visible";
}
};
/**
* Set a new start and end range
* @param {Date | number | string} [start]
* @param {Date | number | string} [end]
* @param {Object} options Available options:
* {boolean | {duration: number, easingFunction: string}} [animation=false]
* If true, the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* {boolean} [byUser=false]
* {Event} event Mouse event
* @param {Function} callback a callback function to be executed at the end of this function
* @param {Function} frameCallback a callback function executed each frame of the range animation.
* The callback will be passed three parameters:
* {number} easeCoefficient an easing coefficent
* {boolean} willDraw If true the caller will redraw after the callback completes
* {boolean} done If true then animation is ending after the current frame
*/
Range.prototype.setRange = function (start, end, options, callback, frameCallback) {
if (!options) {
options = {};
}
if (options.byUser !== true) {
options.byUser = false;
}
var me = this;
var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null;
var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null;
this._cancelAnimation();
this.millisecondsPerPixelCache = undefined;
if (options.animation) {
// true or an Object
var initStart = this.start;
var initEnd = this.end;
var duration = (0, _typeof3['default'])(options.animation) === 'object' && 'duration' in options.animation ? options.animation.duration : 500;
var easingName = (0, _typeof3['default'])(options.animation) === 'object' && 'easingFunction' in options.animation ? options.animation.easingFunction : 'easeInOutQuad';
var easingFunction = util.easingFunctions[easingName];
if (!easingFunction) {
throw new Error('Unknown easing function ' + (0, _stringify2['default'])(easingName) + '. ' + 'Choose from: ' + (0, _keys2['default'])(util.easingFunctions).join(', '));
}
var initTime = new Date().valueOf();
var anyChanged = false;
var next = function next() {
if (!me.props.touch.dragging) {
var now = new Date().valueOf();
var time = now - initTime;
var ease = easingFunction(time / duration);
var done = time > duration;
var s = done || finalStart === null ? finalStart : initStart + (finalStart - initStart) * ease;
var e = done || finalEnd === null ? finalEnd : initEnd + (finalEnd - initEnd) * ease;
changed = me._applyRange(s, e);
DateUtil.updateHiddenDates(me.options.moment, me.body, me.options.hiddenDates);
anyChanged = anyChanged || changed;
var params = {
start: new Date(me.start),
end: new Date(me.end),
byUser: options.byUser,
event: options.event
};
if (frameCallback) {
frameCallback(ease, changed, done);
}
if (changed) {
me.body.emitter.emit('rangechange', params);
}
if (done) {
if (anyChanged) {
me.body.emitter.emit('rangechanged', params);
if (callback) {
return callback();
}
}
} else {
// animate with as high as possible frame rate, leave 20 ms in between
// each to prevent the browser from blocking
me.animationTimer = setTimeout(next, 20);
}
}
};
return next();
} else {
var changed = this._applyRange(finalStart, finalEnd);
DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
if (changed) {
var params = {
start: new Date(this.start),
end: new Date(this.end),
byUser: options.byUser,
event: options.event
};
this.body.emitter.emit('rangechange', params);
clearTimeout(me.timeoutID);
me.timeoutID = setTimeout(function () {
me.body.emitter.emit('rangechanged', params);
}, 200);
if (callback) {
return callback();
}
}
}
};
/**
* Get the number of milliseconds per pixel.
*
* @returns {undefined|number}
*/
Range.prototype.getMillisecondsPerPixel = function () {
if (this.millisecondsPerPixelCache === undefined) {
this.millisecondsPerPixelCache = (this.end - this.start) / this.body.dom.center.clientWidth;
}
return this.millisecondsPerPixelCache;
};
/**
* Stop an animation
* @private
*/
Range.prototype._cancelAnimation = function () {
if (this.animationTimer) {
clearTimeout(this.animationTimer);
this.animationTimer = null;
}
};
/**
* Set a new start and end range. This method is the same as setRange, but
* does not trigger a range change and range changed event, and it returns
* true when the range is changed
* @param {number} [start]
* @param {number} [end]
* @return {boolean} changed
* @private
*/
Range.prototype._applyRange = function (start, end) {
var newStart = start != null ? util.convert(start, 'Date').valueOf() : this.start,
newEnd = end != null ? util.convert(end, 'Date').valueOf() : this.end,
max = this.options.max != null ? util.convert(this.options.max, 'Date').valueOf() : null,
min = this.options.min != null ? util.convert(this.options.min, 'Date').valueOf() : null,
diff;
// check for valid number
if (isNaN(newStart) || newStart === null) {
throw new Error('Invalid start "' + start + '"');
}
if (isNaN(newEnd) || newEnd === null) {
throw new Error('Invalid end "' + end + '"');
}
// prevent end < start
if (newEnd < newStart) {
newEnd = newStart;
}
// prevent start < min
if (min !== null) {
if (newStart < min) {
diff = min - newStart;
newStart += diff;
newEnd += diff;
// prevent end > max
if (max != null) {
if (newEnd > max) {
newEnd = max;
}
}
}
}
// prevent end > max
if (max !== null) {
if (newEnd > max) {
diff = newEnd - max;
newStart -= diff;
newEnd -= diff;
// prevent start < min
if (min != null) {
if (newStart < min) {
newStart = min;
}
}
}
}
// prevent (end-start) < zoomMin
if (this.options.zoomMin !== null) {
var zoomMin = parseFloat(this.options.zoomMin);
if (zoomMin < 0) {
zoomMin = 0;
}
if (newEnd - newStart < zoomMin) {
// compensate for a scale of 0.5 ms
var compensation = 0.5;
if (this.end - this.start === zoomMin && newStart >= this.start - compensation && newEnd <= this.end) {
// ignore this action, we are already zoomed to the minimum
newStart = this.start;
newEnd = this.end;
} else {
// zoom to the minimum
diff = zoomMin - (newEnd - newStart);
newStart -= diff / 2;
newEnd += diff / 2;
}
}
}
// prevent (end-start) > zoomMax
if (this.options.zoomMax !== null) {
var zoomMax = parseFloat(this.options.zoomMax);
if (zoomMax < 0) {
zoomMax = 0;
}
if (newEnd - newStart > zoomMax) {
if (this.end - this.start === zoomMax && newStart < this.start && newEnd > this.end) {
// ignore this action, we are already zoomed to the maximum
newStart = this.start;
newEnd = this.end;
} else {
// zoom to the maximum
diff = newEnd - newStart - zoomMax;
newStart += diff / 2;
newEnd -= diff / 2;
}
}
}
var changed = this.start != newStart || this.end != newEnd;
// if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
if (!(newStart >= this.start && newStart <= this.end || newEnd >= this.start && newEnd <= this.end) && !(this.start >= newStart && this.start <= newEnd || this.end >= newStart && this.end <= newEnd)) {
this.body.emitter.emit('checkRangedItems');
}
this.start = newStart;
this.end = newEnd;
return changed;
};
/**
* Retrieve the current range.
* @return {Object} An object with start and end properties
*/
Range.prototype.getRange = function () {
return {
start: this.start,
end: this.end
};
};
/**
* Calculate the conversion offset and scale for current range, based on
* the provided width
* @param {number} width
* @param {number} [totalHidden=0]
* @returns {{offset: number, scale: number}} conversion
*/
Range.prototype.conversion = function (width, totalHidden) {
return Range.conversion(this.start, this.end, width, totalHidden);
};
/**
* Static method to calculate the conversion offset and scale for a range,
* based on the provided start, end, and width
* @param {number} start
* @param {number} end
* @param {number} width
* @param {number} [totalHidden=0]
* @returns {{offset: number, scale: number}} conversion
*/
Range.conversion = function (start, end, width, totalHidden) {
if (totalHidden === undefined) {
totalHidden = 0;
}
if (width != 0 && end - start != 0) {
return {
offset: start,
scale: width / (end - start - totalHidden)
};
} else {
return {
offset: 0,
scale: 1
};
}
};
/**
* Start dragging horizontally or vertically
* @param {Event} event
* @private
*/
Range.prototype._onDragStart = function (event) {
this.deltaDifference = 0;
this.previousDelta = 0;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// only start dragging when the mouse is inside the current range
if (!this._isInsideRange(event)) return;
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
this.stopRolling();
this.props.touch.start = this.start;
this.props.touch.end = this.end;
this.props.touch.dragging = true;
if (this.body.dom.root) {
this.body.dom.root.style.cursor = 'move';
}
};
/**
* Perform dragging operation
* @param {Event} event
* @private
*/
Range.prototype._onDrag = function (event) {
if (!event) return;
if (!this.props.touch.dragging) return;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// TODO: this may be redundant in hammerjs2
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
var direction = this.options.direction;
validateDirection(direction);
var delta = direction == 'horizontal' ? event.deltaX : event.deltaY;
delta -= this.deltaDifference;
var interval = this.props.touch.end - this.props.touch.start;
// normalize dragging speed if cutout is in between.
var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
interval -= duration;
var width = direction == 'horizontal' ? this.body.domProps.center.width : this.body.domProps.center.height;
var diffRange;
if (this.options.rtl) {
diffRange = delta / width * interval;
} else {
diffRange = -delta / width * interval;
}
var newStart = this.props.touch.start + diffRange;
var newEnd = this.props.touch.end + diffRange;
// snapping times away from hidden zones
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta - delta, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta - delta, true);
if (safeStart != newStart || safeEnd != newEnd) {
this.deltaDifference += delta;
this.props.touch.start = safeStart;
this.props.touch.end = safeEnd;
this._onDrag(event);
return;
}
this.previousDelta = delta;
this._applyRange(newStart, newEnd);
var startDate = new Date(this.start);
var endDate = new Date(this.end);
// fire a rangechange event
this.body.emitter.emit('rangechange', {
start: startDate,
end: endDate,
byUser: true,
event: event
});
// fire a panmove event
this.body.emitter.emit('panmove');
};
/**
* Stop dragging operation
* @param {event} event
* @private
*/
Range.prototype._onDragEnd = function (event) {
if (!this.props.touch.dragging) return;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// TODO: this may be redundant in hammerjs2
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
this.props.touch.dragging = false;
if (this.body.dom.root) {
this.body.dom.root.style.cursor = 'auto';
}
// fire a rangechanged event
this.body.emitter.emit('rangechanged', {
start: new Date(this.start),
end: new Date(this.end),
byUser: true,
event: event
});
};
/**
* Event handler for mouse wheel event, used to zoom
* Code from http://adomas.org/javascript-mouse-wheel/
* @param {Event} event
* @private
*/
Range.prototype._onMouseWheel = function (event) {
// retrieve delta
var delta = 0;
if (event.wheelDelta) {
/* IE/Opera. */
delta = event.wheelDelta / 120;
} else if (event.detail) {
/* Mozilla case. */
// In Mozilla, sign of delta is different than in IE.
// Also, delta is multiple of 3.
delta = -event.detail / 3;
}
// don't allow zoom when the according key is pressed and the zoomKey option or not zoomable but movable
if (this.options.zoomKey && !event[this.options.zoomKey] && this.options.zoomable || !this.options.zoomable && this.options.moveable) {
return;
}
// only allow zooming when configured as zoomable and moveable
if (!(this.options.zoomable && this.options.moveable)) return;
// only zoom when the mouse is inside the current range
if (!this._isInsideRange(event)) return;
// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if (delta) {
// perform the zoom action. Delta is normally 1 or -1
// adjust a negative delta such that zooming in with delta 0.1
// equals zooming out with a delta -0.1
var scale;
if (delta < 0) {
scale = 1 - delta / 5;
} else {
scale = 1 / (1 + delta / 5);
}
// calculate center, the date to zoom around
var pointerDate;
if (this.rolling) {
pointerDate = this.start + (this.end - this.start) * this.options.rollingMode.offset;
} else {
var pointer = this.getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center);
pointerDate = this._pointerToDate(pointer);
}
this.zoom(scale, pointerDate, delta, event);
// Prevent default actions caused by mouse wheel
// (else the page and timeline both scroll)
event.preventDefault();
}
};
/**
* Start of a touch gesture
* @param {Event} event
* @private
*/
Range.prototype._onTouch = function (event) {
// eslint-disable-line no-unused-vars
this.props.touch.start = this.start;
this.props.touch.end = this.end;
this.props.touch.allowDragging = true;
this.props.touch.center = null;
this.scaleOffset = 0;
this.deltaDifference = 0;
// Disable the browser default handling of this event.
util.preventDefault(event);
};
/**
* Handle pinch event
* @param {Event} event
* @private
*/
Range.prototype._onPinch = function (event) {
// only allow zooming when configured as zoomable and moveable
if (!(this.options.zoomable && this.options.moveable)) return;
// Disable the browser default handling of this event.
util.preventDefault(event);
this.props.touch.allowDragging = false;
if (!this.props.touch.center) {
this.props.touch.center = this.getPointer(event.center, this.body.dom.center);
}
this.stopRolling();
var scale = 1 / (event.scale + this.scaleOffset);
var centerDate = this._pointerToDate(this.props.touch.center);
var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, centerDate);
var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
// calculate new start and end
var newStart = centerDate - hiddenDurationBefore + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
var newEnd = centerDate + hiddenDurationAfter + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
// snapping times away from hidden zones
this.startToFront = 1 - scale <= 0; // used to do the right auto correction with periodic hidden times
this.endToFront = scale - 1 <= 0; // used to do the right auto correction with periodic hidden times
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
if (safeStart != newStart || safeEnd != newEnd) {
this.props.touch.start = safeStart;
this.props.touch.end = safeEnd;
this.scaleOffset = 1 - event.scale;
newStart = safeStart;
newEnd = safeEnd;
}
var options = {
animation: false,
byUser: true,
event: event
};
this.setRange(newStart, newEnd, options);
this.startToFront = false; // revert to default
this.endToFront = true; // revert to default
};
/**
* Test whether the mouse from a mouse event is inside the visible window,
* between the current start and end date
* @param {Object} event
* @return {boolean} Returns true when inside the visible window
* @private
*/
Range.prototype._isInsideRange = function (event) {
// calculate the time where the mouse is, check whether inside
// and no scroll action should happen.
var clientX = event.center ? event.center.x : event.clientX;
var x;
if (this.options.rtl) {
x = clientX - util.getAbsoluteLeft(this.body.dom.centerContainer);
} else {
x = util.getAbsoluteRight(this.body.dom.centerContainer) - clientX;
}
var time = this.body.util.toTime(x);
return time >= this.start && time <= this.end;
};
/**
* Helper function to calculate the center date for zooming
* @param {{x: number, y: number}} pointer
* @return {number} date
* @private
*/
Range.prototype._pointerToDate = function (pointer) {
var conversion;
var direction = this.options.direction;
validateDirection(direction);
if (direction == 'horizontal') {
return this.body.util.toTime(pointer.x).valueOf();
} else {
var height = this.body.domProps.center.height;
conversion = this.conversion(height);
return pointer.y / conversion.scale + conversion.offset;
}
};
/**
* Get the pointer location relative to the location of the dom element
* @param {{x: number, y: number}} touch
* @param {Element} element HTML DOM element
* @return {{x: number, y: number}} pointer
* @private
*/
Range.prototype.getPointer = function (touch, element) {
if (this.options.rtl) {
return {
x: util.getAbsoluteRight(element) - touch.x,
y: touch.y - util.getAbsoluteTop(element)
};
} else {
return {
x: touch.x - util.getAbsoluteLeft(element),
y: touch.y - util.getAbsoluteTop(element)
};
}
};
/**
* Zoom the range the given scale in or out. Start and end date will
* be adjusted, and the timeline will be redrawn. You can optionally give a
* date around which to zoom.
* For example, try scale = 0.9 or 1.1
* @param {number} scale Scaling factor. Values above 1 will zoom out,
* values below 1 will zoom in.
* @param {number} [center] Value representing a date around which will
* be zoomed.
* @param {number} delta
* @param {Event} event
*/
Range.prototype.zoom = function (scale, center, delta, event) {
// if centerDate is not provided, take it half between start Date and end Date
if (center == null) {
center = (this.start + this.end) / 2;
}
var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, center);
var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
// calculate new start and end
var newStart = center - hiddenDurationBefore + (this.start - (center - hiddenDurationBefore)) * scale;
var newEnd = center + hiddenDurationAfter + (this.end - (center + hiddenDurationAfter)) * scale;
// snapping times away from hidden zones
this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
if (safeStart != newStart || safeEnd != newEnd) {
newStart = safeStart;
newEnd = safeEnd;
}
var options = {
animation: false,
byUser: true,
event: event
};
this.setRange(newStart, newEnd, options);
this.startToFront = false; // revert to default
this.endToFront = true; // revert to default
};
/**
* Move the range with a given delta to the left or right. Start and end
* value will be adjusted. For example, try delta = 0.1 or -0.1
* @param {number} delta Moving amount. Positive value will move right,
* negative value will move left
*/
Range.prototype.move = function (delta) {
// zoom start Date and end Date relative to the centerDate
var diff = this.end - this.start;
// apply new values
var newStart = this.start + diff * delta;
var newEnd = this.end + diff * delta;
// TODO: reckon with min and max range
this.start = newStart;
this.end = newEnd;
};
/**
* Move the range to a new center point
* @param {number} moveTo New center point of the range
*/
Range.prototype.moveTo = function (moveTo) {
var center = (this.start + this.end) / 2;
var diff = center - moveTo;
// calculate new start and end
var newStart = this.start - diff;
var newEnd = this.end - diff;
var options = {
animation: false,
byUser: true,
event: null
};
this.setRange(newStart, newEnd, options);
};
module.exports = Range;
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _stringify = __webpack_require__(19);
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Emitter = __webpack_require__(44);
var Hammer = __webpack_require__(10);
var hammerUtil = __webpack_require__(37);
var util = __webpack_require__(2);
var TimeAxis = __webpack_require__(45);
var Activator = __webpack_require__(97);
var DateUtil = __webpack_require__(36);
var CustomTime = __webpack_require__(46);
/**
* Create a timeline visualization
* @constructor Core
*/
function Core() {}
// turn Core into an event emitter
Emitter(Core.prototype);
/**
* Create the main DOM for the Core: a root panel containing left, right,
* top, bottom, content, and background panel.
* @param {Element} container The container element where the Core will
* be attached.
* @protected
*/
Core.prototype._create = function (container) {
this.dom = {};
this.dom.container = container;
this.dom.root = document.createElement('div');
this.dom.background = document.createElement('div');
this.dom.backgroundVertical = document.createElement('div');
this.dom.backgroundHorizontal = document.createElement('div');
this.dom.centerContainer = document.createElement('div');
this.dom.leftContainer = document.createElement('div');
this.dom.rightContainer = document.createElement('div');
this.dom.center = document.createElement('div');
this.dom.left = document.createElement('div');
this.dom.right = document.createElement('div');
this.dom.top = document.createElement('div');
this.dom.bottom = document.createElement('div');
this.dom.shadowTop = document.createElement('div');
this.dom.shadowBottom = document.createElement('div');
this.dom.shadowTopLeft = document.createElement('div');
this.dom.shadowBottomLeft = document.createElement('div');
this.dom.shadowTopRight = document.createElement('div');
this.dom.shadowBottomRight = document.createElement('div');
this.dom.rollingModeBtn = document.createElement('div');
this.dom.root.className = 'vis-timeline';
this.dom.background.className = 'vis-panel vis-background';
this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
this.dom.centerContainer.className = 'vis-panel vis-center';
this.dom.leftContainer.className = 'vis-panel vis-left';
this.dom.rightContainer.className = 'vis-panel vis-right';
this.dom.top.className = 'vis-panel vis-top';
this.dom.bottom.className = 'vis-panel vis-bottom';
this.dom.left.className = 'vis-content';
this.dom.center.className = 'vis-content';
this.dom.right.className = 'vis-content';
this.dom.shadowTop.className = 'vis-shadow vis-top';
this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
this.dom.shadowTopRight.className = 'vis-shadow vis-top';
this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
this.dom.rollingModeBtn.className = 'vis-rolling-mode-btn';
this.dom.root.appendChild(this.dom.background);
this.dom.root.appendChild(this.dom.backgroundVertical);
this.dom.root.appendChild(this.dom.backgroundHorizontal);
this.dom.root.appendChild(this.dom.centerContainer);
this.dom.root.appendChild(this.dom.leftContainer);
this.dom.root.appendChild(this.dom.rightContainer);
this.dom.root.appendChild(this.dom.top);
this.dom.root.appendChild(this.dom.bottom);
this.dom.root.appendChild(this.dom.bottom);
this.dom.root.appendChild(this.dom.rollingModeBtn);
this.dom.centerContainer.appendChild(this.dom.center);
this.dom.leftContainer.appendChild(this.dom.left);
this.dom.rightContainer.appendChild(this.dom.right);
this.dom.centerContainer.appendChild(this.dom.shadowTop);
this.dom.centerContainer.appendChild(this.dom.shadowBottom);
this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
// size properties of each of the panels
this.props = {
root: {},
background: {},
centerContainer: {},
leftContainer: {},
rightContainer: {},
center: {},
left: {},
right: {},
top: {},
bottom: {},
border: {},
scrollTop: 0,
scrollTopMin: 0
};
this.on('rangechange', function () {
if (this.initialDrawDone === true) {
this._redraw();
}
}.bind(this));
this.on('rangechanged', function () {
if (!this.initialRangeChangeDone) {
this.initialRangeChangeDone = true;
}
}.bind(this));
this.on('touch', this._onTouch.bind(this));
this.on('panmove', this._onDrag.bind(this));
var me = this;
this._origRedraw = this._redraw.bind(this);
this._redraw = util.throttle(this._origRedraw);
this.on('_change', function (properties) {
if (me.itemSet && me.itemSet.initialItemSetDrawn && properties && properties.queue == true) {
me._redraw();
} else {
me._origRedraw();
}
});
// create event listeners for all interesting events, these events will be
// emitted via emitter
this.hammer = new Hammer(this.dom.root);
var pinchRecognizer = this.hammer.get('pinch').set({ enable: true });
hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
this.listeners = {};
var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend'
// TODO: cleanup
//'touch', 'pinch',
//'tap', 'doubletap', 'hold',
//'dragstart', 'drag', 'dragend',
//'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
];
events.forEach(function (type) {
var listener = function listener(event) {
if (me.isActive()) {
me.emit(type, event);
}
};
me.hammer.on(type, listener);
me.listeners[type] = listener;
});
// emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
hammerUtil.onTouch(this.hammer, function (event) {
me.emit('touch', event);
}.bind(this));
// emulate a release event (emitted after a pan, pinch, tap, or press)
hammerUtil.onRelease(this.hammer, function (event) {
me.emit('release', event);
}.bind(this));
/**
*
* @param {WheelEvent} event
*/
function onMouseWheel(event) {
if (this.isActive()) {
this.emit('mousewheel', event);
}
// deltaX and deltaY normalization from jquery.mousewheel.js
var deltaX = 0;
var deltaY = 0;
// Old school scrollwheel delta
if ('detail' in event) {
deltaY = event.detail * -1;
}
if ('wheelDelta' in event) {
deltaY = event.wheelDelta;
}
if ('wheelDeltaY' in event) {
deltaY = event.wheelDeltaY;
}
if ('wheelDeltaX' in event) {
deltaX = event.wheelDeltaX * -1;
}
// Firefox < 17 horizontal scrolling related to DOMMouseScroll event
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
deltaX = deltaY * -1;
deltaY = 0;
}
// New school wheel delta (wheel event)
if ('deltaY' in event) {
deltaY = event.deltaY * -1;
}
if ('deltaX' in event) {
deltaX = event.deltaX;
}
// prevent scrolling when zoomKey defined or activated
if (!this.options.zoomKey || event[this.options.zoomKey]) return;
// Prevent default actions caused by mouse wheel
// (else the page and timeline both scroll)
event.preventDefault();
if (this.options.verticalScroll && Math.abs(deltaY) >= Math.abs(deltaX)) {
var current = this.props.scrollTop;
var adjusted = current + deltaY;
if (this.isActive()) {
this._setScrollTop(adjusted);
this._redraw();
this.emit('scroll', event);
}
} else if (this.options.horizontalScroll) {
var delta = Math.abs(deltaX) >= Math.abs(deltaY) ? deltaX : deltaY;
// calculate a single scroll jump relative to the range scale
var diff = delta / 120 * (this.range.end - this.range.start) / 20;
// calculate new start and end
var newStart = this.range.start + diff;
var newEnd = this.range.end + diff;
var options = {
animation: false,
byUser: true,
event: event
};
this.range.setRange(newStart, newEnd, options);
}
}
if (this.dom.centerContainer.addEventListener) {
// IE9, Chrome, Safari, Opera
this.dom.centerContainer.addEventListener("mousewheel", onMouseWheel.bind(this), false);
// Firefox
this.dom.centerContainer.addEventListener("DOMMouseScroll", onMouseWheel.bind(this), false);
} else {
// IE 6/7/8
this.dom.centerContainer.attachEvent("onmousewheel", onMouseWheel.bind(this));
}
/**
*
* @param {scroll} event
*/
function onMouseScrollSide(event) {
if (!me.options.verticalScroll) return;
event.preventDefault();
if (me.isActive()) {
var adjusted = -event.target.scrollTop;
me._setScrollTop(adjusted);
me._redraw();
me.emit('scrollSide', event);
}
}
this.dom.left.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
this.dom.right.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
var itemAddedToTimeline = false;
/**
*
* @param {dragover} event
* @returns {boolean}
*/
function handleDragOver(event) {
if (event.preventDefault) {
event.preventDefault(); // Necessary. Allows us to drop.
}
// make sure your target is a vis element
if (!event.target.className.indexOf("vis") > -1) return;
// make sure only one item is added every time you're over the timeline
if (itemAddedToTimeline) return;
event.dataTransfer.dropEffect = 'move';
itemAddedToTimeline = true;
return false;
}
/**
*
* @param {drop} event
* @returns {boolean}
*/
function handleDrop(event) {
// prevent redirect to blank page - Firefox
if (event.preventDefault) {
event.preventDefault();
}
if (event.stopPropagation) {
event.stopPropagation();
}
// return when dropping non-vis items
try {
var itemData = JSON.parse(event.dataTransfer.getData("text"));
if (!itemData || !itemData.content) return;
} catch (err) {
return false;
}
itemAddedToTimeline = false;
event.center = {
x: event.clientX,
y: event.clientY
};
if (itemData.target !== 'item') {
me.itemSet._onAddItem(event);
} else {
me.itemSet._onDropObjectOnItem(event);
}
me.emit('drop', me.getEventProperties(event));
return false;
}
this.dom.center.addEventListener('dragover', handleDragOver.bind(this), false);
this.dom.center.addEventListener('drop', handleDrop.bind(this), false);
this.customTimes = [];
// store state information needed for touch events
this.touch = {};
this.redrawCount = 0;
this.initialDrawDone = false;
this.initialRangeChangeDone = false;
// attach the root panel to the provided container
if (!container) throw new Error('No container provided');
container.appendChild(this.dom.root);
};
/**
* Set options. Options will be passed to all components loaded in the Timeline.
* @param {Object} [options]
* {String} orientation
* Vertical orientation for the Timeline,
* can be 'bottom' (default) or 'top'.
* {string | number} width
* Width for the timeline, a number in pixels or
* a css string like '1000px' or '75%'. '100%' by default.
* {string | number} height
* Fixed height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'. If undefined,
* The Timeline will automatically size such that
* its contents fit.
* {string | number} minHeight
* Minimum height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'.
* {string | number} maxHeight
* Maximum height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'.
* {number | Date | string} start
* Start date for the visible window
* {number | Date | string} end
* End date for the visible window
*/
Core.prototype.setOptions = function (options) {
if (options) {
// copy the known options
var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates', 'locale', 'locales', 'moment', 'rtl', 'zoomKey', 'horizontalScroll', 'verticalScroll'];
util.selectiveExtend(fields, this.options, options);
this.dom.rollingModeBtn.style.visibility = 'hidden';
if (this.options.rtl) {
this.dom.container.style.direction = "rtl";
this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical-rtl';
}
if (this.options.verticalScroll) {
if (this.options.rtl) {
this.dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
} else {
this.dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
}
}
if ((0, _typeof3['default'])(this.options.orientation) !== 'object') {
this.options.orientation = { item: undefined, axis: undefined };
}
if ('orientation' in options) {
if (typeof options.orientation === 'string') {
this.options.orientation = {
item: options.orientation,
axis: options.orientation
};
} else if ((0, _typeof3['default'])(options.orientation) === 'object') {
if ('item' in options.orientation) {
this.options.orientation.item = options.orientation.item;
}
if ('axis' in options.orientation) {
this.options.orientation.axis = options.orientation.axis;
}
}
}
if (this.options.orientation.axis === 'both') {
if (!this.timeAxis2) {
var timeAxis2 = this.timeAxis2 = new TimeAxis(this.body);
timeAxis2.setOptions = function (options) {
var _options = options ? util.extend({}, options) : {};
_options.orientation = 'top'; // override the orientation option, always top
TimeAxis.prototype.setOptions.call(timeAxis2, _options);
};
this.components.push(timeAxis2);
}
} else {
if (this.timeAxis2) {
var index = this.components.indexOf(this.timeAxis2);
if (index !== -1) {
this.components.splice(index, 1);
}
this.timeAxis2.destroy();
this.timeAxis2 = null;
}
}
// if the graph2d's drawPoints is a function delegate the callback to the onRender property
if (typeof options.drawPoints == 'function') {
options.drawPoints = {
onRender: options.drawPoints
};
}
if ('hiddenDates' in this.options) {
DateUtil.convertHiddenOptions(this.options.moment, this.body, this.options.hiddenDates);
}
if ('clickToUse' in options) {
if (options.clickToUse) {
if (!this.activator) {
this.activator = new Activator(this.dom.root);
}
} else {
if (this.activator) {
this.activator.destroy();
delete this.activator;
}
}
}
if ('showCustomTime' in options) {
throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])');
}
// enable/disable autoResize
this._initAutoResize();
}
// propagate options to all components
this.components.forEach(function (component) {
return component.setOptions(options);
});
// enable/disable configure
if ('configure' in options) {
if (!this.configurator) {
this.configurator = this._createConfigurator();
}
this.configurator.setOptions(options.configure);
// collect the settings of all components, and pass them to the configuration system
var appliedOptions = util.deepExtend({}, this.options);
this.components.forEach(function (component) {
util.deepExtend(appliedOptions, component.options);
});
this.configurator.setModuleOptions({ global: appliedOptions });
}
this._redraw();
};
/**
* Returns true when the Timeline is active.
* @returns {boolean}
*/
Core.prototype.isActive = function () {
return !this.activator || this.activator.active;
};
/**
* Destroy the Core, clean up all DOM elements and event listeners.
*/
Core.prototype.destroy = function () {
// unbind datasets
this.setItems(null);
this.setGroups(null);
// remove all event listeners
this.off();
// stop checking for changed size
this._stopAutoResize();
// remove from DOM
if (this.dom.root.parentNode) {
this.dom.root.parentNode.removeChild(this.dom.root);
}
this.dom = null;
// remove Activator
if (this.activator) {
this.activator.destroy();
delete this.activator;
}
// cleanup hammer touch events
for (var event in this.listeners) {
if (this.listeners.hasOwnProperty(event)) {
delete this.listeners[event];
}
}
this.listeners = null;
this.hammer = null;
// give all components the opportunity to cleanup
this.components.forEach(function (component) {
return component.destroy();
});
this.body = null;
};
/**
* Set a custom time bar
* @param {Date} time
* @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
*/
Core.prototype.setCustomTime = function (time, id) {
var customTimes = this.customTimes.filter(function (component) {
return id === component.options.id;
});
if (customTimes.length === 0) {
throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
}
if (customTimes.length > 0) {
customTimes[0].setCustomTime(time);
}
};
/**
* Retrieve the current custom time.
* @param {number} [id=undefined] Id of the custom time bar.
* @return {Date | undefined} customTime
*/
Core.prototype.getCustomTime = function (id) {
var customTimes = this.customTimes.filter(function (component) {
return component.options.id === id;
});
if (customTimes.length === 0) {
throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
}
return customTimes[0].getCustomTime();
};
/**
* Set a custom title for the custom time bar.
* @param {string} [title] Custom title
* @param {number} [id=undefined] Id of the custom time bar.
* @returns {*}
*/
Core.prototype.setCustomTimeTitle = function (title, id) {
var customTimes = this.customTimes.filter(function (component) {
return component.options.id === id;
});
if (customTimes.length === 0) {
throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
}
if (customTimes.length > 0) {
return customTimes[0].setCustomTitle(title);
}
};
/**
* Retrieve meta information from an event.
* Should be overridden by classes extending Core
* @param {Event} event
* @return {Object} An object with related information.
*/
Core.prototype.getEventProperties = function (event) {
return { event: event };
};
/**
* Add custom vertical bar
* @param {Date | string | number} [time] A Date, unix timestamp, or
* ISO date string. Time point where
* the new bar should be placed.
* If not provided, `new Date()` will
* be used.
* @param {number | string} [id=undefined] Id of the new bar. Optional
* @return {number | string} Returns the id of the new bar
*/
Core.prototype.addCustomTime = function (time, id) {
var timestamp = time !== undefined ? util.convert(time, 'Date').valueOf() : new Date();
var exists = this.customTimes.some(function (customTime) {
return customTime.options.id === id;
});
if (exists) {
throw new Error('A custom time with id ' + (0, _stringify2['default'])(id) + ' already exists');
}
var customTime = new CustomTime(this.body, util.extend({}, this.options, {
time: timestamp,
id: id
}));
this.customTimes.push(customTime);
this.components.push(customTime);
this._redraw();
return id;
};
/**
* Remove previously added custom bar
* @param {int} id ID of the custom bar to be removed
* [at]returns {boolean} True if the bar exists and is removed, false otherwise
*/
Core.prototype.removeCustomTime = function (id) {
var customTimes = this.customTimes.filter(function (bar) {
return bar.options.id === id;
});
if (customTimes.length === 0) {
throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
}
customTimes.forEach(function (customTime) {
this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
this.components.splice(this.components.indexOf(customTime), 1);
customTime.destroy();
}.bind(this));
};
/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/
Core.prototype.getVisibleItems = function () {
return this.itemSet && this.itemSet.getVisibleItems() || [];
};
/**
* Set Core window such that it fits all items
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
Core.prototype.fit = function (options, callback) {
var range = this.getDataRange();
// skip range set if there is no min and max date
if (range.min === null && range.max === null) {
return;
}
// apply a margin of 1% left and right of the data
var interval = range.max - range.min;
var min = new Date(range.min.valueOf() - interval * 0.01);
var max = new Date(range.max.valueOf() + interval * 0.01);
var animation = options && options.animation !== undefined ? options.animation : true;
this.range.setRange(min, max, { animation: animation }, callback);
};
/**
* Calculate the data range of the items start and end dates
* [at]returns {{min: [Date], max: [Date]}}
* @protected
*/
Core.prototype.getDataRange = function () {
// must be implemented by Timeline and Graph2d
throw new Error('Cannot invoke abstract method getDataRange');
};
/**
* Set the visible window. Both parameters are optional, you can change only
* start or only end. Syntax:
*
* TimeLine.setWindow(start, end)
* TimeLine.setWindow(start, end, options)
* TimeLine.setWindow(range)
*
* Where start and end can be a Date, number, or string, and range is an
* object with properties start and end.
*
* @param {Date | number | string | Object} [start] Start date of visible window
* @param {Date | number | string} [end] End date of visible window
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
Core.prototype.setWindow = function (start, end, options, callback) {
if (typeof arguments[2] == "function") {
callback = arguments[2];
options = {};
}
var animation;
var range;
if (arguments.length == 1) {
range = arguments[0];
animation = range.animation !== undefined ? range.animation : true;
this.range.setRange(range.start, range.end, { animation: animation });
} else if (arguments.length == 2 && typeof arguments[1] == "function") {
range = arguments[0];
callback = arguments[1];
animation = range.animation !== undefined ? range.animation : true;
this.range.setRange(range.start, range.end, { animation: animation }, callback);
} else {
animation = options && options.animation !== undefined ? options.animation : true;
this.range.setRange(start, end, { animation: animation }, callback);
}
};
/**
* Move the window such that given time is centered on screen.
* @param {Date | number | string} time
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
Core.prototype.moveTo = function (time, options, callback) {
if (typeof arguments[1] == "function") {
callback = arguments[1];
options = {};
}
var interval = this.range.end - this.range.start;
var t = util.convert(time, 'Date').valueOf();
var start = t - interval / 2;
var end = t + interval / 2;
var animation = options && options.animation !== undefined ? options.animation : true;
this.range.setRange(start, end, { animation: animation }, callback);
};
/**
* Get the visible window
* @return {{start: Date, end: Date}} Visible range
*/
Core.prototype.getWindow = function () {
var range = this.range.getRange();
return {
start: new Date(range.start),
end: new Date(range.end)
};
};
/**
* Zoom in the window such that given time is centered on screen.
* @param {number} percentage - must be between [0..1]
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
Core.prototype.zoomIn = function (percentage, options, callback) {
if (!percentage || percentage < 0 || percentage > 1) return;
if (typeof arguments[1] == "function") {
callback = arguments[1];
options = {};
}
var range = this.getWindow();
var start = range.start.valueOf();
var end = range.end.valueOf();
var interval = end - start;
var newInterval = interval / (1 + percentage);
var distance = (interval - newInterval) / 2;
var newStart = start + distance;
var newEnd = end - distance;
this.setWindow(newStart, newEnd, options, callback);
};
/**
* Zoom out the window such that given time is centered on screen.
* @param {number} percentage - must be between [0..1]
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
Core.prototype.zoomOut = function (percentage, options, callback) {
if (!percentage || percentage < 0 || percentage > 1) return;
if (typeof arguments[1] == "function") {
callback = arguments[1];
options = {};
}
var range = this.getWindow();
var start = range.start.valueOf();
var end = range.end.valueOf();
var interval = end - start;
var newStart = start - interval * percentage / 2;
var newEnd = end + interval * percentage / 2;
this.setWindow(newStart, newEnd, options, callback);
};
/**
* Force a redraw. Can be overridden by implementations of Core
*
* Note: this function will be overridden on construction with a trottled version
*/
Core.prototype.redraw = function () {
this._redraw();
};
/**
* Redraw for internal use. Redraws all components. See also the public
* method redraw.
* @protected
*/
Core.prototype._redraw = function () {
this.redrawCount++;
var resized = false;
var options = this.options;
var props = this.props;
var dom = this.dom;
if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
// update class names
if (options.orientation == 'top') {
util.addClassName(dom.root, 'vis-top');
util.removeClassName(dom.root, 'vis-bottom');
} else {
util.removeClassName(dom.root, 'vis-top');
util.addClassName(dom.root, 'vis-bottom');
}
// update root width and height options
dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
dom.root.style.width = util.option.asSize(options.width, '');
// calculate border widths
props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
props.border.right = props.border.left;
props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
props.border.bottom = props.border.top;
props.borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight;
props.borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
// workaround for a bug in IE: the clientWidth of an element with
// a height:0px and overflow:hidden is not calculated and always has value 0
if (dom.centerContainer.clientHeight === 0) {
props.border.left = props.border.top;
props.border.right = props.border.left;
}
if (dom.root.clientHeight === 0) {
props.borderRootWidth = props.borderRootHeight;
}
// calculate the heights. If any of the side panels is empty, we set the height to
// minus the border width, such that the border will be invisible
props.center.height = dom.center.offsetHeight;
props.left.height = dom.left.offsetHeight;
props.right.height = dom.right.offsetHeight;
props.top.height = dom.top.clientHeight || -props.border.top;
props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
// TODO: compensate borders when any of the panels is empty.
// apply auto height
// TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
var autoHeight = props.top.height + contentHeight + props.bottom.height + props.borderRootHeight + props.border.top + props.border.bottom;
dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
// calculate heights of the content panels
props.root.height = dom.root.offsetHeight;
props.background.height = props.root.height - props.borderRootHeight;
var containerHeight = props.root.height - props.top.height - props.bottom.height - props.borderRootHeight;
props.centerContainer.height = containerHeight;
props.leftContainer.height = containerHeight;
props.rightContainer.height = props.leftContainer.height;
// calculate the widths of the panels
props.root.width = dom.root.offsetWidth;
props.background.width = props.root.width - props.borderRootWidth;
if (!this.initialDrawDone) {
props.scrollbarWidth = util.getScrollBarWidth();
}
if (options.verticalScroll) {
if (options.rtl) {
props.left.width = dom.leftContainer.clientWidth || -props.border.left;
props.right.width = dom.rightContainer.clientWidth + props.scrollbarWidth || -props.border.right;
} else {
props.left.width = dom.leftContainer.clientWidth + props.scrollbarWidth || -props.border.left;
props.right.width = dom.rightContainer.clientWidth || -props.border.right;
}
} else {
props.left.width = dom.leftContainer.clientWidth || -props.border.left;
props.right.width = dom.rightContainer.clientWidth || -props.border.right;
}
this._setDOM();
// update the scrollTop, feasible range for the offset can be changed
// when the height of the Core or of the contents of the center changed
var offset = this._updateScrollTop();
// reposition the scrollable contents
if (options.orientation.item != 'top') {
offset += Math.max(props.centerContainer.height - props.center.height - props.border.top - props.border.bottom, 0);
}
dom.center.style.top = offset + 'px';
// show shadows when vertical scrolling is available
var visibilityTop = props.scrollTop == 0 ? 'hidden' : '';
var visibilityBottom = props.scrollTop == props.scrollTopMin ? 'hidden' : '';
dom.shadowTop.style.visibility = visibilityTop;
dom.shadowBottom.style.visibility = visibilityBottom;
dom.shadowTopLeft.style.visibility = visibilityTop;
dom.shadowBottomLeft.style.visibility = visibilityBottom;
dom.shadowTopRight.style.visibility = visibilityTop;
dom.shadowBottomRight.style.visibility = visibilityBottom;
if (options.verticalScroll) {
dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
dom.shadowTopRight.style.visibility = "hidden";
dom.shadowBottomRight.style.visibility = "hidden";
dom.shadowTopLeft.style.visibility = "hidden";
dom.shadowBottomLeft.style.visibility = "hidden";
dom.left.style.top = '0px';
dom.right.style.top = '0px';
}
if (!options.verticalScroll || props.center.height < props.centerContainer.height) {
dom.left.style.top = offset + 'px';
dom.right.style.top = offset + 'px';
dom.rightContainer.className = dom.rightContainer.className.replace(new RegExp('(?:^|\\s)' + 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
dom.leftContainer.className = dom.leftContainer.className.replace(new RegExp('(?:^|\\s)' + 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
props.left.width = dom.leftContainer.clientWidth || -props.border.left;
props.right.width = dom.rightContainer.clientWidth || -props.border.right;
this._setDOM();
}
// enable/disable vertical panning
var contentsOverflow = props.center.height > props.centerContainer.height;
this.hammer.get('pan').set({
direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
});
// redraw all components
this.components.forEach(function (component) {
resized = component.redraw() || resized;
});
var MAX_REDRAW = 5;
if (resized) {
if (this.redrawCount < MAX_REDRAW) {
this.body.emitter.emit('_change');
return;
} else {
console.log('WARNING: infinite loop in redraw?');
}
} else {
this.redrawCount = 0;
}
//Emit public 'changed' event for UI updates, see issue #1592
this.body.emitter.emit("changed");
};
Core.prototype._setDOM = function () {
var props = this.props;
var dom = this.dom;
props.leftContainer.width = props.left.width;
props.rightContainer.width = props.right.width;
var centerWidth = props.root.width - props.left.width - props.right.width - props.borderRootWidth;
props.center.width = centerWidth;
props.centerContainer.width = centerWidth;
props.top.width = centerWidth;
props.bottom.width = centerWidth;
// resize the panels
dom.background.style.height = props.background.height + 'px';
dom.backgroundVertical.style.height = props.background.height + 'px';
dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
dom.centerContainer.style.height = props.centerContainer.height + 'px';
dom.leftContainer.style.height = props.leftContainer.height + 'px';
dom.rightContainer.style.height = props.rightContainer.height + 'px';
dom.background.style.width = props.background.width + 'px';
dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
dom.backgroundHorizontal.style.width = props.background.width + 'px';
dom.centerContainer.style.width = props.center.width + 'px';
dom.top.style.width = props.top.width + 'px';
dom.bottom.style.width = props.bottom.width + 'px';
// reposition the panels
dom.background.style.left = '0';
dom.background.style.top = '0';
dom.backgroundVertical.style.left = props.left.width + props.border.left + 'px';
dom.backgroundVertical.style.top = '0';
dom.backgroundHorizontal.style.left = '0';
dom.backgroundHorizontal.style.top = props.top.height + 'px';
dom.centerContainer.style.left = props.left.width + 'px';
dom.centerContainer.style.top = props.top.height + 'px';
dom.leftContainer.style.left = '0';
dom.leftContainer.style.top = props.top.height + 'px';
dom.rightContainer.style.left = props.left.width + props.center.width + 'px';
dom.rightContainer.style.top = props.top.height + 'px';
dom.top.style.left = props.left.width + 'px';
dom.top.style.top = '0';
dom.bottom.style.left = props.left.width + 'px';
dom.bottom.style.top = props.top.height + props.centerContainer.height + 'px';
dom.center.style.left = '0';
dom.left.style.left = '0';
dom.right.style.left = '0';
};
// TODO: deprecated since version 1.1.0, remove some day
Core.prototype.repaint = function () {
throw new Error('Function repaint is deprecated. Use redraw instead.');
};
/**
* Set a current time. This can be used for example to ensure that a client's
* time is synchronized with a shared server time.
* Only applicable when option `showCurrentTime` is true.
* @param {Date | string | number} time A Date, unix timestamp, or
* ISO date string.
*/
Core.prototype.setCurrentTime = function (time) {
if (!this.currentTime) {
throw new Error('Option showCurrentTime must be true');
}
this.currentTime.setCurrentTime(time);
};
/**
* Get the current time.
* Only applicable when option `showCurrentTime` is true.
* @return {Date} Returns the current time.
*/
Core.prototype.getCurrentTime = function () {
if (!this.currentTime) {
throw new Error('Option showCurrentTime must be true');
}
return this.currentTime.getCurrentTime();
};
/**
* Convert a position on screen (pixels) to a datetime
* @param {int} x Position on the screen in pixels
* @return {Date} time The datetime the corresponds with given position x
* @protected
*/
// TODO: move this function to Range
Core.prototype._toTime = function (x) {
return DateUtil.toTime(this, x, this.props.center.width);
};
/**
* Convert a position on the global screen (pixels) to a datetime
* @param {int} x Position on the screen in pixels
* @return {Date} time The datetime the corresponds with given position x
* @protected
*/
// TODO: move this function to Range
Core.prototype._toGlobalTime = function (x) {
return DateUtil.toTime(this, x, this.props.root.width);
//var conversion = this.range.conversion(this.props.root.width);
//return new Date(x / conversion.scale + conversion.offset);
};
/**
* Convert a datetime (Date object) into a position on the screen
* @param {Date} time A date
* @return {int} x The position on the screen in pixels which corresponds
* with the given date.
* @protected
*/
// TODO: move this function to Range
Core.prototype._toScreen = function (time) {
return DateUtil.toScreen(this, time, this.props.center.width);
};
/**
* Convert a datetime (Date object) into a position on the root
* This is used to get the pixel density estimate for the screen, not the center panel
* @param {Date} time A date
* @return {int} x The position on root in pixels which corresponds
* with the given date.
* @protected
*/
// TODO: move this function to Range
Core.prototype._toGlobalScreen = function (time) {
return DateUtil.toScreen(this, time, this.props.root.width);
//var conversion = this.range.conversion(this.props.root.width);
//return (time.valueOf() - conversion.offset) * conversion.scale;
};
/**
* Initialize watching when option autoResize is true
* @private
*/
Core.prototype._initAutoResize = function () {
if (this.options.autoResize == true) {
this._startAutoResize();
} else {
this._stopAutoResize();
}
};
/**
* Watch for changes in the size of the container. On resize, the Panel will
* automatically redraw itself.
* @private
*/
Core.prototype._startAutoResize = function () {
var me = this;
this._stopAutoResize();
this._onResize = function () {
if (me.options.autoResize != true) {
// stop watching when the option autoResize is changed to false
me._stopAutoResize();
return;
}
if (me.dom.root) {
// check whether the frame is resized
// Note: we compare offsetWidth here, not clientWidth. For some reason,
// IE does not restore the clientWidth from 0 to the actual width after
// changing the timeline's container display style from none to visible
if (me.dom.root.offsetWidth != me.props.lastWidth || me.dom.root.offsetHeight != me.props.lastHeight) {
me.props.lastWidth = me.dom.root.offsetWidth;
me.props.lastHeight = me.dom.root.offsetHeight;
me.props.scrollbarWidth = util.getScrollBarWidth();
me.body.emitter.emit('_change');
}
}
};
// add event listener to window resize
util.addEventListener(window, 'resize', this._onResize);
//Prevent initial unnecessary redraw
if (me.dom.root) {
me.props.lastWidth = me.dom.root.offsetWidth;
me.props.lastHeight = me.dom.root.offsetHeight;
}
this.watchTimer = setInterval(this._onResize, 1000);
};
/**
* Stop watching for a resize of the frame.
* @private
*/
Core.prototype._stopAutoResize = function () {
if (this.watchTimer) {
clearInterval(this.watchTimer);
this.watchTimer = undefined;
}
// remove event listener on window.resize
if (this._onResize) {
util.removeEventListener(window, 'resize', this._onResize);
this._onResize = null;
}
};
/**
* Start moving the timeline vertically
* @param {Event} event
* @private
*/
Core.prototype._onTouch = function (event) {
// eslint-disable-line no-unused-vars
this.touch.allowDragging = true;
this.touch.initialScrollTop = this.props.scrollTop;
};
/**
* Start moving the timeline vertically
* @param {Event} event
* @private
*/
Core.prototype._onPinch = function (event) {
// eslint-disable-line no-unused-vars
this.touch.allowDragging = false;
};
/**
* Move the timeline vertically
* @param {Event} event
* @private
*/
Core.prototype._onDrag = function (event) {
if (!event) return;
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.touch.allowDragging) return;
var delta = event.deltaY;
var oldScrollTop = this._getScrollTop();
var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
if (this.options.verticalScroll) {
this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
}
if (newScrollTop != oldScrollTop) {
this.emit("verticalDrag");
}
};
/**
* Apply a scrollTop
* @param {number} scrollTop
* @returns {number} scrollTop Returns the applied scrollTop
* @private
*/
Core.prototype._setScrollTop = function (scrollTop) {
this.props.scrollTop = scrollTop;
this._updateScrollTop();
return this.props.scrollTop;
};
/**
* Update the current scrollTop when the height of the containers has been changed
* @returns {number} scrollTop Returns the applied scrollTop
* @private
*/
Core.prototype._updateScrollTop = function () {
// recalculate the scrollTopMin
var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
if (scrollTopMin != this.props.scrollTopMin) {
// in case of bottom orientation, change the scrollTop such that the contents
// do not move relative to the time axis at the bottom
if (this.options.orientation.item != 'top') {
this.props.scrollTop += scrollTopMin - this.props.scrollTopMin;
}
this.props.scrollTopMin = scrollTopMin;
}
// limit the scrollTop to the feasible scroll range
if (this.props.scrollTop > 0) this.props.scrollTop = 0;
if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
if (this.options.verticalScroll) {
this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
}
return this.props.scrollTop;
};
/**
* Get the current scrollTop
* @returns {number} scrollTop
* @private
*/
Core.prototype._getScrollTop = function () {
return this.props.scrollTop;
};
/**
* Load a configurator
* [at]returns {Object}
* @private
*/
Core.prototype._createConfigurator = function () {
throw new Error('Cannot invoke abstract method _createConfigurator');
};
module.exports = Core;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var moment = __webpack_require__(9);
var DateUtil = __webpack_require__(36);
var util = __webpack_require__(2);
/**
* The class TimeStep is an iterator for dates. You provide a start date and an
* end date. The class itself determines the best scale (step size) based on the
* provided start Date, end Date, and minimumStep.
*
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
*
* Alternatively, you can set a scale by hand.
* After creation, you can initialize the class by executing first(). Then you
* can iterate from the start date to the end date via next(). You can check if
* the end date is reached with the function hasNext(). After each step, you can
* retrieve the current date via getCurrent().
* The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
* days, to years.
*
* Version: 1.2
*
* @param {Date} [start] The start date, for example new Date(2010, 9, 21)
* or new Date(2010, 9, 21, 23, 45, 00)
* @param {Date} [end] The end date
* @param {number} [minimumStep] Optional. Minimum step size in milliseconds
* @param {Date|Array.} [hiddenDates] Optional.
* @param {{showMajorLabels: boolean}} [options] Optional.
* @constructor TimeStep
*/
function TimeStep(start, end, minimumStep, hiddenDates, options) {
this.moment = moment;
// variables
this.current = this.moment();
this._start = this.moment();
this._end = this.moment();
this.autoScale = true;
this.scale = 'day';
this.step = 1;
// initialize the range
this.setRange(start, end, minimumStep);
// hidden Dates options
this.switchedDay = false;
this.switchedMonth = false;
this.switchedYear = false;
if (Array.isArray(hiddenDates)) {
this.hiddenDates = hiddenDates;
} else if (hiddenDates != undefined) {
this.hiddenDates = [hiddenDates];
} else {
this.hiddenDates = [];
}
this.format = TimeStep.FORMAT; // default formatting
this.options = options ? options : {};
}
// Time formatting
TimeStep.FORMAT = {
minorLabels: {
millisecond: 'SSS',
second: 's',
minute: 'HH:mm',
hour: 'HH:mm',
weekday: 'ddd D',
day: 'D',
week: 'w',
month: 'MMM',
year: 'YYYY'
},
majorLabels: {
millisecond: 'HH:mm:ss',
second: 'D MMMM HH:mm',
minute: 'ddd D MMMM',
hour: 'ddd D MMMM',
weekday: 'MMMM YYYY',
day: 'MMMM YYYY',
week: 'MMMM YYYY',
month: 'YYYY',
year: ''
}
};
/**
* Set custom constructor function for moment. Can be used to set dates
* to UTC or to set a utcOffset.
* @param {function} moment
*/
TimeStep.prototype.setMoment = function (moment) {
this.moment = moment;
// update the date properties, can have a new utcOffset
this.current = this.moment(this.current.valueOf());
this._start = this.moment(this._start.valueOf());
this._end = this.moment(this._end.valueOf());
};
/**
* Set custom formatting for the minor an major labels of the TimeStep.
* Both `minorLabels` and `majorLabels` are an Object with properties:
* 'millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'.
* @param {{minorLabels: Object, majorLabels: Object}} format
*/
TimeStep.prototype.setFormat = function (format) {
var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
this.format = util.deepExtend(defaultFormat, format);
};
/**
* Set a new range
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
* @param {Date} [start] The start date and time.
* @param {Date} [end] The end date and time.
* @param {int} [minimumStep] Optional. Minimum step size in milliseconds
*/
TimeStep.prototype.setRange = function (start, end, minimumStep) {
if (!(start instanceof Date) || !(end instanceof Date)) {
throw "No legal start or end date in method setRange";
}
this._start = start != undefined ? this.moment(start.valueOf()) : new Date();
this._end = end != undefined ? this.moment(end.valueOf()) : new Date();
if (this.autoScale) {
this.setMinimumStep(minimumStep);
}
};
/**
* Set the range iterator to the start date.
*/
TimeStep.prototype.start = function () {
this.current = this._start.clone();
this.roundToMinor();
};
/**
* Round the current date to the first minor date value
* This must be executed once when the current date is set to start Date
*/
TimeStep.prototype.roundToMinor = function () {
// round to floor
// to prevent year & month scales rounding down to the first day of week we perform this separately
if (this.scale == 'week') {
this.current.weekday(0);
}
// IMPORTANT: we have no breaks in this switch! (this is no bug)
// noinspection FallThroughInSwitchStatementJS
switch (this.scale) {
case 'year':
this.current.year(this.step * Math.floor(this.current.year() / this.step));
this.current.month(0);
case 'month':
this.current.date(1); // eslint-disable-line no-fallthrough
case 'week': // eslint-disable-line no-fallthrough
case 'day': // eslint-disable-line no-fallthrough
case 'weekday':
this.current.hours(0); // eslint-disable-line no-fallthrough
case 'hour':
this.current.minutes(0); // eslint-disable-line no-fallthrough
case 'minute':
this.current.seconds(0); // eslint-disable-line no-fallthrough
case 'second':
this.current.milliseconds(0); // eslint-disable-line no-fallthrough
//case 'millisecond': // nothing to do for milliseconds
}
if (this.step != 1) {
// round down to the first minor value that is a multiple of the current step size
switch (this.scale) {
case 'millisecond':
this.current.subtract(this.current.milliseconds() % this.step, 'milliseconds');break;
case 'second':
this.current.subtract(this.current.seconds() % this.step, 'seconds');break;
case 'minute':
this.current.subtract(this.current.minutes() % this.step, 'minutes');break;
case 'hour':
this.current.subtract(this.current.hours() % this.step, 'hours');break;
case 'weekday': // intentional fall through
case 'day':
this.current.subtract((this.current.date() - 1) % this.step, 'day');break;
case 'week':
this.current.subtract(this.current.week() % this.step, 'week');break;
case 'month':
this.current.subtract(this.current.month() % this.step, 'month');break;
case 'year':
this.current.subtract(this.current.year() % this.step, 'year');break;
default:
break;
}
}
};
/**
* Check if the there is a next step
* @return {boolean} true if the current date has not passed the end date
*/
TimeStep.prototype.hasNext = function () {
return this.current.valueOf() <= this._end.valueOf();
};
/**
* Do the next step
*/
TimeStep.prototype.next = function () {
var prev = this.current.valueOf();
// Two cases, needed to prevent issues with switching daylight savings
// (end of March and end of October)
switch (this.scale) {
case 'millisecond':
this.current.add(this.step, 'millisecond');break;
case 'second':
this.current.add(this.step, 'second');break;
case 'minute':
this.current.add(this.step, 'minute');break;
case 'hour':
this.current.add(this.step, 'hour');
if (this.current.month() < 6) {
this.current.subtract(this.current.hours() % this.step, 'hour');
} else {
if (this.current.hours() % this.step !== 0) {
this.current.add(this.step - this.current.hours() % this.step, 'hour');
}
}
break;
case 'weekday': // intentional fall through
case 'day':
this.current.add(this.step, 'day');break;
case 'week':
if (this.current.weekday() !== 0) {
// we had a month break not correlating with a week's start before
this.current.weekday(0); // switch back to week cycles
this.current.add(this.step, 'week');
} else if (this.options.showMajorLabels === false) {
this.current.add(this.step, 'week'); // the default case
} else {
// first day of the week
var nextWeek = this.current.clone();
nextWeek.add(1, 'week');
if (nextWeek.isSame(this.current, 'month')) {
// is the first day of the next week in the same month?
this.current.add(this.step, 'week'); // the default case
} else {
// inject a step at each first day of the month
this.current.add(this.step, 'week');
this.current.date(1);
}
}
break;
case 'month':
this.current.add(this.step, 'month');break;
case 'year':
this.current.add(this.step, 'year');break;
default:
break;
}
if (this.step != 1) {
// round down to the correct major value
switch (this.scale) {
case 'millisecond':
if (this.current.milliseconds() > 0 && this.current.milliseconds() < this.step) this.current.milliseconds(0);break;
case 'second':
if (this.current.seconds() > 0 && this.current.seconds() < this.step) this.current.seconds(0);break;
case 'minute':
if (this.current.minutes() > 0 && this.current.minutes() < this.step) this.current.minutes(0);break;
case 'hour':
if (this.current.hours() > 0 && this.current.hours() < this.step) this.current.hours(0);break;
case 'weekday': // intentional fall through
case 'day':
if (this.current.date() < this.step + 1) this.current.date(1);break;
case 'week':
if (this.current.week() < this.step) this.current.week(1);break; // week numbering starts at 1, not 0
case 'month':
if (this.current.month() < this.step) this.current.month(0);break;
case 'year':
break; // nothing to do for year
default:
break;
}
}
// safety mechanism: if current time is still unchanged, move to the end
if (this.current.valueOf() == prev) {
this.current = this._end.clone();
}
// Reset switches for year, month and day. Will get set to true where appropriate in DateUtil.stepOverHiddenDates
this.switchedDay = false;
this.switchedMonth = false;
this.switchedYear = false;
DateUtil.stepOverHiddenDates(this.moment, this, prev);
};
/**
* Get the current datetime
* @return {Moment} current The current date
*/
TimeStep.prototype.getCurrent = function () {
return this.current;
};
/**
* Set a custom scale. Autoscaling will be disabled.
* For example setScale('minute', 5) will result
* in minor steps of 5 minutes, and major steps of an hour.
*
* @param {{scale: string, step: number}} params
* An object containing two properties:
* - A string 'scale'. Choose from 'millisecond', 'second',
* 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'.
* - A number 'step'. A step size, by default 1.
* Choose for example 1, 2, 5, or 10.
*/
TimeStep.prototype.setScale = function (params) {
if (params && typeof params.scale == 'string') {
this.scale = params.scale;
this.step = params.step > 0 ? params.step : 1;
this.autoScale = false;
}
};
/**
* Enable or disable autoscaling
* @param {boolean} enable If true, autoascaling is set true
*/
TimeStep.prototype.setAutoScale = function (enable) {
this.autoScale = enable;
};
/**
* Automatically determine the scale that bests fits the provided minimum step
* @param {number} [minimumStep] The minimum step size in milliseconds
*/
TimeStep.prototype.setMinimumStep = function (minimumStep) {
if (minimumStep == undefined) {
return;
}
//var b = asc + ds;
var stepYear = 1000 * 60 * 60 * 24 * 30 * 12;
var stepMonth = 1000 * 60 * 60 * 24 * 30;
var stepDay = 1000 * 60 * 60 * 24;
var stepHour = 1000 * 60 * 60;
var stepMinute = 1000 * 60;
var stepSecond = 1000;
var stepMillisecond = 1;
// find the smallest step that is larger than the provided minimumStep
if (stepYear * 1000 > minimumStep) {
this.scale = 'year';this.step = 1000;
}
if (stepYear * 500 > minimumStep) {
this.scale = 'year';this.step = 500;
}
if (stepYear * 100 > minimumStep) {
this.scale = 'year';this.step = 100;
}
if (stepYear * 50 > minimumStep) {
this.scale = 'year';this.step = 50;
}
if (stepYear * 10 > minimumStep) {
this.scale = 'year';this.step = 10;
}
if (stepYear * 5 > minimumStep) {
this.scale = 'year';this.step = 5;
}
if (stepYear > minimumStep) {
this.scale = 'year';this.step = 1;
}
if (stepMonth * 3 > minimumStep) {
this.scale = 'month';this.step = 3;
}
if (stepMonth > minimumStep) {
this.scale = 'month';this.step = 1;
}
if (stepDay * 5 > minimumStep) {
this.scale = 'day';this.step = 5;
}
if (stepDay * 2 > minimumStep) {
this.scale = 'day';this.step = 2;
}
if (stepDay > minimumStep) {
this.scale = 'day';this.step = 1;
}
if (stepDay / 2 > minimumStep) {
this.scale = 'weekday';this.step = 1;
}
if (stepHour * 4 > minimumStep) {
this.scale = 'hour';this.step = 4;
}
if (stepHour > minimumStep) {
this.scale = 'hour';this.step = 1;
}
if (stepMinute * 15 > minimumStep) {
this.scale = 'minute';this.step = 15;
}
if (stepMinute * 10 > minimumStep) {
this.scale = 'minute';this.step = 10;
}
if (stepMinute * 5 > minimumStep) {
this.scale = 'minute';this.step = 5;
}
if (stepMinute > minimumStep) {
this.scale = 'minute';this.step = 1;
}
if (stepSecond * 15 > minimumStep) {
this.scale = 'second';this.step = 15;
}
if (stepSecond * 10 > minimumStep) {
this.scale = 'second';this.step = 10;
}
if (stepSecond * 5 > minimumStep) {
this.scale = 'second';this.step = 5;
}
if (stepSecond > minimumStep) {
this.scale = 'second';this.step = 1;
}
if (stepMillisecond * 200 > minimumStep) {
this.scale = 'millisecond';this.step = 200;
}
if (stepMillisecond * 100 > minimumStep) {
this.scale = 'millisecond';this.step = 100;
}
if (stepMillisecond * 50 > minimumStep) {
this.scale = 'millisecond';this.step = 50;
}
if (stepMillisecond * 10 > minimumStep) {
this.scale = 'millisecond';this.step = 10;
}
if (stepMillisecond * 5 > minimumStep) {
this.scale = 'millisecond';this.step = 5;
}
if (stepMillisecond > minimumStep) {
this.scale = 'millisecond';this.step = 1;
}
};
/**
* Snap a date to a rounded value.
* The snap intervals are dependent on the current scale and step.
* Static function
* @param {Date} date the date to be snapped.
* @param {string} scale Current scale, can be 'millisecond', 'second',
* 'minute', 'hour', 'weekday, 'day', 'week', 'month', 'year'.
* @param {number} step Current step (1, 2, 4, 5, ...
* @return {Date} snappedDate
*/
TimeStep.snap = function (date, scale, step) {
var clone = moment(date);
if (scale == 'year') {
var year = clone.year() + Math.round(clone.month() / 12);
clone.year(Math.round(year / step) * step);
clone.month(0);
clone.date(0);
clone.hours(0);
clone.minutes(0);
clone.seconds(0);
clone.milliseconds(0);
} else if (scale == 'month') {
if (clone.date() > 15) {
clone.date(1);
clone.add(1, 'month');
// important: first set Date to 1, after that change the month.
} else {
clone.date(1);
}
clone.hours(0);
clone.minutes(0);
clone.seconds(0);
clone.milliseconds(0);
} else if (scale == 'week') {
if (clone.weekday() > 2) {
// doing it the momentjs locale aware way
clone.weekday(0);
clone.add(1, 'week');
} else {
clone.weekday(0);
}
clone.hours(0);
clone.minutes(0);
clone.seconds(0);
clone.milliseconds(0);
} else if (scale == 'day') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 5:
case 2:
clone.hours(Math.round(clone.hours() / 24) * 24);break;
default:
clone.hours(Math.round(clone.hours() / 12) * 12);break;
}
clone.minutes(0);
clone.seconds(0);
clone.milliseconds(0);
} else if (scale == 'weekday') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 5:
case 2:
clone.hours(Math.round(clone.hours() / 12) * 12);break;
default:
clone.hours(Math.round(clone.hours() / 6) * 6);break;
}
clone.minutes(0);
clone.seconds(0);
clone.milliseconds(0);
} else if (scale == 'hour') {
switch (step) {
case 4:
clone.minutes(Math.round(clone.minutes() / 60) * 60);break;
default:
clone.minutes(Math.round(clone.minutes() / 30) * 30);break;
}
clone.seconds(0);
clone.milliseconds(0);
} else if (scale == 'minute') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 15:
case 10:
clone.minutes(Math.round(clone.minutes() / 5) * 5);
clone.seconds(0);
break;
case 5:
clone.seconds(Math.round(clone.seconds() / 60) * 60);break;
default:
clone.seconds(Math.round(clone.seconds() / 30) * 30);break;
}
clone.milliseconds(0);
} else if (scale == 'second') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 15:
case 10:
clone.seconds(Math.round(clone.seconds() / 5) * 5);
clone.milliseconds(0);
break;
case 5:
clone.milliseconds(Math.round(clone.milliseconds() / 1000) * 1000);break;
default:
clone.milliseconds(Math.round(clone.milliseconds() / 500) * 500);break;
}
} else if (scale == 'millisecond') {
var _step = step > 5 ? step / 2 : 1;
clone.milliseconds(Math.round(clone.milliseconds() / _step) * _step);
}
return clone;
};
/**
* Check if the current value is a major value (for example when the step
* is DAY, a major value is each first day of the MONTH)
* @return {boolean} true if current date is major, else false.
*/
TimeStep.prototype.isMajor = function () {
if (this.switchedYear == true) {
switch (this.scale) {
case 'year':
case 'month':
case 'week':
case 'weekday':
case 'day':
case 'hour':
case 'minute':
case 'second':
case 'millisecond':
return true;
default:
return false;
}
} else if (this.switchedMonth == true) {
switch (this.scale) {
case 'week':
case 'weekday':
case 'day':
case 'hour':
case 'minute':
case 'second':
case 'millisecond':
return true;
default:
return false;
}
} else if (this.switchedDay == true) {
switch (this.scale) {
case 'millisecond':
case 'second':
case 'minute':
case 'hour':
return true;
default:
return false;
}
}
var date = this.moment(this.current);
switch (this.scale) {
case 'millisecond':
return date.milliseconds() == 0;
case 'second':
return date.seconds() == 0;
case 'minute':
return date.hours() == 0 && date.minutes() == 0;
case 'hour':
return date.hours() == 0;
case 'weekday': // intentional fall through
case 'day':
return date.date() == 1;
case 'week':
return date.date() == 1;
case 'month':
return date.month() == 0;
case 'year':
return false;
default:
return false;
}
};
/**
* Returns formatted text for the minor axislabel, depending on the current
* date and the scale. For example when scale is MINUTE, the current time is
* formatted as "hh:mm".
* @param {Date} [date=this.current] custom date. if not provided, current date is taken
* @returns {String}
*/
TimeStep.prototype.getLabelMinor = function (date) {
if (date == undefined) {
date = this.current;
}
if (date instanceof Date) {
date = this.moment(date);
}
if (typeof this.format.minorLabels === "function") {
return this.format.minorLabels(date, this.scale, this.step);
}
var format = this.format.minorLabels[this.scale];
// noinspection FallThroughInSwitchStatementJS
switch (this.scale) {
case 'week':
if (this.isMajor() && date.weekday() !== 0) {
return "";
}
default:
// eslint-disable-line no-fallthrough
return format && format.length > 0 ? this.moment(date).format(format) : '';
}
};
/**
* Returns formatted text for the major axis label, depending on the current
* date and the scale. For example when scale is MINUTE, the major scale is
* hours, and the hour will be formatted as "hh".
* @param {Date} [date=this.current] custom date. if not provided, current date is taken
* @returns {String}
*/
TimeStep.prototype.getLabelMajor = function (date) {
if (date == undefined) {
date = this.current;
}
if (date instanceof Date) {
date = this.moment(date);
}
if (typeof this.format.majorLabels === "function") {
return this.format.majorLabels(date, this.scale, this.step);
}
var format = this.format.majorLabels[this.scale];
return format && format.length > 0 ? this.moment(date).format(format) : '';
};
TimeStep.prototype.getClassName = function () {
var _moment = this.moment;
var m = this.moment(this.current);
var current = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function
var step = this.step;
var classNames = [];
/**
*
* @param {number} value
* @returns {String}
*/
function even(value) {
return value / step % 2 == 0 ? ' vis-even' : ' vis-odd';
}
/**
*
* @param {Date} date
* @returns {String}
*/
function today(date) {
if (date.isSame(new Date(), 'day')) {
return ' vis-today';
}
if (date.isSame(_moment().add(1, 'day'), 'day')) {
return ' vis-tomorrow';
}
if (date.isSame(_moment().add(-1, 'day'), 'day')) {
return ' vis-yesterday';
}
return '';
}
/**
*
* @param {Date} date
* @returns {String}
*/
function currentWeek(date) {
return date.isSame(new Date(), 'week') ? ' vis-current-week' : '';
}
/**
*
* @param {Date} date
* @returns {String}
*/
function currentMonth(date) {
return date.isSame(new Date(), 'month') ? ' vis-current-month' : '';
}
/**
*
* @param {Date} date
* @returns {String}
*/
function currentYear(date) {
return date.isSame(new Date(), 'year') ? ' vis-current-year' : '';
}
switch (this.scale) {
case 'millisecond':
classNames.push(today(current));
classNames.push(even(current.milliseconds()));
break;
case 'second':
classNames.push(today(current));
classNames.push(even(current.seconds()));
break;
case 'minute':
classNames.push(today(current));
classNames.push(even(current.minutes()));
break;
case 'hour':
classNames.push('vis-h' + current.hours() + (this.step == 4 ? '-h' + (current.hours() + 4) : ''));
classNames.push(today(current));
classNames.push(even(current.hours()));
break;
case 'weekday':
classNames.push('vis-' + current.format('dddd').toLowerCase());
classNames.push(today(current));
classNames.push(currentWeek(current));
classNames.push(even(current.date()));
break;
case 'day':
classNames.push('vis-day' + current.date());
classNames.push('vis-' + current.format('MMMM').toLowerCase());
classNames.push(today(current));
classNames.push(currentMonth(current));
classNames.push(this.step <= 2 ? today(current) : '');
classNames.push(this.step <= 2 ? 'vis-' + current.format('dddd').toLowerCase() : '');
classNames.push(even(current.date() - 1));
break;
case 'week':
classNames.push('vis-week' + current.format('w'));
classNames.push(currentWeek(current));
classNames.push(even(current.week()));
break;
case 'month':
classNames.push('vis-' + current.format('MMMM').toLowerCase());
classNames.push(currentMonth(current));
classNames.push(even(current.month()));
break;
case 'year':
classNames.push('vis-year' + current.year());
classNames.push(currentYear(current));
classNames.push(even(current.year()));
break;
}
return classNames.filter(String).join(" ");
};
module.exports = TimeStep;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(2);
var Component = __webpack_require__(16);
var moment = __webpack_require__(9);
var locales = __webpack_require__(98);
/**
* A current time bar
* @param {{range: Range, dom: Object, domProps: Object}} body
* @param {Object} [options] Available parameters:
* {Boolean} [showCurrentTime]
* @constructor CurrentTime
* @extends Component
*/
function CurrentTime(body, options) {
this.body = body;
// default options
this.defaultOptions = {
rtl: false,
showCurrentTime: true,
moment: moment,
locales: locales,
locale: 'en'
};
this.options = util.extend({}, this.defaultOptions);
this.offset = 0;
this._create();
this.setOptions(options);
}
CurrentTime.prototype = new Component();
/**
* Create the HTML DOM for the current time bar
* @private
*/
CurrentTime.prototype._create = function () {
var bar = document.createElement('div');
bar.className = 'vis-current-time';
bar.style.position = 'absolute';
bar.style.top = '0px';
bar.style.height = '100%';
this.bar = bar;
};
/**
* Destroy the CurrentTime bar
*/
CurrentTime.prototype.destroy = function () {
this.options.showCurrentTime = false;
this.redraw(); // will remove the bar from the DOM and stop refreshing
this.body = null;
};
/**
* Set options for the component. Options will be merged in current options.
* @param {Object} options Available parameters:
* {boolean} [showCurrentTime]
*/
CurrentTime.prototype.setOptions = function (options) {
if (options) {
// copy all options that we know
util.selectiveExtend(['rtl', 'showCurrentTime', 'moment', 'locale', 'locales'], this.options, options);
}
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
CurrentTime.prototype.redraw = function () {
if (this.options.showCurrentTime) {
var parent = this.body.dom.backgroundVertical;
if (this.bar.parentNode != parent) {
// attach to the dom
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
parent.appendChild(this.bar);
this.start();
}
var now = this.options.moment(new Date().valueOf() + this.offset);
var x = this.body.util.toScreen(now);
var locale = this.options.locales[this.options.locale];
if (!locale) {
if (!this.warned) {
console.log('WARNING: options.locales[\'' + this.options.locale + '\'] not found. See http://visjs.org/docs/timeline/#Localization');
this.warned = true;
}
locale = this.options.locales['en']; // fall back on english when not available
}
var title = locale.current + ' ' + locale.time + ': ' + now.format('dddd, MMMM Do YYYY, H:mm:ss');
title = title.charAt(0).toUpperCase() + title.substring(1);
if (this.options.rtl) {
this.bar.style.right = x + 'px';
} else {
this.bar.style.left = x + 'px';
}
this.bar.title = title;
} else {
// remove the line from the DOM
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
this.stop();
}
return false;
};
/**
* Start auto refreshing the current time bar
*/
CurrentTime.prototype.start = function () {
var me = this;
/**
* Updates the current time.
*/
function update() {
me.stop();
// determine interval to refresh
var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
var interval = 1 / scale / 10;
if (interval < 30) interval = 30;
if (interval > 1000) interval = 1000;
me.redraw();
me.body.emitter.emit('currentTimeTick');
// start a renderTimer to adjust for the new time
me.currentTimeTimer = setTimeout(update, interval);
}
update();
};
/**
* Stop auto refreshing the current time bar
*/
CurrentTime.prototype.stop = function () {
if (this.currentTimeTimer !== undefined) {
clearTimeout(this.currentTimeTimer);
delete this.currentTimeTimer;
}
};
/**
* Set a current time. This can be used for example to ensure that a client's
* time is synchronized with a shared server time.
* @param {Date | string | number} time A Date, unix timestamp, or
* ISO date string.
*/
CurrentTime.prototype.setCurrentTime = function (time) {
var t = util.convert(time, 'Date').valueOf();
var now = new Date().valueOf();
this.offset = t - now;
this.redraw();
};
/**
* Get the current time.
* @return {Date} Returns the current time.
*/
CurrentTime.prototype.getCurrentTime = function () {
return new Date(new Date().valueOf() + this.offset);
};
module.exports = CurrentTime;
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _keys = __webpack_require__(8);
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var stack = __webpack_require__(100);
/**
* @param {number | string} groupId
* @param {Object} data
* @param {ItemSet} itemSet
* @constructor Group
*/
function Group(groupId, data, itemSet) {
this.groupId = groupId;
this.subgroups = {};
this.subgroupStack = {};
this.subgroupStackAll = false;
this.doInnerStack = false;
this.subgroupIndex = 0;
this.subgroupOrderer = data && data.subgroupOrder;
this.itemSet = itemSet;
this.isVisible = null;
this.stackDirty = true; // if true, items will be restacked on next redraw
if (data && data.nestedGroups) {
this.nestedGroups = data.nestedGroups;
if (data.showNested == false) {
this.showNested = false;
} else {
this.showNested = true;
}
}
if (data && data.subgroupStack) {
if (typeof data.subgroupStack === "boolean") {
this.doInnerStack = data.subgroupStack;
this.subgroupStackAll = data.subgroupStack;
} else {
// We might be doing stacking on specific sub groups, but only
// if at least one is set to do stacking
for (var key in data.subgroupStack) {
this.subgroupStack[key] = data.subgroupStack[key];
this.doInnerStack = this.doInnerStack || data.subgroupStack[key];
}
}
}
this.nestedInGroup = null;
this.dom = {};
this.props = {
label: {
width: 0,
height: 0
}
};
this.className = null;
this.items = {}; // items filtered by groupId of this group
this.visibleItems = []; // items currently visible in window
this.itemsInRange = []; // items currently in range
this.orderedItems = {
byStart: [],
byEnd: []
};
this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
var me = this;
this.itemSet.body.emitter.on("checkRangedItems", function () {
me.checkRangedItems = true;
});
this._create();
this.setData(data);
}
/**
* Create DOM elements for the group
* @private
*/
Group.prototype._create = function () {
var label = document.createElement('div');
if (this.itemSet.options.groupEditable.order) {
label.className = 'vis-label draggable';
} else {
label.className = 'vis-label';
}
this.dom.label = label;
var inner = document.createElement('div');
inner.className = 'vis-inner';
label.appendChild(inner);
this.dom.inner = inner;
var foreground = document.createElement('div');
foreground.className = 'vis-group';
foreground['timeline-group'] = this;
this.dom.foreground = foreground;
this.dom.background = document.createElement('div');
this.dom.background.className = 'vis-group';
this.dom.axis = document.createElement('div');
this.dom.axis.className = 'vis-group';
// create a hidden marker to detect when the Timelines container is attached
// to the DOM, or the style of a parent of the Timeline is changed from
// display:none is changed to visible.
this.dom.marker = document.createElement('div');
this.dom.marker.style.visibility = 'hidden';
this.dom.marker.style.position = 'absolute';
this.dom.marker.innerHTML = '';
this.dom.background.appendChild(this.dom.marker);
};
/**
* Set the group data for this group
* @param {Object} data Group data, can contain properties content and className
*/
Group.prototype.setData = function (data) {
// update contents
var content;
var templateFunction;
if (this.itemSet.options && this.itemSet.options.groupTemplate) {
templateFunction = this.itemSet.options.groupTemplate.bind(this);
content = templateFunction(data, this.dom.inner);
} else {
content = data && data.content;
}
if (content instanceof Element) {
this.dom.inner.appendChild(content);
while (this.dom.inner.firstChild) {
this.dom.inner.removeChild(this.dom.inner.firstChild);
}
this.dom.inner.appendChild(content);
} else if (content instanceof Object) {
templateFunction(data, this.dom.inner);
} else if (content !== undefined && content !== null) {
this.dom.inner.innerHTML = content;
} else {
this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
}
// update title
this.dom.label.title = data && data.title || '';
if (!this.dom.inner.firstChild) {
util.addClassName(this.dom.inner, 'vis-hidden');
} else {
util.removeClassName(this.dom.inner, 'vis-hidden');
}
if (data && data.nestedGroups) {
if (!this.nestedGroups || this.nestedGroups != data.nestedGroups) {
this.nestedGroups = data.nestedGroups;
}
if (data.showNested !== undefined || this.showNested === undefined) {
if (data.showNested == false) {
this.showNested = false;
} else {
this.showNested = true;
}
}
util.addClassName(this.dom.label, 'vis-nesting-group');
var collapsedDirClassName = this.itemSet.options.rtl ? 'collapsed-rtl' : 'collapsed';
if (this.showNested) {
util.removeClassName(this.dom.label, collapsedDirClassName);
util.addClassName(this.dom.label, 'expanded');
} else {
util.removeClassName(this.dom.label, 'expanded');
util.addClassName(this.dom.label, collapsedDirClassName);
}
} else if (this.nestedGroups) {
this.nestedGroups = null;
collapsedDirClassName = this.itemSet.options.rtl ? 'collapsed-rtl' : 'collapsed';
util.removeClassName(this.dom.label, collapsedDirClassName);
util.removeClassName(this.dom.label, 'expanded');
util.removeClassName(this.dom.label, 'vis-nesting-group');
}
if (data && data.nestedInGroup) {
util.addClassName(this.dom.label, 'vis-nested-group');
if (this.itemSet.options && this.itemSet.options.rtl) {
this.dom.inner.style.paddingRight = '30px';
} else {
this.dom.inner.style.paddingLeft = '30px';
}
}
// update className
var className = data && data.className || null;
if (className != this.className) {
if (this.className) {
util.removeClassName(this.dom.label, this.className);
util.removeClassName(this.dom.foreground, this.className);
util.removeClassName(this.dom.background, this.className);
util.removeClassName(this.dom.axis, this.className);
}
util.addClassName(this.dom.label, className);
util.addClassName(this.dom.foreground, className);
util.addClassName(this.dom.background, className);
util.addClassName(this.dom.axis, className);
this.className = className;
}
// update style
if (this.style) {
util.removeCssText(this.dom.label, this.style);
this.style = null;
}
if (data && data.style) {
util.addCssText(this.dom.label, data.style);
this.style = data.style;
}
};
/**
* Get the width of the group label
* @return {number} width
*/
Group.prototype.getLabelWidth = function () {
return this.props.label.width;
};
Group.prototype._didMarkerHeightChange = function () {
var markerHeight = this.dom.marker.clientHeight;
if (markerHeight != this.lastMarkerHeight) {
this.lastMarkerHeight = markerHeight;
var redrawQueue = {};
var redrawQueueLength = 0;
util.forEach(this.items, function (item, key) {
item.dirty = true;
if (item.displayed) {
var returnQueue = true;
redrawQueue[key] = item.redraw(returnQueue);
redrawQueueLength = redrawQueue[key].length;
}
});
var needRedraw = redrawQueueLength > 0;
if (needRedraw) {
// redraw all regular items
for (var i = 0; i < redrawQueueLength; i++) {
util.forEach(redrawQueue, function (fns) {
fns[i]();
});
}
}
return true;
}
};
Group.prototype._calculateGroupSizeAndPosition = function () {
var offsetTop = this.dom.foreground.offsetTop;
var offsetLeft = this.dom.foreground.offsetLeft;
var offsetWidth = this.dom.foreground.offsetWidth;
this.top = offsetTop;
this.right = offsetLeft;
this.width = offsetWidth;
};
Group.prototype._redrawItems = function (forceRestack, lastIsVisible, margin, range) {
var restack = forceRestack || this.stackDirty || this.isVisible && !lastIsVisible;
// if restacking, reposition visible items vertically
if (restack) {
var visibleSubgroups = {};
var subgroup = null;
if (typeof this.itemSet.options.order === 'function') {
// a custom order function
// brute force restack of all items
// show all items
var me = this;
var limitSize = false;
var redrawQueue = {};
var redrawQueueLength = 0;
util.forEach(this.items, function (item, key) {
if (!item.displayed) {
var returnQueue = true;
redrawQueue[key] = item.redraw(returnQueue);
redrawQueueLength = redrawQueue[key].length;
me.visibleItems.push(item);
}
});
var needRedraw = redrawQueueLength > 0;
if (needRedraw) {
// redraw all regular items
for (var i = 0; i < redrawQueueLength; i++) {
util.forEach(redrawQueue, function (fns) {
fns[i]();
});
}
}
util.forEach(this.items, function (item) {
item.repositionX(limitSize);
});
if (this.doInnerStack && this.itemSet.options.stackSubgroups) {
// Order the items within each subgroup
for (subgroup in this.subgroups) {
visibleSubgroups[subgroup] = this.subgroups[subgroup].items.slice().sort(function (a, b) {
return me.itemSet.options.order(a.data, b.data);
});
}
stack.stackSubgroupsWithInnerStack(visibleSubgroups, margin, this.subgroups);
} else {
// order all items and force a restacking
var customOrderedItems = this.orderedItems.byStart.slice().sort(function (a, b) {
return me.itemSet.options.order(a.data, b.data);
});
stack.stack(customOrderedItems, margin, true /* restack=true */);
}
this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
} else {
// no custom order function, lazy stacking
this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
if (this.itemSet.options.stack) {
if (this.doInnerStack && this.itemSet.options.stackSubgroups) {
for (subgroup in this.subgroups) {
visibleSubgroups[subgroup] = this.subgroups[subgroup].items;
}
stack.stackSubgroupsWithInnerStack(visibleSubgroups, margin, this.subgroups);
} else {
// TODO: ugly way to access options...
stack.stack(this.visibleItems, margin, true /* restack=true */);
}
} else {
// no stacking
stack.nostack(this.visibleItems, margin, this.subgroups, this.itemSet.options.stackSubgroups);
}
}
this.stackDirty = false;
}
};
Group.prototype._didResize = function (resized, height) {
resized = util.updateProperty(this, 'height', height) || resized;
// recalculate size of label
var labelWidth = this.dom.inner.clientWidth;
var labelHeight = this.dom.inner.clientHeight;
resized = util.updateProperty(this.props.label, 'width', labelWidth) || resized;
resized = util.updateProperty(this.props.label, 'height', labelHeight) || resized;
return resized;
};
Group.prototype._applyGroupHeight = function (height) {
this.dom.background.style.height = height + 'px';
this.dom.foreground.style.height = height + 'px';
this.dom.label.style.height = height + 'px';
};
// update vertical position of items after they are re-stacked and the height of the group is calculated
Group.prototype._updateItemsVerticalPosition = function (margin) {
for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
var item = this.visibleItems[i];
item.repositionY(margin);
if (!this.isVisible && this.groupId != "__background__") {
if (item.displayed) item.hide();
}
}
};
/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [forceRestack=false] Force restacking of all items
* @param {boolean} [returnQueue=false] return the queue or if the group resized
* @return {boolean} Returns true if the group is resized or the redraw queue if returnQueue=true
*/
Group.prototype.redraw = function (range, margin, forceRestack, returnQueue) {
var resized = false;
var lastIsVisible = this.isVisible;
var height;
var queue = [
// force recalculation of the height of the items when the marker height changed
// (due to the Timeline being attached to the DOM or changed from display:none to visible)
function () {
forceRestack = this._didMarkerHeightChange.bind(this);
}.bind(this),
// recalculate the height of the subgroups
this._updateSubGroupHeights.bind(this, margin),
// calculate actual size and position
this._calculateGroupSizeAndPosition.bind(this),
// check if group is visible
function () {
this.isVisible = this._isGroupVisible.bind(this)(range, margin);
}.bind(this),
// redraw Items if needed
function () {
this._redrawItems.bind(this)(forceRestack, lastIsVisible, margin, range);
}.bind(this),
// update subgroups
this._updateSubgroupsSizes.bind(this),
// recalculate the height of the group
function () {
height = this._calculateHeight.bind(this)(margin);
}.bind(this),
// calculate actual size and position again
this._calculateGroupSizeAndPosition.bind(this),
// check if resized
function () {
resized = this._didResize.bind(this)(resized, height);
}.bind(this),
// apply group height
function () {
this._applyGroupHeight.bind(this)(height);
}.bind(this),
// update vertical position of items after they are re-stacked and the height of the group is calculated
function () {
this._updateItemsVerticalPosition.bind(this)(margin);
}.bind(this), function () {
if (!this.isVisible && this.height) {
resized = false;
}
return resized;
}];
if (returnQueue) {
return queue;
} else {
var result;
queue.forEach(function (fn) {
result = fn();
});
return result;
}
};
/**
* recalculate the height of the subgroups
*
* @param {{item: vis.Item}} margin
* @private
*/
Group.prototype._updateSubGroupHeights = function (margin) {
if ((0, _keys2['default'])(this.subgroups).length > 0) {
var me = this;
this.resetSubgroups();
util.forEach(this.visibleItems, function (item) {
if (item.data.subgroup !== undefined) {
me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height + margin.item.vertical);
me.subgroups[item.data.subgroup].visible = true;
}
});
}
};
/**
* check if group is visible
*
* @param {vis.Range} range
* @param {{axis: vis.DataAxis}} margin
* @returns {boolean} is visible
* @private
*/
Group.prototype._isGroupVisible = function (range, margin) {
return this.top <= range.body.domProps.centerContainer.height - range.body.domProps.scrollTop + margin.axis && this.top + this.height + margin.axis >= -range.body.domProps.scrollTop;
};
/**
* recalculate the height of the group
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @returns {number} Returns the height
* @private
*/
Group.prototype._calculateHeight = function (margin) {
// recalculate the height of the group
var height;
var itemsInRange = this.visibleItems;
if (itemsInRange.length > 0) {
var min = itemsInRange[0].top;
var max = itemsInRange[0].top + itemsInRange[0].height;
util.forEach(itemsInRange, function (item) {
min = Math.min(min, item.top);
max = Math.max(max, item.top + item.height);
});
if (min > margin.axis) {
// there is an empty gap between the lowest item and the axis
var offset = min - margin.axis;
max -= offset;
util.forEach(itemsInRange, function (item) {
item.top -= offset;
});
}
height = max + margin.item.vertical / 2;
} else {
height = 0;
}
height = Math.max(height, this.props.label.height);
return height;
};
/**
* Show this group: attach to the DOM
*/
Group.prototype.show = function () {
if (!this.dom.label.parentNode) {
this.itemSet.dom.labelSet.appendChild(this.dom.label);
}
if (!this.dom.foreground.parentNode) {
this.itemSet.dom.foreground.appendChild(this.dom.foreground);
}
if (!this.dom.background.parentNode) {
this.itemSet.dom.background.appendChild(this.dom.background);
}
if (!this.dom.axis.parentNode) {
this.itemSet.dom.axis.appendChild(this.dom.axis);
}
};
/**
* Hide this group: remove from the DOM
*/
Group.prototype.hide = function () {
var label = this.dom.label;
if (label.parentNode) {
label.parentNode.removeChild(label);
}
var foreground = this.dom.foreground;
if (foreground.parentNode) {
foreground.parentNode.removeChild(foreground);
}
var background = this.dom.background;
if (background.parentNode) {
background.parentNode.removeChild(background);
}
var axis = this.dom.axis;
if (axis.parentNode) {
axis.parentNode.removeChild(axis);
}
};
/**
* Add an item to the group
* @param {Item} item
*/
Group.prototype.add = function (item) {
this.items[item.id] = item;
item.setParent(this);
this.stackDirty = true;
// add to
if (item.data.subgroup !== undefined) {
this._addToSubgroup(item);
this.orderSubgroups();
}
if (this.visibleItems.indexOf(item) == -1) {
var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
this._checkIfVisible(item, this.visibleItems, range);
}
};
Group.prototype._addToSubgroup = function (item, subgroupId) {
subgroupId = subgroupId || item.data.subgroup;
if (subgroupId != undefined && this.subgroups[subgroupId] === undefined) {
this.subgroups[subgroupId] = {
height: 0,
top: 0,
start: item.data.start,
end: item.data.end || item.data.start,
visible: false,
index: this.subgroupIndex,
items: [],
stack: this.subgroupStackAll || this.subgroupStack[subgroupId] || false
};
this.subgroupIndex++;
}
if (new Date(item.data.start) < new Date(this.subgroups[subgroupId].start)) {
this.subgroups[subgroupId].start = item.data.start;
}
var itemEnd = item.data.end || item.data.start;
if (new Date(itemEnd) > new Date(this.subgroups[subgroupId].end)) {
this.subgroups[subgroupId].end = itemEnd;
}
this.subgroups[subgroupId].items.push(item);
};
Group.prototype._updateSubgroupsSizes = function () {
var me = this;
if (me.subgroups) {
for (var subgroup in me.subgroups) {
var initialEnd = me.subgroups[subgroup].items[0].data.end || me.subgroups[subgroup].items[0].data.start;
var newStart = me.subgroups[subgroup].items[0].data.start;
var newEnd = initialEnd - 1;
me.subgroups[subgroup].items.forEach(function (item) {
if (new Date(item.data.start) < new Date(newStart)) {
newStart = item.data.start;
}
var itemEnd = item.data.end || item.data.start;
if (new Date(itemEnd) > new Date(newEnd)) {
newEnd = itemEnd;
}
});
me.subgroups[subgroup].start = newStart;
me.subgroups[subgroup].end = new Date(newEnd - 1); // -1 to compensate for colliding end to start subgroups;
}
}
};
Group.prototype.orderSubgroups = function () {
if (this.subgroupOrderer !== undefined) {
var sortArray = [];
var subgroup;
if (typeof this.subgroupOrderer == 'string') {
for (subgroup in this.subgroups) {
sortArray.push({ subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer] });
}
sortArray.sort(function (a, b) {
return a.sortField - b.sortField;
});
} else if (typeof this.subgroupOrderer == 'function') {
for (subgroup in this.subgroups) {
sortArray.push(this.subgroups[subgroup].items[0].data);
}
sortArray.sort(this.subgroupOrderer);
}
if (sortArray.length > 0) {
for (var i = 0; i < sortArray.length; i++) {
this.subgroups[sortArray[i].subgroup].index = i;
}
}
}
};
Group.prototype.resetSubgroups = function () {
for (var subgroup in this.subgroups) {
if (this.subgroups.hasOwnProperty(subgroup)) {
this.subgroups[subgroup].visible = false;
this.subgroups[subgroup].height = 0;
}
}
};
/**
* Remove an item from the group
* @param {Item} item
*/
Group.prototype.remove = function (item) {
delete this.items[item.id];
item.setParent(null);
this.stackDirty = true;
// remove from visible items
var index = this.visibleItems.indexOf(item);
if (index != -1) this.visibleItems.splice(index, 1);
if (item.data.subgroup !== undefined) {
this._removeFromSubgroup(item);
this.orderSubgroups();
}
};
Group.prototype._removeFromSubgroup = function (item, subgroupId) {
subgroupId = subgroupId || item.data.subgroup;
if (subgroupId != undefined) {
var subgroup = this.subgroups[subgroupId];
if (subgroup) {
var itemIndex = subgroup.items.indexOf(item);
// Check the item is actually in this subgroup. How should items not in the group be handled?
if (itemIndex >= 0) {
subgroup.items.splice(itemIndex, 1);
if (!subgroup.items.length) {
delete this.subgroups[subgroupId];
} else {
this._updateSubgroupsSizes();
}
}
}
}
};
/**
* Remove an item from the corresponding DataSet
* @param {Item} item
*/
Group.prototype.removeFromDataSet = function (item) {
this.itemSet.removeItem(item.id);
};
/**
* Reorder the items
*/
Group.prototype.order = function () {
var array = util.toArray(this.items);
var startArray = [];
var endArray = [];
for (var i = 0; i < array.length; i++) {
if (array[i].data.end !== undefined) {
endArray.push(array[i]);
}
startArray.push(array[i]);
}
this.orderedItems = {
byStart: startArray,
byEnd: endArray
};
stack.orderByStart(this.orderedItems.byStart);
stack.orderByEnd(this.orderedItems.byEnd);
};
/**
* Update the visible items
* @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
* @param {Item[]} oldVisibleItems The previously visible items.
* @param {{start: number, end: number}} range Visible range
* @return {Item[]} visibleItems The new visible items.
* @private
*/
Group.prototype._updateItemsInRange = function (orderedItems, oldVisibleItems, range) {
var visibleItems = [];
var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
var interval = (range.end - range.start) / 4;
var lowerBound = range.start - interval;
var upperBound = range.end + interval;
// this function is used to do the binary search.
var searchFunction = function searchFunction(value) {
if (value < lowerBound) {
return -1;
} else if (value <= upperBound) {
return 0;
} else {
return 1;
}
};
// first check if the items that were in view previously are still in view.
// IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
// also cleans up invisible items.
if (oldVisibleItems.length > 0) {
for (var i = 0; i < oldVisibleItems.length; i++) {
this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
}
}
// we do a binary search for the items that have only start values.
var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start');
// trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
return item.data.start < lowerBound || item.data.start > upperBound;
});
// if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
// We therefore have to brute force check all items in the byEnd list
if (this.checkRangedItems == true) {
this.checkRangedItems = false;
for (i = 0; i < orderedItems.byEnd.length; i++) {
this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
}
} else {
// we do a binary search for the items that have defined end times.
var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data', 'end');
// trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
return item.data.end < lowerBound || item.data.end > upperBound;
});
}
var redrawQueue = {};
var redrawQueueLength = 0;
for (i = 0; i < visibleItems.length; i++) {
var item = visibleItems[i];
if (!item.displayed) {
var returnQueue = true;
redrawQueue[i] = item.redraw(returnQueue);
redrawQueueLength = redrawQueue[i].length;
}
}
var needRedraw = redrawQueueLength > 0;
if (needRedraw) {
// redraw all regular items
for (var j = 0; j < redrawQueueLength; j++) {
util.forEach(redrawQueue, function (fns) {
fns[j]();
});
}
}
for (i = 0; i < visibleItems.length; i++) {
visibleItems[i].repositionX();
}
return visibleItems;
};
Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
if (initialPos != -1) {
var i, item;
for (i = initialPos; i >= 0; i--) {
item = items[i];
if (breakCondition(item)) {
break;
} else {
if (visibleItemsLookup[item.id] === undefined) {
visibleItemsLookup[item.id] = true;
visibleItems.push(item);
}
}
}
for (i = initialPos + 1; i < items.length; i++) {
item = items[i];
if (breakCondition(item)) {
break;
} else {
if (visibleItemsLookup[item.id] === undefined) {
visibleItemsLookup[item.id] = true;
visibleItems.push(item);
}
}
}
}
};
/**
* this function is very similar to the _checkIfInvisible() but it does not
* return booleans, hides the item if it should not be seen and always adds to
* the visibleItems.
* this one is for brute forcing and hiding.
*
* @param {Item} item
* @param {Array} visibleItems
* @param {{start:number, end:number}} range
* @private
*/
Group.prototype._checkIfVisible = function (item, visibleItems, range) {
if (item.isVisible(range)) {
if (!item.displayed) item.show();
// reposition item horizontally
item.repositionX();
visibleItems.push(item);
} else {
if (item.displayed) item.hide();
}
};
/**
* this function is very similar to the _checkIfInvisible() but it does not
* return booleans, hides the item if it should not be seen and always adds to
* the visibleItems.
* this one is for brute forcing and hiding.
*
* @param {Item} item
* @param {Array.} visibleItems
* @param {Object} visibleItemsLookup
* @param {{start:number, end:number}} range
* @private
*/
Group.prototype._checkIfVisibleWithReference = function (item, visibleItems, visibleItemsLookup, range) {
if (item.isVisible(range)) {
if (visibleItemsLookup[item.id] === undefined) {
visibleItemsLookup[item.id] = true;
visibleItems.push(item);
}
} else {
if (item.displayed) item.hide();
}
};
Group.prototype.changeSubgroup = function (item, oldSubgroup, newSubgroup) {
this._removeFromSubgroup(item, oldSubgroup);
this._addToSubgroup(item, newSubgroup);
this.orderSubgroups();
};
module.exports = Group;
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _create = __webpack_require__(29);
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Group = __webpack_require__(68);
/**
* @constructor BackgroundGroup
* @param {number | string} groupId
* @param {Object} data
* @param {ItemSet} itemSet
* @extends Group
*/
function BackgroundGroup(groupId, data, itemSet) {
Group.call(this, groupId, data, itemSet);
this.width = 0;
this.height = 0;
this.top = 0;
this.left = 0;
}
BackgroundGroup.prototype = (0, _create2['default'])(Group.prototype);
/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [forceRestack=false] Force restacking of all items
* @return {boolean} Returns true if the group is resized
*/
BackgroundGroup.prototype.redraw = function (range, margin, forceRestack) {
// eslint-disable-line no-unused-vars
var resized = false;
this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
// calculate actual size
this.width = this.dom.background.offsetWidth;
// apply new height (just always zero for BackgroundGroup
this.dom.background.style.height = '0';
// update vertical position of items after they are re-stacked and the height of the group is calculated
for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
var item = this.visibleItems[i];
item.repositionY(margin);
}
return resized;
};
/**
* Show this group: attach to the DOM
*/
BackgroundGroup.prototype.show = function () {
if (!this.dom.background.parentNode) {
this.itemSet.dom.background.appendChild(this.dom.background);
}
};
module.exports = BackgroundGroup;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Item = __webpack_require__(38);
/**
* @constructor RangeItem
* @extends Item
* @param {Object} data Object containing parameters start, end
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe options
*/
function RangeItem(data, conversion, options) {
this.props = {
content: {
width: 0
}
};
this.overflow = false; // if contents can overflow (css styling), this flag is set to true
this.options = options;
// validate data
if (data) {
if (data.start == undefined) {
throw new Error('Property "start" missing in item ' + data.id);
}
if (data.end == undefined) {
throw new Error('Property "end" missing in item ' + data.id);
}
}
Item.call(this, data, conversion, options);
}
RangeItem.prototype = new Item(null, null, null);
RangeItem.prototype.baseClassName = 'vis-item vis-range';
/**
* Check whether this item is visible inside given range
*
* @param {vis.Range} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
RangeItem.prototype.isVisible = function (range) {
// determine visibility
return this.data.start < range.end && this.data.end > range.start;
};
RangeItem.prototype._createDomElement = function () {
if (!this.dom) {
// create DOM
this.dom = {};
// background box
this.dom.box = document.createElement('div');
// className is updated in redraw()
// frame box (to prevent the item contents from overflowing)
this.dom.frame = document.createElement('div');
this.dom.frame.className = 'vis-item-overflow';
this.dom.box.appendChild(this.dom.frame);
// visible frame box (showing the frame that is always visible)
this.dom.visibleFrame = document.createElement('div');
this.dom.visibleFrame.className = 'vis-item-visible-frame';
this.dom.box.appendChild(this.dom.visibleFrame);
// contents box
this.dom.content = document.createElement('div');
this.dom.content.className = 'vis-item-content';
this.dom.frame.appendChild(this.dom.content);
// attach this item as attribute
this.dom.box['timeline-item'] = this;
this.dirty = true;
}
};
RangeItem.prototype._appendDomElement = function () {
if (!this.parent) {
throw new Error('Cannot redraw item: no parent attached');
}
if (!this.dom.box.parentNode) {
var foreground = this.parent.dom.foreground;
if (!foreground) {
throw new Error('Cannot redraw item: parent has no foreground container element');
}
foreground.appendChild(this.dom.box);
}
this.displayed = true;
};
RangeItem.prototype._updateDirtyDomComponents = function () {
// update dirty DOM. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if (this.dirty) {
this._updateContents(this.dom.content);
this._updateDataAttributes(this.dom.box);
this._updateStyle(this.dom.box);
var editable = this.editable.updateTime || this.editable.updateGroup;
// update class
var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
this.dom.box.className = this.baseClassName + className;
// turn off max-width to be able to calculate the real width
// this causes an extra browser repaint/reflow, but so be it
this.dom.content.style.maxWidth = 'none';
}
};
RangeItem.prototype._getDomComponentsSizes = function () {
// determine from css whether this box has overflow
this.overflow = window.getComputedStyle(this.dom.frame).overflow !== 'hidden';
return {
content: {
width: this.dom.content.offsetWidth
},
box: {
height: this.dom.box.offsetHeight
}
};
};
RangeItem.prototype._updateDomComponentsSizes = function (sizes) {
this.props.content.width = sizes.content.width;
this.height = sizes.box.height;
this.dom.content.style.maxWidth = '';
this.dirty = false;
};
RangeItem.prototype._repaintDomAdditionals = function () {
this._repaintOnItemUpdateTimeTooltip(this.dom.box);
this._repaintDeleteButton(this.dom.box);
this._repaintDragCenter();
this._repaintDragLeft();
this._repaintDragRight();
};
/**
* Repaint the item
* @param {boolean} [returnQueue=false] return the queue
* @return {boolean} the redraw queue if returnQueue=true
*/
RangeItem.prototype.redraw = function (returnQueue) {
var sizes;
var queue = [
// create item DOM
this._createDomElement.bind(this),
// append DOM to parent DOM
this._appendDomElement.bind(this),
// update dirty DOM
this._updateDirtyDomComponents.bind(this), function () {
if (this.dirty) {
sizes = this._getDomComponentsSizes.bind(this)();
}
}.bind(this), function () {
if (this.dirty) {
this._updateDomComponentsSizes.bind(this)(sizes);
}
}.bind(this),
// repaint DOM additionals
this._repaintDomAdditionals.bind(this)];
if (returnQueue) {
return queue;
} else {
var result;
queue.forEach(function (fn) {
result = fn();
});
return result;
}
};
/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
*/
RangeItem.prototype.show = function () {
if (!this.displayed) {
this.redraw();
}
};
/**
* Hide the item from the DOM (when visible)
*/
RangeItem.prototype.hide = function () {
if (this.displayed) {
var box = this.dom.box;
if (box.parentNode) {
box.parentNode.removeChild(box);
}
this.displayed = false;
}
};
/**
* Reposition the item horizontally
* @param {boolean} [limitSize=true] If true (default), the width of the range
* item will be limited, as the browser cannot
* display very wide divs. This means though
* that the applied left and width may
* not correspond to the ranges start and end
* @Override
*/
RangeItem.prototype.repositionX = function (limitSize) {
var parentWidth = this.parent.width;
var start = this.conversion.toScreen(this.data.start);
var end = this.conversion.toScreen(this.data.end);
var align = this.data.align === undefined ? this.options.align : this.data.align;
var contentStartPosition;
var contentWidth;
// limit the width of the range, as browsers cannot draw very wide divs
// unless limitSize: false is explicitly set in item data
if (this.data.limitSize !== false && (limitSize === undefined || limitSize === true)) {
if (start < -parentWidth) {
start = -parentWidth;
}
if (end > 2 * parentWidth) {
end = 2 * parentWidth;
}
}
// add 0.5 to compensate floating-point values rounding
var boxWidth = Math.max(end - start + 0.5, 1);
if (this.overflow) {
if (this.options.rtl) {
this.right = start;
} else {
this.left = start;
}
this.width = boxWidth + this.props.content.width;
contentWidth = this.props.content.width;
// Note: The calculation of width is an optimistic calculation, giving
// a width which will not change when moving the Timeline
// So no re-stacking needed, which is nicer for the eye;
} else {
if (this.options.rtl) {
this.right = start;
} else {
this.left = start;
}
this.width = boxWidth;
contentWidth = Math.min(end - start, this.props.content.width);
}
if (this.options.rtl) {
this.dom.box.style.right = this.right + 'px';
} else {
this.dom.box.style.left = this.left + 'px';
}
this.dom.box.style.width = boxWidth + 'px';
switch (align) {
case 'left':
if (this.options.rtl) {
this.dom.content.style.right = '0';
} else {
this.dom.content.style.left = '0';
}
break;
case 'right':
if (this.options.rtl) {
this.dom.content.style.right = Math.max(boxWidth - contentWidth, 0) + 'px';
} else {
this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px';
}
break;
case 'center':
if (this.options.rtl) {
this.dom.content.style.right = Math.max((boxWidth - contentWidth) / 2, 0) + 'px';
} else {
this.dom.content.style.left = Math.max((boxWidth - contentWidth) / 2, 0) + 'px';
}
break;
default:
// 'auto'
// when range exceeds left of the window, position the contents at the left of the visible area
if (this.overflow) {
if (end > 0) {
contentStartPosition = Math.max(-start, 0);
} else {
contentStartPosition = -contentWidth; // ensure it's not visible anymore
}
} else {
if (start < 0) {
contentStartPosition = -start;
} else {
contentStartPosition = 0;
}
}
if (this.options.rtl) {
this.dom.content.style.right = contentStartPosition + 'px';
} else {
this.dom.content.style.left = contentStartPosition + 'px';
this.dom.content.style.width = 'calc(100% - ' + contentStartPosition + 'px)';
}
}
};
/**
* Reposition the item vertically
* @Override
*/
RangeItem.prototype.repositionY = function () {
var orientation = this.options.orientation.item;
var box = this.dom.box;
if (orientation == 'top') {
box.style.top = this.top + 'px';
} else {
box.style.top = this.parent.height - this.top - this.height + 'px';
}
};
/**
* Repaint a drag area on the left side of the range when the range is selected
* @protected
*/
RangeItem.prototype._repaintDragLeft = function () {
if ((this.selected || this.options.itemsAlwaysDraggable.range) && this.options.editable.updateTime && !this.dom.dragLeft) {
// create and show drag area
var dragLeft = document.createElement('div');
dragLeft.className = 'vis-drag-left';
dragLeft.dragLeftItem = this;
this.dom.box.appendChild(dragLeft);
this.dom.dragLeft = dragLeft;
} else if (!this.selected && !this.options.itemsAlwaysDraggable.range && this.dom.dragLeft) {
// delete drag area
if (this.dom.dragLeft.parentNode) {
this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
}
this.dom.dragLeft = null;
}
};
/**
* Repaint a drag area on the right side of the range when the range is selected
* @protected
*/
RangeItem.prototype._repaintDragRight = function () {
if ((this.selected || this.options.itemsAlwaysDraggable.range) && this.options.editable.updateTime && !this.dom.dragRight) {
// create and show drag area
var dragRight = document.createElement('div');
dragRight.className = 'vis-drag-right';
dragRight.dragRightItem = this;
this.dom.box.appendChild(dragRight);
this.dom.dragRight = dragRight;
} else if (!this.selected && !this.options.itemsAlwaysDraggable.range && this.dom.dragRight) {
// delete drag area
if (this.dom.dragRight.parentNode) {
this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
}
this.dom.dragRight = null;
}
};
module.exports = RangeItem;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = __webpack_require__(19);
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var ColorPicker = __webpack_require__(179)['default'];
/**
* The way this works is for all properties of this.possible options, you can supply the property name in any form to list the options.
* Boolean options are recognised as Boolean
* Number options should be written as array: [default value, min value, max value, stepsize]
* Colors should be written as array: ['color', '#ffffff']
* Strings with should be written as array: [option1, option2, option3, ..]
*
* The options are matched with their counterparts in each of the modules and the values used in the configuration are
*/
var Configurator = function () {
/**
* @param {Object} parentModule | the location where parentModule.setOptions() can be called
* @param {Object} defaultContainer | the default container of the module
* @param {Object} configureOptions | the fully configured and predefined options set found in allOptions.js
* @param {number} pixelRatio | canvas pixel ratio
*/
function Configurator(parentModule, defaultContainer, configureOptions) {
var pixelRatio = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
(0, _classCallCheck3['default'])(this, Configurator);
this.parent = parentModule;
this.changedOptions = [];
this.container = defaultContainer;
this.allowCreation = false;
this.options = {};
this.initialized = false;
this.popupCounter = 0;
this.defaultOptions = {
enabled: false,
filter: true,
container: undefined,
showButton: true
};
util.extend(this.options, this.defaultOptions);
this.configureOptions = configureOptions;
this.moduleOptions = {};
this.domElements = [];
this.popupDiv = {};
this.popupLimit = 5;
this.popupHistory = {};
this.colorPicker = new ColorPicker(pixelRatio);
this.wrapper = undefined;
}
/**
* refresh all options.
* Because all modules parse their options by themselves, we just use their options. We copy them here.
*
* @param {Object} options
*/
(0, _createClass3['default'])(Configurator, [{
key: 'setOptions',
value: function setOptions(options) {
if (options !== undefined) {
// reset the popup history because the indices may have been changed.
this.popupHistory = {};
this._removePopup();
var enabled = true;
if (typeof options === 'string') {
this.options.filter = options;
} else if (options instanceof Array) {
this.options.filter = options.join();
} else if ((typeof options === 'undefined' ? 'undefined' : (0, _typeof3['default'])(options)) === 'object') {
if (options.container !== undefined) {
this.options.container = options.container;
}
if (options.filter !== undefined) {
this.options.filter = options.filter;
}
if (options.showButton !== undefined) {
this.options.showButton = options.showButton;
}
if (options.enabled !== undefined) {
enabled = options.enabled;
}
} else if (typeof options === 'boolean') {
this.options.filter = true;
enabled = options;
} else if (typeof options === 'function') {
this.options.filter = options;
enabled = true;
}
if (this.options.filter === false) {
enabled = false;
}
this.options.enabled = enabled;
}
this._clean();
}
/**
*
* @param {Object} moduleOptions
*/
}, {
key: 'setModuleOptions',
value: function setModuleOptions(moduleOptions) {
this.moduleOptions = moduleOptions;
if (this.options.enabled === true) {
this._clean();
if (this.options.container !== undefined) {
this.container = this.options.container;
}
this._create();
}
}
/**
* Create all DOM elements
* @private
*/
}, {
key: '_create',
value: function _create() {
var _this = this;
this._clean();
this.changedOptions = [];
var filter = this.options.filter;
var counter = 0;
var show = false;
for (var option in this.configureOptions) {
if (this.configureOptions.hasOwnProperty(option)) {
this.allowCreation = false;
show = false;
if (typeof filter === 'function') {
show = filter(option, []);
show = show || this._handleObject(this.configureOptions[option], [option], true);
} else if (filter === true || filter.indexOf(option) !== -1) {
show = true;
}
if (show !== false) {
this.allowCreation = true;
// linebreak between categories
if (counter > 0) {
this._makeItem([]);
}
// a header for the category
this._makeHeader(option);
// get the sub options
this._handleObject(this.configureOptions[option], [option]);
}
counter++;
}
}
if (this.options.showButton === true) {
var generateButton = document.createElement('div');
generateButton.className = 'vis-configuration vis-config-button';
generateButton.innerHTML = 'generate options';
generateButton.onclick = function () {
_this._printOptions();
};
generateButton.onmouseover = function () {
generateButton.className = 'vis-configuration vis-config-button hover';
};
generateButton.onmouseout = function () {
generateButton.className = 'vis-configuration vis-config-button';
};
this.optionsContainer = document.createElement('div');
this.optionsContainer.className = 'vis-configuration vis-config-option-container';
this.domElements.push(this.optionsContainer);
this.domElements.push(generateButton);
}
this._push();
//~ this.colorPicker.insertTo(this.container);
}
/**
* draw all DOM elements on the screen
* @private
*/
}, {
key: '_push',
value: function _push() {
this.wrapper = document.createElement('div');
this.wrapper.className = 'vis-configuration-wrapper';
this.container.appendChild(this.wrapper);
for (var i = 0; i < this.domElements.length; i++) {
this.wrapper.appendChild(this.domElements[i]);
}
this._showPopupIfNeeded();
}
/**
* delete all DOM elements
* @private
*/
}, {
key: '_clean',
value: function _clean() {
for (var i = 0; i < this.domElements.length; i++) {
this.wrapper.removeChild(this.domElements[i]);
}
if (this.wrapper !== undefined) {
this.container.removeChild(this.wrapper);
this.wrapper = undefined;
}
this.domElements = [];
this._removePopup();
}
/**
* get the value from the actualOptions if it exists
* @param {array} path | where to look for the actual option
* @returns {*}
* @private
*/
}, {
key: '_getValue',
value: function _getValue(path) {
var base = this.moduleOptions;
for (var i = 0; i < path.length; i++) {
if (base[path[i]] !== undefined) {
base = base[path[i]];
} else {
base = undefined;
break;
}
}
return base;
}
/**
* all option elements are wrapped in an item
* @param {Array} path | where to look for the actual option
* @param {Array.} domElements
* @returns {number}
* @private
*/
}, {
key: '_makeItem',
value: function _makeItem(path) {
if (this.allowCreation === true) {
var item = document.createElement('div');
item.className = 'vis-configuration vis-config-item vis-config-s' + path.length;
for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
domElements[_key - 1] = arguments[_key];
}
domElements.forEach(function (element) {
item.appendChild(element);
});
this.domElements.push(item);
return this.domElements.length;
}
return 0;
}
/**
* header for major subjects
* @param {string} name
* @private
*/
}, {
key: '_makeHeader',
value: function _makeHeader(name) {
var div = document.createElement('div');
div.className = 'vis-configuration vis-config-header';
div.innerHTML = name;
this._makeItem([], div);
}
/**
* make a label, if it is an object label, it gets different styling.
* @param {string} name
* @param {array} path | where to look for the actual option
* @param {string} objectLabel
* @returns {HTMLElement}
* @private
*/
}, {
key: '_makeLabel',
value: function _makeLabel(name, path) {
var objectLabel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var div = document.createElement('div');
div.className = 'vis-configuration vis-config-label vis-config-s' + path.length;
if (objectLabel === true) {
div.innerHTML = '' + name + ':';
} else {
div.innerHTML = name + ':';
}
return div;
}
/**
* make a dropdown list for multiple possible string optoins
* @param {Array.} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_makeDropdown',
value: function _makeDropdown(arr, value, path) {
var select = document.createElement('select');
select.className = 'vis-configuration vis-config-select';
var selectedValue = 0;
if (value !== undefined) {
if (arr.indexOf(value) !== -1) {
selectedValue = arr.indexOf(value);
}
}
for (var i = 0; i < arr.length; i++) {
var option = document.createElement('option');
option.value = arr[i];
if (i === selectedValue) {
option.selected = 'selected';
}
option.innerHTML = arr[i];
select.appendChild(option);
}
var me = this;
select.onchange = function () {
me._update(this.value, path);
};
var label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, select);
}
/**
* make a range object for numeric options
* @param {Array.} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_makeRange',
value: function _makeRange(arr, value, path) {
var defaultValue = arr[0];
var min = arr[1];
var max = arr[2];
var step = arr[3];
var range = document.createElement('input');
range.className = 'vis-configuration vis-config-range';
try {
range.type = 'range'; // not supported on IE9
range.min = min;
range.max = max;
}
// TODO: Add some error handling and remove this lint exception
catch (err) {} // eslint-disable-line no-empty
range.step = step;
// set up the popup settings in case they are needed.
var popupString = '';
var popupValue = 0;
if (value !== undefined) {
var factor = 1.20;
if (value < 0 && value * factor < min) {
range.min = Math.ceil(value * factor);
popupValue = range.min;
popupString = 'range increased';
} else if (value / factor < min) {
range.min = Math.ceil(value / factor);
popupValue = range.min;
popupString = 'range increased';
}
if (value * factor > max && max !== 1) {
range.max = Math.ceil(value * factor);
popupValue = range.max;
popupString = 'range increased';
}
range.value = value;
} else {
range.value = defaultValue;
}
var input = document.createElement('input');
input.className = 'vis-configuration vis-config-rangeinput';
input.value = range.value;
var me = this;
range.onchange = function () {
input.value = this.value;me._update(Number(this.value), path);
};
range.oninput = function () {
input.value = this.value;
};
var label = this._makeLabel(path[path.length - 1], path);
var itemIndex = this._makeItem(path, label, range, input);
// if a popup is needed AND it has not been shown for this value, show it.
if (popupString !== '' && this.popupHistory[itemIndex] !== popupValue) {
this.popupHistory[itemIndex] = popupValue;
this._setupPopup(popupString, itemIndex);
}
}
/**
* prepare the popup
* @param {string} string
* @param {number} index
* @private
*/
}, {
key: '_setupPopup',
value: function _setupPopup(string, index) {
var _this2 = this;
if (this.initialized === true && this.allowCreation === true && this.popupCounter < this.popupLimit) {
var div = document.createElement("div");
div.id = "vis-configuration-popup";
div.className = "vis-configuration-popup";
div.innerHTML = string;
div.onclick = function () {
_this2._removePopup();
};
this.popupCounter += 1;
this.popupDiv = { html: div, index: index };
}
}
/**
* remove the popup from the dom
* @private
*/
}, {
key: '_removePopup',
value: function _removePopup() {
if (this.popupDiv.html !== undefined) {
this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);
clearTimeout(this.popupDiv.hideTimeout);
clearTimeout(this.popupDiv.deleteTimeout);
this.popupDiv = {};
}
}
/**
* Show the popup if it is needed.
* @private
*/
}, {
key: '_showPopupIfNeeded',
value: function _showPopupIfNeeded() {
var _this3 = this;
if (this.popupDiv.html !== undefined) {
var correspondingElement = this.domElements[this.popupDiv.index];
var rect = correspondingElement.getBoundingClientRect();
this.popupDiv.html.style.left = rect.left + "px";
this.popupDiv.html.style.top = rect.top - 30 + "px"; // 30 is the height;
document.body.appendChild(this.popupDiv.html);
this.popupDiv.hideTimeout = setTimeout(function () {
_this3.popupDiv.html.style.opacity = 0;
}, 1500);
this.popupDiv.deleteTimeout = setTimeout(function () {
_this3._removePopup();
}, 1800);
}
}
/**
* make a checkbox for boolean options.
* @param {number} defaultValue
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_makeCheckbox',
value: function _makeCheckbox(defaultValue, value, path) {
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'vis-configuration vis-config-checkbox';
checkbox.checked = defaultValue;
if (value !== undefined) {
checkbox.checked = value;
if (value !== defaultValue) {
if ((typeof defaultValue === 'undefined' ? 'undefined' : (0, _typeof3['default'])(defaultValue)) === 'object') {
if (value !== defaultValue.enabled) {
this.changedOptions.push({ path: path, value: value });
}
} else {
this.changedOptions.push({ path: path, value: value });
}
}
}
var me = this;
checkbox.onchange = function () {
me._update(this.checked, path);
};
var label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, checkbox);
}
/**
* make a text input field for string options.
* @param {number} defaultValue
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_makeTextInput',
value: function _makeTextInput(defaultValue, value, path) {
var checkbox = document.createElement('input');
checkbox.type = 'text';
checkbox.className = 'vis-configuration vis-config-text';
checkbox.value = value;
if (value !== defaultValue) {
this.changedOptions.push({ path: path, value: value });
}
var me = this;
checkbox.onchange = function () {
me._update(this.value, path);
};
var label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, checkbox);
}
/**
* make a color field with a color picker for color fields
* @param {Array.} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_makeColorField',
value: function _makeColorField(arr, value, path) {
var _this4 = this;
var defaultColor = arr[1];
var div = document.createElement('div');
value = value === undefined ? defaultColor : value;
if (value !== 'none') {
div.className = 'vis-configuration vis-config-colorBlock';
div.style.backgroundColor = value;
} else {
div.className = 'vis-configuration vis-config-colorBlock none';
}
value = value === undefined ? defaultColor : value;
div.onclick = function () {
_this4._showColorPicker(value, div, path);
};
var label = this._makeLabel(path[path.length - 1], path);
this._makeItem(path, label, div);
}
/**
* used by the color buttons to call the color picker.
* @param {number} value
* @param {HTMLElement} div
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_showColorPicker',
value: function _showColorPicker(value, div, path) {
var _this5 = this;
// clear the callback from this div
div.onclick = function () {};
this.colorPicker.insertTo(div);
this.colorPicker.show();
this.colorPicker.setColor(value);
this.colorPicker.setUpdateCallback(function (color) {
var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')';
div.style.backgroundColor = colorString;
_this5._update(colorString, path);
});
// on close of the colorpicker, restore the callback.
this.colorPicker.setCloseCallback(function () {
div.onclick = function () {
_this5._showColorPicker(value, div, path);
};
});
}
/**
* parse an object and draw the correct items
* @param {Object} obj
* @param {array} [path=[]] | where to look for the actual option
* @param {boolean} [checkOnly=false]
* @returns {boolean}
* @private
*/
}, {
key: '_handleObject',
value: function _handleObject(obj) {
var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var checkOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var show = false;
var filter = this.options.filter;
var visibleInSet = false;
for (var subObj in obj) {
if (obj.hasOwnProperty(subObj)) {
show = true;
var item = obj[subObj];
var newPath = util.copyAndExtendArray(path, subObj);
if (typeof filter === 'function') {
show = filter(subObj, path);
// if needed we must go deeper into the object.
if (show === false) {
if (!(item instanceof Array) && typeof item !== 'string' && typeof item !== 'boolean' && item instanceof Object) {
this.allowCreation = false;
show = this._handleObject(item, newPath, true);
this.allowCreation = checkOnly === false;
}
}
}
if (show !== false) {
visibleInSet = true;
var value = this._getValue(newPath);
if (item instanceof Array) {
this._handleArray(item, value, newPath);
} else if (typeof item === 'string') {
this._makeTextInput(item, value, newPath);
} else if (typeof item === 'boolean') {
this._makeCheckbox(item, value, newPath);
} else if (item instanceof Object) {
// collapse the physics options that are not enabled
var draw = true;
if (path.indexOf('physics') !== -1) {
if (this.moduleOptions.physics.solver !== subObj) {
draw = false;
}
}
if (draw === true) {
// initially collapse options with an disabled enabled option.
if (item.enabled !== undefined) {
var enabledPath = util.copyAndExtendArray(newPath, 'enabled');
var enabledValue = this._getValue(enabledPath);
if (enabledValue === true) {
var label = this._makeLabel(subObj, newPath, true);
this._makeItem(newPath, label);
visibleInSet = this._handleObject(item, newPath) || visibleInSet;
} else {
this._makeCheckbox(item, enabledValue, newPath);
}
} else {
var _label = this._makeLabel(subObj, newPath, true);
this._makeItem(newPath, _label);
visibleInSet = this._handleObject(item, newPath) || visibleInSet;
}
}
} else {
console.error('dont know how to handle', item, subObj, newPath);
}
}
}
}
return visibleInSet;
}
/**
* handle the array type of option
* @param {Array.} arr
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_handleArray',
value: function _handleArray(arr, value, path) {
if (typeof arr[0] === 'string' && arr[0] === 'color') {
this._makeColorField(arr, value, path);
if (arr[1] !== value) {
this.changedOptions.push({ path: path, value: value });
}
} else if (typeof arr[0] === 'string') {
this._makeDropdown(arr, value, path);
if (arr[0] !== value) {
this.changedOptions.push({ path: path, value: value });
}
} else if (typeof arr[0] === 'number') {
this._makeRange(arr, value, path);
if (arr[0] !== value) {
this.changedOptions.push({ path: path, value: Number(value) });
}
}
}
/**
* called to update the network with the new settings.
* @param {number} value
* @param {array} path | where to look for the actual option
* @private
*/
}, {
key: '_update',
value: function _update(value, path) {
var options = this._constructOptions(value, path);
if (this.parent.body && this.parent.body.emitter && this.parent.body.emitter.emit) {
this.parent.body.emitter.emit("configChange", options);
}
this.initialized = true;
this.parent.setOptions(options);
}
/**
*
* @param {string|Boolean} value
* @param {Array.} path
* @param {{}} optionsObj
* @returns {{}}
* @private
*/
}, {
key: '_constructOptions',
value: function _constructOptions(value, path) {
var optionsObj = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var pointer = optionsObj;
// when dropdown boxes can be string or boolean, we typecast it into correct types
value = value === 'true' ? true : value;
value = value === 'false' ? false : value;
for (var i = 0; i < path.length; i++) {
if (path[i] !== 'global') {
if (pointer[path[i]] === undefined) {
pointer[path[i]] = {};
}
if (i !== path.length - 1) {
pointer = pointer[path[i]];
} else {
pointer[path[i]] = value;
}
}
}
return optionsObj;
}
/**
* @private
*/
}, {
key: '_printOptions',
value: function _printOptions() {
var options = this.getOptions();
this.optionsContainer.innerHTML = '
';
}
/**
*
* @returns {{}} options
*/
}, {
key: 'getOptions',
value: function getOptions() {
var options = {};
for (var i = 0; i < this.changedOptions.length; i++) {
this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options);
}
return options;
}
}]);
return Configurator;
}();
exports['default'] = Configurator;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var DOMutil = __webpack_require__(14);
/**
*
* @param {number | string} groupId
* @param {Object} options // TODO: Describe options
*
* @constructor Points
*/
function Points(groupId, options) {} // eslint-disable-line no-unused-vars
/**
* draw the data points
*
* @param {Array} dataset
* @param {GraphGroup} group
* @param {Object} framework | SVG DOM element
* @param {number} [offset]
*/
Points.draw = function (dataset, group, framework, offset) {
offset = offset || 0;
var callback = getCallback(framework, group);
for (var i = 0; i < dataset.length; i++) {
if (!callback) {
// draw the point the simple way.
DOMutil.drawPoint(dataset[i].screen_x + offset, dataset[i].screen_y, getGroupTemplate(group), framework.svgElements, framework.svg, dataset[i].label);
} else {
var callbackResult = callback(dataset[i], group); // result might be true, false or an object
if (callbackResult === true || (typeof callbackResult === 'undefined' ? 'undefined' : (0, _typeof3['default'])(callbackResult)) === 'object') {
DOMutil.drawPoint(dataset[i].screen_x + offset, dataset[i].screen_y, getGroupTemplate(group, callbackResult), framework.svgElements, framework.svg, dataset[i].label);
}
}
}
};
Points.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
var fillHeight = iconHeight * 0.5;
var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
outline.setAttributeNS(null, "x", x);
outline.setAttributeNS(null, "y", y - fillHeight);
outline.setAttributeNS(null, "width", iconWidth);
outline.setAttributeNS(null, "height", 2 * fillHeight);
outline.setAttributeNS(null, "class", "vis-outline");
//Don't call callback on icon
DOMutil.drawPoint(x + 0.5 * iconWidth, y, getGroupTemplate(group), framework.svgElements, framework.svg);
};
/**
*
* @param {vis.Group} group
* @param {any} callbackResult
* @returns {{style: *, styles: (*|string), size: *, className: *}}
*/
function getGroupTemplate(group, callbackResult) {
callbackResult = typeof callbackResult === 'undefined' ? {} : callbackResult;
return {
style: callbackResult.style || group.options.drawPoints.style,
styles: callbackResult.styles || group.options.drawPoints.styles,
size: callbackResult.size || group.options.drawPoints.size,
className: callbackResult.className || group.className
};
}
/**
*
* @param {Object} framework | SVG DOM element
* @param {vis.Group} group
* @returns {function}
*/
function getCallback(framework, group) {
var callback = undefined;
// check for the graph2d onRender
if (framework.options && framework.options.drawPoints && framework.options.drawPoints.onRender && typeof framework.options.drawPoints.onRender == 'function') {
callback = framework.options.drawPoints.onRender;
}
// override it with the group onRender if defined
if (group.group.options && group.group.options.drawPoints && group.group.options.drawPoints.onRender && typeof group.group.options.drawPoints.onRender == 'function') {
callback = group.group.options.drawPoints.onRender;
}
return callback;
}
module.exports = Points;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = __webpack_require__(3);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(4);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(5);
var _inherits3 = _interopRequireDefault(_inherits2);
var _NodeBase2 = __webpack_require__(23);
var _NodeBase3 = _interopRequireDefault(_NodeBase2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* NOTE: This is a bad base class
*
* Child classes are:
*
* Image - uses *only* image methods
* Circle - uses *only* _drawRawCircle
* CircleImage - uses all
*
* TODO: Refactor, move _drawRawCircle to different module, derive Circle from NodeBase
* Rename this to ImageBase
* Consolidate common code in Image and CircleImage to base class
*
* @extends NodeBase
*/
var CircleImageBase = function (_NodeBase) {
(0, _inherits3['default'])(CircleImageBase, _NodeBase);
/**
* @param {Object} options
* @param {Object} body
* @param {Label} labelModule
*/
function CircleImageBase(options, body, labelModule) {
(0, _classCallCheck3['default'])(this, CircleImageBase);
var _this = (0, _possibleConstructorReturn3['default'])(this, (CircleImageBase.__proto__ || (0, _getPrototypeOf2['default'])(CircleImageBase)).call(this, options, body, labelModule));
_this.labelOffset = 0;
_this.selected = false;
return _this;
}
/**
*
* @param {Object} options
* @param {Object} [imageObj]
* @param {Object} [imageObjAlt]
*/
(0, _createClass3['default'])(CircleImageBase, [{
key: 'setOptions',
value: function setOptions(options, imageObj, imageObjAlt) {
this.options = options;
if (!(imageObj === undefined && imageObjAlt === undefined)) {
this.setImages(imageObj, imageObjAlt);
}
}
/**
* Set the images for this node.
*
* The images can be updated after the initial setting of options;
* therefore, this method needs to be reentrant.
*
* For correct working in error cases, it is necessary to properly set
* field 'nodes.brokenImage' in the options.
*
* @param {Image} imageObj required; main image to show for this node
* @param {Image|undefined} imageObjAlt optional; image to show when node is selected
*/
}, {
key: 'setImages',
value: function setImages(imageObj, imageObjAlt) {
if (imageObjAlt && this.selected) {
this.imageObj = imageObjAlt;
this.imageObjAlt = imageObj;
} else {
this.imageObj = imageObj;
this.imageObjAlt = imageObjAlt;
}
}
/**
* Set selection and switch between the base and the selected image.
*
* Do the switch only if imageObjAlt exists.
*
* @param {boolean} selected value of new selected state for current node
*/
}, {
key: 'switchImages',
value: function switchImages(selected) {
var selection_changed = selected && !this.selected || !selected && this.selected;
this.selected = selected; // Remember new selection
if (this.imageObjAlt !== undefined && selection_changed) {
var imageTmp = this.imageObj;
this.imageObj = this.imageObjAlt;
this.imageObjAlt = imageTmp;
}
}
/**
* Adjust the node dimensions for a loaded image.
*
* Pre: this.imageObj is valid
*/
}, {
key: '_resizeImage',
value: function _resizeImage() {
var width, height;
if (this.options.shapeProperties.useImageSize === false) {
// Use the size property
var ratio_width = 1;
var ratio_height = 1;
// Only calculate the proper ratio if both width and height not zero
if (this.imageObj.width && this.imageObj.height) {
if (this.imageObj.width > this.imageObj.height) {
ratio_width = this.imageObj.width / this.imageObj.height;
} else {
ratio_height = this.imageObj.height / this.imageObj.width;
}
}
width = this.options.size * 2 * ratio_width;
height = this.options.size * 2 * ratio_height;
} else {
// Use the image size
width = this.imageObj.width;
height = this.imageObj.height;
}
this.width = width;
this.height = height;
this.radius = 0.5 * this.width;
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
* @private
*/
}, {
key: '_drawRawCircle',
value: function _drawRawCircle(ctx, x, y, values) {
this.initContextForDraw(ctx, values);
ctx.circle(x, y, values.size);
this.performFill(ctx, values);
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
* @private
*/
}, {
key: '_drawImageAtPosition',
value: function _drawImageAtPosition(ctx, values) {
if (this.imageObj.width != 0) {
// draw the image
ctx.globalAlpha = 1.0;
// draw shadow if enabled
this.enableShadow(ctx, values);
var factor = 1;
if (this.options.shapeProperties.interpolation === true) {
factor = this.imageObj.width / this.width / this.body.view.scale;
}
this.imageObj.drawImageAtPosition(ctx, factor, this.left, this.top, this.width, this.height);
// disable shadows for other elements.
this.disableShadow(ctx, values);
}
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {number} x width
* @param {number} y height
* @param {boolean} selected
* @param {boolean} hover
* @private
*/
}, {
key: '_drawImageLabel',
value: function _drawImageLabel(ctx, x, y, selected, hover) {
var yLabel;
var offset = 0;
if (this.height !== undefined) {
offset = this.height * 0.5;
var labelDimensions = this.labelModule.getTextSize(ctx, selected, hover);
if (labelDimensions.lineCount >= 1) {
offset += labelDimensions.height / 2;
}
}
yLabel = y + offset;
if (this.options.label) {
this.labelOffset = offset;
}
this.labelModule.draw(ctx, x, yLabel, selected, hover, 'hanging');
}
}]);
return CircleImageBase;
}(_NodeBase3['default']);
exports['default'] = CircleImageBase;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = __webpack_require__(19);
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
var _create = __webpack_require__(29);
var _create2 = _interopRequireDefault(_create);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = __webpack_require__(2);
var Label = __webpack_require__(117)['default'];
var ComponentUtil = __webpack_require__(48)['default'];
var CubicBezierEdge = __webpack_require__(215)['default'];
var BezierEdgeDynamic = __webpack_require__(217)['default'];
var BezierEdgeStatic = __webpack_require__(218)['default'];
var StraightEdge = __webpack_require__(219)['default'];
/**
* An edge connects two nodes and has a specific direction.
*/
var Edge = function () {
/**
* @param {Object} options values specific to this edge, must contain at least 'from' and 'to'
* @param {Object} body shared state from Network instance
* @param {Object} globalOptions options from the EdgesHandler instance
* @param {Object} defaultOptions default options from the EdgeHandler instance. Value and reference are constant
*/
function Edge(options, body, globalOptions, defaultOptions) {
(0, _classCallCheck3['default'])(this, Edge);
if (body === undefined) {
throw new Error("No body provided");
}
// Since globalOptions is constant in values as well as reference,
// Following needs to be done only once.
this.options = util.bridgeObject(globalOptions);
this.globalOptions = globalOptions;
this.defaultOptions = defaultOptions;
this.body = body;
// initialize variables
this.id = undefined;
this.fromId = undefined;
this.toId = undefined;
this.selected = false;
this.hover = false;
this.labelDirty = true;
this.baseWidth = this.options.width;
this.baseFontSize = this.options.font.size;
this.from = undefined; // a node
this.to = undefined; // a node
this.edgeType = undefined;
this.connected = false;
this.labelModule = new Label(this.body, this.options, true /* It's an edge label */);
this.setOptions(options);
}
/**
* Set or overwrite options for the edge
* @param {Object} options an object with options
* @returns {null|boolean} null if no options, boolean if date changed
*/
(0, _createClass3['default'])(Edge, [{
key: 'setOptions',
value: function setOptions(options) {
if (!options) {
return;
}
Edge.parseOptions(this.options, options, true, this.globalOptions);
if (options.id !== undefined) {
this.id = options.id;
}
if (options.from !== undefined) {
this.fromId = options.from;
}
if (options.to !== undefined) {
this.toId = options.to;
}
if (options.title !== undefined) {
this.title = options.title;
}
if (options.value !== undefined) {
options.value = parseFloat(options.value);
}
var pile = [options, this.options, this.defaultOptions];
this.chooser = ComponentUtil.choosify('edge', pile);
// update label Module
this.updateLabelModule(options);
var dataChanged = this.updateEdgeType();
// if anything has been updates, reset the selection width and the hover width
this._setInteractionWidths();
// A node is connected when it has a from and to node that both exist in the network.body.nodes.
this.connect();
if (options.hidden !== undefined || options.physics !== undefined) {
dataChanged = true;
}
return dataChanged;
}
/**
*
* @param {Object} parentOptions
* @param {Object} newOptions
* @param {boolean} [allowDeletion=false]
* @param {Object} [globalOptions={}]
* @param {boolean} [copyFromGlobals=false]
*/
}, {
key: 'getFormattingValues',
/**
*
* @returns {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}}
*/
value: function getFormattingValues() {
var toArrow = this.options.arrows.to === true || this.options.arrows.to.enabled === true;
var fromArrow = this.options.arrows.from === true || this.options.arrows.from.enabled === true;
var middleArrow = this.options.arrows.middle === true || this.options.arrows.middle.enabled === true;
var inheritsColor = this.options.color.inherit;
var values = {
toArrow: toArrow,
toArrowScale: this.options.arrows.to.scaleFactor,
toArrowType: this.options.arrows.to.type,
middleArrow: middleArrow,
middleArrowScale: this.options.arrows.middle.scaleFactor,
middleArrowType: this.options.arrows.middle.type,
fromArrow: fromArrow,
fromArrowScale: this.options.arrows.from.scaleFactor,
fromArrowType: this.options.arrows.from.type,
arrowStrikethrough: this.options.arrowStrikethrough,
color: inheritsColor ? undefined : this.options.color.color,
inheritsColor: inheritsColor,
opacity: this.options.color.opacity,
hidden: this.options.hidden,
length: this.options.length,
shadow: this.options.shadow.enabled,
shadowColor: this.options.shadow.color,
shadowSize: this.options.shadow.size,
shadowX: this.options.shadow.x,
shadowY: this.options.shadow.y,
dashes: this.options.dashes,
width: this.options.width
};
if (this.selected || this.hover) {
if (this.chooser === true) {
if (this.selected) {
var selectedWidth = this.options.selectionWidth;
if (typeof selectedWidth === 'function') {
values.width = selectedWidth(values.width);
} else if (typeof selectedWidth === 'number') {
values.width += selectedWidth;
}
values.width = Math.max(values.width, 0.3 / this.body.view.scale);
values.color = this.options.color.highlight;
values.shadow = this.options.shadow.enabled;
} else if (this.hover) {
var hoverWidth = this.options.hoverWidth;
if (typeof hoverWidth === 'function') {
values.width = hoverWidth(values.width);
} else if (typeof hoverWidth === 'number') {
values.width += hoverWidth;
}
values.width = Math.max(values.width, 0.3 / this.body.view.scale);
values.color = this.options.color.hover;
values.shadow = this.options.shadow.enabled;
}
} else if (typeof this.chooser === 'function') {
this.chooser(values, this.options.id, this.selected, this.hover);
if (values.color !== undefined) {
values.inheritsColor = false;
}
if (values.shadow === false) {
if (values.shadowColor !== this.options.shadow.color || values.shadowSize !== this.options.shadow.size || values.shadowX !== this.options.shadow.x || values.shadowY !== this.options.shadow.y) {
values.shadow = true;
}
}
}
} else {
values.shadow = this.options.shadow.enabled;
values.width = Math.max(values.width, 0.3 / this.body.view.scale);
}
return values;
}
/**
* update the options in the label module
*
* @param {Object} options
*/
}, {
key: 'updateLabelModule',
value: function updateLabelModule(options) {
var pile = [options, this.options, this.globalOptions, // Currently set global edge options
this.defaultOptions];
this.labelModule.update(this.options, pile);
if (this.labelModule.baseSize !== undefined) {
this.baseFontSize = this.labelModule.baseSize;
}
}
/**
* update the edge type, set the options
* @returns {boolean}
*/
}, {
key: 'updateEdgeType',
value: function updateEdgeType() {
var smooth = this.options.smooth;
var dataChanged = false;
var changeInType = true;
if (this.edgeType !== undefined) {
if (this.edgeType instanceof BezierEdgeDynamic && smooth.enabled === true && smooth.type === 'dynamic' || this.edgeType instanceof CubicBezierEdge && smooth.enabled === true && smooth.type === 'cubicBezier' || this.edgeType instanceof BezierEdgeStatic && smooth.enabled === true && smooth.type !== 'dynamic' && smooth.type !== 'cubicBezier' || this.edgeType instanceof StraightEdge && smooth.type.enabled === false) {
changeInType = false;
}
if (changeInType === true) {
dataChanged = this.cleanup();
}
}
if (changeInType === true) {
if (smooth.enabled === true) {
if (smooth.type === 'dynamic') {
dataChanged = true;
this.edgeType = new BezierEdgeDynamic(this.options, this.body, this.labelModule);
} else if (smooth.type === 'cubicBezier') {
this.edgeType = new CubicBezierEdge(this.options, this.body, this.labelModule);
} else {
this.edgeType = new BezierEdgeStatic(this.options, this.body, this.labelModule);
}
} else {
this.edgeType = new StraightEdge(this.options, this.body, this.labelModule);
}
} else {
// if nothing changes, we just set the options.
this.edgeType.setOptions(this.options);
}
return dataChanged;
}
/**
* Connect an edge to its nodes
*/
}, {
key: 'connect',
value: function connect() {
this.disconnect();
this.from = this.body.nodes[this.fromId] || undefined;
this.to = this.body.nodes[this.toId] || undefined;
this.connected = this.from !== undefined && this.to !== undefined;
if (this.connected === true) {
this.from.attachEdge(this);
this.to.attachEdge(this);
} else {
if (this.from) {
this.from.detachEdge(this);
}
if (this.to) {
this.to.detachEdge(this);
}
}
this.edgeType.connect();
}
/**
* Disconnect an edge from its nodes
*/
}, {
key: 'disconnect',
value: function disconnect() {
if (this.from) {
this.from.detachEdge(this);
this.from = undefined;
}
if (this.to) {
this.to.detachEdge(this);
this.to = undefined;
}
this.connected = false;
}
/**
* get the title of this edge.
* @return {string} title The title of the edge, or undefined when no title
* has been set.
*/
}, {
key: 'getTitle',
value: function getTitle() {
return this.title;
}
/**
* check if this node is selecte
* @return {boolean} selected True if node is selected, else false
*/
}, {
key: 'isSelected',
value: function isSelected() {
return this.selected;
}
/**
* Retrieve the value of the edge. Can be undefined
* @return {number} value
*/
}, {
key: 'getValue',
value: function getValue() {
return this.options.value;
}
/**
* Adjust the value range of the edge. The edge will adjust it's width
* based on its value.
* @param {number} min
* @param {number} max
* @param {number} total
*/
}, {
key: 'setValueRange',
value: function setValueRange(min, max, total) {
if (this.options.value !== undefined) {
var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
var widthDiff = this.options.scaling.max - this.options.scaling.min;
if (this.options.scaling.label.enabled === true) {
var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
}
this.options.width = this.options.scaling.min + scale * widthDiff;
} else {
this.options.width = this.baseWidth;
this.options.font.size = this.baseFontSize;
}
this._setInteractionWidths();
this.updateLabelModule();
}
/**
*
* @private
*/
}, {
key: '_setInteractionWidths',
value: function _setInteractionWidths() {
if (typeof this.options.hoverWidth === 'function') {
this.edgeType.hoverWidth = this.options.hoverWidth(this.options.width);
} else {
this.edgeType.hoverWidth = this.options.hoverWidth + this.options.width;
}
if (typeof this.options.selectionWidth === 'function') {
this.edgeType.selectionWidth = this.options.selectionWidth(this.options.width);
} else {
this.edgeType.selectionWidth = this.options.selectionWidth + this.options.width;
}
}
/**
* Redraw a edge
* Draw this edge in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
*/
}, {
key: 'draw',
value: function draw(ctx) {
var values = this.getFormattingValues();
if (values.hidden) {
return;
}
// get the via node from the edge type
var viaNode = this.edgeType.getViaNode();
var arrowData = {};
// restore edge targets to defaults
this.edgeType.fromPoint = this.edgeType.from;
this.edgeType.toPoint = this.edgeType.to;
// from and to arrows give a different end point for edges. we set them here
if (values.fromArrow) {
arrowData.from = this.edgeType.getArrowData(ctx, 'from', viaNode, this.selected, this.hover, values);
if (values.arrowStrikethrough === false) this.edgeType.fromPoint = arrowData.from.core;
}
if (values.toArrow) {
arrowData.to = this.edgeType.getArrowData(ctx, 'to', viaNode, this.selected, this.hover, values);
if (values.arrowStrikethrough === false) this.edgeType.toPoint = arrowData.to.core;
}
// the middle arrow depends on the line, which can depend on the to and from arrows so we do this one lastly.
if (values.middleArrow) {
arrowData.middle = this.edgeType.getArrowData(ctx, 'middle', viaNode, this.selected, this.hover, values);
}
// draw everything
this.edgeType.drawLine(ctx, values, this.selected, this.hover, viaNode);
this.drawArrows(ctx, arrowData, values);
this.drawLabel(ctx, viaNode);
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {Object} arrowData
* @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
*/
}, {
key: 'drawArrows',
value: function drawArrows(ctx, arrowData, values) {
if (values.fromArrow) {
this.edgeType.drawArrowHead(ctx, values, this.selected, this.hover, arrowData.from);
}
if (values.middleArrow) {
this.edgeType.drawArrowHead(ctx, values, this.selected, this.hover, arrowData.middle);
}
if (values.toArrow) {
this.edgeType.drawArrowHead(ctx, values, this.selected, this.hover, arrowData.to);
}
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {Node} viaNode
*/
}, {
key: 'drawLabel',
value: function drawLabel(ctx, viaNode) {
if (this.options.label !== undefined) {
// set style
var node1 = this.from;
var node2 = this.to;
if (this.labelModule.differentState(this.selected, this.hover)) {
this.labelModule.getTextSize(ctx, this.selected, this.hover);
}
if (node1.id != node2.id) {
this.labelModule.pointToSelf = false;
var point = this.edgeType.getPoint(0.5, viaNode);
ctx.save();
var rotationPoint = this._getRotation(ctx);
if (rotationPoint.angle != 0) {
ctx.translate(rotationPoint.x, rotationPoint.y);
ctx.rotate(rotationPoint.angle);
}
// draw the label
this.labelModule.draw(ctx, point.x, point.y, this.selected, this.hover);
/*
// Useful debug code: draw a border around the label
// This should **not** be enabled in production!
var size = this.labelModule.getSize();; // ;; intentional so lint catches it
ctx.strokeStyle = "#ff0000";
ctx.strokeRect(size.left, size.top, size.width, size.height);
// End debug code
*/
ctx.restore();
} else {
// Ignore the orientations.
this.labelModule.pointToSelf = true;
var x, y;
var radius = this.options.selfReferenceSize;
if (node1.shape.width > node1.shape.height) {
x = node1.x + node1.shape.width * 0.5;
y = node1.y - radius;
} else {
x = node1.x + radius;
y = node1.y - node1.shape.height * 0.5;
}
point = this._pointOnCircle(x, y, radius, 0.125);
this.labelModule.draw(ctx, point.x, point.y, this.selected, this.hover);
}
}
}
/**
* Determine all visual elements of this edge instance, in which the given
* point falls within the bounding shape.
*
* @param {point} point
* @returns {Array.} list with the items which are on the point
*/
}, {
key: 'getItemsOnPoint',
value: function getItemsOnPoint(point) {
var ret = [];
if (this.labelModule.visible()) {
var rotationPoint = this._getRotation();
if (ComponentUtil.pointInRect(this.labelModule.getSize(), point, rotationPoint)) {
ret.push({ edgeId: this.id, labelId: 0 });
}
}
var obj = {
left: point.x,
top: point.y
};
if (this.isOverlappingWith(obj)) {
ret.push({ edgeId: this.id });
}
return ret;
}
/**
* Check if this object is overlapping with the provided object
* @param {Object} obj an object with parameters left, top
* @return {boolean} True if location is located on the edge
*/
}, {
key: 'isOverlappingWith',
value: function isOverlappingWith(obj) {
if (this.connected) {
var distMax = 10;
var xFrom = this.from.x;
var yFrom = this.from.y;
var xTo = this.to.x;
var yTo = this.to.y;
var xObj = obj.left;
var yObj = obj.top;
var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
return dist < distMax;
} else {
return false;
}
}
/**
* Determine the rotation point, if any.
*
* @param {CanvasRenderingContext2D} [ctx] if passed, do a recalculation of the label size
* @returns {rotationPoint} the point to rotate around and the angle in radians to rotate
* @private
*/
}, {
key: '_getRotation',
value: function _getRotation(ctx) {
var viaNode = this.edgeType.getViaNode();
var point = this.edgeType.getPoint(0.5, viaNode);
if (ctx !== undefined) {
this.labelModule.calculateLabelSize(ctx, this.selected, this.hover, point.x, point.y);
}
var ret = {
x: point.x,
y: this.labelModule.size.yLine,
angle: 0
};
if (!this.labelModule.visible()) {
return ret; // Don't even bother doing the atan2, there's nothing to draw
}
if (this.options.font.align === "horizontal") {
return ret; // No need to calculate angle
}
var dy = this.from.y - this.to.y;
var dx = this.from.x - this.to.x;
var angle = Math.atan2(dy, dx); // radians
// rotate so that label is readable
if (angle < -1 && dx < 0 || angle > 0 && dx < 0) {
angle += Math.PI;
}
ret.angle = angle;
return ret;
}
/**
* Get a point on a circle
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} percentage Value between 0 (line start) and 1 (line end)
* @return {Object} point
* @private
*/
}, {
key: '_pointOnCircle',
value: function _pointOnCircle(x, y, radius, percentage) {
var angle = percentage * 2 * Math.PI;
return {
x: x + radius * Math.cos(angle),
y: y - radius * Math.sin(angle)
};
}
/**
* Sets selected state to true
*/
}, {
key: 'select',
value: function select() {
this.selected = true;
}
/**
* Sets selected state to false
*/
}, {
key: 'unselect',
value: function unselect() {
this.selected = false;
}
/**
* cleans all required things on delete
* @returns {*}
*/
}, {
key: 'cleanup',
value: function cleanup() {
return this.edgeType.cleanup();
}
/**
* Remove edge from the list and perform necessary cleanup.
*/
}, {
key: 'remove',
value: function remove() {
this.cleanup();
this.disconnect();
delete this.body.edges[this.id];
}
/**
* Check if both connecting nodes exist
* @returns {boolean}
*/
}, {
key: 'endPointsValid',
value: function endPointsValid() {
return this.body.nodes[this.fromId] !== undefined && this.body.nodes[this.toId] !== undefined;
}
}], [{
key: 'parseOptions',
value: function parseOptions(parentOptions, newOptions) {
var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var copyFromGlobals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var fields = ['arrowStrikethrough', 'id', 'from', 'hidden', 'hoverWidth', 'labelHighlightBold', 'length', 'line', 'opacity', 'physics', 'scaling', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width', 'font', 'chosen', 'widthConstraint'];
// only deep extend the items in the field array. These do not have shorthand.
util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion);
// Only copy label if it's a legal value.
if (ComponentUtil.isValidLabel(newOptions.label)) {
parentOptions.label = newOptions.label;
} else {
parentOptions.label = undefined;
}
util.mergeOptions(parentOptions, newOptions, 'smooth', globalOptions);
util.mergeOptions(parentOptions, newOptions, 'shadow', globalOptions);
if (newOptions.dashes !== undefined && newOptions.dashes !== null) {
parentOptions.dashes = newOptions.dashes;
} else if (allowDeletion === true && newOptions.dashes === null) {
parentOptions.dashes = (0, _create2['default'])(globalOptions.dashes); // this sets the pointer of the option back to the global option.
}
// set the scaling newOptions
if (newOptions.scaling !== undefined && newOptions.scaling !== null) {
if (newOptions.scaling.min !== undefined) {
parentOptions.scaling.min = newOptions.scaling.min;
}
if (newOptions.scaling.max !== undefined) {
parentOptions.scaling.max = newOptions.scaling.max;
}
util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', globalOptions.scaling);
} else if (allowDeletion === true && newOptions.scaling === null) {
parentOptions.scaling = (0, _create2['default'])(globalOptions.scaling); // this sets the pointer of the option back to the global option.
}
// handle multiple input cases for arrows
if (newOptions.arrows !== undefined && newOptions.arrows !== null) {
if (typeof newOptions.arrows === 'string') {
var arrows = newOptions.arrows.toLowerCase();
parentOptions.arrows.to.enabled = arrows.indexOf("to") != -1;
parentOptions.arrows.middle.enabled = arrows.indexOf("middle") != -1;
parentOptions.arrows.from.enabled = arrows.indexOf("from") != -1;
} else if ((0, _typeof3['default'])(newOptions.arrows) === 'object') {
util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to', globalOptions.arrows);
util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle', globalOptions.arrows);
util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from', globalOptions.arrows);
} else {
throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:" + (0, _stringify2['default'])(newOptions.arrows));
}
} else if (allowDeletion === true && newOptions.arrows === null) {
parentOptions.arrows = (0, _create2['default'])(globalOptions.arrows); // this sets the pointer of the option back to the global option.
}
// handle multiple input cases for color
if (newOptions.color !== undefined && newOptions.color !== null) {
var fromColor = newOptions.color;
var toColor = parentOptions.color;
// If passed, fill in values from default options - required in the case of no prototype bridging
if (copyFromGlobals) {
util.deepExtend(toColor, globalOptions.color, false, allowDeletion);
} else {
// Clear local properties - need to do it like this in order to retain prototype bridges
for (var i in toColor) {
if (toColor.hasOwnProperty(i)) {
delete toColor[i];
}
}
}
if (util.isString(toColor)) {
toColor.color = toColor;
toColor.highlight = toColor;
toColor.hover = toColor;
toColor.inherit = false;
if (fromColor.opacity === undefined) {
toColor.opacity = 1.0; // set default
}
} else {
var colorsDefined = false;
if (fromColor.color !== undefined) {
toColor.color = fromColor.color;colorsDefined = true;
}
if (fromColor.highlight !== undefined) {
toColor.highlight = fromColor.highlight;colorsDefined = true;
}
if (fromColor.hover !== undefined) {
toColor.hover = fromColor.hover;colorsDefined = true;
}
if (fromColor.inherit !== undefined) {
toColor.inherit = fromColor.inherit;
}
if (fromColor.opacity !== undefined) {
toColor.opacity = Math.min(1, Math.max(0, fromColor.opacity));
}
if (colorsDefined === true) {
toColor.inherit = false;
} else {
if (toColor.inherit === undefined) {
toColor.inherit = 'from'; // Set default
}
}
}
} else if (allowDeletion === true && newOptions.color === null) {
parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
}
if (allowDeletion === true && newOptions.font === null) {
parentOptions.font = util.bridgeObject(globalOptions.font); // set the object back to the global options
}
}
}]);
return Edge;
}();
exports['default'] = Edge;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = __webpack_require__(3);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(4);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(5);
var _inherits3 = _interopRequireDefault(_inherits2);
var _EdgeBase2 = __webpack_require__(118);
var _EdgeBase3 = _interopRequireDefault(_EdgeBase2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* The Base Class for all Bezier edges. Bezier curves are used to model smooth
* gradual curves in paths between nodes.
*
* @extends EdgeBase
*/
var BezierEdgeBase = function (_EdgeBase) {
(0, _inherits3['default'])(BezierEdgeBase, _EdgeBase);
/**
* @param {Object} options
* @param {Object} body
* @param {Label} labelModule
*/
function BezierEdgeBase(options, body, labelModule) {
(0, _classCallCheck3['default'])(this, BezierEdgeBase);
return (0, _possibleConstructorReturn3['default'])(this, (BezierEdgeBase.__proto__ || (0, _getPrototypeOf2['default'])(BezierEdgeBase)).call(this, options, body, labelModule));
}
/**
* This function uses binary search to look for the point where the bezier curve crosses the border of the node.
*
* @param {Node} nearNode
* @param {CanvasRenderingContext2D} ctx
* @param {Node} viaNode
* @returns {*}
* @private
*/
(0, _createClass3['default'])(BezierEdgeBase, [{
key: '_findBorderPositionBezier',
value: function _findBorderPositionBezier(nearNode, ctx) {
var viaNode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this._getViaCoordinates();
var maxIterations = 10;
var iteration = 0;
var low = 0;
var high = 1;
var pos, angle, distanceToBorder, distanceToPoint, difference;
var threshold = 0.2;
var node = this.to;
var from = false;
if (nearNode.id === this.from.id) {
node = this.from;
from = true;
}
while (low <= high && iteration < maxIterations) {
var middle = (low + high) * 0.5;
pos = this.getPoint(middle, viaNode);
angle = Math.atan2(node.y - pos.y, node.x - pos.x);
distanceToBorder = node.distanceToBorder(ctx, angle);
distanceToPoint = Math.sqrt(Math.pow(pos.x - node.x, 2) + Math.pow(pos.y - node.y, 2));
difference = distanceToBorder - distanceToPoint;
if (Math.abs(difference) < threshold) {
break; // found
} else if (difference < 0) {
// distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
if (from === false) {
low = middle;
} else {
high = middle;
}
} else {
if (from === false) {
high = middle;
} else {
low = middle;
}
}
iteration++;
}
pos.t = middle;
return pos;
}
/**
* Calculate the distance between a point (x3,y3) and a line segment from
* (x1,y1) to (x2,y2).
* http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
* @param {number} x1 from x
* @param {number} y1 from y
* @param {number} x2 to x
* @param {number} y2 to y
* @param {number} x3 point to check x
* @param {number} y3 point to check y
* @param {Node} via
* @returns {number}
* @private
*/
}, {
key: '_getDistanceToBezierEdge',
value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) {
// x3,y3 is the point
var minDistance = 1e9;
var distance = void 0;
var i = void 0,
t = void 0,
x = void 0,
y = void 0;
var lastX = x1;
var lastY = y1;
for (i = 1; i < 10; i++) {
t = 0.1 * i;
x = Math.pow(1 - t, 2) * x1 + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * x2;
y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * y2;
if (i > 0) {
distance = this._getDistanceToLine(lastX, lastY, x, y, x3, y3);
minDistance = distance < minDistance ? distance : minDistance;
}
lastX = x;
lastY = y;
}
return minDistance;
}
/**
* Draw a bezier curve between two nodes
*
* The method accepts zero, one or two control points.
* Passing zero control points just draws a straight line
*
* @param {CanvasRenderingContext2D} ctx
* @param {Object} values | options for shadow drawing
* @param {Object|undefined} viaNode1 | first control point for curve drawing
* @param {Object|undefined} viaNode2 | second control point for curve drawing
*
* @protected
*/
}, {
key: '_bezierCurve',
value: function _bezierCurve(ctx, values, viaNode1, viaNode2) {
var hasNode1 = viaNode1 !== undefined && viaNode1.x !== undefined;
var hasNode2 = viaNode2 !== undefined && viaNode2.x !== undefined;
ctx.beginPath();
ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
if (hasNode1 && hasNode2) {
ctx.bezierCurveTo(viaNode1.x, viaNode1.y, viaNode2.x, viaNode2.y, this.toPoint.x, this.toPoint.y);
} else if (hasNode1) {
ctx.quadraticCurveTo(viaNode1.x, viaNode1.y, this.toPoint.x, this.toPoint.y);
} else {
// fallback to normal straight edge
ctx.lineTo(this.toPoint.x, this.toPoint.y);
}
// draw shadow if enabled
this.enableShadow(ctx, values);
ctx.stroke();
this.disableShadow(ctx, values);
}
/**
*
* @returns {*|{x, y}|{x: undefined, y: undefined}}
*/
}, {
key: 'getViaNode',
value: function getViaNode() {
return this._getViaCoordinates();
}
}]);
return BezierEdgeBase;
}(_EdgeBase3['default']);
exports['default'] = BezierEdgeBase;
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = __webpack_require__(0);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(1);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var util = __webpack_require__(2);
/**
* Utility Class
*/
var NetworkUtil = function () {
/**
* @ignore
*/
function NetworkUtil() {
(0, _classCallCheck3["default"])(this, NetworkUtil);
}
/**
* Find the center position of the network considering the bounding boxes
*
* @param {Array.} allNodes
* @param {Array.} [specificNodes=[]]
* @returns {{minX: number, maxX: number, minY: number, maxY: number}}
* @static
*/
(0, _createClass3["default"])(NetworkUtil, null, [{
key: "getRange",
value: function getRange(allNodes) {
var specificNodes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var minY = 1e9,
maxY = -1e9,
minX = 1e9,
maxX = -1e9,
node;
if (specificNodes.length > 0) {
for (var i = 0; i < specificNodes.length; i++) {
node = allNodes[specificNodes[i]];
if (minX > node.shape.boundingBox.left) {
minX = node.shape.boundingBox.left;
}
if (maxX < node.shape.boundingBox.right) {
maxX = node.shape.boundingBox.right;
}
if (minY > node.shape.boundingBox.top) {
minY = node.shape.boundingBox.top;
} // top is negative, bottom is positive
if (maxY < node.shape.boundingBox.bottom) {
maxY = node.shape.boundingBox.bottom;
} // top is negative, bottom is positive
}
}
if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
minY = 0, maxY = 0, minX = 0, maxX = 0;
}
return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
}
/**
* Find the center position of the network
*
* @param {Array.} allNodes
* @param {Array.} [specificNodes=[]]
* @returns {{minX: number, maxX: number, minY: number, maxY: number}}
* @static
*/
}, {
key: "getRangeCore",
value: function getRangeCore(allNodes) {
var specificNodes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var minY = 1e9,
maxY = -1e9,
minX = 1e9,
maxX = -1e9,
node;
if (specificNodes.length > 0) {
for (var i = 0; i < specificNodes.length; i++) {
node = allNodes[specificNodes[i]];
if (minX > node.x) {
minX = node.x;
}
if (maxX < node.x) {
maxX = node.x;
}
if (minY > node.y) {
minY = node.y;
} // top is negative, bottom is positive
if (maxY < node.y) {
maxY = node.y;
} // top is negative, bottom is positive
}
}
if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
minY = 0, maxY = 0, minX = 0, maxX = 0;
}
return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
}
/**
* @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
* @returns {{x: number, y: number}}
* @static
*/
}, {
key: "findCenter",
value: function findCenter(range) {
return { x: 0.5 * (range.maxX + range.minX),
y: 0.5 * (range.maxY + range.minY) };
}
/**
* This returns a clone of the options or options of the edge or node to be used for construction of new edges or check functions for new nodes.
* @param {vis.Item} item
* @param {'node'|undefined} type
* @returns {{}}
* @static
*/
}, {
key: "cloneOptions",
value: function cloneOptions(item, type) {
var clonedOptions = {};
if (type === undefined || type === 'node') {
util.deepExtend(clonedOptions, item.options, true);
clonedOptions.x = item.x;
clonedOptions.y = item.y;
clonedOptions.amountOfConnections = item.edges.length;
} else {
util.deepExtend(clonedOptions, item.options, true);
}
return clonedOptions;
}
}]);
return NetworkUtil;
}();
exports["default"] = NetworkUtil;
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(124), __esModule: true };
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(50);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(52);
var $export = __webpack_require__(17);
var redefine = __webpack_require__(83);
var hide = __webpack_require__(26);
var has = __webpack_require__(22);
var Iterators = __webpack_require__(31);
var $iterCreate = __webpack_require__(129);
var setToStringTag = __webpack_require__(59);
var getPrototypeOf = __webpack_require__(85);
var ITERATOR = __webpack_require__(13)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(128);
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(21) && !__webpack_require__(28)(function () {
return Object.defineProperty(__webpack_require__(82)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(32);
var document = __webpack_require__(18).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(26);
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(22);
var toIObject = __webpack_require__(25);
var arrayIndexOf = __webpack_require__(131)(false);
var IE_PROTO = __webpack_require__(56)('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(22);
var toObject = __webpack_require__(41);
var IE_PROTO = __webpack_require__(56)('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(50);
var TAG = __webpack_require__(13)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(17);
var core = __webpack_require__(7);
var fails = __webpack_require__(28);
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(84);
var hiddenKeys = __webpack_require__(58).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(42);
var createDesc = __webpack_require__(39);
var toIObject = __webpack_require__(25);
var toPrimitive = __webpack_require__(53);
var has = __webpack_require__(22);
var IE8_DOM_DEFINE = __webpack_require__(81);
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(21) ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(162), __esModule: true };
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @prototype Point2d
* @param {number} [x]
* @param {number} [y]
*/
function Point2d(x, y) {
this.x = x !== undefined ? x : 0;
this.y = y !== undefined ? y : 0;
}
module.exports = Point2d;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(2);
/**
* An html slider control with start/stop/prev/next buttons
*
* @constructor Slider
* @param {Element} container The element where the slider will be created
* @param {Object} options Available options:
* {boolean} visible If true (default) the
* slider is visible.
*/
function Slider(container, options) {
if (container === undefined) {
throw new Error('No container element defined');
}
this.container = container;
this.visible = options && options.visible != undefined ? options.visible : true;
if (this.visible) {
this.frame = document.createElement('DIV');
//this.frame.style.backgroundColor = '#E5E5E5';
this.frame.style.width = '100%';
this.frame.style.position = 'relative';
this.container.appendChild(this.frame);
this.frame.prev = document.createElement('INPUT');
this.frame.prev.type = 'BUTTON';
this.frame.prev.value = 'Prev';
this.frame.appendChild(this.frame.prev);
this.frame.play = document.createElement('INPUT');
this.frame.play.type = 'BUTTON';
this.frame.play.value = 'Play';
this.frame.appendChild(this.frame.play);
this.frame.next = document.createElement('INPUT');
this.frame.next.type = 'BUTTON';
this.frame.next.value = 'Next';
this.frame.appendChild(this.frame.next);
this.frame.bar = document.createElement('INPUT');
this.frame.bar.type = 'BUTTON';
this.frame.bar.style.position = 'absolute';
this.frame.bar.style.border = '1px solid red';
this.frame.bar.style.width = '100px';
this.frame.bar.style.height = '6px';
this.frame.bar.style.borderRadius = '2px';
this.frame.bar.style.MozBorderRadius = '2px';
this.frame.bar.style.border = '1px solid #7F7F7F';
this.frame.bar.style.backgroundColor = '#E5E5E5';
this.frame.appendChild(this.frame.bar);
this.frame.slide = document.createElement('INPUT');
this.frame.slide.type = 'BUTTON';
this.frame.slide.style.margin = '0px';
this.frame.slide.value = ' ';
this.frame.slide.style.position = 'relative';
this.frame.slide.style.left = '-100px';
this.frame.appendChild(this.frame.slide);
// create events
var me = this;
this.frame.slide.onmousedown = function (event) {
me._onMouseDown(event);
};
this.frame.prev.onclick = function (event) {
me.prev(event);
};
this.frame.play.onclick = function (event) {
me.togglePlay(event);
};
this.frame.next.onclick = function (event) {
me.next(event);
};
}
this.onChangeCallback = undefined;
this.values = [];
this.index = undefined;
this.playTimeout = undefined;
this.playInterval = 1000; // milliseconds
this.playLoop = true;
}
/**
* Select the previous index
*/
Slider.prototype.prev = function () {
var index = this.getIndex();
if (index > 0) {
index--;
this.setIndex(index);
}
};
/**
* Select the next index
*/
Slider.prototype.next = function () {
var index = this.getIndex();
if (index < this.values.length - 1) {
index++;
this.setIndex(index);
}
};
/**
* Select the next index
*/
Slider.prototype.playNext = function () {
var start = new Date();
var index = this.getIndex();
if (index < this.values.length - 1) {
index++;
this.setIndex(index);
} else if (this.playLoop) {
// jump to the start
index = 0;
this.setIndex(index);
}
var end = new Date();
var diff = end - start;
// calculate how much time it to to set the index and to execute the callback
// function.
var interval = Math.max(this.playInterval - diff, 0);
// document.title = diff // TODO: cleanup
var me = this;
this.playTimeout = setTimeout(function () {
me.playNext();
}, interval);
};
/**
* Toggle start or stop playing
*/
Slider.prototype.togglePlay = function () {
if (this.playTimeout === undefined) {
this.play();
} else {
this.stop();
}
};
/**
* Start playing
*/
Slider.prototype.play = function () {
// Test whether already playing
if (this.playTimeout) return;
this.playNext();
if (this.frame) {
this.frame.play.value = 'Stop';
}
};
/**
* Stop playing
*/
Slider.prototype.stop = function () {
clearInterval(this.playTimeout);
this.playTimeout = undefined;
if (this.frame) {
this.frame.play.value = 'Play';
}
};
/**
* Set a callback function which will be triggered when the value of the
* slider bar has changed.
*
* @param {function} callback
*/
Slider.prototype.setOnChangeCallback = function (callback) {
this.onChangeCallback = callback;
};
/**
* Set the interval for playing the list
* @param {number} interval The interval in milliseconds
*/
Slider.prototype.setPlayInterval = function (interval) {
this.playInterval = interval;
};
/**
* Retrieve the current play interval
* @return {number} interval The interval in milliseconds
*/
Slider.prototype.getPlayInterval = function () {
return this.playInterval;
};
/**
* Set looping on or off
* @param {boolean} doLoop If true, the slider will jump to the start when
* the end is passed, and will jump to the end
* when the start is passed.
*
*/
Slider.prototype.setPlayLoop = function (doLoop) {
this.playLoop = doLoop;
};
/**
* Execute the onchange callback function
*/
Slider.prototype.onChange = function () {
if (this.onChangeCallback !== undefined) {
this.onChangeCallback();
}
};
/**
* redraw the slider on the correct place
*/
Slider.prototype.redraw = function () {
if (this.frame) {
// resize the bar
this.frame.bar.style.top = this.frame.clientHeight / 2 - this.frame.bar.offsetHeight / 2 + 'px';
this.frame.bar.style.width = this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30 + 'px';
// position the slider button
var left = this.indexToLeft(this.index);
this.frame.slide.style.left = left + 'px';
}
};
/**
* Set the list with values for the slider
* @param {Array} values A javascript array with values (any type)
*/
Slider.prototype.setValues = function (values) {
this.values = values;
if (this.values.length > 0) this.setIndex(0);else this.index = undefined;
};
/**
* Select a value by its index
* @param {number} index
*/
Slider.prototype.setIndex = function (index) {
if (index < this.values.length) {
this.index = index;
this.redraw();
this.onChange();
} else {
throw new Error('Index out of range');
}
};
/**
* retrieve the index of the currently selected vaue
* @return {number} index
*/
Slider.prototype.getIndex = function () {
return this.index;
};
/**
* retrieve the currently selected value
* @return {*} value
*/
Slider.prototype.get = function () {
return this.values[this.index];
};
Slider.prototype._onMouseDown = function (event) {
// only react on left mouse button down
var leftButtonDown = event.which ? event.which === 1 : event.button === 1;
if (!leftButtonDown) return;
this.startClientX = event.clientX;
this.startSlideX = parseFloat(this.frame.slide.style.left);
this.frame.style.cursor = 'move';
// add event listeners to handle moving the contents
// we store the function onmousemove and onmouseup in the graph, so we can
// remove the eventlisteners lateron in the function mouseUp()
var me = this;
this.onmousemove = function (event) {
me._onMouseMove(event);
};
this.onmouseup = function (event) {
me._onMouseUp(event);
};
util.addEventListener(document, 'mousemove', this.onmousemove);
util.addEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault(event);
};
Slider.prototype.leftToIndex = function (left) {
var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
var x = left - 3;
var index = Math.round(x / width * (this.values.length - 1));
if (index < 0) index = 0;
if (index > this.values.length - 1) index = this.values.length - 1;
return index;
};
Slider.prototype.indexToLeft = function (index) {
var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
var x = index / (this.values.length - 1) * width;
var left = x + 3;
return left;
};
Slider.prototype._onMouseMove = function (event) {
var diff = event.clientX - this.startClientX;
var x = this.startSlideX + diff;
var index = this.leftToIndex(x);
this.setIndex(index);
util.preventDefault();
};
Slider.prototype._onMouseUp = function (event) {
// eslint-disable-line no-unused-vars
this.frame.style.cursor = 'auto';
// remove event listeners
util.removeEventListener(document, 'mousemove', this.onmousemove);
util.removeEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault();
};
module.exports = Slider;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @prototype StepNumber
* The class StepNumber is an iterator for Numbers. You provide a start and end
* value, and a best step size. StepNumber itself rounds to fixed values and
* a finds the step that best fits the provided step.
*
* If prettyStep is true, the step size is chosen as close as possible to the
* provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
*
* Example usage:
* var step = new StepNumber(0, 10, 2.5, true);
* step.start();
* while (!step.end()) {
* alert(step.getCurrent());
* step.next();
* }
*
* Version: 1.0
*
* @param {number} start The start value
* @param {number} end The end value
* @param {number} step Optional. Step size. Must be a positive value.
* @param {boolean} prettyStep Optional. If true, the step size is rounded
* To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
function StepNumber(start, end, step, prettyStep) {
// set default values
this._start = 0;
this._end = 0;
this._step = 1;
this.prettyStep = true;
this.precision = 5;
this._current = 0;
this.setRange(start, end, step, prettyStep);
}
/**
* Check for input values, to prevent disasters from happening
*
* Source: http://stackoverflow.com/a/1830844
*
* @param {string} n
* @returns {boolean}
*/
StepNumber.prototype.isNumeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/**
* Set a new range: start, end and step.
*
* @param {number} start The start value
* @param {number} end The end value
* @param {number} step Optional. Step size. Must be a positive value.
* @param {boolean} prettyStep Optional. If true, the step size is rounded
* To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
StepNumber.prototype.setRange = function (start, end, step, prettyStep) {
if (!this.isNumeric(start)) {
throw new Error('Parameter \'start\' is not numeric; value: ' + start);
}
if (!this.isNumeric(end)) {
throw new Error('Parameter \'end\' is not numeric; value: ' + start);
}
if (!this.isNumeric(step)) {
throw new Error('Parameter \'step\' is not numeric; value: ' + start);
}
this._start = start ? start : 0;
this._end = end ? end : 0;
this.setStep(step, prettyStep);
};
/**
* Set a new step size
* @param {number} step New step size. Must be a positive value
* @param {boolean} prettyStep Optional. If true, the provided step is rounded
* to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
StepNumber.prototype.setStep = function (step, prettyStep) {
if (step === undefined || step <= 0) return;
if (prettyStep !== undefined) this.prettyStep = prettyStep;
if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step;
};
/**
* Calculate a nice step size, closest to the desired step size.
* Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
* integer Number. For example 1, 2, 5, 10, 20, 50, etc...
* @param {number} step Desired step size
* @return {number} Nice step size
*/
StepNumber.calculatePrettyStep = function (step) {
var log10 = function log10(x) {
return Math.log(x) / Math.LN10;
};
// try three steps (multiple of 1, 2, or 5
var step1 = Math.pow(10, Math.round(log10(step))),
step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
// choose the best step (closest to minimum step)
var prettyStep = step1;
if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
// for safety
if (prettyStep <= 0) {
prettyStep = 1;
}
return prettyStep;
};
/**
* returns the current value of the step
* @return {number} current value
*/
StepNumber.prototype.getCurrent = function () {
return parseFloat(this._current.toPrecision(this.precision));
};
/**
* returns the current step size
* @return {number} current step size
*/
StepNumber.prototype.getStep = function () {
return this._step;
};
/**
* Set the current to its starting value.
*
* By default, this will be the largest value smaller than start, which
* is a multiple of the step size.
*
* Parameters checkFirst is optional, default false.
* If set to true, move the current value one step if smaller than start.
*
* @param {boolean} [checkFirst=false]
*/
StepNumber.prototype.start = function (checkFirst) {
if (checkFirst === undefined) {
checkFirst = false;
}
this._current = this._start - this._start % this._step;
if (checkFirst) {
if (this.getCurrent() < this._start) {
this.next();
}
}
};
/**
* Do a step, add the step size to the current value
*/
StepNumber.prototype.next = function () {
this._current += this._step;
};
/**
* Returns true whether the end is reached
* @return {boolean} True if the current value has passed the end value.
*/
StepNumber.prototype.end = function () {
return this._current > this._end;
};
module.exports = StepNumber;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
////////////////////////////////////////////////////////////////////////////////
// This modules handles the options for Graph3d.
//
////////////////////////////////////////////////////////////////////////////////
var util = __webpack_require__(2);
var Camera = __webpack_require__(95);
var Point3d = __webpack_require__(34);
// enumerate the available styles
var STYLE = {
BAR: 0,
BARCOLOR: 1,
BARSIZE: 2,
DOT: 3,
DOTLINE: 4,
DOTCOLOR: 5,
DOTSIZE: 6,
GRID: 7,
LINE: 8,
SURFACE: 9
};
// The string representations of the styles
var STYLENAME = {
'dot': STYLE.DOT,
'dot-line': STYLE.DOTLINE,
'dot-color': STYLE.DOTCOLOR,
'dot-size': STYLE.DOTSIZE,
'line': STYLE.LINE,
'grid': STYLE.GRID,
'surface': STYLE.SURFACE,
'bar': STYLE.BAR,
'bar-color': STYLE.BARCOLOR,
'bar-size': STYLE.BARSIZE
};
/**
* Field names in the options hash which are of relevance to the user.
*
* Specifically, these are the fields which require no special handling,
* and can be directly copied over.
*/
var OPTIONKEYS = ['width', 'height', 'filterLabel', 'legendLabel', 'xLabel', 'yLabel', 'zLabel', 'xValueLabel', 'yValueLabel', 'zValueLabel', 'showXAxis', 'showYAxis', 'showZAxis', 'showGrid', 'showPerspective', 'showShadow', 'keepAspectRatio', 'verticalRatio', 'dotSizeRatio', 'dotSizeMinFraction', 'dotSizeMaxFraction', 'showAnimationControls', 'animationInterval', 'animationPreload', 'animationAutoStart', 'axisColor', 'gridColor', 'xCenter', 'yCenter'];
/**
* Field names in the options hash which are of relevance to the user.
*
* Same as OPTIONKEYS, but internally these fields are stored with
* prefix 'default' in the name.
*/
var PREFIXEDOPTIONKEYS = ['xBarWidth', 'yBarWidth', 'valueMin', 'valueMax', 'xMin', 'xMax', 'xStep', 'yMin', 'yMax', 'yStep', 'zMin', 'zMax', 'zStep'];
// Placeholder for DEFAULTS reference
var DEFAULTS = undefined;
/**
* Check if given hash is empty.
*
* Source: http://stackoverflow.com/a/679937
*
* @param {object} obj
* @returns {boolean}
*/
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) return false;
}
return true;
}
/**
* Make first letter of parameter upper case.
*
* Source: http://stackoverflow.com/a/1026087
*
* @param {string} str
* @returns {string}
*/
function capitalize(str) {
if (str === undefined || str === "" || typeof str != "string") {
return str;
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Add a prefix to a field name, taking style guide into account
*
* @param {string} prefix
* @param {string} fieldName
* @returns {string}
*/
function prefixFieldName(prefix, fieldName) {
if (prefix === undefined || prefix === "") {
return fieldName;
}
return prefix + capitalize(fieldName);
}
/**
* Forcibly copy fields from src to dst in a controlled manner.
*
* A given field in dst will always be overwitten. If this field
* is undefined or not present in src, the field in dst will
* be explicitly set to undefined.
*
* The intention here is to be able to reset all option fields.
*
* Only the fields mentioned in array 'fields' will be handled.
*
* @param {object} src
* @param {object} dst
* @param {array} fields array with names of fields to copy
* @param {string} [prefix] prefix to use for the target fields.
*/
function forceCopy(src, dst, fields, prefix) {
var srcKey;
var dstKey;
for (var i = 0; i < fields.length; ++i) {
srcKey = fields[i];
dstKey = prefixFieldName(prefix, srcKey);
dst[dstKey] = src[srcKey];
}
}
/**
* Copy fields from src to dst in a safe and controlled manner.
*
* Only the fields mentioned in array 'fields' will be copied over,
* and only if these are actually defined.
*
* @param {object} src
* @param {object} dst
* @param {array} fields array with names of fields to copy
* @param {string} [prefix] prefix to use for the target fields.
*/
function safeCopy(src, dst, fields, prefix) {
var srcKey;
var dstKey;
for (var i = 0; i < fields.length; ++i) {
srcKey = fields[i];
if (src[srcKey] === undefined) continue;
dstKey = prefixFieldName(prefix, srcKey);
dst[dstKey] = src[srcKey];
}
}
/**
* Initialize dst with the values in src.
*
* src is the hash with the default values.
* A reference DEFAULTS to this hash is stored locally for
* further handling.
*
* For now, dst is assumed to be a Graph3d instance.
* @param {object} src
* @param {object} dst
*/
function setDefaults(src, dst) {
if (src === undefined || isEmpty(src)) {
throw new Error('No DEFAULTS passed');
}
if (dst === undefined) {
throw new Error('No dst passed');
}
// Remember defaults for future reference
DEFAULTS = src;
// Handle the defaults which can be simply copied over
forceCopy(src, dst, OPTIONKEYS);
forceCopy(src, dst, PREFIXEDOPTIONKEYS, 'default');
// Handle the more complex ('special') fields
setSpecialSettings(src, dst);
// Following are internal fields, not part of the user settings
dst.margin = 10; // px
dst.showGrayBottom = false; // TODO: this does not work correctly
dst.showTooltip = false;
dst.onclick_callback = null;
dst.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
}
/**
*
* @param {object} options
* @param {object} dst
*/
function setOptions(options, dst) {
if (options === undefined) {
return;
}
if (dst === undefined) {
throw new Error('No dst passed');
}
if (DEFAULTS === undefined || isEmpty(DEFAULTS)) {
throw new Error('DEFAULTS not set for module Settings');
}
// Handle the parameters which can be simply copied over
safeCopy(options, dst, OPTIONKEYS);
safeCopy(options, dst, PREFIXEDOPTIONKEYS, 'default');
// Handle the more complex ('special') fields
setSpecialSettings(options, dst);
}
/**
* Special handling for certain parameters
*
* 'Special' here means: setting requires more than a simple copy
*
* @param {object} src
* @param {object} dst
*/
function setSpecialSettings(src, dst) {
if (src.backgroundColor !== undefined) {
setBackgroundColor(src.backgroundColor, dst);
}
setDataColor(src.dataColor, dst);
setStyle(src.style, dst);
setShowLegend(src.showLegend, dst);
setCameraPosition(src.cameraPosition, dst);
// As special fields go, this is an easy one; just a translation of the name.
// Can't use this.tooltip directly, because that field exists internally
if (src.tooltip !== undefined) {
dst.showTooltip = src.tooltip;
}
if (src.onclick != undefined) {
dst.onclick_callback = src.onclick;
}
if (src.tooltipStyle !== undefined) {
util.selectiveDeepExtend(['tooltipStyle'], dst, src);
}
}
/**
* Set the value of setting 'showLegend'
*
* This depends on the value of the style fields, so it must be called
* after the style field has been initialized.
*
* @param {boolean} showLegend
* @param {object} dst
*/
function setShowLegend(showLegend, dst) {
if (showLegend === undefined) {
// If the default was auto, make a choice for this field
var isAutoByDefault = DEFAULTS.showLegend === undefined;
if (isAutoByDefault) {
// these styles default to having legends
var isLegendGraphStyle = dst.style === STYLE.DOTCOLOR || dst.style === STYLE.DOTSIZE;
dst.showLegend = isLegendGraphStyle;
} else {
// Leave current value as is
}
} else {
dst.showLegend = showLegend;
}
}
/**
* Retrieve the style index from given styleName
* @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
* @return {number} styleNumber Enumeration value representing the style, or -1
* when not found
*/
function getStyleNumberByName(styleName) {
var number = STYLENAME[styleName];
if (number === undefined) {
return -1;
}
return number;
}
/**
* Check if given number is a valid style number.
*
* @param {string | number} style
* @return {boolean} true if valid, false otherwise
*/
function checkStyleNumber(style) {
var valid = false;
for (var n in STYLE) {
if (STYLE[n] === style) {
valid = true;
break;
}
}
return valid;
}
/**
*
* @param {string | number} style
* @param {Object} dst
*/
function setStyle(style, dst) {
if (style === undefined) {
return; // Nothing to do
}
var styleNumber;
if (typeof style === 'string') {
styleNumber = getStyleNumberByName(style);
if (styleNumber === -1) {
throw new Error('Style \'' + style + '\' is invalid');
}
} else {
// Do a pedantic check on style number value
if (!checkStyleNumber(style)) {
throw new Error('Style \'' + style + '\' is invalid');
}
styleNumber = style;
}
dst.style = styleNumber;
}
/**
* Set the background styling for the graph
* @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
* @param {Object} dst
*/
function setBackgroundColor(backgroundColor, dst) {
var fill = 'white';
var stroke = 'gray';
var strokeWidth = 1;
if (typeof backgroundColor === 'string') {
fill = backgroundColor;
stroke = 'none';
strokeWidth = 0;
} else if ((typeof backgroundColor === 'undefined' ? 'undefined' : (0, _typeof3['default'])(backgroundColor)) === 'object') {
if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
} else {
throw new Error('Unsupported type of backgroundColor');
}
dst.frame.style.backgroundColor = fill;
dst.frame.style.borderColor = stroke;
dst.frame.style.borderWidth = strokeWidth + 'px';
dst.frame.style.borderStyle = 'solid';
}
/**
*
* @param {string | Object} dataColor
* @param {Object} dst
*/
function setDataColor(dataColor, dst) {
if (dataColor === undefined) {
return; // Nothing to do
}
if (dst.dataColor === undefined) {
dst.dataColor = {};
}
if (typeof dataColor === 'string') {
dst.dataColor.fill = dataColor;
dst.dataColor.stroke = dataColor;
} else {
if (dataColor.fill) {
dst.dataColor.fill = dataColor.fill;
}
if (dataColor.stroke) {
dst.dataColor.stroke = dataColor.stroke;
}
if (dataColor.strokeWidth !== undefined) {
dst.dataColor.strokeWidth = dataColor.strokeWidth;
}
}
}
/**
*
* @param {Object} cameraPosition
* @param {Object} dst
*/
function setCameraPosition(cameraPosition, dst) {
var camPos = cameraPosition;
if (camPos === undefined) {
return;
}
if (dst.camera === undefined) {
dst.camera = new Camera();
}
dst.camera.setArmRotation(camPos.horizontal, camPos.vertical);
dst.camera.setArmLength(camPos.distance);
}
module.exports.STYLE = STYLE;
module.exports.setDefaults = setDefaults;
module.exports.setOptions = setOptions;
module.exports.setCameraPosition = setCameraPosition;
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _sign = __webpack_require__(165);
var _sign2 = _interopRequireDefault(_sign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Point3d = __webpack_require__(34);
/**
* The camera is mounted on a (virtual) camera arm. The camera arm can rotate
* The camera is always looking in the direction of the origin of the arm.
* This way, the camera always rotates around one fixed point, the location
* of the camera arm.
*
* Documentation:
* http://en.wikipedia.org/wiki/3D_projection
* @class Camera
*/
function Camera() {
this.armLocation = new Point3d();
this.armRotation = {};
this.armRotation.horizontal = 0;
this.armRotation.vertical = 0;
this.armLength = 1.7;
this.cameraOffset = new Point3d();
this.offsetMultiplier = 0.6;
this.cameraLocation = new Point3d();
this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0);
this.calculateCameraOrientation();
}
/**
* Set offset camera in camera coordinates
* @param {number} x offset by camera horisontal
* @param {number} y offset by camera vertical
*/
Camera.prototype.setOffset = function (x, y) {
var abs = Math.abs,
sign = _sign2['default'],
mul = this.offsetMultiplier,
border = this.armLength * mul;
if (abs(x) > border) {
x = sign(x) * border;
}
if (abs(y) > border) {
y = sign(y) * border;
}
this.cameraOffset.x = x;
this.cameraOffset.y = y;
this.calculateCameraOrientation();
};
/**
* Get camera offset by horizontal and vertical
* @returns {number}
*/
Camera.prototype.getOffset = function () {
return this.cameraOffset;
};
/**
* Set the location (origin) of the arm
* @param {number} x Normalized value of x
* @param {number} y Normalized value of y
* @param {number} z Normalized value of z
*/
Camera.prototype.setArmLocation = function (x, y, z) {
this.armLocation.x = x;
this.armLocation.y = y;
this.armLocation.z = z;
this.calculateCameraOrientation();
};
/**
* Set the rotation of the camera arm
* @param {number} horizontal The horizontal rotation, between 0 and 2*PI.
* Optional, can be left undefined.
* @param {number} vertical The vertical rotation, between 0 and 0.5*PI
* if vertical=0.5*PI, the graph is shown from the
* top. Optional, can be left undefined.
*/
Camera.prototype.setArmRotation = function (horizontal, vertical) {
if (horizontal !== undefined) {
this.armRotation.horizontal = horizontal;
}
if (vertical !== undefined) {
this.armRotation.vertical = vertical;
if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
if (this.armRotation.vertical > 0.5 * Math.PI) this.armRotation.vertical = 0.5 * Math.PI;
}
if (horizontal !== undefined || vertical !== undefined) {
this.calculateCameraOrientation();
}
};
/**
* Retrieve the current arm rotation
* @return {object} An object with parameters horizontal and vertical
*/
Camera.prototype.getArmRotation = function () {
var rot = {};
rot.horizontal = this.armRotation.horizontal;
rot.vertical = this.armRotation.vertical;
return rot;
};
/**
* Set the (normalized) length of the camera arm.
* @param {number} length A length between 0.71 and 5.0
*/
Camera.prototype.setArmLength = function (length) {
if (length === undefined) return;
this.armLength = length;
// Radius must be larger than the corner of the graph,
// which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
// graph
if (this.armLength < 0.71) this.armLength = 0.71;
if (this.armLength > 5.0) this.armLength = 5.0;
this.setOffset(this.cameraOffset.x, this.cameraOffset.y);
this.calculateCameraOrientation();
};
/**
* Retrieve the arm length
* @return {number} length
*/
Camera.prototype.getArmLength = function () {
return this.armLength;
};
/**
* Retrieve the camera location
* @return {Point3d} cameraLocation
*/
Camera.prototype.getCameraLocation = function () {
return this.cameraLocation;
};
/**
* Retrieve the camera rotation
* @return {Point3d} cameraRotation
*/
Camera.prototype.getCameraRotation = function () {
return this.cameraRotation;
};
/**
* Calculate the location and rotation of the camera based on the
* position and orientation of the camera arm
*/
Camera.prototype.calculateCameraOrientation = function () {
// calculate location of the camera
this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
// calculate rotation of the camera
this.cameraRotation.x = Math.PI / 2 - this.armRotation.vertical;
this.cameraRotation.y = 0;
this.cameraRotation.z = -this.armRotation.horizontal;
var xa = this.cameraRotation.x;
var za = this.cameraRotation.z;
var dx = this.cameraOffset.x;
var dy = this.cameraOffset.y;
var sin = Math.sin,
cos = Math.cos;
this.cameraLocation.x = this.cameraLocation.x + dx * cos(za) + dy * -sin(za) * cos(xa);
this.cameraLocation.y = this.cameraLocation.y + dx * sin(za) + dy * cos(za) * cos(xa);
this.cameraLocation.z = this.cameraLocation.z + dy * sin(xa);
};
module.exports = Camera;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var DataView = __webpack_require__(12);
/**
* @class Filter
*
* @param {DataGroup} dataGroup the data group
* @param {number} column The index of the column to be filtered
* @param {Graph3d} graph The graph
*/
function Filter(dataGroup, column, graph) {
this.dataGroup = dataGroup;
this.column = column;
this.graph = graph; // the parent graph
this.index = undefined;
this.value = undefined;
// read all distinct values and select the first one
this.values = dataGroup.getDistinctValues(this.column);
if (this.values.length > 0) {
this.selectValue(0);
}
// create an array with the filtered datapoints. this will be loaded afterwards
this.dataPoints = [];
this.loaded = false;
this.onLoadCallback = undefined;
if (graph.animationPreload) {
this.loaded = false;
this.loadInBackground();
} else {
this.loaded = true;
}
}
/**
* Return the label
* @return {string} label
*/
Filter.prototype.isLoaded = function () {
return this.loaded;
};
/**
* Return the loaded progress
* @return {number} percentage between 0 and 100
*/
Filter.prototype.getLoadedProgress = function () {
var len = this.values.length;
var i = 0;
while (this.dataPoints[i]) {
i++;
}
return Math.round(i / len * 100);
};
/**
* Return the label
* @return {string} label
*/
Filter.prototype.getLabel = function () {
return this.graph.filterLabel;
};
/**
* Return the columnIndex of the filter
* @return {number} columnIndex
*/
Filter.prototype.getColumn = function () {
return this.column;
};
/**
* Return the currently selected value. Returns undefined if there is no selection
* @return {*} value
*/
Filter.prototype.getSelectedValue = function () {
if (this.index === undefined) return undefined;
return this.values[this.index];
};
/**
* Retrieve all values of the filter
* @return {Array} values
*/
Filter.prototype.getValues = function () {
return this.values;
};
/**
* Retrieve one value of the filter
* @param {number} index
* @return {*} value
*/
Filter.prototype.getValue = function (index) {
if (index >= this.values.length) throw new Error('Index out of range');
return this.values[index];
};
/**
* Retrieve the (filtered) dataPoints for the currently selected filter index
* @param {number} [index] (optional)
* @return {Array} dataPoints
*/
Filter.prototype._getDataPoints = function (index) {
if (index === undefined) index = this.index;
if (index === undefined) return [];
var dataPoints;
if (this.dataPoints[index]) {
dataPoints = this.dataPoints[index];
} else {
var f = {};
f.column = this.column;
f.value = this.values[index];
var dataView = new DataView(this.dataGroup.getDataSet(), { filter: function filter(item) {
return item[f.column] == f.value;
} }).get();
dataPoints = this.dataGroup._getDataPoints(dataView);
this.dataPoints[index] = dataPoints;
}
return dataPoints;
};
/**
* Set a callback function when the filter is fully loaded.
*
* @param {function} callback
*/
Filter.prototype.setOnLoadCallback = function (callback) {
this.onLoadCallback = callback;
};
/**
* Add a value to the list with available values for this filter
* No double entries will be created.
* @param {number} index
*/
Filter.prototype.selectValue = function (index) {
if (index >= this.values.length) throw new Error('Index out of range');
this.index = index;
this.value = this.values[index];
};
/**
* Load all filtered rows in the background one by one
* Start this method without providing an index!
*
* @param {number} [index=0]
*/
Filter.prototype.loadInBackground = function (index) {
if (index === undefined) index = 0;
var frame = this.graph.frame;
if (index < this.values.length) {
// create a progress box
if (frame.progress === undefined) {
frame.progress = document.createElement('DIV');
frame.progress.style.position = 'absolute';
frame.progress.style.color = 'gray';
frame.appendChild(frame.progress);
}
var progress = this.getLoadedProgress();
frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
// TODO: this is no nice solution...
frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
frame.progress.style.left = 10 + 'px';
var me = this;
setTimeout(function () {
me.loadInBackground(index + 1);
}, 10);
this.loaded = false;
} else {
this.loaded = true;
// remove the progress box
if (frame.progress !== undefined) {
frame.removeChild(frame.progress);
frame.progress = undefined;
}
if (this.onLoadCallback) this.onLoadCallback();
}
};
module.exports = Filter;
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keycharm = __webpack_require__(35);
var Emitter = __webpack_require__(44);
var Hammer = __webpack_require__(10);
var util = __webpack_require__(2);
/**
* Turn an element into an clickToUse element.
* When not active, the element has a transparent overlay. When the overlay is
* clicked, the mode is changed to active.
* When active, the element is displayed with a blue border around it, and
* the interactive contents of the element can be used. When clicked outside
* the element, the elements mode is changed to inactive.
* @param {Element} container
* @constructor Activator
*/
function Activator(container) {
this.active = false;
this.dom = {
container: container
};
this.dom.overlay = document.createElement('div');
this.dom.overlay.className = 'vis-overlay';
this.dom.container.appendChild(this.dom.overlay);
this.hammer = Hammer(this.dom.overlay);
this.hammer.on('tap', this._onTapOverlay.bind(this));
// block all touch events (except tap)
var me = this;
var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend'];
events.forEach(function (event) {
me.hammer.on(event, function (event) {
event.stopPropagation();
});
});
// attach a click event to the window, in order to deactivate when clicking outside the timeline
if (document && document.body) {
this.onClick = function (event) {
if (!_hasParent(event.target, container)) {
me.deactivate();
}
};
document.body.addEventListener('click', this.onClick);
}
if (this.keycharm !== undefined) {
this.keycharm.destroy();
}
this.keycharm = keycharm();
// keycharm listener only bounded when active)
this.escListener = this.deactivate.bind(this);
}
// turn into an event emitter
Emitter(Activator.prototype);
// The currently active activator
Activator.current = null;
/**
* Destroy the activator. Cleans up all created DOM and event listeners
*/
Activator.prototype.destroy = function () {
this.deactivate();
// remove dom
this.dom.overlay.parentNode.removeChild(this.dom.overlay);
// remove global event listener
if (this.onClick) {
document.body.removeEventListener('click', this.onClick);
}
// cleanup hammer instances
this.hammer.destroy();
this.hammer = null;
// FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
};
/**
* Activate the element
* Overlay is hidden, element is decorated with a blue shadow border
*/
Activator.prototype.activate = function () {
// we allow only one active activator at a time
if (Activator.current) {
Activator.current.deactivate();
}
Activator.current = this;
this.active = true;
this.dom.overlay.style.display = 'none';
util.addClassName(this.dom.container, 'vis-active');
this.emit('change');
this.emit('activate');
// ugly hack: bind ESC after emitting the events, as the Network rebinds all
// keyboard events on a 'change' event
this.keycharm.bind('esc', this.escListener);
};
/**
* Deactivate the element
* Overlay is displayed on top of the element
*/
Activator.prototype.deactivate = function () {
this.active = false;
this.dom.overlay.style.display = '';
util.removeClassName(this.dom.container, 'vis-active');
this.keycharm.unbind('esc', this.escListener);
this.emit('change');
this.emit('deactivate');
};
/**
* Handle a tap event: activate the container
* @param {Event} event The event
* @private
*/
Activator.prototype._onTapOverlay = function (event) {
// activate the container
this.activate();
event.stopPropagation();
};
/**
* Test whether the element has the requested parent element somewhere in
* its chain of parent nodes.
* @param {HTMLElement} element
* @param {HTMLElement} parent
* @returns {boolean} Returns true when the parent is found somewhere in the
* chain of parent nodes.
* @private
*/
function _hasParent(element, parent) {
while (element) {
if (element === parent) {
return true;
}
element = element.parentNode;
}
return false;
}
module.exports = Activator;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// English
exports['en'] = {
current: 'current',
time: 'time'
};
exports['en_EN'] = exports['en'];
exports['en_US'] = exports['en'];
// Italiano
exports['it'] = {
current: 'attuale',
time: 'tempo'
};
exports['it_IT'] = exports['it'];
exports['it_CH'] = exports['it'];
// Dutch
exports['nl'] = {
current: 'huidige',
time: 'tijd'
};
exports['nl_NL'] = exports['nl'];
exports['nl_BE'] = exports['nl'];
// German
exports['de'] = {
current: 'Aktuelle',
time: 'Zeit'
};
exports['de_DE'] = exports['de'];
// French
exports['fr'] = {
current: 'actuel',
time: 'heure'
};
exports['fr_FR'] = exports['fr'];
exports['fr_CA'] = exports['fr'];
exports['fr_BE'] = exports['fr'];
// Espanol
exports['es'] = {
current: 'corriente',
time: 'hora'
};
exports['es_ES'] = exports['es'];
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _create = __webpack_require__(29);
var _create2 = _interopRequireDefault(_create);
var _typeof2 = __webpack_require__(6);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var Hammer = __webpack_require__(10);
var util = __webpack_require__(2);
var DataSet = __webpack_require__(11);
var DataView = __webpack_require__(12);
var TimeStep = __webpack_require__(66);
var Component = __webpack_require__(16);
var Group = __webpack_require__(68);
var BackgroundGroup = __webpack_require__(69);
var BoxItem = __webpack_require__(101);
var PointItem = __webpack_require__(102);
var RangeItem = __webpack_require__(70);
var BackgroundItem = __webpack_require__(103);
var Popup = __webpack_require__(104)['default'];
var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
var BACKGROUND = '__background__'; // reserved group id for background items without group
/**
* An ItemSet holds a set of items and ranges which can be displayed in a
* range. The width is determined by the parent of the ItemSet, and the height
* is determined by the size of the items.
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
* @param {Object} [options] See ItemSet.setOptions for the available options.
* @constructor ItemSet
* @extends Component
*/
function ItemSet(body, options) {
this.body = body;
this.defaultOptions = {
type: null, // 'box', 'point', 'range', 'background'
orientation: {
item: 'bottom' // item orientation: 'top' or 'bottom'
},
align: 'auto', // alignment of box items
stack: true,
stackSubgroups: true,
groupOrderSwap: function groupOrderSwap(fromGroup, toGroup, groups) {
// eslint-disable-line no-unused-vars
var targetOrder = toGroup.order;
toGroup.order = fromGroup.order;
fromGroup.order = targetOrder;
},
groupOrder: 'order',
selectable: true,
multiselect: false,
itemsAlwaysDraggable: {
item: false,
range: false
},
editable: {
updateTime: false,
updateGroup: false,
add: false,
remove: false,
overrideItems: false
},
groupEditable: {
order: false,
add: false,
remove: false
},
snap: TimeStep.snap,
// Only called when `objectData.target === 'item'.
onDropObjectOnItem: function onDropObjectOnItem(objectData, item, callback) {
callback(item);
},
onAdd: function onAdd(item, callback) {
callback(item);
},
onUpdate: function onUpdate(item, callback) {
callback(item);
},
onMove: function onMove(item, callback) {
callback(item);
},
onRemove: function onRemove(item, callback) {
callback(item);
},
onMoving: function onMoving(item, callback) {
callback(item);
},
onAddGroup: function onAddGroup(item, callback) {
callback(item);
},
onMoveGroup: function onMoveGroup(item, callback) {
callback(item);
},
onRemoveGroup: function onRemoveGroup(item, callback) {
callback(item);
},
margin: {
item: {
horizontal: 10,
vertical: 10
},
axis: 20
},
showTooltips: true,
tooltip: {
followMouse: false,
overflowMethod: 'flip'
},
tooltipOnItemUpdateTime: false
};
// options is shared by this ItemSet and all its items
this.options = util.extend({}, this.defaultOptions);
this.options.rtl = options.rtl;
// options for getting items from the DataSet with the correct type
this.itemOptions = {
type: { start: 'Date', end: 'Date' }
};
this.conversion = {
toScreen: body.util.toScreen,
toTime: body.util.toTime
};
this.dom = {};
this.props = {};
this.hammer = null;
var me = this;
this.itemsData = null; // DataSet
this.groupsData = null; // DataSet
// listeners for the DataSet of the items
this.itemListeners = {
'add': function add(event, params, senderId) {
// eslint-disable-line no-unused-vars
me._onAdd(params.items);
},
'update': function update(event, params, senderId) {
// eslint-disable-line no-unused-vars
me._onUpdate(params.items);
},
'remove': function remove(event, params, senderId) {
// eslint-disable-line no-unused-vars
me._onRemove(params.items);
}
};
// listeners for the DataSet of the groups
this.groupListeners = {
'add': function add(event, params, senderId) {
// eslint-disable-line no-unused-vars
me._onAddGroups(params.items);
if (me.groupsData && me.groupsData.length > 0) {
var groupsData = me.groupsData.getDataSet();
groupsData.get().forEach(function (groupData) {
if (groupData.nestedGroups) {
if (groupData.showNested != false) {
groupData.showNested = true;
}
var updatedGroups = [];
groupData.nestedGroups.forEach(function (nestedGroupId) {
var updatedNestedGroup = groupsData.get(nestedGroupId);
if (!updatedNestedGroup) {
return;
}
updatedNestedGroup.nestedInGroup = groupData.id;
if (groupData.showNested == false) {
updatedNestedGroup.visible = false;
}
updatedGroups = updatedGroups.concat(updatedNestedGroup);
});
groupsData.update(updatedGroups, senderId);
}
});
}
},
'update': function update(event, params, senderId) {
// eslint-disable-line no-unused-vars
me._onUpdateGroups(params.items);
},
'remove': function remove(event, params, senderId) {
// eslint-disable-line no-unused-vars
me._onRemoveGroups(params.items);
}
};
this.items = {}; // object with an Item for every data item
this.groups = {}; // Group object for every group
this.groupIds = [];
this.selection = []; // list with the ids of all selected nodes
this.popup = null;
this.touchParams = {}; // stores properties while dragging
this.groupTouchParams = {};
// create the HTML DOM
this._create();
this.setOptions(options);
}
ItemSet.prototype = new Component();
// available item types will be registered here
ItemSet.types = {
background: BackgroundItem,
box: BoxItem,
range: RangeItem,
point: PointItem
};
/**
* Create the HTML DOM for the ItemSet
*/
ItemSet.prototype._create = function () {
var frame = document.createElement('div');
frame.className = 'vis-itemset';
frame['timeline-itemset'] = this;
this.dom.frame = frame;
// create background panel
var background = document.createElement('div');
background.className = 'vis-background';
frame.appendChild(background);
this.dom.background = background;
// create foreground panel
var foreground = document.createElement('div');
foreground.className = 'vis-foreground';
frame.appendChild(foreground);
this.dom.foreground = foreground;
// create axis panel
var axis = document.createElement('div');
axis.className = 'vis-axis';
this.dom.axis = axis;
// create labelset
var labelSet = document.createElement('div');
labelSet.className = 'vis-labelset';
this.dom.labelSet = labelSet;
// create ungrouped Group
this._updateUngrouped();
// create background Group
var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
backgroundGroup.show();
this.groups[BACKGROUND] = backgroundGroup;
// attach event listeners
// Note: we bind to the centerContainer for the case where the height
// of the center container is larger than of the ItemSet, so we
// can click in the empty area to create a new item or deselect an item.
this.hammer = new Hammer(this.body.dom.centerContainer);
// drag items when selected
this.hammer.on('hammer.input', function (event) {
if (event.isFirst) {
this._onTouch(event);
}
}.bind(this));
this.hammer.on('panstart', this._onDragStart.bind(this));
this.hammer.on('panmove', this._onDrag.bind(this));
this.hammer.on('panend', this._onDragEnd.bind(this));
this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
// single select (or unselect) when tapping an item
this.hammer.on('tap', this._onSelectItem.bind(this));
// multi select when holding mouse/touch, or on ctrl+click
this.hammer.on('press', this._onMultiSelectItem.bind(this));
// add item on doubletap
this.hammer.on('doubletap', this._onAddItem.bind(this));
if (this.options.rtl) {
this.groupHammer = new Hammer(this.body.dom.rightContainer);
} else {
this.groupHammer = new Hammer(this.body.dom.leftContainer);
}
this.groupHammer.on('tap', this._onGroupClick.bind(this));
this.groupHammer.on('panstart', this._onGroupDragStart.bind(this));
this.groupHammer.on('panmove', this._onGroupDrag.bind(this));
this.groupHammer.on('panend', this._onGroupDragEnd.bind(this));
this.groupHammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_VERTICAL });
this.body.dom.centerContainer.addEventListener('mouseover', this._onMouseOver.bind(this));
this.body.dom.centerContainer.addEventListener('mouseout', this._onMouseOut.bind(this));
this.body.dom.centerContainer.addEventListener('mousemove', this._onMouseMove.bind(this));
// right-click on timeline
this.body.dom.centerContainer.addEventListener('contextmenu', this._onDragEnd.bind(this));
this.body.dom.centerContainer.addEventListener('mousewheel', this._onMouseWheel.bind(this));
// attach to the DOM
this.show();
};
/**
* Set options for the ItemSet. Existing options will be extended/overwritten.
* @param {Object} [options] The following options are available:
* {string} type
* Default type for the items. Choose from 'box'
* (default), 'point', 'range', or 'background'.
* The default style can be overwritten by
* individual items.
* {string} align
* Alignment for the items, only applicable for
* BoxItem. Choose 'center' (default), 'left', or
* 'right'.
* {string} orientation.item
* Orientation of the item set. Choose 'top' or
* 'bottom' (default).
* {Function} groupOrder
* A sorting function for ordering groups
* {boolean} stack
* If true (default), items will be stacked on
* top of each other.
* {number} margin.axis
* Margin between the axis and the items in pixels.
* Default is 20.
* {number} margin.item.horizontal
* Horizontal margin between items in pixels.
* Default is 10.
* {number} margin.item.vertical
* Vertical Margin between items in pixels.
* Default is 10.
* {number} margin.item
* Margin between items in pixels in both horizontal
* and vertical direction. Default is 10.
* {number} margin
* Set margin for both axis and items in pixels.
* {boolean} selectable
* If true (default), items can be selected.
* {boolean} multiselect
* If true, multiple items can be selected.
* False by default.
* {boolean} editable
* Set all editable options to true or false
* {boolean} editable.updateTime
* Allow dragging an item to an other moment in time
* {boolean} editable.updateGroup
* Allow dragging an item to an other group
* {boolean} editable.add
* Allow creating new items on double tap
* {boolean} editable.remove
* Allow removing items by clicking the delete button
* top right of a selected item.
* {Function(item: Item, callback: Function)} onAdd
* Callback function triggered when an item is about to be added:
* when the user double taps an empty space in the Timeline.
* {Function(item: Item, callback: Function)} onUpdate
* Callback function fired when an item is about to be updated.
* This function typically has to show a dialog where the user
* change the item. If not implemented, nothing happens.
* {Function(item: Item, callback: Function)} onMove
* Fired when an item has been moved. If not implemented,
* the move action will be accepted.
* {Function(item: Item, callback: Function)} onRemove
* Fired when an item is about to be deleted.
* If not implemented, the item will be always removed.
*/
ItemSet.prototype.setOptions = function (options) {
if (options) {
// copy all options that we know
var fields = ['type', 'rtl', 'align', 'order', 'stack', 'stackSubgroups', 'selectable', 'multiselect', 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'visibleFrameTemplate', 'hide', 'snap', 'groupOrderSwap', 'showTooltips', 'tooltip', 'tooltipOnItemUpdateTime'];
util.selectiveExtend(fields, this.options, options);
if ('itemsAlwaysDraggable' in options) {
if (typeof options.itemsAlwaysDraggable === 'boolean') {
this.options.itemsAlwaysDraggable.item = options.itemsAlwaysDraggable;
this.options.itemsAlwaysDraggable.range = false;
} else if ((0, _typeof3['default'])(options.itemsAlwaysDraggable) === 'object') {
util.selectiveExtend(['item', 'range'], this.options.itemsAlwaysDraggable, options.itemsAlwaysDraggable);
// only allow range always draggable when item is always draggable as well
if (!this.options.itemsAlwaysDraggable.item) {
this.options.itemsAlwaysDraggable.range = false;
}
}
}
if ('orientation' in options) {
if (typeof options.orientation === 'string') {
this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
} else if ((0, _typeof3['default'])(options.orientation) === 'object' && 'item' in options.orientation) {
this.options.orientation.item = options.orientation.item;
}
}
if ('margin' in options) {
if (typeof options.margin === 'number') {
this.options.margin.axis = options.margin;
this.options.margin.item.horizontal = options.margin;
this.options.margin.item.vertical = options.margin;
} else if ((0, _typeof3['default'])(options.margin) === 'object') {
util.selectiveExtend(['axis'], this.options.margin, options.margin);
if ('item' in options.margin) {
if (typeof options.margin.item === 'number') {
this.options.margin.item.horizontal = options.margin.item;
this.options.margin.item.vertical = options.margin.item;
} else if ((0, _typeof3['default'])(options.margin.item) === 'object') {
util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
}
}
}
}
if ('editable' in options) {
if (typeof options.editable === 'boolean') {
this.options.editable.updateTime = options.editable;
this.options.editable.updateGroup = options.editable;
this.options.editable.add = options.editable;
this.options.editable.remove = options.editable;
this.options.editable.overrideItems = false;
} else if ((0, _typeof3['default'])(options.editable) === 'object') {
util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove', 'overrideItems'], this.options.editable, options.editable);
}
}
if ('groupEditable' in options) {
if (typeof options.groupEditable === 'boolean') {
this.options.groupEditable.order = options.groupEditable;
this.options.groupEditable.add = options.groupEditable;
this.options.groupEditable.remove = options.groupEditable;
} else if ((0, _typeof3['default'])(options.groupEditable) === 'object') {
util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
}
}
// callback functions
var addCallback = function (name) {
var fn = options[name];
if (fn) {
if (!(fn instanceof Function)) {
throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
}
this.options[name] = fn;
}
}.bind(this);
['onDropObjectOnItem', 'onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
// force the itemSet to refresh: options like orientation and margins may be changed
this.markDirty();
}
};
/**
* Mark the ItemSet dirty so it will refresh everything with next redraw.
* Optionally, all items can be marked as dirty and be refreshed.
* @param {{refreshItems: boolean}} [options]
*/
ItemSet.prototype.markDirty = function (options) {
this.groupIds = [];
if (options && options.refreshItems) {
util.forEach(this.items, function (item) {
item.dirty = true;
if (item.displayed) item.redraw();
});
}
};
/**
* Destroy the ItemSet
*/
ItemSet.prototype.destroy = function () {
this.hide();
this.setItems(null);
this.setGroups(null);
this.hammer = null;
this.body = null;
this.conversion = null;
};
/**
* Hide the component from the DOM
*/
ItemSet.prototype.hide = function () {
// remove the frame containing the items
if (this.dom.frame.parentNode) {
this.dom.frame.parentNode.removeChild(this.dom.frame);
}
// remove the axis with dots
if (this.dom.axis.parentNode) {
this.dom.axis.parentNode.removeChild(this.dom.axis);
}
// remove the labelset containing all group labels
if (this.dom.labelSet.parentNode) {
this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
}
};
/**
* Show the component in the DOM (when not already visible).
*/
ItemSet.prototype.show = function () {
// show frame containing the items
if (!this.dom.frame.parentNode) {
this.body.dom.center.appendChild(this.dom.frame);
}
// show axis with dots
if (!this.dom.axis.parentNode) {
this.body.dom.backgroundVertical.appendChild(this.dom.axis);
}
// show labelset containing labels
if (!this.dom.labelSet.parentNode) {
if (this.options.rtl) {
this.body.dom.right.appendChild(this.dom.labelSet);
} else {
this.body.dom.left.appendChild(this.dom.labelSet);
}
}
};
/**
* Set selected items by their id. Replaces the current selection
* Unknown id's are silently ignored.
* @param {string[] | string} [ids] An array with zero or more id's of the items to be
* selected, or a single item id. If ids is undefined
* or an empty array, all items will be unselected.
*/
ItemSet.prototype.setSelection = function (ids) {
var i, ii, id, item;
if (ids == undefined) ids = [];
if (!Array.isArray(ids)) ids = [ids];
// unselect currently selected items
for (i = 0, ii = this.selection.length; i < ii; i++) {
id = this.selection[i];
item = this.items[id];
if (item) item.unselect();
}
// select items
this.selection = [];
for (i = 0, ii = ids.length; i < ii; i++) {
id = ids[i];
item = this.items[id];
if (item) {
this.selection.push(id);
item.select();
}
}
};
/**
* Get the selected items by their id
* @return {Array} ids The ids of the selected items
*/
ItemSet.prototype.getSelection = function () {
return this.selection.concat([]);
};
/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/
ItemSet.prototype.getVisibleItems = function () {
var range = this.body.range.getRange();
var right, left;
if (this.options.rtl) {
right = this.body.util.toScreen(range.start);
left = this.body.util.toScreen(range.end);
} else {
left = this.body.util.toScreen(range.start);
right = this.body.util.toScreen(range.end);
}
var ids = [];
for (var groupId in this.groups) {
if (this.groups.hasOwnProperty(groupId)) {
var group = this.groups[groupId];
var rawVisibleItems = group.isVisible ? group.visibleItems : [];
// filter the "raw" set with visibleItems into a set which is really
// visible by pixels
for (var i = 0; i < rawVisibleItems.length; i++) {
var item = rawVisibleItems[i];
// TODO: also check whether visible vertically
if (this.options.rtl) {
if (item.right < left && item.right + item.width > right) {
ids.push(item.id);
}
} else {
if (item.left < right && item.left + item.width > left) {
ids.push(item.id);
}
}
}
}
}
return ids;
};
/**
* Deselect a selected item
* @param {string | number} id
* @private
*/
ItemSet.prototype._deselect = function (id) {
var selection = this.selection;
for (var i = 0, ii = selection.length; i < ii; i++) {
if (selection[i] == id) {
// non-strict comparison!
selection.splice(i, 1);
break;
}
}
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
ItemSet.prototype.redraw = function () {
var margin = this.options.margin,
range = this.body.range,
asSize = util.option.asSize,
options = this.options,
orientation = options.orientation.item,
resized = false,
frame = this.dom.frame;
// recalculate absolute position (before redrawing groups)
this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
if (this.options.rtl) {
this.props.right = this.body.domProps.right.width + this.body.domProps.border.right;
} else {
this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
}
// update class name
frame.className = 'vis-itemset';
// reorder the groups (if needed)
resized = this._orderGroups() || resized;
// check whether zoomed (in that case we need to re-stack everything)
// TODO: would be nicer to get this as a trigger from Range
var visibleInterval = range.end - range.start;
var zoomed = visibleInterval != this.lastVisibleInterval || this.props.width != this.props.lastWidth;
var scrolled = range.start != this.lastRangeStart;
var changedStackOption = options.stack != this.lastStack;
var changedStackSubgroupsOption = options.stackSubgroups != this.lastStackSubgroups;
var forceRestack = zoomed || scrolled || changedStackOption || changedStackSubgroupsOption;
this.lastVisibleInterval = visibleInterval;
this.lastRangeStart = range.start;
this.lastStack = options.stack;
this.lastStackSubgroups = options.stackSubgroups;
this.props.lastWidth = this.props.width;
var firstGroup = this._firstGroup();
var firstMargin = {
item: margin.item,
axis: margin.axis
};
var nonFirstMargin = {
item: margin.item,
axis: margin.item.vertical / 2
};
var height = 0;
var minHeight = margin.axis + margin.item.vertical;
// redraw the background group
this.groups[BACKGROUND].redraw(range, nonFirstMargin, forceRestack);
var redrawQueue = {};
var redrawQueueLength = 0;
// collect redraw functions
util.forEach(this.groups, function (group, key) {
if (key === BACKGROUND) return;
var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin;
var returnQueue = true;
redrawQueue[key] = group.redraw(range, groupMargin, forceRestack, returnQueue);
redrawQueueLength = redrawQueue[key].length;
});
var needRedraw = redrawQueueLength > 0;
if (needRedraw) {
var redrawResults = {};
for (var i = 0; i < redrawQueueLength; i++) {
util.forEach(redrawQueue, function (fns, key) {
redrawResults[key] = fns[i]();
});
}
// redraw all regular groups
util.forEach(this.groups, function (group, key) {
if (key === BACKGROUND) return;
var groupResized = redrawResults[key];
resized = groupResized || resized;
height += group.height;
});
height = Math.max(height, minHeight);
}
height = Math.max(height, minHeight);
// update frame height
frame.style.height = asSize(height);
// calculate actual size
this.props.width = frame.offsetWidth;
this.props.height = height;
// reposition axis
this.dom.axis.style.top = asSize(orientation == 'top' ? this.body.domProps.top.height + this.body.domProps.border.top : this.body.domProps.top.height + this.body.domProps.centerContainer.height);
if (this.options.rtl) {
this.dom.axis.style.right = '0';
} else {
this.dom.axis.style.left = '0';
}
this.initialItemSetDrawn = true;
// check if this component is resized
resized = this._isResized() || resized;
return resized;
};
/**
* Get the first group, aligned with the axis
* @return {Group | null} firstGroup
* @private
*/
ItemSet.prototype._firstGroup = function () {
var firstGroupIndex = this.options.orientation.item == 'top' ? 0 : this.groupIds.length - 1;
var firstGroupId = this.groupIds[firstGroupIndex];
var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
return firstGroup || null;
};
/**
* Create or delete the group holding all ungrouped items. This group is used when
* there are no groups specified.
* @protected
*/
ItemSet.prototype._updateUngrouped = function () {
var ungrouped = this.groups[UNGROUPED];
var item, itemId;
if (this.groupsData) {
// remove the group holding all ungrouped items
if (ungrouped) {
ungrouped.hide();
delete this.groups[UNGROUPED];
for (itemId in this.items) {
if (this.items.hasOwnProperty(itemId)) {
item = this.items[itemId];
item.parent && item.parent.remove(item);
var groupId = this._getGroupId(item.data);
var group = this.groups[groupId];
group && group.add(item) || item.hide();
}
}
}
} else {
// create a group holding all (unfiltered) items
if (!ungrouped) {
var id = null;
var data = null;
ungrouped = new Group(id, data, this);
this.groups[UNGROUPED] = ungrouped;
for (itemId in this.items) {
if (this.items.hasOwnProperty(itemId)) {
item = this.items[itemId];
ungrouped.add(item);
}
}
ungrouped.show();
}
}
};
/**
* Get the element for the labelset
* @return {HTMLElement} labelSet
*/
ItemSet.prototype.getLabelSet = function () {
return this.dom.labelSet;
};
/**
* Set items
* @param {vis.DataSet | null} items
*/
ItemSet.prototype.setItems = function (items) {
var me = this,
ids,
oldItemsData = this.itemsData;
// replace the dataset
if (!items) {
this.itemsData = null;
} else if (items instanceof DataSet || items instanceof DataView) {
this.itemsData = items;
} else {
throw new TypeError('Data must be an instance of DataSet or DataView');
}
if (oldItemsData) {
// unsubscribe from old dataset
util.forEach(this.itemListeners, function (callback, event) {
oldItemsData.off(event, callback);
});
// remove all drawn items
ids = oldItemsData.getIds();
this._onRemove(ids);
}
if (this.itemsData) {
// subscribe to new dataset
var id = this.id;
util.forEach(this.itemListeners, function (callback, event) {
me.itemsData.on(event, callback, id);
});
// add all new items
ids = this.itemsData.getIds();
this._onAdd(ids);
// update the group holding all ungrouped items
this._updateUngrouped();
}
this.body.emitter.emit('_change', { queue: true });
};
/**
* Get the current items
* @returns {vis.DataSet | null}
*/
ItemSet.prototype.getItems = function () {
return this.itemsData;
};
/**
* Set groups
* @param {vis.DataSet} groups
*/
ItemSet.prototype.setGroups = function (groups) {
var me = this,
ids;
// unsubscribe from current dataset
if (this.groupsData) {
util.forEach(this.groupListeners, function (callback, event) {
me.groupsData.off(event, callback);
});
// remove all drawn groups
ids = this.groupsData.getIds();
this.groupsData = null;
this._onRemoveGroups(ids); // note: this will cause a redraw
}
// replace the dataset
if (!groups) {
this.groupsData = null;
} else if (groups instanceof DataSet || groups instanceof DataView) {
this.groupsData = groups;
} else {
throw new TypeError('Data must be an instance of DataSet or DataView');
}
if (this.groupsData) {
// go over all groups nesting
var groupsData = this.groupsData;
if (this.groupsData instanceof DataView) {
groupsData = this.groupsData.getDataSet();
}
groupsData.get().forEach(function (group) {
if (group.nestedGroups) {
group.nestedGroups.forEach(function (nestedGroupId) {
var updatedNestedGroup = groupsData.get(nestedGroupId);
updatedNestedGroup.nestedInGroup = group.id;
if (group.showNested == false) {
updatedNestedGroup.visible = false;
}
groupsData.update(updatedNestedGroup);
});
}
});
// subscribe to new dataset
var id = this.id;
util.forEach(this.groupListeners, function (callback, event) {
me.groupsData.on(event, callback, id);
});
// draw all ms
ids = this.groupsData.getIds();
this._onAddGroups(ids);
}
// update the group holding all ungrouped items
this._updateUngrouped();
// update the order of all items in each group
this._order();
this.body.emitter.emit('_change', { queue: true });
};
/**
* Get the current groups
* @returns {vis.DataSet | null} groups
*/
ItemSet.prototype.getGroups = function () {
return this.groupsData;
};
/**
* Remove an item by its id
* @param {string | number} id
*/
ItemSet.prototype.removeItem = function (id) {
var item = this.itemsData.get(id),
dataset = this.itemsData.getDataSet();
if (item) {
// confirm deletion
this.options.onRemove(item, function (item) {
if (item) {
// remove by id here, it is possible that an item has no id defined
// itself, so better not delete by the item itself
dataset.remove(id);
}
});
}
};
/**
* Get the time of an item based on it's data and options.type
* @param {Object} itemData
* @returns {string} Returns the type
* @private
*/
ItemSet.prototype._getType = function (itemData) {
return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
};
/**
* Get the group id for an item
* @param {Object} itemData
* @returns {string} Returns the groupId
* @private
*/
ItemSet.prototype._getGroupId = function (itemData) {
var type = this._getType(itemData);
if (type == 'background' && itemData.group == undefined) {
return BACKGROUND;
} else {
return this.groupsData ? itemData.group : UNGROUPED;
}
};
/**
* Handle updated items
* @param {number[]} ids
* @protected
*/
ItemSet.prototype._onUpdate = function (ids) {
var me = this;
ids.forEach(function (id) {
var itemData = me.itemsData.get(id, me.itemOptions);
var item = me.items[id];
var type = itemData ? me._getType(itemData) : null;
var constructor = ItemSet.types[type];
var selected;
if (item) {
// update item
if (!constructor || !(item instanceof constructor)) {
// item type has changed, delete the item and recreate it
selected = item.selected; // preserve selection of this item
me._removeItem(item);
item = null;
} else {
me._updateItem(item, itemData);
}
}
if (!item && itemData) {
// create item
if (constructor) {
item = new constructor(itemData, me.conversion, me.options);
item.id = id; // TODO: not so nice setting id afterwards
me._addItem(item);
if (selected) {
this.selection.push(id);
item.select();
}
} else if (type == 'rangeoverflow') {
// TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' + '.vis-item.vis-range .vis-item-content {overflow: visible;}');
} else {
throw new TypeError('Unknown item type "' + type + '"');
}
}
}.bind(this));
this._order();
this.body.emitter.emit('_change', { queue: true });
};
/**
* Handle added items
* @param {number[]} ids
* @protected
*/
ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
/**
* Handle removed items
* @param {number[]} ids
* @protected
*/
ItemSet.prototype._onRemove = function (ids) {
var count = 0;
var me = this;
ids.forEach(function (id) {
var item = me.items[id];
if (item) {
count++;
me._removeItem(item);
}
});
if (count) {
// update order
this._order();
this.body.emitter.emit('_change', { queue: true });
}
};
/**
* Update the order of item in all groups
* @private
*/
ItemSet.prototype._order = function () {
// reorder the items in all groups
// TODO: optimization: only reorder groups affected by the changed items
util.forEach(this.groups, function (group) {
group.order();
});
};
/**
* Handle updated groups
* @param {number[]} ids
* @private
*/
ItemSet.prototype._onUpdateGroups = function (ids) {
this._onAddGroups(ids);
};
/**
* Handle changed groups (added or updated)
* @param {number[]} ids
* @private
*/
ItemSet.prototype._onAddGroups = function (ids) {
var me = this;
ids.forEach(function (id) {
var groupData = me.groupsData.get(id);
var group = me.groups[id];
if (!group) {
// check for reserved ids
if (id == UNGROUPED || id == BACKGROUND) {
throw new Error('Illegal group id. ' + id + ' is a reserved id.');
}
var groupOptions = (0, _create2['default'])(me.options);
util.extend(groupOptions, {
height: null
});
group = new Group(id, groupData, me);
me.groups[id] = group;
// add items with this groupId to the new group
for (var itemId in me.items) {
if (me.items.hasOwnProperty(itemId)) {
var item = me.items[itemId];
if (item.data.group == id) {
group.add(item);
}
}
}
group.order();
group.show();
} else {
// update group
group.setData(groupData);
}
});
this.body.emitter.emit('_change', { queue: true });
};
/**
* Handle removed groups
* @param {number[]} ids
* @private
*/
ItemSet.prototype._onRemoveGroups = function (ids) {
var groups = this.groups;
ids.forEach(function (id) {
var group = groups[id];
if (group) {
group.hide();
delete groups[id];
}
});
this.markDirty();
this.body.emitter.emit('_change', { queue: true });
};
/**
* Reorder the groups if needed
* @return {boolean} changed
* @private
*/
ItemSet.prototype._orderGroups = function () {
if (this.groupsData) {
// reorder the groups
var groupIds = this.groupsData.getIds({
order: this.options.groupOrder
});
groupIds = this._orderNestedGroups(groupIds);
var changed = !util.equalArray(groupIds, this.groupIds);
if (changed) {
// hide all groups, removes them from the DOM
var groups = this.groups;
groupIds.forEach(function (groupId) {
groups[groupId].hide();
});
// show the groups again, attach them to the DOM in correct order
groupIds.forEach(function (groupId) {
groups[groupId].show();
});
this.groupIds = groupIds;
}
return changed;
} else {
return false;
}
};
/**
* Reorder the nested groups
*
* @param {Array.} groupIds
* @returns {Array.}
* @private
*/
ItemSet.prototype._orderNestedGroups = function (groupIds) {
var newGroupIdsOrder = [];
groupIds.forEach(function (groupId) {
var groupData = this.groupsData.get(groupId);
if (!groupData.nestedInGroup) {
newGroupIdsOrder.push(groupId);
}
if (groupData.nestedGroups) {
var nestedGroups = this.groupsData.get({
filter: function filter(nestedGroup) {
return nestedGroup.nestedInGroup == groupId;
},
order: this.options.groupOrder
});
var nestedGroupIds = nestedGroups.map(function (nestedGroup) {
return nestedGroup.id;
});
newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
}
}, this);
return newGroupIdsOrder;
};
/**
* Add a new item
* @param {Item} item
* @private
*/
ItemSet.prototype._addItem = function (item) {
this.items[item.id] = item;
// add to group
var groupId = this._getGroupId(item.data);
var group = this.groups[groupId];
if (!group) {
item.groupShowing = false;
} else if (group && group.data && group.data.showNested) {
item.groupShowing = true;
}
if (group) group.add(item);
};
/**
* Update an existing item
* @param {Item} item
* @param {Object} itemData
* @private
*/
ItemSet.prototype._updateItem = function (item, itemData) {
// update the items data (will redraw the item when displayed)
item.setData(itemData);
var groupId = this._getGroupId(item.data);
var group = this.groups[groupId];
if (!group) {
item.groupShowing = false;
} else if (group && group.data && group.data.showNested) {
item.groupShowing = true;
}
};
/**
* Delete an item from the ItemSet: remove it from the DOM, from the map
* with items, and from the map with visible items, and from the selection
* @param {Item} item
* @private
*/
ItemSet.prototype._removeItem = function (item) {
// remove from DOM
item.hide();
// remove from items
delete this.items[item.id];
// remove from selection
var index = this.selection.indexOf(item.id);
if (index != -1) this.selection.splice(index, 1);
// remove from group
item.parent && item.parent.remove(item);
};
/**
* Create an array containing all items being a range (having an end date)
* @param {Array.